#!/usr/bin/env python3
"""Measurement behind the sec-ref.tools expiry study: for each domain in a pinned Tranco
list, record the TLS certificate it serves and its security.txt (RFC 9116).

Method and opt-out are published at https://sec-ref.tools/measurement.html; keep the two
in step. Per domain this makes one verified TLS handshake (plus one unverified only when
verification fails, so expired certificates are still recorded), one GET of
/.well-known/security.txt and, only if that is absent, one GET of /security.txt. Redirects
are followed up to 5 hops, HTTPS only, and no domain gets more than 10 connections.

Rules that came out of the design review (docs/specs/2026-11-12-sec-ref-expiry-design.md):
  - DNS goes over DNS-over-HTTPS. The local resolver sinkholes ad/tracker domains to
    0.0.0.0, and a connect to 0.0.0.0:443 reaches this machine's own TLS listener.
    Non-public answers are recorded as dns-nonpublic, never connected to.
  - Unreachable, blocked and forbidden are "not measured", never "absent".
  - Raw responses stay local (data/ is gitignored); only aggregates are published.

Trust: verification here uses the scanning host's CA store, which can differ from a browser's
(local distrusts, missing intermediates a browser would fetch). analyze.js therefore does not
take this verdict alone; see its "public certificate authority" rule.

Usage (from the one egress named on the method page):
  ./scan.py --top 10000 [--workers 16] [--controls-only]
Writes data/scan-<UTC date>.jsonl, appending; domains already in the file are skipped,
so an interrupted run resumes.
"""
import argparse
import base64
import concurrent.futures as cf
import datetime as dt
import hashlib
import http.client
import ipaddress
import json
import os
import re
import socket
import ssl
import sys
import threading
import time
import urllib.parse
import urllib.request

from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa
from cryptography.x509.oid import ExtensionOID, NameOID

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "data")
LIST = os.path.join(DATA, "tranco-PY2NJ.csv")
LIST_SHA = "7b3b5a453b5cb4124dd85a35f34c3327b94b2efd9c928961176a581b8b3bb7d5"
DENY = os.path.join(HERE, "denylist.txt")
UA = "sec-ref.tools-study/1.0 (+https://sec-ref.tools/measurement.html)"
TIMEOUT = 10
MAX_BODY = 32 * 1024
MAX_CONN = 10
MAX_HOPS = 5


# ---------------- DNS ----------------
def doh(name):
    """A records over DoH. Returns (status, [ips]); status in ok/nxdomain/servfail/noanswer/error."""
    url = "https://cloudflare-dns.com/dns-query?" + urllib.parse.urlencode({"name": name, "type": "A"})
    req = urllib.request.Request(url, headers={"accept": "application/dns-json"})
    for attempt in range(3):
        try:
            r = json.load(urllib.request.urlopen(req, timeout=TIMEOUT))
            break
        except Exception as e:  # network hiccup: retry, then report
            err = f"error:{type(e).__name__}"
            time.sleep(1 + attempt)
    else:
        return err, []
    st = {0: "ok", 2: "servfail", 3: "nxdomain"}.get(r.get("Status"), f"rcode{r.get('Status')}")
    ips = [a["data"] for a in r.get("Answer", []) if a.get("type") == 1]
    if st == "ok" and not ips:
        st = "noanswer"
    return st, ips


def public_ip(ips):
    for ip in ips:
        try:
            if ipaddress.ip_address(ip).is_global:
                return ip
        except ValueError:
            pass
    return None


class Budget:
    """Connection cap per domain, enforced at the one place connections are opened."""
    def __init__(self):
        self.n = 0

    def take(self):
        if self.n >= MAX_CONN:
            raise RuntimeError("connection budget exhausted")
        self.n += 1


def connect(ip, host, verify, budget, port=443):
    budget.take()
    ctx = ssl.create_default_context()
    if not verify:
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    raw = socket.create_connection((ip, port), timeout=TIMEOUT)
    try:
        return ctx.wrap_socket(raw, server_hostname=host)
    except Exception:
        raw.close()
        raise


# ---------------- certificate ----------------
def name_attr(name, oid):
    v = name.get_attributes_for_oid(oid)
    return v[0].value if v else None


