#!/usr/bin/env python3 """pqcheck: does a public endpoint accept post-quantum key exchange? One ordinary handshake per question, standard library only, nothing installed. python3 pqcheck.py example.com # HTTPS on 443 python3 pqcheck.py example.com:8443 git.example.com:22 python3 pqcheck.py near:alice.near # which kinds of keys control a NEAR account python3 pqcheck.py --targets targets.json --vantage "frankfurt-vps" --json out.json How it works (TLS): it sends a TLS 1.3 ClientHello that offers ONE key-exchange group and no key share. A server that supports the group must answer with a HelloRetryRequest naming it; a server that does not answers with a handshake_failure alert. The same hello with classical x25519 runs beside it as a control, so a refusal is told apart from a network problem. Nothing is decrypted and no handshake is completed. How it works (SSH): it reads the list of key-exchange methods the server advertises in its first, unencrypted packet, then hangs up. No login is attempted. What a result means: "accepts" = the server accepts that group when it is the only one offered. It does NOT tell you what the server prefers, what its users' software offers, or what happens behind it. "classical only" is not "broken": no public quantum computer can break today's key exchange. Check any row yourself with a second, independent tool (OpenSSL 3.5 or newer): openssl s_client -connect HOST:443 -groups X25519MLKEM768 -tls1_3 """ import argparse import ipaddress import json import re import os import socket import ssl import struct import sys import threading import time import urllib.request VERSION = "0.2.0" TIMEOUT = 10 # seconds for each connection DNS_TIMEOUT = 8 # seconds for the name lookup ALLOWED_PORTS = {443, 8443, 9443, 22} # TLS named groups (IANA TLS Supported Groups registry) X25519 = 0x001D X25519MLKEM768 = 0x11EC # the hybrid browsers and CDNs deploy SECP384R1MLKEM1024 = 0x11ED # hybrid at the larger key size MLKEM1024 = 0x0202 # pure ML-KEM-1024 HRR_RANDOM = bytes.fromhex("CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C") SSH_PQ_KEX = ("mlkem768x25519-sha256", "mlkem768nistp256-sha256", "mlkem1024nistp384-sha384", "sntrup761x25519-sha512", "sntrup761x25519-sha512@openssh.com") SIG_OIDS = { "1.2.840.113549.1.1.11": "RSA with SHA-256", "1.2.840.113549.1.1.12": "RSA with SHA-384", "1.2.840.113549.1.1.13": "RSA with SHA-512", "1.2.840.113549.1.1.10": "RSA-PSS", "1.2.840.10045.4.3.2": "ECDSA with SHA-256", "1.2.840.10045.4.3.3": "ECDSA with SHA-384", "1.2.840.10045.4.3.4": "ECDSA with SHA-512", "1.3.101.112": "Ed25519", "2.16.840.1.101.3.4.3.17": "ML-DSA-44", "2.16.840.1.101.3.4.3.18": "ML-DSA-65", "2.16.840.1.101.3.4.3.19": "ML-DSA-87", } PQ_SIG_PREFIX = "ML-DSA" class Refused(Exception): pass def resolve(host): """Look the name up once, within a time limit, and refuse anything that is not a public address. Every probe then connects to this one address, so the name cannot point somewhere else between the check and the handshake, and a slow resolver cannot stall the run. """ box = {} def work(): try: box["infos"] = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM) except OSError as e: box["error"] = e t = threading.Thread(target=work, daemon=True) t.start() t.join(DNS_TIMEOUT) if t.is_alive(): raise Refused(f"{host}: name lookup took longer than {DNS_TIMEOUT} s; not measured") if "error" in box: raise Refused(f"{host}: name lookup failed; not measured") addresses = [info[4][0] for info in box["infos"]] for a in addresses: ip = ipaddress.ip_address(a) if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast or ip.is_unspecified: raise Refused(f"{host} resolves to a non-public address; not measured") v4 = [a for a in addresses if ":" not in a] return (v4 or addresses)[0] public_address = resolve def _ext(kind, body): return struct.pack("!HH", kind, len(body)) + body def client_hello(host, group): name = host.encode("idna") exts = _ext(0, struct.pack("!H", len(name) + 3) + bytes([0]) + struct.pack("!H", len(name)) + name) exts += _ext(10, struct.pack("!HH", 2, group)) sigs = b"".join(struct.pack("!H", s) for s in (0x0403, 0x0804, 0x0401, 0x0503, 0x0805, 0x0501, 0x0806, 0x0601, 0x0807)) exts += _ext(13, struct.pack("!H", len(sigs)) + sigs) exts += _ext(43, bytes([2]) + struct.pack("!H", 0x0304)) # TLS 1.3 only exts += _ext(51, struct.pack("!H", 0)) # empty key share: "you choose" alpn = bytes([2]) + b"h2" + bytes([8]) + b"http/1.1" exts += _ext(16, struct.pack("!H", len(alpn)) + alpn) ciphers = struct.pack("!HHH", 0x1301, 0x1302, 0x1303) body = struct.pack("!H", 0x0303) + os.urandom(32) + bytes([32]) + os.urandom(32) body += struct.pack("!H", len(ciphers)) + ciphers + bytes([1, 0]) + struct.pack("!H", len(exts)) + exts handshake = bytes([1]) + struct.pack("!I", len(body))[1:] + body return bytes([22]) + struct.pack("!HH", 0x0301, len(handshake)) + handshake def _read_record(sock): buf = b"" deadline = time.time() + TIMEOUT while len(buf) < 5 and time.time() < deadline: chunk = sock.recv(4096) if not chunk: break buf += chunk if len(buf) < 5: return None, b"" kind, _, length = struct.unpack("!BHH", buf[:5]) while len(buf) < 5 + length and time.time() < deadline: chunk = sock.recv(4096) if not chunk: break buf += chunk return kind, buf[5:5 + length] def tls_offer(host, port, group, ip=None): """Offer one group. Returns 'accepts', 'declines', 'no-tls13', or 'unclear: '.""" try: with socket.create_connection((ip or host, port), timeout=TIMEOUT) as sock: sock.sendall(client_hello(host, group)) kind, rec = _read_record(sock) except OSError as e: return f"unclear: {type(e).__name__}" if kind is None: return "unclear: connection closed without an answer" if kind == 21 and len(rec) >= 2: if rec[1] == 40: return "declines" if rec[1] == 70: return "no-tls13" return f"unclear: alert {rec[1]}" if kind != 22 or not rec or rec[0] != 2: return f"unclear: unexpected record type {kind}" try: p = 4 + 2 random = rec[p:p + 32] p += 32 p += 1 + rec[p] p += 3 ext_len = struct.unpack("!H", rec[p:p + 2])[0] p += 2 end = p + ext_len selected = None while p + 4 <= end: kind_, length = struct.unpack("!HH", rec[p:p + 4]) p += 4 if kind_ == 51 and length >= 2: selected = struct.unpack("!H", rec[p:p + 2])[0] p += length except (IndexError, struct.error): return "unclear: could not parse the server's answer" if selected == group: return "accepts" return f"unclear: server answered with group {selected}" + (" (retry)" if random == HRR_RANDOM else "") def _oid(der): first = der[0] parts = [first // 40, first % 40] value = 0 for b in der[1:]: value = (value << 7) | (b & 0x7F) if not b & 0x80: parts.append(value) value = 0 return ".".join(str(x) for x in parts) def _tlv(data, pos): tag = data[pos] length = data[pos + 1] pos += 2 if length & 0x80: n = length & 0x7F length = int.from_bytes(data[pos:pos + n], "big") pos += n return tag, pos, pos + length def certificate_signature(host, port, ip=None): """Signature algorithm on the certificate the server presents to an ordinary client.""" try: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with socket.create_connection((ip or host, port), timeout=TIMEOUT) as raw: with ctx.wrap_socket(raw, server_hostname=host) as tls: der = tls.getpeercert(binary_form=True) version = tls.version() _, start, _ = _tlv(der, 0) # Certificate _, _, tbs_end = _tlv(der, start) # tbsCertificate _, alg_start, _ = _tlv(der, tbs_end) # signatureAlgorithm _, oid_start, oid_end = _tlv(der, alg_start) # OID oid = _oid(der[oid_start:oid_end]) return SIG_OIDS.get(oid, oid), version except (OSError, ssl.SSLError, IndexError, ValueError) as e: return f"unclear: {type(e).__name__}", None def ssh_kex(host, port, ip=None): """Key-exchange methods the SSH server advertises in its first, unencrypted packet.""" try: with socket.create_connection((ip or host, port), timeout=TIMEOUT) as sock: banner = b"" while not banner.endswith(b"\n") and len(banner) < 512: c = sock.recv(1) if not c: break banner += c sock.sendall(b"SSH-2.0-pqcheck_" + VERSION.encode() + b"\r\n") head = b"" while len(head) < 5: c = sock.recv(5 - len(head)) if not c: return "unclear: connection closed", [] head += c length, pad = struct.unpack("!IB", head) if length > 65536: return "unclear: oversized packet", [] body = b"" while len(body) < length - 1: c = sock.recv(length - 1 - len(body)) if not c: break body += c if not body or body[0] != 20: return "unclear: no key-exchange list", [] n = struct.unpack("!I", body[17:21])[0] methods = body[21:21 + n].decode("ascii", "replace").split(",") pq = [m for m in methods if m in SSH_PQ_KEX] return ("accepts" if pq else "declines"), pq except (OSError, struct.error, IndexError) as e: return f"unclear: {type(e).__name__}", [] NEAR_RPC = "https://rpc.mainnet.near.org" def _near_rpc(params): body = json.dumps({"jsonrpc": "2.0", "id": "pqcheck", "method": "query", "params": params}).encode() req = urllib.request.Request(NEAR_RPC, data=body, headers={"content-type": "application/json", "user-agent": "pqcheck/" + VERSION}) with urllib.request.urlopen(req, timeout=TIMEOUT * 2) as r: return json.load(r) def near_account(account, vantage): """Which kinds of keys can act for a NEAR account, read from the public RPC. Nothing is signed or sent.""" row = {"endpoint": "near:" + account, "protocol": "near", "vantage": vantage, "tool": "pqcheck " + VERSION, "measured_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "verify": "curl -s " + NEAR_RPC + " -H 'content-type: application/json' -d '" + json.dumps( {"jsonrpc": "2.0", "id": 1, "method": "query", "params": {"request_type": "view_access_key_list", "finality": "final", "account_id": account}}) + "'"} if not re.fullmatch(r"[a-z0-9._-]{2,64}", account): row["verdict"], row["note"] = "not measured", "that is not a NEAR account name" return row try: exists = _near_rpc({"request_type": "view_account", "finality": "final", "account_id": account}) if "error" in exists or "error" in exists.get("result", {}): row["verdict"], row["note"] = "not measured", "no such account on NEAR mainnet" return row listing = _near_rpc({"request_type": "view_access_key_list", "finality": "final", "account_id": account}) keys = listing["result"]["keys"] except (OSError, KeyError, ValueError) as e: row["verdict"], row["note"] = "unclear", "the RPC did not give a key list (" + type(e).__name__ + ")" return row full = {"post-quantum": 0, "classical": 0} limited = {"post-quantum": 0, "classical": 0} for k in keys: kind = "post-quantum" if k["public_key"].split(":")[0].startswith("ml-dsa") else "classical" (full if k["access_key"]["permission"] == "FullAccess" else limited)[kind] += 1 row["full_access_keys"], row["limited_keys"] = full, limited if full["post-quantum"] and not full["classical"]: row["verdict"] = "post-quantum keys only" elif full["post-quantum"]: row["verdict"] = "post-quantum key added, classical keys still active" elif full["classical"]: row["verdict"] = "classical keys only" else: row["verdict"] = "unclear" row["note"] = "no full-access key on this account" return row def check(target, vantage): if target.lower().startswith("near:"): return near_account(target[5:].strip().lower(), vantage) host, _, port = target.partition(":") port = int(port) if port else 443 row = {"endpoint": f"{host}:{port}", "protocol": "ssh" if port == 22 else "tls", "vantage": vantage, "measured_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "tool": "pqcheck " + VERSION} if port not in ALLOWED_PORTS: row["verdict"] = "not measured" row["note"] = f"port {port} is outside the standard ports this tool measures" return row try: ip = resolve(host) except (Refused, OSError) as e: row["verdict"] = "not measured" row["note"] = str(e) return row if port == 22: verdict, pq = ssh_kex(host, port, ip) row["post_quantum_key_exchange"] = verdict row["methods"] = pq row["verify"] = f"ssh -vv -o KexAlgorithms=mlkem768x25519-sha256 -o PubkeyAuthentication=no -o BatchMode=yes git@{host} 2>&1 | grep 'kex: algorithm'" else: control = tls_offer(host, port, X25519, ip) hybrid = tls_offer(host, port, X25519MLKEM768, ip) row["classical_control"] = control row["post_quantum_key_exchange"] = hybrid if control.startswith("unclear") and hybrid.startswith("unclear"): row["verdict"] = "unclear" row["larger_key_size"] = "not measured" row["verify"] = f"openssl s_client -connect {host}:{port} -groups X25519MLKEM768 -tls1_3" return row row["larger_key_size"] = "accepts" if "accepts" in (tls_offer(host, port, MLKEM1024, ip), tls_offer(host, port, SECP384R1MLKEM1024, ip)) else "declines" row["certificate_signature"], row["tls_version_with_ordinary_client"] = certificate_signature(host, port, ip) row["post_quantum_certificate"] = "yes" if str(row["certificate_signature"]).startswith(PQ_SIG_PREFIX) else "no" row["verify"] = f"openssl s_client -connect {host}:{port} -groups X25519MLKEM768 -tls1_3" verdict = hybrid if control != "accepts": verdict = "older TLS only" if control == "no-tls13" and hybrid == "no-tls13" else "unclear" row["larger_key_size"] = "not measured" row["verdict"] = {"accepts": "accepts", "declines": "classical only"}.get(verdict, verdict if verdict == "older TLS only" else "unclear") return row def main(): ap = argparse.ArgumentParser(description="Does a public endpoint accept post-quantum key exchange?") ap.add_argument("targets", nargs="*", help="host or host:port (443, 8443, 9443 for TLS; 22 for SSH)") ap.add_argument("--targets", dest="file", help="JSON file: a list of strings or of objects with an 'endpoint' field") ap.add_argument("--vantage", default="unspecified", help="where this is measured from, in your own words") ap.add_argument("--json", dest="out", help="write full results to this file") ap.add_argument("--pause", type=float, default=0.5, help="seconds between endpoints") args = ap.parse_args() targets = list(args.targets) if args.file: with open(args.file, encoding="utf-8") as f: for item in json.load(f): targets.append(item if isinstance(item, str) else item["endpoint"]) if not targets: ap.error("give at least one endpoint") rows = [] for t in targets: row = check(t, args.vantage) rows.append(row) if row["protocol"] == "near": extra = row.get("note") or f"full-access keys {row.get('full_access_keys')}" print(f"{row['endpoint']:<40} {row['verdict']} {extra}") else: extra = row.get("certificate_signature") or ",".join(row.get("methods", [])) or row.get("note", "") print(f"{row['endpoint']:<40} {row['verdict']:<15} larger key: {row.get('larger_key_size', '-'):<13} {extra}") sys.stdout.flush() time.sleep(args.pause) counts = {} for r in rows: counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1 print(counts) if args.out: with open(args.out, "w", encoding="utf-8", newline="\n") as f: json.dump({"tool": "pqcheck " + VERSION, "vantage": args.vantage, "summary": counts, "rows": rows}, f, indent=1) if __name__ == "__main__": main()