"""
Scans an account snapshot (JSON shaped like AWS API output) for 7 common cloud misconfigurations.
Runs offline. Never touches a real account.
Usage: python3 scan_lab.py lab_data/vulnerable_account.json
"""
import json, sys

WEB_PORTS = {80, 443}                       # fine to expose on a load balancer
SECRET_WORDS = ("PASSWORD", "SECRET", "TOKEN", "API_KEY", "PRIVATE_KEY")

def _statements(doc):
    st = doc["Statement"]
    return st if isinstance(st, list) else [st]

def _as_list(x):
    return x if isinstance(x, list) else [x]

def looks_like_reference(value):
    # a pointer to a secret store is not a secret
    return value.startswith("arn:aws:secretsmanager") or value.startswith("arn:aws:ssm") or value.startswith("{{resolve:")

def scan(a):
    out = []
    def add(code, sev, where, msg, fix): out.append({"code": code, "sev": sev, "where": where, "msg": msg, "fix": fix})

    for b in a["s3_buckets"]:
        pab = b["PublicAccessBlock"]
        for s in (_statements(b["Policy"]) if b["Policy"] else []):
            if s["Effect"] == "Allow" and s.get("Principal") == "*" and not pab["BlockPublicPolicy"]:
                add("M1", "HIGH", f"s3:{b['Name']}", "bucket policy grants anyone read access and public access block is off",
                    "turn on Block Public Access, serve files via CloudFront or presigned URLs")
        if not b["Encryption"]:
            add("M5", "MEDIUM", f"s3:{b['Name']}", "no default encryption", "enable default SSE (aws:kms)")

    for u in a["iam_users"]:
        for p in u["Policies"]:
            for s in _statements(p["Document"]):
                if s["Effect"] == "Allow" and "*" in _as_list(s["Action"]) and "*" in _as_list(s["Resource"]):
                    add("M2", "HIGH", f"iam:{u['UserName']}/{p['PolicyName']}", "Action * on Resource * (full admin)",
                        "replace with the specific actions and resources the user needs")

    for g in a["security_groups"]:
        for p in g["IpPermissions"]:
            world = any(r["CidrIp"] == "0.0.0.0/0" for r in p["IpRanges"])
            if world and p["FromPort"] not in WEB_PORTS:
                add("M3", "HIGH", f"sg:{g['GroupName']}", f"port {p['FromPort']} open to 0.0.0.0/0",
                    "restrict to a VPN/office CIDR, or remove the rule and use SSM Session Manager")

    for fn in a["lambda_functions"]:
        for k, v in fn["Environment"]["Variables"].items():
            if any(w in k.upper() for w in SECRET_WORDS) and not looks_like_reference(v):
                add("M4", "HIGH", f"lambda:{fn['FunctionName']}", f"plaintext value in env var {k}",
                    "move to Secrets Manager and pass only the ARN")

    for v in a["ebs_volumes"]:
        if not v["Encrypted"]:
            add("M5", "MEDIUM", f"ebs:{v['VolumeId']}", "volume not encrypted", "snapshot, copy with encryption, swap the volume")

    for r in a["iam_roles"]:
        for s in _statements(r["AssumeRolePolicyDocument"]):
            princ = s.get("Principal", {})
            if s["Effect"] == "Allow" and (princ == "*" or (isinstance(princ, dict) and "*" in _as_list(princ.get("AWS", [])))):
                add("M6", "HIGH", f"role:{r['RoleName']}", "trust policy lets any AWS principal assume this role",
                    "name the exact account or role, add an ExternalId condition")

    if not a["cloudtrail_trails"]:
        add("M7", "HIGH", "cloudtrail", "no trail exists", "create a multi-region trail")
    for t in a["cloudtrail_trails"]:
        if not t["IsLogging"] or not t["IsMultiRegionTrail"]:
            why = "trail exists but logging is OFF" if not t["IsLogging"] else "trail is single-region"
            add("M7", "HIGH", f"cloudtrail:{t['Name']}", why, "start logging, make it multi-region")
    return out

def report(findings, title):
    print(f"== {title}")
    for f in findings:
        print(f"  [{f['sev']:<6}] {f['code']}  {f['where']:<36} {f['msg']}")
    cats = sorted({f['code'] for f in findings})
    print(f"  findings: {len(findings)}   categories hit: {len(cats)}   {' '.join(cats) if cats else '(none)'}")

if __name__ == "__main__":
    report(scan(json.load(open(sys.argv[1]))), sys.argv[1])