def san_match(host, sans):
    host = host.lower().rstrip(".")
    for s in sans:
        s = s.lower().rstrip(".")
        if s == host:
            return True
        if s.startswith("*.") and host.count(".") >= 2 and host.split(".", 1)[1] == s[2:]:
            return True
    return False


def describe_cert(der, host):
    c = x509.load_der_x509_certificate(der)
    try:
        sans = c.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value.get_values_for_type(x509.DNSName)
    except x509.ExtensionNotFound:
        sans = []
    try:
        scts = c.extensions.get_extension_for_oid(ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS).value
        sct = min(s.timestamp for s in scts).replace(tzinfo=dt.timezone.utc).isoformat()
    except (x509.ExtensionNotFound, ValueError):
        sct = None
    k = c.public_key()
    ktype = ("RSA-%d" % k.key_size if isinstance(k, rsa.RSAPublicKey) else
             "EC-%s" % k.curve.name if isinstance(k, ec.EllipticCurvePublicKey) else
             "Ed25519" if isinstance(k, ed25519.Ed25519PublicKey) else type(k).__name__)
    return {
        "not_before": c.not_valid_before_utc.isoformat(),
        "not_after": c.not_valid_after_utc.isoformat(),
        "sct_first": sct,
        "issuer_o": name_attr(c.issuer, NameOID.ORGANIZATION_NAME),
        "issuer_cn": name_attr(c.issuer, NameOID.COMMON_NAME),
        "self_issued": c.issuer == c.subject,
        "san_count": len(sans),
        "san_match": san_match(host, sans),
        "san_sample": sorted(sans)[:5],  # for edge classification (e.g. *.cloudflaressl.com); local only
        "key": ktype,
        "sha256": hashlib.sha256(der).hexdigest(),
    }


def tls_probe(ip, host, budget):
    out = {"verified": None, "verify_error": None}
    try:
        s = connect(ip, host, True, budget)
        out["verified"] = True
    except ssl.SSLCertVerificationError as e:
        out["verified"] = False
        out["verify_error"] = e.verify_message or str(e)[:120]
        s = connect(ip, host, False, budget)
    with s:
        out["tls_version"] = s.version()
        out.update(describe_cert(s.getpeercert(binary_form=True), host))
    return out


# ---------------- HTTP ----------------
# Bot-challenge pages. Not "access denied": that is also S3's answer for a missing object in a
# private bucket (intuit.com in the pilot), which is "forbidden", not a challenge. Akamai's
# bot block is caught by the 403 + server rule below.
CHALLENGE_MARKERS = ("just a moment", "attention required", "cf-chl", "_incapsula_", "captcha",
                     "request unsuccessful", "ddos protection", "checking your browser")


def get(url, budget, resolved):
    """One HTTPS GET. Returns dict with status, headers (lowercased), body (bytes, capped)."""
    u = urllib.parse.urlsplit(url)
    host = u.hostname
    if host not in resolved:
        st, ips = doh(host)
        resolved[host] = public_ip(ips) if st == "ok" else None
        if st == "ok" and not resolved[host]:
            resolved[host] = None
    ip = resolved[host]
    if not ip:
        return {"error": "dns", "host": host}
    s = connect(ip, host, False, budget, u.port or 443)  # validity is recorded by tls_probe, not enforced here
    conn = http.client.HTTPSConnection(host, u.port or 443, timeout=TIMEOUT)
    conn.sock = s
    path = (u.path or "/") + ("?" + u.query if u.query else "")
    try:
        conn.request("GET", path, headers={"Host": host, "User-Agent": UA,
                                           "Accept": "text/plain, */*;q=0.1",
                                           "Accept-Encoding": "identity", "Connection": "close"})
        r = conn.getresponse()
        body = r.read(MAX_BODY)
        return {"status": r.status, "headers": {k.lower(): v for k, v in r.getheaders()}, "body": body}
    finally:
        conn.close()


FIELD_OR_COMMENT = re.compile(r"^(-----BEGIN PGP SIGNED MESSAGE-----|#|[A-Za-z][A-Za-z0-9-]*:[ \t]*\S)", re.M)


