"""Which Tranco top-1,000 sites chain to an ECDSA P-256 CA key?

Chrome announced on 2026-12-03 that from 2027-03-15 it intends to stop
trusting CA keys that use ECDSA P-256. This script measures how many of the
Tranco top 1,000 (list K97GW) would be affected, looking at the chain each
server actually sends.

For every domain it runs `openssl s_client -showcerts` (bare name first, then
www.<domain>), parses every certificate the server sent with the
`cryptography` package, and records for each one: subject, issuer, its own
public key type, and whether it is a CA certificate. The root is usually not
sent, so the top certificate's issuer is looked up by subject name in
Mozilla's root bundle (curl's cacert.pem) to get the root key type too.

Nothing beyond the TLS handshake is sent.

Usage:
  python p256-ca-survey.py tranco-K97GW-top1000.csv cacert.pem p256-ca-results.csv
Requires: OpenSSL 3.x on PATH, Python 3.10+, cryptography (pip install cryptography)
"""
import csv
import json
import re
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor

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

OPENSSL = "openssl"
TIMEOUT = 12
PEM_RE = re.compile(rb"-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----", re.S)


def key_type(cert):
    k = cert.public_key()
    if isinstance(k, ec.EllipticCurvePublicKey):
        return {"secp256r1": "P-256", "secp384r1": "P-384",
                "secp521r1": "P-521"}.get(k.curve.name, k.curve.name)
    if isinstance(k, rsa.RSAPublicKey):
        return f"RSA-{k.key_size}"
    if isinstance(k, ed25519.Ed25519PublicKey):
        return "Ed25519"
    return type(k).__name__


def is_ca(cert):
    try:
        return cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca
    except x509.ExtensionNotFound:
        return False


def load_roots(path):
    roots = {}
    data = open(path, "rb").read()
    for pem in PEM_RE.findall(data):
        c = x509.load_pem_x509_certificate(pem)
        roots.setdefault(c.subject.rfc4514_string(), set()).add(key_type(c))
    return roots


def fetch_chain(host):
    cmd = [OPENSSL, "s_client", "-connect", f"{host}:443", "-servername", host,
           "-showcerts"]
    try:
        p = subprocess.run(cmd, input=b"", capture_output=True, timeout=TIMEOUT)
    except subprocess.TimeoutExpired:
        return None, "timeout"
    pems = PEM_RE.findall(p.stdout)
    if not pems:
        return None, "no-handshake"
    return [x509.load_pem_x509_certificate(x) for x in pems], ""


def survey(args):
    (rank, domain), roots = args
    chain, err = None, ""
    for host in (domain, "www." + domain):
        chain, err = fetch_chain(host)
        if chain:
            break
    rec = {"rank": rank, "domain": domain, "host": host if chain else "",
           "ok": bool(chain), "err": err}
    if not chain:
        return rec
    certs = [{"subject": c.subject.rfc4514_string(),
              "issuer": c.issuer.rfc4514_string(),
              "key": key_type(c), "ca": is_ca(c)} for c in chain]
    leaf = certs[0]
    sent_ca = certs[1:]
    # The leaf's issuing CA key: the sent cert whose subject is the leaf's issuer.
    issuer_key = next((c["key"] for c in sent_ca if c["subject"] == leaf["issuer"]), "")
    top = certs[-1]
    root_name = top["issuer"] if top["subject"] != top["issuer"] else top["subject"]
    root_keys = roots.get(root_name, set())
    rec.update({
        "leaf_key": leaf["key"],
        "leaf_not_after": chain[0].not_valid_after_utc.strftime("%Y-%m-%d"),
        "issuer_name": leaf["issuer"],
        "issuer_key": issuer_key,
        "sent_ca_keys": " | ".join(c["key"] for c in sent_ca),
        "root_name": root_name,
        "root_key": "/".join(sorted(root_keys)) if root_keys else "not-in-mozilla",
        "chain": json.dumps(certs),
    })
    return rec


def main():
    src, roots_path, dst = sys.argv[1], sys.argv[2], sys.argv[3]
    roots = load_roots(roots_path)
    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, [(r, roots) for r in rows]))
    fields = ["rank", "domain", "host", "ok", "err", "leaf_key", "leaf_not_after", "issuer_name",
              "issuer_key", "sent_ca_keys", "root_name", "root_key", "chain"]
    with open(dst, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        w.writerows(recs)
    print(f"{len(recs)} domains in {time.time() - t0:.0f} s, "
          f"{len(roots)} Mozilla root names loaded, run at "
          f"{time.strftime('%Y-%m-%d %H:%M %Z')}")


if __name__ == "__main__":
    main()
