"""Post-quantum TLS key exchange survey of the Tranco top 1,000 (list K97GW).

For every domain this opens TLS connections with the local `openssl s_client`
(OpenSSL 3.5.9, which implements the X25519MLKEM768 hybrid group) and records:

  probe 1 ("browser-like"): offer X25519MLKEM768 and X25519 key shares, plus
          secp256r1 and secp384r1 without shares, so the server can pick
          either the hybrid or a classical group in one round trip.
          Record the TLS version, the group the server picked, the handshake
          signature type and the key type of every certificate it sent.
  probe 2 (only when probe 1 did not end on X25519MLKEM768 over TLS 1.3):
          offer X25519MLKEM768 and nothing else. A completed handshake means
          the server supports the hybrid but preferred a classical group.

The bare domain is tried first, then www.<domain> if the bare name gives no
TLS answer. Nothing beyond the handshake is sent: no HTTP request.

Usage: python pq-tls-survey.py tranco-K97GW-top1000.csv pq-tls-results.csv
"""
import csv
import re
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor

OPENSSL = "openssl"
TIMEOUT = 12
BROWSER_GROUPS = "*X25519MLKEM768:*X25519:secp256r1:secp384r1"
PQ_ONLY = "X25519MLKEM768"


def s_client(host, groups):
    cmd = [OPENSSL, "s_client", "-connect", f"{host}:443", "-servername", host,
           "-groups", groups, "-showcerts"]
    try:
        p = subprocess.run(cmd, input=b"", capture_output=True, timeout=TIMEOUT)
    except subprocess.TimeoutExpired:
        return {"ok": False, "err": "timeout"}
    out = p.stdout.decode("utf-8", "replace") + p.stderr.decode("utf-8", "replace")
    proto = re.search(r"^Protocol: (\S+)", out, re.M)
    if not proto or "Cipher is (NONE)" in out:
        err = "no-handshake"
        if re.search(r"getaddrinfo|Name or service not known|nodename nor servname|No such host", out, re.I):
            err = "dns"
        elif re.search(r"connect:errno|Connection refused|BIO_connect", out):
            err = "connect"
        elif re.search(r"handshake failure|alert", out, re.I):
            err = "tls-alert"
        return {"ok": False, "err": err}
    m = re.search(r"Negotiated TLS1\.3 group: (\S+)", out)
    group = m.group(1) if m else ""
    if not m:
        # Classical groups are printed as "Peer Temp Key: X25519, 253 bits"
        # or "Peer Temp Key: ECDH, prime256v1, 256 bits".
        t = re.search(r"(?:Peer|Server) Temp Key: (.+)", out)
        if t:
            parts = [p.strip() for p in t.group(1).split(",")]
            group = parts[1] if parts[0] in ("ECDH", "DH") and len(parts) > 2 else parts[0]
    sig = re.search(r"Peer signature type: (\S+)", out)
    keys = re.findall(r"^\s*\d+ s:.*\n\s*i:.*\n\s*a:PKEY: ([^;]+);", out, re.M)
    return {
        "ok": True,
        "proto": proto.group(1),
        "group": group,
        "sig": sig.group(1) if sig else "",
        "leaf_key": keys[0].strip() if keys else "",
        "chain_keys": " | ".join(k.strip() for k in keys[1:]),
    }


def survey(row):
    rank, domain = row
    for host in (domain, "www." + domain):
        r1 = s_client(host, BROWSER_GROUPS)
        if r1["ok"]:
            break
    rec = {"rank": rank, "domain": domain, "host": host if r1["ok"] else "",
           "tls_ok": r1["ok"], "err": r1.get("err", ""),
           "proto": r1.get("proto", ""), "group": r1.get("group", ""),
           "sig": r1.get("sig", ""), "leaf_key": r1.get("leaf_key", ""),
           "chain_keys": r1.get("chain_keys", ""), "pq_only_ok": ""}
    if r1["ok"] and not (r1["proto"] == "TLSv1.3" and r1["group"] == "X25519MLKEM768"):
        r2 = s_client(host, PQ_ONLY)
        rec["pq_only_ok"] = bool(r2["ok"] and r2.get("group") == "X25519MLKEM768")
    return rec


def main():
    src, dst = sys.argv[1], sys.argv[2]
    with open(src, newline="") as f:
        rows = [(int(r[0]), r[1].strip()) for r in csv.reader(f) if r]
    t0 = time.time()
    with ThreadPoolExecutor(32) as ex:
        recs = list(ex.map(survey, rows))
    with open(dst, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(recs[0].keys()))
        w.writeheader()
        w.writerows(recs)
    print(f"{len(recs)} domains in {time.time() - t0:.0f} s, run at "
          f"{time.strftime('%Y-%m-%d %H:%M %Z')}")


if __name__ == "__main__":
    main()