def classify(resp):
    """found / absent / blocked / forbidden / http-error / ratelimited."""
    st, h = resp["status"], resp["headers"]
    if 200 < st < 300 or "x-amzn-waf-action" in h:
        return "blocked"   # AWS WAF answers a challenge with 202; no other 2xx is a file
    text = resp["body"][:4096].decode("utf-8", "replace").lower()
    server = h.get("server", "").lower()
    if st == 429:
        return "ratelimited"
    if st in (404, 410) and "cf-mitigated" not in h:
        return "absent"   # checked first: S3 and others put words like "denied" in plain 404 pages
    challenged = ("cf-mitigated" in h or any(m in text for m in CHALLENGE_MARKERS)
                  or (st in (403, 503) and any(e in server for e in ("cloudflare", "akamai", "imperva", "incapsula", "sucuri"))))
    if challenged and st != 200:
        return "blocked"
    if 200 <= st < 300:
        html = text.lstrip().startswith(("<!doctype", "<html", "<head", "<body", "<script", "<meta", "<title")) or "text/html" in h.get("content-type", "")
        if challenged and html:
            return "blocked"
        if html or not FIELD_OR_COMMENT.search(resp["body"].decode("utf-8", "replace").lstrip("\ufeff")):
            return "absent"   # soft-404 or placeholder ("OK", empty, JSON, an image)
        return "found"
    if st in (401, 403):
        return "forbidden"
    return "http-error"


def fetch_sectxt(host, path, budget, resolved):
    """Follow up to MAX_HOPS redirects (HTTPS only). Returns record with chain and outcome."""
    url = f"https://{host}{path}"
    chain = []
    for hop in range(MAX_HOPS + 1):
        resp = get(url, budget, resolved)
        if "error" in resp:
            return {"outcome": "dns-error", "chain": chain + [url]}
        chain.append(f"{resp['status']} {url}")
        if resp["status"] == 429:
            ra = resp["headers"].get("retry-after", "")
            time.sleep(min(int(ra), 60) if ra.isdigit() else 30)
            resp = get(url, budget, resolved)
            chain.append(f"{resp.get('status')} {url} (after retry-after)")
            if "error" in resp:
                return {"outcome": "dns-error", "chain": chain}
        if resp["status"] in (301, 302, 303, 307, 308) and resp["headers"].get("location"):
            nxt = urllib.parse.urljoin(url, resp["headers"]["location"])
            if not nxt.lower().startswith("https://"):
                return {"outcome": "redirect-not-https", "chain": chain + [nxt]}
            url = nxt
            continue
        out = {"outcome": classify(resp), "chain": chain, "final_url": url,
               "content_type": resp["headers"].get("content-type"), "server": resp["headers"].get("server")}
        if out["outcome"] == "found":
            out["body_b64"] = base64.b64encode(resp["body"]).decode()
            out["truncated"] = len(resp["body"]) >= MAX_BODY
        return out
    return {"outcome": "too-many-redirects", "chain": chain}


