p256check 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
p256check/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """p256check: cryptography inventory and post-quantum readiness scanner (stdlib only)."""
2
+ __version__ = "0.2.0"
p256check/__main__.py ADDED
@@ -0,0 +1,174 @@
1
+ """p256check: will Chrome, Edge or Windows stop trusting your site's certificate chain in 2027?
2
+
3
+ p256check HOST [HOST ...] the P-256 CA rules (Chrome and Edge 15 March 2027, Windows 23 Feb 2027)
4
+ plus post-quantum (ML-KEM) key exchange; same as `p256check check`
5
+ p256check scan [PATH ...] [--tls host[:port]] [--ssh host[:port]] [--jwks URL|domain]
6
+ [--dnssec zone] [--domain example.com] [--profile dec2026|pqc] [-o DIR] [--json]
7
+ [--fail-on LEVEL] cryptography inventory (CBOM) for the post-quantum move
8
+ p256check mcp MCP server on stdio for coding agents
9
+ p256check serve [DIR] [--port N] the scoreboard page plus the live checker API
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+ from datetime import datetime
18
+
19
+ from . import __version__, cbom, profiles, report
20
+ from .model import merge, PRIORITY_ORDER
21
+ from .scan import scan_path
22
+
23
+
24
+ def check_main(argv):
25
+ """p256check HOST [HOST ...]: Chrome's 15 March 2027 P-256 CA rule plus post-quantum key exchange."""
26
+ from . import p256
27
+ ap = argparse.ArgumentParser(prog="p256check", description="Will Chrome, Edge or Windows stop trusting this site in 2027? "
28
+ "Builds the certificate path to a Chrome root and reads every CA key on it; also "
29
+ "checks whether the server accepts an ML-KEM (post-quantum) key exchange.")
30
+ ap.add_argument("hosts", nargs="+", metavar="HOST[:PORT]")
31
+ ap.add_argument("--json", action="store_true", help="print results as JSON")
32
+ ap.add_argument("--no-pq", action="store_true", help="skip the key exchange probe")
33
+ ap.add_argument("--timeout", type=float, default=6.0)
34
+ ap.add_argument("--exit-zero", action="store_true", help="exit 0 even when a site is blocked")
35
+ a = ap.parse_args(argv)
36
+ results = []
37
+ for h in a.hosts:
38
+ try:
39
+ results.append(p256.check(h, a.timeout, pq=not a.no_pq))
40
+ except p256.CheckError as e:
41
+ results.append({"target": h, "error": str(e)})
42
+ if not a.json:
43
+ print(p256.render(results[-1], color=sys.stdout.isatty()) + "\n")
44
+ if a.json:
45
+ print(json.dumps(results if len(results) > 1 else results[0], indent=1))
46
+ else:
47
+ print(f"Rule: {p256.ANNOUNCEMENT} (Chrome Root Store version {p256.load_store().version})")
48
+ if any("error" in r for r in results):
49
+ return 2
50
+ if not a.exit_zero and any(r["status"] in ("blocked", "renewal-at-risk") for r in results):
51
+ return 1
52
+ return 0
53
+
54
+
55
+ def main(argv=None):
56
+ argv = sys.argv[1:] if argv is None else argv
57
+ if not argv or argv[0] in ("-h", "--help", "help"):
58
+ print(__doc__.strip())
59
+ return 0 if argv else 2
60
+ if argv[0] == "--version":
61
+ print(f"p256check {__version__}")
62
+ return 0
63
+ if argv[0] == "check":
64
+ return check_main(argv[1:])
65
+ if argv[0] == "scan":
66
+ return scan_main(argv[1:])
67
+ if argv[0] == "mcp":
68
+ from . import mcp
69
+ return mcp.serve()
70
+ if argv[0] == "serve":
71
+ from . import web
72
+ sp = argparse.ArgumentParser(prog="p256check serve", description="Serve the scoreboard page and the "
73
+ "live checker (/api/check) on one port.")
74
+ sp.add_argument("site", nargs="?", default="docs", help="folder with index.html (default: docs)")
75
+ sp.add_argument("--port", type=int, default=8080)
76
+ sp.add_argument("--bind", default="127.0.0.1")
77
+ x = sp.parse_args(argv[1:])
78
+ return web.serve(os.path.abspath(x.site), x.port, x.bind)
79
+ return check_main(argv)
80
+
81
+
82
+ def scan_main(argv):
83
+ """p256check scan PATH ...: the cryptography inventory and post-quantum ranking."""
84
+ ap = argparse.ArgumentParser(prog="p256check scan", description="Find the cryptography a project uses and rank it "
85
+ "for the post-quantum move. Writes cbom.json (CycloneDX 1.6) and report.html.")
86
+ ap.add_argument("paths", nargs="*", help="folders, files, archives (.jar .whl .zip .tgz) or binaries")
87
+ ap.add_argument("--tls", action="append", default=[], metavar="HOST[:PORT]",
88
+ help="probe a TLS server: key exchange groups and certificate chain (~12 handshakes)")
89
+ ap.add_argument("--ssh", action="append", default=[], metavar="HOST[:PORT]",
90
+ help="probe an SSH server: offered key exchange and host key algorithms, host keys")
91
+ ap.add_argument("--jwks", action="append", default=[], metavar="URL|DOMAIN",
92
+ help="read an OpenID provider's discovery document and JSON Web Key Set")
93
+ ap.add_argument("--dnssec", action="append", default=[], metavar="ZONE",
94
+ help="read a zone's DNSSEC keys (DNSKEY) through the system resolver")
95
+ ap.add_argument("--resolver", help="DNS server for --dnssec (default: from /etc/resolv.conf)")
96
+ ap.add_argument("--domain", action="append", default=[], metavar="DOMAIN",
97
+ help="shortcut: --tls DOMAIN --jwks DOMAIN --dnssec DOMAIN (SSH stays explicit)")
98
+ ap.add_argument("--profile", choices=profiles.PROFILES, default="dec2026",
99
+ help="ranking: dec2026 (default; 256-bit curves suspect after the 2 Dec 2026 NSA advisory) "
100
+ "or pqc (quantum-only timeline, NIST IR 8547)")
101
+ ap.add_argument("-o", "--out", default="p256check-out", help="output folder (default: p256check-out)")
102
+ ap.add_argument("--json", action="store_true", help="print findings as JSON instead of the summary")
103
+ ap.add_argument("--vendored", action="store_true", help="also scan node_modules, vendor, .venv, target ...")
104
+ ap.add_argument("--no-binaries", action="store_true", help="skip compiled files")
105
+ ap.add_argument("--no-write", action="store_true", help="do not write cbom.json/report.html")
106
+ ap.add_argument("--fail-on", choices=["fix-now", "suspect-now", "high", "medium"], help="exit 1 if anything at this level or "
107
+ "worse is found in non-test code (for CI)")
108
+ ap.add_argument("--limit", type=int, default=12, help="rows per section in the terminal (default 12)")
109
+ ap.add_argument("--version", action="version", version=f"p256check {__version__}")
110
+ a = ap.parse_args(argv)
111
+ profiles.set_profile(a.profile)
112
+ for d in a.domain:
113
+ a.tls.append(d)
114
+ a.jwks.append(d)
115
+ a.dnssec.append(d)
116
+ probes = a.tls or a.ssh or a.jwks or a.dnssec
117
+ if not a.paths and not probes:
118
+ a.paths = ["."]
119
+
120
+ opts = {"vendored": a.vendored, "binaries": not a.no_binaries}
121
+ findings, stats = [], {"files": 0, "bytes": 0, "seconds": 0.0}
122
+ for p in a.paths:
123
+ if not os.path.exists(p):
124
+ print(f"p256check: {p}: no such file or folder", file=sys.stderr)
125
+ return 2
126
+ f, s = scan_path(p, opts)
127
+ if len(a.paths) > 1:
128
+ for x in f:
129
+ x.path = f"{os.path.basename(os.path.abspath(p))}/{x.path}"
130
+ findings += f
131
+ for k in ("files", "bytes", "seconds"):
132
+ stats[k] = round(stats[k] + s.get(k, 0), 2)
133
+ from . import anchors, tls
134
+ tls_reports = []
135
+ runs = [(tls.probe, t, "tls") for t in a.tls] + [(anchors.probe_ssh, t, "ssh") for t in a.ssh] \
136
+ + [(anchors.probe_jwks, t, "jwks") for t in a.jwks] \
137
+ + [(lambda z: anchors.probe_dnssec(z, a.resolver), t, "dnssec") for t in a.dnssec]
138
+ for fn, t, kind in runs:
139
+ f, r = fn(t)
140
+ r.setdefault("kind", kind)
141
+ findings += f
142
+ tls_reports.append(r)
143
+ findings = merge(findings)
144
+ target = ", ".join(a.paths + [f"{k}://{t}" for _, t, k in runs])
145
+
146
+ if a.json:
147
+ print(json.dumps({"target": target, "profile": a.profile, "stats": stats, "probes": tls_reports,
148
+ "findings": [f.to_dict() for f in findings]}, indent=1, default=str))
149
+ else:
150
+ print(report.terminal(findings, stats, target, tls_reports, a.limit, color=sys.stdout.isatty()))
151
+
152
+ if not a.no_write:
153
+ os.makedirs(a.out, exist_ok=True)
154
+ with open(os.path.join(a.out, "cbom.json"), "w") as fh:
155
+ json.dump(cbom.build(findings, target, stats), fh, indent=1, default=str)
156
+ with open(os.path.join(a.out, "report.html"), "w") as fh:
157
+ fh.write(report.html_report(findings, stats, target, tls_reports,
158
+ datetime.now().strftime("%Y-%m-%d %H:%M")))
159
+ if not a.json:
160
+ print(f"\nWrote {a.out}/cbom.json and {a.out}/report.html")
161
+
162
+ if a.fail_on:
163
+ worst = PRIORITY_ORDER.index(a.fail_on)
164
+ if any(PRIORITY_ORDER.index(f.priority) <= worst and f.context == "code" for f in findings):
165
+ return 1
166
+ return 0
167
+
168
+
169
+ def entry():
170
+ sys.exit(main())
171
+
172
+
173
+ if __name__ == "__main__":
174
+ entry()
p256check/anchors.py ADDED
@@ -0,0 +1,353 @@
1
+ """Probes for authentication anchors on live systems: SSH servers, OIDC/JWT key sets, DNSSEC zones.
2
+
3
+ All three read public data only:
4
+ SSH the server's KEXINIT message (sent in the clear before any key exchange) lists the key
5
+ exchange and host key algorithms it offers; ssh-keyscan, when installed, adds the host
6
+ keys themselves (RSA size, curve).
7
+ JWKS the OpenID discovery document and the JSON Web Key Set it points to.
8
+ DNSSEC the zone's DNSKEY records, asked of the system resolver (or --resolver).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import socket
18
+ import struct
19
+ import subprocess
20
+ import urllib.error
21
+ import urllib.parse
22
+ import urllib.request
23
+
24
+ from . import __version__
25
+ from . import catalog as C
26
+ from .artifacts import scan_ssh_pubkeys
27
+ from .catalog import classify
28
+ from .model import Finding
29
+
30
+ UA = f"p256check/{__version__}"
31
+
32
+ # ---------------------------------------------------------------- SSH
33
+
34
+
35
+ def _ssh_kexinit(host, port, timeout):
36
+ with socket.create_connection((host, port), timeout=timeout) as s:
37
+ s.settimeout(timeout)
38
+ buf = b""
39
+ while b"\n" not in buf or not re.search(rb"(?m)^SSH-", buf):
40
+ chunk = s.recv(4096)
41
+ if not chunk:
42
+ raise ConnectionError("closed before banner")
43
+ buf += chunk
44
+ if len(buf) > 16384:
45
+ raise ConnectionError("no SSH banner")
46
+ m = re.search(rb"(?m)^(SSH-[^\r\n]*)\r?\n", buf)
47
+ banner = m.group(1).decode("ascii", "replace")
48
+ rest = buf[m.end():]
49
+ s.sendall(f"SSH-2.0-p256check_{__version__}\r\n".encode())
50
+ while len(rest) < 5:
51
+ rest += s.recv(4096)
52
+ length = struct.unpack(">I", rest[:4])[0]
53
+ if length > 256 * 1024:
54
+ raise ConnectionError("oversized packet")
55
+ while len(rest) < 4 + length:
56
+ chunk = s.recv(65536)
57
+ if not chunk:
58
+ break
59
+ rest += chunk
60
+ pad = rest[4]
61
+ payload = rest[5:4 + length - pad]
62
+ if not payload or payload[0] != 20:
63
+ raise ConnectionError("first packet is not KEXINIT")
64
+ i = 17
65
+ lists = []
66
+ for _ in range(10):
67
+ n = struct.unpack(">I", payload[i:i + 4])[0]
68
+ lists.append(payload[i + 4:i + 4 + n].decode("ascii", "replace").split(",") if n else [])
69
+ i += 4 + n
70
+ keys = ("kex", "hostkey", "enc_cs", "enc_sc", "mac_cs", "mac_sc")
71
+ return banner, dict(zip(keys, lists[:6]))
72
+
73
+
74
+ _SSH_PSEUDO = re.compile(r"^(?:ext-info-[cs]|kex-strict-[cs]-v00@openssh\.com|kex-strict-[cs]|none)$")
75
+
76
+
77
+ def probe_ssh(target: str, timeout=6.0):
78
+ host, _, port = target.rpartition(":") if target.count(":") == 1 else (target, "", "22")
79
+ host = host or target
80
+ port = int(port or 22)
81
+ label = f"ssh://{host}:{port}"
82
+ rep = {"target": f"{host}:{port}", "kind": "ssh"}
83
+ try:
84
+ banner, alg = _ssh_kexinit(host, port, timeout)
85
+ except (OSError, ConnectionError, struct.error, IndexError) as e:
86
+ rep["error"] = str(e)
87
+ return [], rep
88
+ rep.update(banner=banner, kex=alg["kex"], hostkey=alg["hostkey"])
89
+ out = []
90
+ kex = [k for k in alg["kex"] if not _SSH_PSEUDO.match(k)]
91
+ has_pq = any(h.family == "HYBRID-KEM" or C.status_of(h.family) == C.PQ for k in kex for h in classify(k))
92
+ for name in kex:
93
+ for h in classify(name):
94
+ note = None
95
+ if has_pq and C.status_of(h.family) == C.VULNERABLE:
96
+ note = "offered as a fallback next to a PQ hybrid; old clients will pick it"
97
+ out.append(Finding(h.family, "network", label, None, h.param or name, C.KEX,
98
+ f"SSH key exchange offered: {name}", "high", "code", note))
99
+ offered = []
100
+ for name in alg["hostkey"]:
101
+ for h in classify(name):
102
+ offered.append(Finding(h.family, "network", label, None, h.param, C.SIG,
103
+ f"SSH host key algorithm offered: {name}", "high", "code", h.note))
104
+ weak = [c for c in set(alg["enc_cs"] + alg["enc_sc"]) if any(
105
+ h.family in ("3DES", "DES", "RC4", "Blowfish") for h in classify(c))]
106
+ for c in weak:
107
+ out.append(Finding(classify(c)[0].family, "network", label, None, c, C.CIPHER, f"SSH cipher offered: {c}"))
108
+
109
+ # actual host keys (sizes, curves) if ssh-keyscan is installed
110
+ if shutil.which("ssh-keyscan"):
111
+ try:
112
+ r = subprocess.run(["ssh-keyscan", "-T", str(int(timeout)), "-p", str(port), "-t",
113
+ "rsa,ecdsa,ed25519", host], capture_output=True, text=True, timeout=timeout * 4)
114
+ keys = scan_ssh_pubkeys(label, r.stdout)
115
+ rep["host_keys"] = [f"{k.family} {k.param}" for k in keys]
116
+ for k in keys:
117
+ k.layer, k.evidence, k.line = "network", f"SSH host key ({k.evidence.split('(')[-1].rstrip(')')})", None
118
+ out.append(k)
119
+ except (OSError, subprocess.SubprocessError):
120
+ pass
121
+ # the real keys (size, curve) replace the offered algorithm names of the same family
122
+ have = {k.family for k in out if k.evidence.startswith("SSH host key (")}
123
+ out += [f for f in offered if f.family not in have]
124
+ return out, rep
125
+
126
+
127
+ # ---------------------------------------------------------------- JWKS / OIDC
128
+
129
+
130
+ def _get_json(url, timeout):
131
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
132
+ with urllib.request.urlopen(req, timeout=timeout) as r:
133
+ data = r.read(2 * 1024 * 1024)
134
+ return json.loads(data.decode("utf-8", "replace"))
135
+
136
+
137
+ def _b64u_len_bits(s):
138
+ raw = base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
139
+ return len(raw.lstrip(b"\x00")) * 8
140
+
141
+
142
+ def jwk_finding(key: dict, label: str):
143
+ kty, crv, alg, use = key.get("kty"), key.get("crv"), key.get("alg"), key.get("use")
144
+ kid = key.get("kid", "?")
145
+ role = C.KEX if use == "enc" else C.SIG
146
+ ev = f"JWK kid={kid} kty={kty}" + (f" crv={crv}" if crv else "") + (f" alg={alg}" if alg else "")
147
+ if kty == "RSA" and key.get("n"):
148
+ try:
149
+ bits = str(_b64u_len_bits(key["n"]))
150
+ except (ValueError, TypeError):
151
+ bits = None
152
+ return Finding("RSA", "network", label, None, bits, role, ev)
153
+ if kty == "EC":
154
+ param = {"P-256": "P-256", "P-384": "P-384", "P-521": "P-521", "secp256k1": "secp256k1"}.get(crv, crv)
155
+ return Finding("ECDH" if use == "enc" else "ECDSA", "network", label, None, param, role, ev)
156
+ if kty == "OKP":
157
+ if crv in ("Ed25519", "Ed448"):
158
+ return Finding("EdDSA", "network", label, None, crv, C.SIG, ev)
159
+ if crv in ("X25519", "X448"):
160
+ return Finding(crv, "network", label, None, crv, C.KEX, ev)
161
+ if kty in ("AKP", "ML-DSA", "ML-KEM") or (alg and re.match(r"ML-(DSA|KEM)", alg)):
162
+ hits = classify(alg or "")
163
+ if hits:
164
+ return Finding(hits[0].family, "network", label, None, hits[0].param, hits[0].role, ev)
165
+ if alg:
166
+ hits = classify(alg)
167
+ if hits:
168
+ return Finding(hits[0].family, "network", label, None, hits[0].param, role, ev)
169
+ return None
170
+
171
+
172
+ def probe_jwks(target: str, timeout=8.0):
173
+ """target: a domain, an issuer URL, a discovery URL or a JWKS URL."""
174
+ rep = {"target": target, "kind": "jwks"}
175
+ out = []
176
+ t = target if re.match(r"https?://", target) else f"https://{target}"
177
+ u = urllib.parse.urlparse(t)
178
+ tries = []
179
+ if u.path.endswith(("jwks.json", "/jwks", "/certs", "/keys")) or "jwks" in u.path:
180
+ tries.append(("jwks", t))
181
+ else:
182
+ base = t.rstrip("/")
183
+ tries.append(("discovery", base + "/.well-known/openid-configuration"
184
+ if "/.well-known/" not in base else base))
185
+ tries.append(("jwks", f"{u.scheme}://{u.netloc}/.well-known/jwks.json"))
186
+ jwks_url, disco = None, None
187
+ advertised = [] # algorithms the discovery document lists; kept only when no key of that family is published
188
+ for kind, url in tries:
189
+ try:
190
+ doc = _get_json(url, timeout)
191
+ except (urllib.error.URLError, ValueError, OSError) as e:
192
+ rep.setdefault("tried", []).append(f"{url}: {getattr(e, 'code', '') or type(e).__name__}")
193
+ continue
194
+ if kind == "discovery" and isinstance(doc, dict) and doc.get("jwks_uri"):
195
+ disco, jwks_url = url, doc["jwks_uri"]
196
+ rep["issuer"] = doc.get("issuer")
197
+ label = f"oidc://{urllib.parse.urlparse(url).netloc}"
198
+ for field in ("id_token_signing_alg_values_supported", "token_endpoint_auth_signing_alg_values_supported",
199
+ "request_object_signing_alg_values_supported", "userinfo_signing_alg_values_supported"):
200
+ for a in doc.get(field) or []:
201
+ for h in classify(str(a)):
202
+ if C.status_of(h.family) in (C.VULNERABLE, C.PQ, C.HYBRID):
203
+ advertised.append(Finding(h.family, "network", label, None, h.param, C.SIG,
204
+ f"discovery {field}: {a}", "medium", "code",
205
+ "advertised; the keys below are what is actually used"))
206
+ break
207
+ if kind == "jwks" and isinstance(doc, dict) and "keys" in doc:
208
+ jwks_url = url
209
+ break
210
+ if not jwks_url:
211
+ rep["not_found"] = True
212
+ return advertised, rep
213
+ try:
214
+ doc = _get_json(jwks_url, timeout)
215
+ except (urllib.error.URLError, ValueError, OSError) as e:
216
+ rep["error"] = f"{jwks_url}: {e}"
217
+ return out, rep
218
+ rep["jwks_uri"] = jwks_url
219
+ label = f"jwks://{urllib.parse.urlparse(jwks_url).netloc}{urllib.parse.urlparse(jwks_url).path}"
220
+ keys = doc.get("keys") or []
221
+ rep["keys"] = []
222
+ for k in keys:
223
+ if not isinstance(k, dict):
224
+ continue
225
+ f = jwk_finding(k, label)
226
+ if f:
227
+ out.append(f)
228
+ rep["keys"].append(f"{k.get('kid', '?')}: {f.family} {f.param or ''}".strip())
229
+ have = {f.family for f in out}
230
+ out += [f for f in advertised if f.family not in have]
231
+ if disco:
232
+ rep["discovery"] = disco
233
+ return out, rep
234
+
235
+
236
+ # ---------------------------------------------------------------- DNSSEC
237
+
238
+ DNSSEC_ALGS = {
239
+ 1: ("RSA", "RSAMD5", ["MD5"]), 3: ("DSA", "DSA", ["SHA1"]), 5: ("RSA", "RSASHA1", ["SHA1"]),
240
+ 6: ("DSA", "DSA-NSEC3-SHA1", ["SHA1"]), 7: ("RSA", "RSASHA1-NSEC3-SHA1", ["SHA1"]), 8: ("RSA", "RSASHA256", []),
241
+ 10: ("RSA", "RSASHA512", []), 12: ("ECDSA", "ECC-GOST", []), 13: ("ECDSA", "P-256", []),
242
+ 14: ("ECDSA", "P-384", []), 15: ("EdDSA", "Ed25519", []), 16: ("EdDSA", "Ed448", []),
243
+ }
244
+
245
+
246
+ def _resolver():
247
+ try:
248
+ for line in open("/etc/resolv.conf"):
249
+ p = line.split()
250
+ if len(p) >= 2 and p[0] == "nameserver":
251
+ return p[1]
252
+ except OSError:
253
+ pass
254
+ return None
255
+
256
+
257
+ def dns_query(name: str, qtype: int, server: str, timeout=4.0, port=53) -> bytes:
258
+ qid = int.from_bytes(os.urandom(2), "big")
259
+ header = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 1)
260
+ labels = [p.encode("idna") for p in name.rstrip(".").split(".") if p]
261
+ q = b"".join(bytes([len(p)]) + p for p in labels) + b"\x00"
262
+ q += struct.pack(">HH", qtype, 1)
263
+ opt = b"\x00" + struct.pack(">HHIH", 41, 4096, 0x00008000, 0) # EDNS0, DO bit
264
+ msg = header + q + opt
265
+ with socket.socket(socket.AF_INET6 if ":" in server else socket.AF_INET, socket.SOCK_DGRAM) as s:
266
+ s.settimeout(timeout)
267
+ s.sendto(msg, (server, port))
268
+ while True:
269
+ data, _ = s.recvfrom(65535)
270
+ if data[:2] == msg[:2]:
271
+ break
272
+ if data[2] & 0x02: # truncated: ask again over TCP
273
+ with socket.create_connection((server, port), timeout=timeout) as s:
274
+ s.sendall(struct.pack(">H", len(msg)) + msg)
275
+ ln = struct.unpack(">H", s.recv(2))[0]
276
+ data = b""
277
+ while len(data) < ln:
278
+ chunk = s.recv(ln - len(data))
279
+ if not chunk:
280
+ break
281
+ data += chunk
282
+ return data
283
+
284
+
285
+ def _skip_name(buf, i):
286
+ while True:
287
+ ln = buf[i]
288
+ if ln == 0:
289
+ return i + 1
290
+ if ln & 0xC0 == 0xC0:
291
+ return i + 2
292
+ i += 1 + ln
293
+
294
+
295
+ def parse_dnskeys(buf: bytes):
296
+ qd, an = struct.unpack(">HH", buf[4:8])
297
+ rcode = buf[3] & 0x0F
298
+ i = 12
299
+ for _ in range(qd):
300
+ i = _skip_name(buf, i) + 4
301
+ keys = []
302
+ for _ in range(an):
303
+ i = _skip_name(buf, i)
304
+ rtype, _, _, rdlen = struct.unpack(">HHIH", buf[i:i + 10])
305
+ i += 10
306
+ rd = buf[i:i + rdlen]
307
+ i += rdlen
308
+ if rtype != 48 or len(rd) < 4:
309
+ continue
310
+ flags, proto, alg = struct.unpack(">HBB", rd[:4])
311
+ pub = rd[4:]
312
+ bits = None
313
+ if alg in (1, 5, 7, 8, 10) and pub:
314
+ if pub[0] == 0:
315
+ elen = struct.unpack(">H", pub[1:3])[0]
316
+ mod = pub[3 + elen:]
317
+ else:
318
+ mod = pub[1 + pub[0]:]
319
+ bits = len(mod.lstrip(b"\x00")) * 8
320
+ keys.append({"flags": flags, "alg": alg, "bits": bits, "role": "KSK" if flags & 1 else "ZSK"})
321
+ return rcode, keys
322
+
323
+
324
+ def probe_dnssec(zone: str, resolver: str | None = None, timeout=4.0, port=53):
325
+ server = resolver or _resolver() or "127.0.0.53"
326
+ label = f"dns://{zone.rstrip('.') or '.'}"
327
+ rep = {"target": zone, "kind": "dnssec", "resolver": server}
328
+ try:
329
+ rcode, keys = parse_dnskeys(dns_query(zone, 48, server, timeout, port))
330
+ except (OSError, struct.error, IndexError) as e:
331
+ rep["error"] = str(e)
332
+ return [], rep
333
+ rep["rcode"] = rcode
334
+ if not keys:
335
+ rep["signed"] = False
336
+ return [], rep
337
+ rep["signed"] = True
338
+ rep["keys"] = []
339
+ out = []
340
+ seen = set()
341
+ for k in keys:
342
+ fam, name, weak = DNSSEC_ALGS.get(k["alg"], (None, f"alg {k['alg']}", []))
343
+ param = str(k["bits"]) if k["bits"] else (name if fam != "RSA" else None)
344
+ rep["keys"].append(f"{k['role']} {name}" + (f" {k['bits']} bits" if k["bits"] else ""))
345
+ if not fam or (k["role"], fam, param) in seen:
346
+ continue
347
+ seen.add((k["role"], fam, param))
348
+ out.append(Finding(fam, "network", label, None, param, C.SIG,
349
+ f"DNSSEC {k['role']} algorithm {k['alg']} ({name})", "high", "code",
350
+ "zone signing key; changing it is an algorithm rollover" if k["role"] == "KSK" else None))
351
+ for w in weak:
352
+ out.append(Finding(w, "network", label, None, name, C.HASH, f"DNSSEC algorithm {k['alg']} ({name})"))
353
+ return out, rep