# ---------------- one domain ----------------
def measure(rank, domain):
    rec = {"rank": rank, "domain": domain, "measured_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
    budget, resolved = Budget(), {}
    host = ip = None
    dns = {}
    for cand in (domain, "www." + domain):
        st, ips = doh(cand)
        pub = public_ip(ips) if st == "ok" else None
        dns[cand] = st if (st != "ok" or pub) else "dns-nonpublic"
        if pub:
            host, ip = cand, pub
            resolved[cand] = pub
            break
    rec["dns"] = dns
    if not host:
        rec["status"] = "dns-unresolved"
        return rec
    rec["host"], rec["ip"] = host, ip
    try:
        rec["tls"] = tls_probe(ip, host, budget)
    except Exception as e:
        rec["tls_error"] = f"{type(e).__name__}: {str(e)[:120]}"
        # apex reachable in DNS but not on 443: try www once, the way a browser user would land
        if host == domain:
            st, ips = doh("www." + domain)
            pub = public_ip(ips) if st == "ok" else None
            if pub:
                host, ip = "www." + domain, pub
                resolved[host] = pub
                rec["host"], rec["ip"] = host, ip
                try:
                    rec["tls"] = tls_probe(ip, host, budget)
                    rec.pop("tls_error")
                except Exception as e2:
                    rec["tls_error"] = f"{type(e2).__name__}: {str(e2)[:120]}"
    if "tls" not in rec:
        rec["status"] = "tls-unreachable"
        return rec
    # Each fetch is guarded on its own, so a failure on the legacy fetch cannot overwrite an
    # already-measured /.well-known/ result.
    def guarded(path):
        try:
            out = fetch_sectxt(host, path, budget, resolved)
        except Exception as e:
            out = {"outcome": "error", "error": f"{type(e).__name__}: {str(e)[:120]}"}
        out["path"] = path
        return out
    rec["sectxt"] = guarded("/.well-known/security.txt")
    if rec["sectxt"]["outcome"] == "absent":
        rec["sectxt_legacy"] = guarded("/security.txt")
    rec["connections"] = budget.n
    rec["status"] = "measured"
    return rec


# ---------------- driver ----------------
CONTROLS = [
    # (domain, check, description) -- each must hold before the main run starts
    ("doubleclick.net", lambda r: r.get("status") == "measured", "sinkholed locally, must resolve publicly via DoH"),
    ("google.com", lambda r: r["tls"]["verified"] and r["tls"]["san_match"], "valid cert, SAN matches"),
    ("github.com", lambda r: r["sectxt"]["outcome"] == "found", "publishes security.txt"),
    ("expired.badssl.com", lambda r: r["tls"]["verified"] is False and "expired" in r["tls"]["verify_error"]
        and r["tls"]["not_after"] < dt.datetime.now(dt.timezone.utc).isoformat(), "expired cert is captured, not dropped"),
    ("wrong.host.badssl.com", lambda r: r["tls"]["san_match"] is False, "SAN mismatch detected"),
    ("self-signed.badssl.com", lambda r: r["tls"]["verified"] is False and r["tls"]["self_issued"], "self-signed captured"),
    ("example.com", lambda r: r["sectxt"]["outcome"] in ("absent",), "no security.txt classifies absent"),
]


def run_controls():
    ok = True
    for d, check, desc in CONTROLS:
        r = measure(0, d)
        try:
            passed = bool(check(r))
        except Exception as e:
            passed = False
            desc += f" ({type(e).__name__}: {e})"
        ok &= passed
        print(f"  [{'ok ' if passed else 'FAIL'}] control {d}: {desc}", flush=True)
        if not passed:
            print("        " + json.dumps({k: v for k, v in r.items() if k != "sectxt"} | {"sectxt": {k: v for k, v in r.get("sectxt", {}).items() if k != "body_b64"}})[:600])
    return ok


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--top", type=int, default=10000)
    ap.add_argument("--workers", type=int, default=16)
    ap.add_argument("--controls-only", action="store_true")
    a = ap.parse_args()

    if hashlib.sha256(open(LIST, "rb").read()).hexdigest() != LIST_SHA:
        sys.exit("Tranco list does not match the pinned sha256")
    print("positive controls:")
    if not run_controls():
        sys.exit("a control failed; not scanning")
    if a.controls_only:
        return

    deny = set()
    if os.path.exists(DENY):
        deny = {l.strip().lower() for l in open(DENY) if l.strip() and not l.startswith("#")}
    domains = []
    for line in open(LIST):
        r, d = line.strip().split(",", 1)
        if int(r) > a.top:
            break
        if d.lower() not in deny:
            domains.append((int(r), d.lower()))
    out = os.path.join(DATA, f"scan-{dt.datetime.now(dt.timezone.utc):%Y%m%d}.jsonl")
    done = set()
    if os.path.exists(out):
        done = {json.loads(l)["domain"] for l in open(out)}
    todo = [x for x in domains if x[1] not in done]
    print(f"{len(domains)} domains ({len(deny)} denylisted), {len(done)} already done, {len(todo)} to go -> {out}", flush=True)
    lock = threading.Lock()
    t0, n = time.time(), 0
    with open(out, "a") as f, cf.ThreadPoolExecutor(a.workers) as ex:
        futs = {ex.submit(measure, r, d): (r, d) for r, d in todo}
        for fu in cf.as_completed(futs):
            r, d = futs[fu]
            try:
                rec = fu.result()
            except Exception as e:
                rec = {"rank": r, "domain": d, "status": "crash", "error": f"{type(e).__name__}: {str(e)[:200]}"}
            with lock:
                f.write(json.dumps(rec) + "\n")
                f.flush()
                n += 1
                if n % 250 == 0:
                    print(f"  {n}/{len(todo)}  {n / (time.time() - t0):.1f}/s", flush=True)
    print("done", out)


if __name__ == "__main__":
    main()
