#!/usr/bin/env python3
# PQ Shift 1.0.0 - find classic public-key cryptography, rank it, prove the move to NIST post-quantum standards.
# https://zirkomirko.com/tools/pq-shift/   MIT licence. One file, Python 3.8+, standard library only.
# Read-only: scan, probe and report never change your files. Never prints private key material.
"""PQ Shift: post-quantum migration inventory, probe, plan and guard."""

import argparse
import base64
import binascii
import datetime as _dt
import fnmatch
import hashlib
import json
import math
import os
import random
import re
import shutil
import socket
import ssl
import stat
import struct
import subprocess
import sys
import tempfile
import time
import uuid

VERSION = "1.0.0"
SCHEMA = "pqshift.findings/1"
DEFAULT_HORIZON = "2030-01-01"
HOME = "https://zirkomirko.com/tools/pq-shift/"

SEVERITIES = ["critical", "high", "medium", "low", "info"]
# Exit codes, the same for every command:
#   0  finished, nothing to act on (scan without --fail-on always ends 0)
#   1  finished, and the check you asked for failed (scan --fail-on, guard, report --expect-closed)
#   2  could not run: wrong arguments, a file that is missing or unreadable, git not available, probe refused
# 130  stopped with Ctrl+C
EXIT_OK, EXIT_FINDINGS, EXIT_USAGE = 0, 1, 2


class UsageError(Exception):
    """A problem the person can fix (bad argument, missing file). main() prints it and exits 2."""


def read_json(path, what):
    try:
        with open(path, "r", encoding="utf-8-sig") as fh:
            return json.load(fh)
    except OSError as ex:
        raise UsageError("cannot read %s %s: %s" % (what, path, ex.strerror or ex))
    except ValueError as ex:
        raise UsageError("%s %s is not valid JSON (%s)" % (what, path, ex))
SEV_SHORT = {"critical": "CRIT", "high": "HIGH", "medium": "MED ", "low": "LOW ", "info": "INFO"}

WHY = {
    "hndl": "Traffic or files captured today can be stored and decrypted later if this algorithm falls. "
            "It is the only category where waiting costs you retroactively.",
    "forgery": "A future break lets someone forge from that day on. Nothing recorded today is exposed. "
               "Rank by how long the key is trusted and how hard it is to replace.",
    "trust-anchor": "This key is trusted for years and replacing it takes a long lead time, so it moves early "
                    "even though signatures are not harvestable.",
    "weak-today": "Breakable or deprecated with ordinary computers. Unrelated to quantum; fix it now.",
    "blocker": "This library or runtime cannot do the new algorithms, so nothing built on it can migrate "
               "until it is upgraded.",
    "obsolete-pq": "Pre-standard post-quantum code. It does not interoperate with FIPS 203/204 and some of it is broken.",
    "unknown": "A classic key is created or stored here. How it is used decides the rank: ask or trace it.",
    "none": "Inventory only.",
}

# id: (severity, exposure, category, title, replace, recipe, refs)
_R = [
    ("WEAK-RSA-SMALL", "critical", "weak-today", "key", "RSA key under 2048 bits",
     "Generate a new key on the migration path; RSA 3072+ only as a stopgap.", "migrate/certs.md", ["NIST SP 800-131A"]),
    ("WEAK-DH-SMALL", "critical", "weak-today", "config", "Diffie-Hellman group under 2048 bits",
     "Remove it; use the hybrid group (X25519MLKEM768) with X25519 as fallback.", "migrate/tls.md", ["RFC 8270", "FIPS 203"]),
    ("WEAK-SIG-SHA1", "critical", "weak-today", "config", "SHA-1 / MD5 signature or DSA",
     "SHA-256+ signatures; Ed25519 or ECDSA now, ML-DSA when the stack has it.", "migrate/certs.md", ["RFC 8758", "FIPS 204"]),
    ("WEAK-TLS-OLD", "critical", "weak-today", "config", "SSLv3, TLS 1.0 or TLS 1.1 enabled",
     "TLS 1.2 minimum, TLS 1.3 preferred.", "migrate/tls.md", ["RFC 8996"]),
    ("OBS-PQ-BROKEN", "critical", "weak-today", "code", "Broken pre-standard post-quantum scheme (SIKE/SIDH/Rainbow)",
     "ML-KEM (FIPS 203) / ML-DSA (FIPS 204).", "migrate/code.md", ["FIPS 203", "FIPS 204"]),
    ("KEX-TLS-PINNED", "high", "hndl", "config", "TLS key-exchange groups pinned to classic curves",
     "Put X25519MLKEM768 first, keep X25519 and P-256 behind it; or delete the pin on a runtime whose default includes the hybrid.",
     "migrate/tls.md", ["FIPS 203", "RFC 10024"]),
    ("KEX-TLS-NO13", "high", "hndl", "config", "TLS 1.3 disabled or capped at TLS 1.2",
     "Enable TLS 1.3 (post-quantum groups exist only in TLS 1.3); keep 1.2 as fallback.", "migrate/tls.md", ["RFC 8446"]),
    ("KEX-TLS-STATIC-RSA", "high", "hndl", "config", "Cipher list allows RSA key transport",
     "Remove static-RSA suites; ECDHE suites only (static RSA also lacks forward secrecy).", "migrate/tls.md", ["RFC 9325"]),
    ("KEX-SSH-PINNED", "high", "hndl", "config", "SSH key exchange pinned without a post-quantum method",
     "Remove the line (OpenSSH 9.0+) or list mlkem768x25519-sha256,sntrup761x25519-sha512 first.", "migrate/ssh.md", ["OpenSSH PQ"]),
    ("KEX-VPN-WG-NOPSK", "high", "hndl", "config", "WireGuard peer without a PresharedKey",
     "Per-peer PresharedKey (wg genpsk), distributed out of band.", "migrate/vpn.md", ["WireGuard protocol"]),
    ("KEX-VPN-OVPN", "high", "hndl", "config", "OpenVPN without tls-crypt or a post-quantum TLS group",
     "tls-crypt-v2; a post-quantum tls-groups entry where the build supports it.", "migrate/vpn.md", ["OpenVPN"]),
    ("KEX-VPN-IKE", "high", "hndl", "config", "IKE/IPsec proposals with classic key exchange only",
     "RFC 9370 additional key exchange with ML-KEM, or RFC 8784 post-quantum preshared key.", "migrate/vpn.md", ["RFC 9370", "RFC 8784"]),
    ("KEX-CODE-ECDH", "high", "hndl", "code", "Elliptic-curve / X25519 key agreement in code",
     "TLS 1.3 hybrid between your own services; otherwise the library's ML-KEM hybrid KEM. No home-made combiner.",
     "migrate/code.md", ["FIPS 203"]),
    ("KEX-CODE-DH", "high", "hndl", "code", "Finite-field Diffie-Hellman in code",
     "TLS 1.3 hybrid, or the library's ML-KEM hybrid KEM.", "migrate/code.md", ["FIPS 203"]),
    ("PKE-CODE-RSA", "high", "hndl", "code", "RSA encryption or key wrapping",
     "Library hybrid KEM + AEAD (HPKE with an ML-KEM hybrid where available); re-wrap stored data keys.",
     "migrate/code.md", ["FIPS 203"]),
    ("PKE-CODE-EC", "high", "hndl", "code", "Elliptic-curve public-key encryption (ECIES, sealed box, JWE ECDH-ES)",
     "Library hybrid KEM + AEAD; re-wrap stored data keys.", "migrate/code.md", ["FIPS 203"]),
    ("PKE-TOOL", "high", "hndl", "code", "Script encrypts to a classic public key",
     "Tool version with post-quantum recipients where it exists; else record as open.", "migrate/code.md", ["FIPS 203"]),
    ("SIG-CODESIGN", "high", "trust-anchor", "code", "Release, package or firmware signing with a classic key",
     "Plan ML-DSA or SLH-DSA (LMS/XMSS for firmware) with the signing vendor; keep the algorithm in config.",
     "migrate/certs.md", ["FIPS 204", "FIPS 205"]),
    ("CRT-CA-HORIZON", "high", "trust-anchor", "cert", "Classic CA certificate valid past the horizon",
     "Plan a re-root; do not issue new long-lived classic CAs.", "migrate/certs.md", ["FIPS 204"]),
    ("KEX-TLS-DHE", "medium", "hndl", "config", "Classic finite-field DHE in use",
     "Hybrid group first; drop DHE.", "migrate/tls.md", ["RFC 9325"]),
    ("KEX-LB-POLICY", "medium", "hndl", "config", "Cloud load-balancer TLS policy without post-quantum key exchange",
     "The provider's post-quantum TLS policy; confirm with probe.", "migrate/tls.md", []),
    ("SIG-CODE-RSA", "medium", "forgery", "code", "RSA signatures in code",
     "Algorithm from config; ML-DSA where both ends are yours and the library supports it.", "migrate/code.md", ["FIPS 204"]),
    ("SIG-CODE-EC", "medium", "forgery", "code", "ECDSA / EdDSA signatures in code",
     "Algorithm from config; ML-DSA where both ends are yours and the library supports it.", "migrate/code.md", ["FIPS 204"]),
    ("SIG-JWT", "medium", "forgery", "token", "JWT/JOSE signed with RSA or elliptic curves",
     "Allow-list algorithms from config, short token life; move when the issuer supports ML-DSA.", "migrate/tokens.md", ["RFC 7518"]),
    ("KEY-GEN", "medium", "unknown", "code", "Classic key generation",
     "Depends on use: see the KEX-* or SIG-* rule that applies.", "migrate/code.md", []),
    ("KEY-FILE", "medium", "unknown", "key", "Classic key file",
     "Depends on use: see the KEX-* or SIG-* rule that applies.", "migrate/certs.md", []),
    ("CRT-CLASSIC", "medium", "forgery", "cert", "Certificate or CSR with a classic key or signature",
     "Short lifetimes and automated reissue now; ML-DSA when your CA offers it.", "migrate/certs.md", ["FIPS 204"]),
    ("DEP-RUNTIME-OLD", "medium", "blocker", "dependency", "Runtime or library too old for ML-KEM hybrids",
     "Upgrade to the version listed in support.json.", "migrate/code.md", []),
    ("OBS-PQ-DRAFT", "medium", "obsolete-pq", "code", "Pre-standard Kyber / Dilithium / draft hybrid",
     "X25519MLKEM768, ML-KEM (FIPS 203), ML-DSA (FIPS 204).", "migrate/code.md", ["FIPS 203", "FIPS 204"]),
    ("KEX-TLS-DEFAULT", "low", "hndl", "config", "TLS server with no group setting (depends on the TLS library)",
     "Probe it; upgrade the TLS library if the probe shows no hybrid.", "migrate/tls.md", ["RFC 10024"]),
    ("KEX-SSH-DEFAULT", "low", "hndl", "config", "sshd without KexAlgorithms (depends on the OpenSSH version)",
     "OpenSSH 9.0+ (sntrup761 default) or 10.0+ (ML-KEM default).", "migrate/ssh.md", ["OpenSSH PQ"]),
    ("SIG-SSH-ALGS", "low", "forgery", "config", "Classic SSH host/user key algorithms",
     "Nothing to switch to in stable OpenSSH yet: inventory, keep Ed25519, watch.", "migrate/ssh.md", []),
    ("DEP-BASE-IMAGE", "low", "blocker", "dependency", "Container base image that may ship OpenSSL older than 3.5",
     "Run `openssl version` inside the image; move the base tag.", "migrate/tls.md", []),
    ("DEP-CRYPTO-LIB", "info", "none", "dependency", "Cryptography library (inventory)", "", "", []),
    ("OK-PQ-KEX", "info", "none", "config", "Hybrid or ML-KEM key exchange present", "", "", ["FIPS 203"]),
    ("OK-PQ-SIG", "info", "none", "code", "ML-DSA / SLH-DSA / LMS / XMSS present", "", "", ["FIPS 204", "FIPS 205"]),
    ("PQ-ONLY", "info", "none", "config", "ML-KEM group list with no classic fallback",
     "Check client compatibility; hybrid is the default advice.", "migrate/tls.md", []),
    ("KEX-ENDPOINT-NO-PQ", "high", "hndl", "endpoint", "TLS endpoint does not accept any ML-KEM hybrid",
     "Enable X25519MLKEM768 on the server or the edge in front of it.", "migrate/tls.md", ["RFC 10024"]),
    ("KEX-ENDPOINT-NOT-PREFERRED", "medium", "hndl", "endpoint", "TLS endpoint supports the hybrid but prefers a classic group",
     "Put the hybrid first in the server's group order.", "migrate/tls.md", ["RFC 10024"]),
    ("KEX-ENDPOINT-SSH-NO-PQ", "high", "hndl", "endpoint", "SSH server offers no post-quantum key exchange",
     "OpenSSH 10.0+ or list mlkem768x25519-sha256 first.", "migrate/ssh.md", ["OpenSSH PQ"]),
    ("ENDPOINT-CERT-CLASSIC", "medium", "forgery", "endpoint", "Served certificate uses a classic key",
     "Short lifetimes and automated reissue now; ML-DSA when your CA offers it.", "migrate/certs.md", []),
    ("ENDPOINT-TLS12", "info", "none", "endpoint", "TLS 1.2 still accepted (those clients get classic key exchange)",
     "Keep for compatibility until your clients are on TLS 1.3.", "migrate/tls.md", []),
    ("POLICY-EXPIRED", "high", "none", "config", "Policy exception past its end date",
     "Renew it with a new reason and date, or fix the finding.", "", []),
]
RULES = {}
for _r in _R:
    RULES[_r[0]] = {"id": _r[0], "severity": _r[1], "exposure": _r[2], "category": _r[3], "title": _r[4],
                    "replace": _r[5], "recipe": _r[6], "refs": _r[7], "why": WHY.get(_r[2], "")}
RULES["POLICY-EXPIRED"]["why"] = "Exceptions need an owner and an end date so they cannot rot quietly."

# Support table. Filled from facts.json at release time; status says what was confirmed and where.
SUPPORT = [
 {
  "component": "OpenSSL",
  "mlkem": "3.5.0",
  "hybrid_kex": "3.5.0: default supported groups prefer hybrid PQC groups; default key shares are X25519MLKEM768 and X25519",
  "mldsa": "3.5.0 (also SLH-DSA)",
  "notes": "Release notes: 'The default TLS keyshares have been changed to offer X25519MLKEM768 and X25519.'",
  "source_url": "https://openssl-library.org/news/openssl-3.5-notes/",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Go",
  "mlkem": "1.24 (crypto/mlkem)",
  "hybrid_kex": "1.24: X25519MLKEM768 on by default when Config.CurvePreferences is nil (GODEBUG tlsmlkem=0 reverts); 1.26 also enables SecP256r1MLKEM768 and SecP384r1MLKEM1024 by default (GODEBUG tlssecpmlkem=0)",
  "mldsa": "1.27 (crypto/mldsa; ML-DSA in crypto/x509 and TLS 1.3 signatures)",
  "notes": "1.24 removed X25519Kyber768Draft00. 1.26 adds crypto/hpke with post-quantum hybrid KEMs. 1.27 released August 2026.",
  "source_url": "https://go.dev/doc/go1.24 ; https://go.dev/doc/go1.26 ; https://go.dev/doc/go1.27",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "OpenJDK",
  "mlkem": "24 (JEP 496, javax.crypto KEM)",
  "hybrid_kex": "27 (JEP 527): X25519MLKEM768 first in the default TLS 1.3 groups; SecP256r1MLKEM768 and SecP384r1MLKEM1024 available, not default",
  "mldsa": "24 (JEP 497)",
  "notes": "JDK 27 default group list: X25519MLKEM768, x25519, secp256r1, secp384r1, secp521r1, x448, ffdhe2048, ffdhe3072, ffdhe4096. Set with jdk.tls.namedGroups.",
  "source_url": "https://openjdk.org/jeps/496 ; https://openjdk.org/jeps/497 ; https://openjdk.org/jeps/527",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Node.js",
  "mlkem": "24.7.0 (ML-KEM key pairs, crypto.encapsulate/decapsulate)",
  "hybrid_kex": "follows bundled OpenSSL; 24.11.1 bundles OpenSSL 3.5.4 and a default client and default server negotiate X25519MLKEM768 (tested 2026-12-03 on Windows 11)",
  "mldsa": "24.6.0 (ML-DSA keys and signing); SLH-DSA 24.8.0",
  "notes": "Official binaries first bundle OpenSSL 3.5 in 22.20.0 and 24.5.0 on those release lines. Check process.versions.openssl for downstream builds.",
  "source_url": "https://nodejs.org/api/crypto.html ; https://nodejs.org/dist/index.json",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Python ssl",
  "mlkem": "n/a",
  "hybrid_kex": "whatever OpenSSL the interpreter is linked to (ssl.OPENSSL_VERSION); the python.org 3.12.6 Windows build we tested links OpenSSL 3.0.15: no hybrid",
  "mldsa": "n/a",
  "notes": "Which python.org builds ship OpenSSL 3.5 is unverified.",
  "source_url": "local test 2026-12-03",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "pyca/cryptography",
  "mlkem": "47.0.0 with AWS-LC or BoringSSL builds only; 48.0.0 adds OpenSSL 3.5.0+ (official wheels are built with OpenSSL 3.5.x)",
  "hybrid_kex": "n/a",
  "mldsa": "47.0.0 (AWS-LC/BoringSSL); 48.0.0 with OpenSSL 3.5.0+; 49.0.0 adds ML-DSA certificate loading/signing in x509; 51.0.0 adds MLDSA44Ed25519 composite keys for OpenSSH",
  "notes": "48.0.0 was released 2026-05-04. The 47.x support applies only to builds against AWS-LC or BoringSSL.",
  "source_url": "https://cryptography.io/en/latest/changelog/",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "OpenSSH",
  "mlkem": "n/a",
  "hybrid_kex": "9.0 prefers sntrup761x25519-sha512@openssh.com; 9.9 adds mlkem768x25519-sha256; 10.0 prefers ML-KEM; 10.1 warns on classic-only negotiation",
  "mldsa": "10.6: ssh-mldsa44-ed25519 hybrid signatures (ML-DSA-44 with Ed25519)",
  "notes": "Tested 2026-12-03: OpenSSH 10.0p2 lists mlkem768x25519-sha256 and sntrup761x25519-sha512 in `ssh -Q kex`. Windows' built-in OpenSSH_for_Windows_9.5p2 lists neither, and its `sshd -t` rejects both names.",
  "source_url": "https://www.openssh.org/pq.html ; https://www.openssh.org/releasenotes.html#10.6",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": ".NET",
  "mlkem": "10 (System.Security.Cryptography.MLKem)",
  "hybrid_kex": "depends on the OS TLS stack (SChannel / OpenSSL / Apple)",
  "mldsa": "10 (MLDsa, SlhDsa)",
  "notes": "The .NET 10 primitives need a supporting OS cryptography provider. Check MLKem.IsSupported and MLDsa.IsSupported. Hybrid TLS depends separately on the OS TLS stack.",
  "source_url": "https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/libraries",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "BoringSSL",
  "mlkem": "yes (rolling)",
  "hybrid_kex": "X25519MLKEM768",
  "mldsa": "check vendor",
  "notes": "Not verified for this release. Confirm the version with the vendor before relying on this row.",
  "source_url": None,
  "checked": "2026-12-03",
  "status": "unverified"
 },
 {
  "component": "AWS-LC",
  "mlkem": "yes (rolling)",
  "hybrid_kex": "X25519MLKEM768",
  "mldsa": "check vendor",
  "notes": "Not verified for this release. pyca/cryptography 47+ uses it for ML-KEM / ML-DSA when built against it.",
  "source_url": None,
  "checked": "2026-12-03",
  "status": "unverified"
 },
 {
  "component": "Bouncy Castle (Java)",
  "mlkem": "1.79",
  "hybrid_kex": "BCJSSE: check vendor",
  "mldsa": "1.79",
  "notes": "The 1.79 release announcement names the final NIST ML-KEM, ML-DSA and SLH-DSA algorithms.",
  "source_url": "https://www.bouncycastle.org/resources/latest-nist-pqc-standards-and-more-bouncy-castle-java-1-79/",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "rustls",
  "mlkem": "via aws-lc-rs provider",
  "hybrid_kex": "X25519MLKEM768 with the aws-lc-rs provider; feature prefer-post-quantum makes it highest priority, and is in the default features of 0.23.47",
  "mldsa": "n/a",
  "notes": "The first version with prefer-post-quantum on by default is unverified; 0.23.47 is what docs.rs showed today.",
  "source_url": "https://docs.rs/rustls/latest/rustls/manual/_05_defaults/index.html ; https://docs.rs/crate/rustls/latest/features",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "liboqs / oqs-provider",
  "mlkem": "yes",
  "hybrid_kex": "oqs-provider adds groups to OpenSSL 3.x",
  "mldsa": "yes",
  "notes": "liboqs current 0.16.0 (2026-07-09). Project: 'should not be considered production quality'. oqs-provider version not checked.",
  "source_url": "https://openquantumsafe.org/liboqs/ ; https://openquantumsafe.org/applications/tls.html",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Caddy",
  "mlkem": "n/a",
  "hybrid_kex": "tls curves accepts x25519mlkem768; docs: 'It is recommended to not change the defaults.'",
  "mldsa": "n/a",
  "notes": "The first version with the hybrid on by default is unverified.",
  "source_url": "https://caddyserver.com/docs/caddyfile/directives/tls",
  "checked": "2026-12-03",
  "status": "unverified"
 },
 {
  "component": "strongSwan",
  "mlkem": "6.0.0 (2024-12-03)",
  "hybrid_kex": "IKEv2 multiple key exchanges (RFC 9370), e.g. proposal x25519-ke1_mlkem768",
  "mldsa": "check vendor",
  "notes": "",
  "source_url": "https://www.strongswan.org/blog/2024/12/03/strongswan-6.0.0-released.html ; https://docs.strongswan.org/docs/latest/config/proposals.html",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "OpenVPN",
  "mlkem": "n/a",
  "hybrid_kex": "tls-groups X25519MLKEM768 (with X25519 after it for mixed clients) when built with OpenSSL 3.5.0+; 2.7.0+ prints the key agreement in use",
  "mldsa": "n/a",
  "notes": "Version 2.7.0 is named only for the log line; PQ groups depend on the TLS library.",
  "source_url": "https://community.openvpn.net/PQCryptoOpenVPN",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Chrome",
  "mlkem": "n/a",
  "hybrid_kex": "131: switched from X25519Kyber768 (0x6399) to X25519MLKEM768 (0x11EC); 124 had shipped Kyber",
  "mldsa": "n/a",
  "notes": "Version numbers are from Google's security blog.",
  "source_url": "https://security.googleblog.com/2024/09/a-new-path-for-kyber-on-web.html",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Firefox",
  "mlkem": "n/a",
  "hybrid_kex": "132: 'Added support for a post-quantum key exchange mechanism for TLS 1.3 (mlkem768x25519)'",
  "mldsa": "n/a",
  "notes": "Release note says 'added support'; whether on by default in 132 on every platform is not stated there.",
  "source_url": "https://www.firefox.com/en-US/firefox/132.0/releasenotes/",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "Safari / Apple OS",
  "mlkem": "n/a",
  "hybrid_kex": "iOS 26, iPadOS 26, macOS Tahoe 26, visionOS 26: ClientHello includes X25519MLKEM768 with a key share; on by default for URLSession and Network APIs",
  "mldsa": "n/a",
  "notes": "Apple names the OS releases; Safari uses the system TLS (Apple security guide). Check with nscurl --tls-diagnostics on macOS 26.",
  "source_url": "https://support.apple.com/en-us/122756",
  "checked": "2026-12-03",
  "status": "verified"
 },
 {
  "component": "nginx / Apache httpd / HAProxy",
  "mlkem": "n/a",
  "hybrid_kex": "follows the linked OpenSSL: 3.5.0+ needed",
  "mldsa": "n/a",
  "notes": "Check nginx -V, httpd -V, haproxy -vv for the OpenSSL version actually linked.",
  "source_url": "https://openssl-library.org/news/openssl-3.5-notes/ ; https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_ecdh_curve ; https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslopensslconfcmd ; https://docs.haproxy.org/3.2/configuration.html#ssl-default-bind-curves",
  "checked": "2026-12-03",
  "status": "verified"
 }
]  # BEGIN-SUPPORT (generated from facts.json by release.py)
# END-SUPPORT

# Thresholds for DEP-RUNTIME-OLD: (component, minimum version tuple, note)
THRESH = {
    "go": ((1, 24), "Go 1.24+ has crypto/mlkem and X25519MLKEM768 in crypto/tls by default."),
    "java": ((27,), "JDK 27 enables X25519MLKEM768 in TLS by default; JDK 24-26 have the ML-KEM API only."),
    "node": ((22, 20), "Official Node binaries bundle OpenSSL 3.5 from 22.20.0 on 22.x and 24.5.0 on 24.x. "
                       "Check process.versions.openssl on the deployed build."),
    "dotnet": ((10,), ".NET 10 adds MLKem and MLDsa."),
    "cryptography": ((48,), "pyca/cryptography 48 exposes ML-KEM/ML-DSA with OpenSSL 3.5+ (47 only on AWS-LC/BoringSSL builds)."),
    "openssl": ((3, 5), "OpenSSL 3.5 adds ML-KEM, ML-DSA, SLH-DSA and offers X25519MLKEM768 by default."),
    "openssh": ((9, 0), "OpenSSH 9.0 defaults to sntrup761x25519; 10.0 to mlkem768x25519."),
    "bcprov": ((1, 79), "Bouncy Castle Java 1.79 added the standardized ML-KEM, ML-DSA and SLH-DSA algorithms."),
}

SKIP_DIRS = {".git", "node_modules", "vendor", "third_party", ".venv", "venv", "site-packages", "dist", "build",
             "out", "target", ".next", "coverage", "__pycache__", ".hg", ".svn", ".tox", ".mypy_cache", ".gradle",
             ".idea", ".terraform", "bower_components", "Pods", ".pqshift"}
VENDOR_DIRS = ("node_modules", "vendor", "third_party", "site-packages")   # scanned with --include-vendored
BUILD_DIRS = ("dist", "build", "out", "target", ".next")                   # scanned with --include-build
MAX_DEPTH = 60                                                             # guards against directory loops
DOC_EXT = {".md", ".rst", ".txt", ".adoc"}
KEY_EXT = {".pem", ".crt", ".cer", ".der", ".key", ".pub", ".csr", ".p7b", ".p12", ".pfx", ".jks", ".keystore",
           ".ppk", ".params", ".dh"}
KEY_NAMES = {"id_rsa", "id_ecdsa", "id_ed25519", "id_dsa", "authorized_keys", "known_hosts", "authorized_keys2"}
TEST_SEGS = {"test", "tests", "spec", "specs", "__tests__", "testdata", "fixtures", "fixture"}
EXAMPLE_SEGS = {"examples", "example", "samples", "sample", "demo"}
DOCS_SEGS = {"docs", "doc"}

LANG = {
    ".py": "py", ".pyw": "py",
    ".js": "js", ".mjs": "js", ".cjs": "js", ".ts": "js", ".tsx": "js", ".jsx": "js", ".mts": "js", ".cts": "js",
    ".go": "go",
    ".java": "java", ".kt": "java", ".kts": "java", ".scala": "java", ".groovy": "java",
    ".cs": "cs",
    ".rs": "rs",
    ".c": "c", ".h": "c", ".cc": "c", ".cpp": "c", ".hpp": "c", ".cxx": "c", ".hh": "c", ".m": "c", ".mm": "c",
    ".php": "php",
    ".rb": "rb",
    ".swift": "swift",
    ".sh": "sh", ".bash": "sh", ".zsh": "sh", ".ps1": "sh", ".psm1": "sh", ".bat": "sh", ".cmd": "sh", ".mk": "sh",
    ".yml": "yaml", ".yaml": "yaml",
    ".tf": "tf", ".tfvars": "tf", ".hcl": "tf",
    ".json": "json", ".toml": "toml", ".ini": "ini", ".conf": "conf", ".cfg": "conf", ".cnf": "conf",
    ".xml": "xml", ".properties": "conf", ".env": "conf", ".ovpn": "conf", ".mod": "conf", ".csproj": "xml",
    ".fsproj": "xml", ".vbproj": "xml", ".props": "xml", ".gradle": "java", ".nvmrc": "conf", ".node-version": "conf",
    ".tool-versions": "conf", ".lock": "conf", ".pqshiftignore": None,
}
COMMENT_PREFIX = {
    "py": ("#",), "sh": ("#", "rem ", "REM ", "::"), "yaml": ("#",), "tf": ("#", "//"), "toml": ("#",), "ini": ("#", ";"),
    "conf": ("#", ";", "//"), "rb": ("#",), "php": ("//", "#", "*", "/*"), "js": ("//", "*", "/*"), "go": ("//", "*", "/*"),
    "java": ("//", "*", "/*"), "cs": ("//", "*", "/*"), "rs": ("//", "*", "/*"), "c": ("//", "*", "/*"),
    "swift": ("//", "*", "/*"), "xml": ("<!--",), "json": (),
}


def now_iso():
    return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def vtuple(s):
    out = []
    for p in re.findall(r"\d+", s or "")[:3]:
        out.append(int(p))
    return tuple(out)


def vlt(found, minimum):
    if not found:
        return False
    n = max(len(found), len(minimum))
    a = tuple(list(found) + [0] * (n - len(found)))
    b = tuple(list(minimum) + [0] * (n - len(minimum)))
    return a < b


_REDACT_KV = re.compile(r"""(?i)((?:private_?key|presharedkey|password|passphrase|secret|token)["']?\s*[=:]\s*)(.*)""")
_REDACT_B64 = re.compile(r"[A-Za-z0-9+/=_-]{40,}")


_CALL_LIKE = re.compile(r"^(?:await\s+|new\s+)?[A-Za-z_][\w.]*\(")


def _redact_kv(m):
    # `private_key = ec.generate_private_key(...)` is a function call, not a secret: keep it readable.
    call = _CALL_LIKE.match(m.group(2))
    if call:
        return m.group(1) + call.group(0) + "<redacted>)"
    return m.group(1) + "<redacted>"


def redact(text):
    t = " ".join((text or "").split())
    t = _REDACT_KV.sub(_redact_kv, t)
    t = _REDACT_B64.sub("<...>", t)
    if len(t) > 160:
        t = t[:157] + "..."
    return t


def context_of(relpath, is_comment=False):
    if is_comment:
        return "comment"
    segs = [s.lower() for s in relpath.replace("\\", "/").split("/")[:-1]]
    name = relpath.replace("\\", "/").split("/")[-1].lower()
    if any(s in ("node_modules", "vendor", "third_party", "site-packages") for s in segs):
        return "vendored"
    if any(s in TEST_SEGS for s in segs) or re.search(r"(^test_|_test\.|\.test\.|\.spec\.)", name):
        return "test"
    if any(s in EXAMPLE_SEGS for s in segs):
        return "example"
    if any(s in DOCS_SEGS for s in segs):
        return "docs"
    return "prod"


class Collector(object):
    """Collects findings for one run; dedups by (rule, path, line)."""

    def __init__(self, root, horizon):
        self.root = root
        self.horizon = horizon
        self.findings = []
        self.not_checked = []
        self.errors = []
        self.suppressed = []
        self._seen = set()
        self._dup = {}
        self.ignores = {}  # relpath -> list of (line, rule)

    def add(self, rule, path, line=None, evidence="", asset=None, severity=None, confidence="high", col=None,
            endpoint=None, context=None, needs=None, extra=None, file_level=False):
        key = (rule, path, line if not file_level else None, endpoint)
        if key in self._seen:
            return None
        self._seen.add(key)
        r = RULES[rule]
        ev = redact(evidence)
        dkey = (rule, path or endpoint, " ".join(ev.split()))
        n = self._dup.get(dkey, 0)
        self._dup[dkey] = n + 1
        fid = "F-" + hashlib.sha256((rule + "\n" + (path or endpoint or "") + "\n" + " ".join(ev.split()) + "\n" +
                                     str(n)).encode("utf-8")).hexdigest()[:10]
        a = {"kind": "algorithm", "algorithm": None, "family": None, "parameter": None, "primitive": None,
             "usage": "unknown", "oid": None, "quantum_safe": rule.startswith("OK-") or rule == "PQ-ONLY"}
        if asset:
            a.update(asset)
        f = {"id": fid, "rule": rule, "title": r["title"], "severity": severity or r["severity"],
             "exposure": r["exposure"], "category": r["category"], "asset": a,
             "location": {"path": path, "line": line, "col": col, "endpoint": endpoint},
             "evidence": ev, "context": context or (context_of(path) if path else "prod"),
             "confidence": confidence, "why": r["why"], "replace": r["replace"], "recipe": r["recipe"],
             "refs": r["refs"], "needs": needs or []}
        if extra:
            f.update(extra)
        # inline ignore
        if path and line:
            for (iline, irule, reason) in self.ignores.get(path, []):
                if irule == rule and iline in (line, line - 1):
                    self.suppressed.append({"id": fid, "rule": rule, "by": "inline", "reason": reason, "until": None,
                                            "location": f["location"]})
                    return None
        self.findings.append(f)
        return f

    def nc(self, what, why):
        for x in self.not_checked:
            if x["what"] == what:
                return
        self.not_checked.append({"what": what, "why": why})


def summarize(col, files_scanned, files_skipped, seconds, command="scan", extra=None):
    bys = dict((s, 0) for s in SEVERITIES)
    bye = {}
    pq = 0
    for f in col.findings:
        bys[f["severity"]] += 1
        bye[f["exposure"]] = bye.get(f["exposure"], 0) + 1
        if f["rule"].startswith("OK-") or f["rule"] == "PQ-ONLY":
            pq += 1
    order = {s: i for i, s in enumerate(SEVERITIES)}
    col.findings.sort(key=lambda f: (order[f["severity"]], f["location"]["path"] or f["location"]["endpoint"] or "",
                                     f["location"]["line"] or 0, f["rule"]))
    out = {"tool": "pqshift", "version": VERSION, "schema": SCHEMA, "command": command, "generated": now_iso(),
           "root": col.root, "horizon": col.horizon,
           "summary": {"files_scanned": files_scanned, "files_skipped": files_skipped, "seconds": round(seconds, 2),
                       "by_severity": bys, "by_exposure": bye, "pq_present": pq},
           "findings": col.findings, "suppressed": col.suppressed, "not_checked": col.not_checked,
           "errors": col.errors}
    if extra:
        out.update(extra)
    return out


FOOTER = 'Severity is migration priority, not "exploitable today" (except CRIT, which is weak with ordinary computers).'


def print_console(res, label, stream=None, limit=None):
    stream = stream or sys.stdout
    s = res["summary"]
    w = stream.write
    if res["command"] == "scan":
        w("PQ Shift %s  scan %s  %d file%s  %.1f s  horizon %s (a policy date, not a prediction)\n" % (
            VERSION, label, s["files_scanned"], "" if s["files_scanned"] == 1 else "s", s["seconds"], res["horizon"]))
    else:
        w("PQ Shift %s  %s %s\n" % (VERSION, res["command"], label))
    shown = 0
    for f in res["findings"]:
        if limit and shown >= limit:
            w("... %d more (use --json for all)\n" % (len(res["findings"]) - shown))
            break
        loc = f["location"]
        where = loc["endpoint"] or ((loc["path"] or "") + (":%d" % loc["line"] if loc["line"] else ""))
        w("%s  %-26s %-44s %s\n" % (SEV_SHORT[f["severity"]], f["rule"], where[:44], f["evidence"][:70]))
        shown += 1
    b = s["by_severity"]
    w("%d critical | %d high | %d medium | %d low | %d info || %d already post-quantum | %d not checked | %d suppressed\n" % (
        b["critical"], b["high"], b["medium"], b["low"], b["info"], s["pq_present"], len(res["not_checked"]),
        len(res["suppressed"])))
    w(FOOTER + "\n")


# ---------------------------------------------------------------------------------------------------------------
# Code tokens. Each entry: (rule, regex, asset). Specific tokens only; quoted-string rules require the quotes.
# ---------------------------------------------------------------------------------------------------------------

def _a(alg=None, fam=None, prim=None, usage="unknown", kind="algorithm", param=None):
    return {"algorithm": alg, "family": fam, "primitive": prim, "usage": usage, "kind": kind, "parameter": param}


ECDH = _a("ECDH", "ECC", "key-agree", "kex")
X25519 = _a("X25519", "ECC", "key-agree", "kex")
DH = _a("DH", "FFDH", "key-agree", "kex")
RSAENC = _a("RSA", "RSA", "pke", "encrypt")
ECENC = _a("ECIES", "ECC", "pke", "encrypt")
RSASIG = _a("RSA", "RSA", "signature", "sign")
ECSIG = _a("ECDSA", "ECC", "signature", "sign")
EDSIG = _a("EdDSA", "ECC", "signature", "sign")
KEYGEN = _a(None, None, None, "keygen", kind="key")
TLSP = _a("ECDH", "ECC", "key-agree", "kex", kind="protocol")
PQK = _a("ML-KEM", "ML-KEM", "kem", "kex")
PQS = _a("ML-DSA", "ML-DSA", "signature", "sign")
PQS["quantum_safe"] = True
PQK["quantum_safe"] = True

CODE = {
    "py": [
        ("KEX-CODE-ECDH", r"\bec\.ECDH\s*\(", ECDH),
        ("KEX-CODE-ECDH", r"\bX25519PrivateKey\b", X25519),
        ("KEX-CODE-ECDH", r"\bX448PrivateKey\b", _a("X448", "ECC", "key-agree", "kex")),
        ("KEX-CODE-ECDH", r"\bnacl\.public\.PrivateKey\b", X25519),
        ("PKE-CODE-EC", r"\bnacl\.public\.(?:Box|SealedBox)\b", ECENC),
        ("PKE-CODE-EC", r"(?<![\w.])(?:SealedBox|Box)\s*\(", ECENC),
        ("KEX-CODE-DH", r"\bdh\.generate_parameters\b|\bDHParameterNumbers\b|\bdh\.DHParameterNumbers\b", DH),
        ("PKE-CODE-RSA", r"\bpadding\.OAEP\s*\(|\bPKCS1_OAEP\b|\bPKCS1_v1_5\.new\b|\brsa\.(?:encrypt|decrypt)\s*\(", RSAENC),
        ("SIG-CODE-RSA", r"\bpadding\.PSS\s*\(|\bpkcs1_15\.new\b|\bpss\.new\b|\brsa\.(?:sign|verify)\s*\(", RSASIG),
        ("SIG-CODE-EC", r"\bec\.ECDSA\s*\(|\bDSS\.new\b|\bnacl\.signing\b|\becdsa\.SigningKey\b", ECSIG),
        ("SIG-CODE-EC", r"\bEd25519PrivateKey\b|\bEd448PrivateKey\b", EDSIG),
        ("KEY-GEN", r"\b(?:rsa|ec|dsa)\.generate_private_key\b|\bRSA\.generate\s*\(|\bECC\.generate\s*\(|"
                    r"\bparamiko\.(?:RSAKey|ECDSAKey|Ed25519Key|DSSKey)\.generate\b|\brsa\.newkeys\s*\(", KEYGEN),
        ("KEX-TLS-PINNED", r"\bset_ecdh_curve\s*\(", TLSP),
        ("KEX-TLS-NO13", r"maximum_version\s*=\s*ssl\.TLSVersion\.TLSv1_2\b", TLSP),
        ("WEAK-TLS-OLD", r"\bPROTOCOL_TLSv1(?:_1)?\b|\bPROTOCOL_SSLv3\b|minimum_version\s*=\s*ssl\.TLSVersion\.(?:TLSv1|TLSv1_1|SSLv3)\b", TLSP),
    ],
    "js": [
        ("KEX-CODE-ECDH", r"\bcreateECDH\s*\(|\bx25519\.getSharedSecret\b|\bdiffieHellman\s*\(|"
                          r"\bname\s*:\s*['\"](?:ECDH|X25519|X448)['\"]|"
                          r"\bgenerateKeyPair(?:Sync)?\s*\(\s*['\"](?:x25519|x448)['\"]", ECDH),
        ("KEX-CODE-DH", r"\bcreateDiffieHellman(?:Group)?\s*\(|\bgetDiffieHellman\s*\(|"
                        r"\bgenerateKeyPair(?:Sync)?\s*\(\s*['\"]dh['\"]", DH),
        ("PKE-CODE-RSA", r"\bpublicEncrypt\s*\(|\bprivateDecrypt\s*\(|\bname\s*:\s*['\"]RSA-OAEP['\"]|"
                         r"\bRSA_PKCS1_OAEP_PADDING\b|\bJSEncrypt\b|\bnew\s+NodeRSA\s*\(", RSAENC),
        ("PKE-CODE-EC", r"\bnacl\.box\b|\bsealedbox\b|\bcrypto_box_seal\b", ECENC),
        ("SIG-CODE-RSA", r"\bname\s*:\s*['\"](?:RSASSA-PKCS1-v1_5|RSA-PSS)['\"]", RSASIG),
        ("SIG-CODE-RSA", r"(?<![\w.])create(?:Sign|Verify)\s*\(|\bcrypto\.create(?:Sign|Verify)\s*\(", dict(RSASIG, algorithm=None)),
        ("SIG-CODE-EC", r"\bname\s*:\s*['\"](?:ECDSA|Ed25519|Ed448)['\"]|\bnacl\.sign\b|\bsecp256k1\.sign\b|\bed25519\.sign\b", ECSIG),
        ("KEY-GEN", r"\bgenerateKeyPair(?:Sync)?\s*\(\s*['\"](?:rsa|rsa-pss|ec|dsa|ed25519|ed448)['\"]|"
                    r"\bforge\.pki\.rsa\.generateKeyPair\b|\bnew\s+EC\s*\(\s*['\"](?:secp256k1|p256|p384|p521|ed25519|curve25519)['\"]", KEYGEN),
        ("KEX-TLS-NO13", r"\bmaxVersion\s*:\s*['\"]TLSv1\.2['\"]", TLSP),
        ("WEAK-TLS-OLD", r"\bminVersion\s*:\s*['\"]TLSv1(?:\.1)?['\"]|\bsecureProtocol\s*:\s*['\"](?:TLSv1|TLSv1_1|SSLv3)_(?:client_|server_)?method['\"]", TLSP),
    ],
    "go": [
        ("KEX-CODE-ECDH", r"\becdh\.(?:P256|P384|P521|X25519)\s*\(\s*\)|\bcurve25519\.(?:X25519|ScalarMult)\b", ECDH),
        ("PKE-CODE-EC", r"\"golang\.org/x/crypto/nacl/box\"|\bbox\.(?:Seal|Open|SealAnonymous)\b", ECENC),
        ("PKE-CODE-RSA", r"\brsa\.(?:EncryptOAEP|EncryptPKCS1v15|DecryptOAEP|DecryptPKCS1v15)\b", RSAENC),
        ("SIG-CODE-RSA", r"\brsa\.(?:SignPKCS1v15|SignPSS|VerifyPKCS1v15|VerifyPSS)\b", RSASIG),
        ("SIG-CODE-EC", r"\becdsa\.(?:Sign|SignASN1|Verify|VerifyASN1)\b", ECSIG),
        ("SIG-CODE-EC", r"\bed25519\.(?:Sign|Verify)\b", EDSIG),
        ("SIG-JWT", r"\bjwt\.SigningMethod(?:RS|PS|ES)(?:256|384|512)\b|\bjwt\.SigningMethodEdDSA\b",
         _a("JWS", None, "signature", "sign", "protocol")),
        ("KEY-GEN", r"\b(?:rsa|ecdsa|ed25519)\.GenerateKey\s*\(|\becdh\.(?:P256|P384|P521|X25519)\(\)\.GenerateKey\s*\(", KEYGEN),
        ("KEX-TLS-NO13", r"\bMaxVersion\s*:\s*tls\.VersionTLS12\b", TLSP),
        ("WEAK-TLS-OLD", r"\bMinVersion\s*:\s*tls\.(?:VersionTLS10|VersionTLS11|VersionSSL30)\b", TLSP),
        ("KEX-TLS-PINNED", r"\btlsmlkem\s*=\s*0\b", TLSP),
    ],
    "java": [
        ("KEX-CODE-ECDH", r"\bKeyAgreement\.getInstance\s*\(\s*\"(?:ECDH|X25519|X448|XDH|ECMQV|ECCDH)\"", ECDH),
        ("KEX-CODE-DH", r"\bKeyAgreement\.getInstance\s*\(\s*\"(?:DH|DiffieHellman)\"", DH),
        ("PKE-CODE-RSA", r"\bCipher\.getInstance\s*\(\s*\"RSA", RSAENC),
        ("PKE-CODE-EC", r"\bCipher\.getInstance\s*\(\s*\"ECIES", ECENC),
        ("WEAK-SIG-SHA1", r"\bSignature\.getInstance\s*\(\s*\"(?:SHA1with\w+|MD5with\w+|\w*withDSA|DSA)\"", RSASIG),
        ("SIG-CODE-RSA", r"\bSignature\.getInstance\s*\(\s*\"[^\"]*RSA[^\"]*\"", RSASIG),
        ("SIG-CODE-EC", r"\bSignature\.getInstance\s*\(\s*\"(?:[^\"]*ECDSA[^\"]*|EdDSA|Ed25519|Ed448)\"", ECSIG),
        ("SIG-JWT", r"\bAlgorithm\.(?:RSA|ECDSA)(?:256|384|512)\s*\(|\bSignatureAlgorithm\.(?:RS|ES|PS)(?:256|384|512)\b|"
                    r"\bJWSAlgorithm\.(?:RS|ES|PS)(?:256|384|512)\b|\bJWSAlgorithm\.EdDSA\b", _a("JWS", None, "signature", "sign", "protocol")),
        ("PKE-CODE-RSA", r"\bJWEAlgorithm\.RSA_OAEP(?:_256)?\b|\bJWEAlgorithm\.RSA1_5\b", RSAENC),
        ("PKE-CODE-EC", r"\bJWEAlgorithm\.ECDH_ES\w*\b", ECENC),
        ("KEY-GEN", r"\bKeyPairGenerator\.getInstance\s*\(\s*\"(?:RSA|EC|DSA|DH|DiffieHellman|X25519|X448|XDH|Ed25519|Ed448|EdDSA|RSASSA-PSS)\"|"
                    r"\bnew\s+ECGenParameterSpec\s*\(|\bnew\s+RSAKeyGenParameterSpec\s*\(", KEYGEN),
        ("KEX-TLS-NO13", r"\bjdk\.tls\.(?:client|server)\.protocols\s*=\s*\"?TLSv1\.2\"?\s*$", TLSP),
        ("PKE-CODE-RSA", r"\"RSA/(?:ECB|NONE|None)/\w+", RSAENC),
        ("WEAK-SIG-SHA1", r"\"(?:SHA1|MD5|MD2)with(?:RSA|ECDSA|DSA)\"", RSASIG),
        ("SIG-CODE-RSA", r"\"(?:SHA(?:224|256|384|512)|SHA3-(?:256|384|512))withRSA(?:/PSS|andMGF1|AndMGF1)?\"", RSASIG),
        ("SIG-CODE-EC", r"\"(?:SHA(?:224|256|384|512)|SHA3-(?:256|384|512))withECDSA(?:inP1363Format)?\"", ECSIG),
    ],
    "cs": [
        ("KEX-CODE-ECDH", r"\bECDiffieHellman(?:Cng|OpenSsl)?\b", ECDH),
        ("PKE-CODE-RSA", r"\bRSAEncryptionPadding\b|\bRSA(?:CryptoServiceProvider)?\b[^;]*\.Encrypt\s*\(", RSAENC),
        ("SIG-CODE-RSA", r"\bRSASignaturePadding\b", RSASIG),
        ("SIG-CODE-EC", r"\bECDsa\b[^;]*\.(?:Sign|Verify)(?:Data|Hash)\s*\(|(?i:\b\w*ecdsa\w*)\.(?:Sign|Verify)(?:Data|Hash)\s*\(", ECSIG),
        ("SIG-JWT", r"\bSecurityAlgorithms\.(?:RsaSha|EcdsaSha|RsaSsaPssSha)(?:256|384|512)\b", _a("JWS", None, "signature", "sign", "protocol")),
        ("KEY-GEN", r"\bRSA\.Create\s*\(|\bnew\s+RSACryptoServiceProvider\s*\(|\bECDsa\.Create\s*\(|\bDSA\.Create\s*\(|"
                    r"\bECDiffieHellman\.Create\s*\(", KEYGEN),
        ("KEX-TLS-NO13", r"\bSslProtocols\s*=\s*SslProtocols\.Tls12\s*[;,)]", TLSP),
        ("WEAK-TLS-OLD", r"\bSslProtocols\.(?:Tls|Tls11|Ssl3)\b(?!\d)", TLSP),
    ],
    "rs": [
        ("KEX-CODE-ECDH", r"\bx25519_dalek\b|\bEphemeralSecret\b|\.diffie_hellman\s*\(|\bagreement::(?:X25519|ECDH_P256|ECDH_P384)\b|"
                          r"\b(?:p256|p384|k256)::ecdh\b", ECDH),
        ("PKE-CODE-RSA", r"\bOaep::new\b|\bPkcs1v15Encrypt\b|\bopenssl::rsa::Padding\b|\bPadding::PKCS1_OAEP\b", RSAENC),
        ("SIG-CODE-EC", r"\bed25519_dalek\b|\becdsa::(?:SigningKey|VerifyingKey)\b|\bsignature::(?:ECDSA_\w+|ED25519)\b", ECSIG),
        ("SIG-CODE-RSA", r"\bsignature::RSA_(?:PKCS1|PSS)\w*\b|\brsa::pkcs1v15::SigningKey\b|\brsa::pss::SigningKey\b", RSASIG),
        ("SIG-JWT", r"\bAlgorithm::(?:RS|ES|PS)(?:256|384|512)\b|\bAlgorithm::EdDSA\b", _a("JWS", None, "signature", "sign", "protocol")),
        ("KEY-GEN", r"\bRsaPrivateKey::new\s*\(|\bRsa::generate\s*\(|\bEcKey::generate\s*\(|\bSigningKey::(?:generate|random)\s*\(|"
                    r"\bEcdsaKeyPair::generate_pkcs8\b|\bEd25519KeyPair::generate_pkcs8\b", KEYGEN),
    ],
    "c": [
        ("KEX-CODE-ECDH", r"\bECDH_compute_key\b|\bEVP_PKEY_derive\b|\bEVP_PKEY_(?:X25519|X448)\b|\bcrypto_kx_\w+|\bcrypto_scalarmult\w*|"
                          r"\bmbedtls_ecdh_\w+|\bwc_ecc_shared_secret\b|\bwc_curve25519_shared_secret\b", ECDH),
        ("KEX-CODE-DH", r"\bDH_generate_key\b|\bDH_compute_key\b|\bEVP_PKEY_DH\b|\bmbedtls_dhm_\w+|\bwc_DhAgree\b", DH),
        ("PKE-CODE-EC", r"\bcrypto_box_\w+", ECENC),
        ("PKE-CODE-RSA", r"\bRSA_public_encrypt\b|\bRSA_private_decrypt\b|\bEVP_PKEY_encrypt\b|\bEVP_PKEY_decrypt\b|\bEVP_SealInit\b|"
                         r"\bmbedtls_rsa_pkcs1_encrypt\b|\bmbedtls_rsa_rsaes_\w+|\bwc_RsaPublicEncrypt\b", RSAENC),
        ("SIG-CODE-EC", r"\bECDSA_(?:sign|verify|do_sign|do_verify)\b|\bEVP_PKEY_ED25519\b|\bcrypto_sign_\w+|\bmbedtls_ecdsa_\w+|"
                        r"\bwc_ecc_sign_hash\b|\bwc_ed25519_sign_msg\b", ECSIG),
        ("SIG-CODE-RSA", r"\bRSA_sign\b|\bRSA_verify\b|\bmbedtls_rsa_pkcs1_sign\b|\bwc_RsaSSL_Sign\b", RSASIG),
        ("KEY-GEN", r"\bRSA_generate_key(?:_ex)?\b|\bEC_KEY_new_by_curve_name\b|\bEC_KEY_generate_key\b|\bEVP_PKEY_(?:RSA|EC|DSA)\b|"
                    r"\bEVP_RSA_gen\b|\bEVP_EC_gen\b|\bwc_MakeRsaKey\b|\bwc_ecc_make_key\w*|\bmbedtls_rsa_gen_key\b|\bmbedtls_ecp_gen_key\b", KEYGEN),
        ("KEX-TLS-NO13", r"\bSSL(?:_CTX)?_set_max_proto_version\s*\([^)]*TLS1_2_VERSION", TLSP),
        ("WEAK-TLS-OLD", r"\bSSL(?:_CTX)?_set_min_proto_version\s*\([^)]*(?:TLS1_VERSION|TLS1_1_VERSION|SSL3_VERSION)\b|\bTLSv1_(?:client|server)?_?method\b", TLSP),
    ],
    "php": [
        ("KEX-CODE-ECDH", r"\bsodium_crypto_kx\w*|\bsodium_crypto_scalarmult\w*|\bopenssl_pkey_derive\s*\(", ECDH),
        ("KEX-CODE-DH", r"\bopenssl_dh_compute_key\s*\(", DH),
        ("PKE-CODE-RSA", r"\bopenssl_public_encrypt\s*\(|\bopenssl_private_decrypt\s*\(|\bopenssl_seal\s*\(", RSAENC),
        ("PKE-CODE-EC", r"\bsodium_crypto_box\w*", ECENC),
        ("SIG-CODE-RSA", r"\bopenssl_sign\s*\(|\bopenssl_verify\s*\(", RSASIG),
        ("SIG-CODE-EC", r"\bsodium_crypto_sign\w*", EDSIG),
        ("KEY-GEN", r"\bopenssl_pkey_new\s*\(|\bOPENSSL_KEYTYPE_(?:RSA|EC|DSA|DH)\b|\bRSA::createKey\s*\(|\bEC::createKey\s*\(", KEYGEN),
    ],
    "rb": [
        ("KEX-CODE-ECDH", r"\.dh_compute_key\s*\(|\bX25519::", ECDH),
        ("PKE-CODE-EC", r"\bRbNaCl::(?:Box|SimpleBox|SealedBox)\b", ECENC),
        ("PKE-CODE-RSA", r"\.public_encrypt\s*\(|\.private_decrypt\s*\(|\.encrypt\s*\([^)]*rsa_padding_mode", RSAENC),
        ("SIG-CODE-EC", r"\bRbNaCl::SigningKey\b|\bEd25519::", EDSIG),
        ("SIG-CODE-RSA", r"OpenSSL::PKey::RSA\b.*\.(?:sign|verify)\s*\(", RSASIG),
        ("KEY-GEN", r"\bOpenSSL::PKey::RSA\.(?:new|generate)\s*\(|\bOpenSSL::PKey::EC\.(?:new|generate)\s*\(|\bOpenSSL::PKey::DH\b|"
                    r"\bOpenSSL::PKey::DSA\b|\bOpenSSL::PKey\.generate_key\s*\(", KEYGEN),
    ],
    "swift": [
        ("KEX-CODE-ECDH", r"\b(?:P256|P384|P521|Curve25519)\.KeyAgreement\b", ECDH),
        ("PKE-CODE-RSA", r"\bSecKeyCreateEncryptedData\b", RSAENC),
        ("SIG-CODE-EC", r"\b(?:P256|P384|P521|Curve25519)\.Signing\b", ECSIG),
        ("KEY-GEN", r"\bSecKeyCreateRandomKey\b|\bkSecAttrKeyTypeRSA\b|\bkSecAttrKeyTypeECSECPrimeRandom\b", KEYGEN),
    ],
}

# Command-line tools: used for shell, Dockerfile, CI YAML, Makefile, and any code that shells out.
SHELL = [
    ("KEY-GEN", r"\bopenssl\s+genrsa\b|\bopenssl\s+genpkey\b[^\n]*-algorithm\s+(?:RSA|EC|DSA|DH|X25519|X448|ED25519|ED448|RSA-PSS)\b|"
                r"\bopenssl\s+ecparam\b[^\n]*-genkey\b|\bopenssl\s+req\b[^\n]*-newkey\s+(?:rsa|ec|ed25519)\b|\bopenssl\s+gendsa\b|"
                r"\bssh-keygen\b[^\n]*-t\s+(?:rsa|ecdsa|ed25519|dsa|ecdsa-sk|ed25519-sk)\b|\bssh-keygen\s+-A\b|"
                r"\bkeytool\b[^\n]*-keyalg\s+(?:RSA|EC|DSA)\b|\bcertbot\b[^\n]*--key-type\s+(?:rsa|ecdsa)\b|"
                r"\bstep\b[^\n]*--kty\s+(?:RSA|EC|OKP)\b|\bwg\s+genkey\b|\bage-keygen\b|"
                r"\bgpg2?\b[^\n]*--(?:gen-key|full-generate-key|full-gen-key|quick-generate-key|quick-gen-key)\b|"
                r"\bcosign\s+generate-key-pair\b|\bNew-SelfSignedCertificate\b[^\n]*-KeyAlgorithm\b|"
                r"\baws\s+kms\s+create-key\b[^\n]*--key-spec\s+(?:RSA_|ECC_)|\baz\s+keyvault\s+key\s+create\b[^\n]*--kty\s+(?:RSA|EC)\b|"
                r"\bgcloud\s+kms\s+keys\s+create\b[^\n]*(?:rsa-|ec-)", KEYGEN),
    ("PKE-TOOL", r"\bopenssl\s+(?:pkeyutl|rsautl)\b[^\n]*-encrypt\b|\bopenssl\s+(?:smime|cms)\b[^\n]*-encrypt\b|"
                 r"\bgpg2?\b[^\n]*\s(?:-e|--encrypt)\b|\bage\b[^\n]*\s-r\s+age1", RSAENC),
    ("SIG-CODESIGN", r"\bopenssl\s+dgst\b[^\n]*\s-sign\b|\bcosign\s+sign(?:-blob)?\b|\bgpg2?\b[^\n]*--(?:detach-sign|clearsign|sign)\b|"
                     r"\bsigntool(?:\.exe)?\s+sign\b|\bjarsigner\b|\bcodesign\b[^\n]*\s-s\b|\brpm\s+--addsign\b|\bminisign\s+-S\b|"
                     r"\bssh-keygen\s+-Y\s+sign\b|\bSet-AuthenticodeSignature\b", _a(None, None, "signature", "sign")),
    ("KEX-TLS-NO13", r"\bcurl\b[^\n]*--tls-max\s+1\.2\b", TLSP),
    ("WEAK-TLS-OLD", r"\bcurl\b[^\n]*--(?:tlsv1\.0|tlsv1\.1|sslv3)\b|\bopenssl\s+s_client\b[^\n]*\s-(?:tls1|tls1_1|ssl3)\b", TLSP),
]

GENERIC = [
    ("SIG-JWT", r"(['\"])(?:RS|PS|ES)(?:256|384|512)\1|(['\"])ES256K\2|(['\"])EdDSA\3", _a("JWS", None, "signature", "sign", "protocol")),
    ("PKE-CODE-RSA", r"(['\"])(?:RSA-OAEP(?:-256|-384|-512)?|RSA1_5)\1", _a("JWE RSA", "RSA", "pke", "encrypt")),
    ("PKE-CODE-EC", r"(['\"])ECDH-ES(?:\+A(?:128|192|256)KW)?\1", _a("JWE ECDH-ES", "ECC", "pke", "encrypt")),
    ("OBS-PQ-BROKEN", r"(?i)(?<![a-z])(?:sike(?:p\d+)?|sidh)(?![a-z])|\bRainbow-?(?:I|III|V|Ia|IIIc|Vc)\b", _a("SIKE/Rainbow", "obsolete", None)),
    ("OBS-PQ-DRAFT", r"(?i)x25519kyber768draft00|\b0x6399\b|(?<![a-z])(?:x25519|p256|p384)_kyber\d+|(?<![a-z])kyber(?:512|768|1024)?(?![a-z])|"
                     r"(?<![a-z])dilithium[235]?(?![a-z])", _a("Kyber/Dilithium draft", "obsolete", None)),
]

SSH_KEX_LIT = re.compile(r"""(['"])(?:curve25519-sha256(?:@libssh\.org)?|ecdh-sha2-nistp(?:256|384|521)|"""
                         r"""diffie-hellman-group(?:1|14|15|16|17|18)-sha(?:1|256|512)|diffie-hellman-group-exchange-sha(?:1|256))\1""")
SSH_PQ_NAME = re.compile(r"mlkem\d+(?:x25519|nistp\d+)|sntrup761x25519")
CODE_LANGS = ("py", "js", "go", "java", "cs", "rs", "c", "php", "rb", "swift")
# A test that says a name must NOT be present (`assert "x" not in kex`) is not a use of it.
NEGATED = re.compile(r"\bnot\s+in\b|\bassert(?:Not|False)\w*\(|\bNotContains\b|\.not\.|!==?|\bdoes_not_|\bdoesNot\w*\(|\brefute\w*\b")

OK_KEX = re.compile(r"(?i)x25519mlkem768|secp256r1mlkem768|secp384r1mlkem1024|mlkem768x25519|mlkem768nistp256|mlkem1024nistp384|"
                    r"sntrup761x25519|(?<![a-z])ml[-_]?kem(?:[-_]?(?:512|768|1024))?(?![a-z])|\bMLKem\b|oqs\.KeyEncapsulation|OQS_KEM_")
OK_SIG = re.compile(r"(?i)(?<![a-z])ml[-_]?dsa(?:[-_]?(?:44|65|87))?(?![a-z])|(?<![a-z])slh[-_]?dsa(?![a-z])|\bSlhDsa\b|\bMLDsa\b|"
                    r"OQS_SIG_|\bPQ_SIGN_|\bLMS_SHA256\w*|\bXMSS\w*")
MLKEM_IN = re.compile(r"(?i)mlkem|ml-kem|ml_kem")

_CODE_C = {}


def _compiled(lang):
    if lang not in _CODE_C:
        _CODE_C[lang] = [(r, re.compile(p), a) for (r, p, a) in CODE.get(lang, [])]
    return _CODE_C[lang]


_SHELL_C = [(r, re.compile(p), a) for (r, p, a) in SHELL]
_GENERIC_C = [(r, re.compile(p), a) for (r, p, a) in GENERIC]
WEAK_BITS = [
    re.compile(r"\b(?:key_size|keysize|modulusLength|modulus_length|rsa_bits|bits|keyLength|key_length|KeySize)\s*[=:]\s*(\d{3,4})\b"),
    re.compile(r"\bopenssl\s+genrsa\b[^\n]*?\s(\d{3,4})\b"),
    re.compile(r"-newkey\s+rsa:(\d{3,4})\b"),
    re.compile(r"\brsa_keygen_bits:(\d{3,4})\b"),
    re.compile(r"\bssh-keygen\b[^\n]*-t\s+rsa\b[^\n]*-b\s+(\d{3,4})\b|\bssh-keygen\b[^\n]*-b\s+(\d{3,4})\b[^\n]*-t\s+rsa\b"),
    re.compile(r"\bRSA_generate_key(?:_ex)?\s*\(\s*[^,]*?(\d{3,4})\s*[,)]"),
    re.compile(r"\bRSA\.(?:generate|Create)\s*\(\s*(\d{3,4})\b|RSACryptoServiceProvider\s*\(\s*(\d{3,4})\s*\)|\.initialize\s*\(\s*(\d{3,4})\s*\)"),
    re.compile(r"\bkeytool\b[^\n]*-keysize\s+(\d{3,4})\b|\bRSA_(1024)\b"),
    re.compile(r"\brsa\.GenerateKey\s*\([^,()]+,\s*(\d{3,4})\s*\)"),
]
NOT_RSA_BITS = re.compile(r"(?i)\b(?:ecdsa|ecdh|ec|ed25519|ed448|dsa|dh|aes|hmac|chacha\w*|nistp\d+|secp\w+|prime\d+v\d|curve\w*)\b|dhparam")
DH_BITS = re.compile(r"\bopenssl\s+dhparam\b(?:[^\n]*?)\s(\d{3,5})\s*$|\bopenssl\s+dhparam\b[^\n]*?\s(\d{3,5})\b")


def is_comment_line(stripped, lang):
    for p in COMMENT_PREFIX.get(lang, ("#",)):
        if stripped.startswith(p):
            return True
    return False


CLASSIC_GROUP = re.compile(r"(?i)^(?:x25519|x448|p-?256|p-?384|p-?521|prime256v1|secp\d+r1|secp256k1|curvep\d+|"
                           r"ffdhe\d+|brainpool\w*|ecdh_\w+|tls\.curvep\d+|tls\.x25519|curve25519|curve448)$")


def group_verdict(value):
    """Classify a TLS group/curve list: 'ok' (hybrid present), 'pqonly', 'pinned' (classic only) or None (auto/empty)."""
    v = (value or "").strip().strip("'\"[]{}()")
    if not v or v.lower() in ("auto", "default"):
        return None
    toks = [t.strip(" '\"") for t in re.split(r"[:,\s]+", v) if t.strip(" '\"")]
    toks = [re.sub(r"^(?:tls\.|ssl\.)", "", t, flags=re.I) for t in toks]
    hybrid = [t for t in toks if t.lower() in ("x25519mlkem768", "secp256r1mlkem768", "secp384r1mlkem1024")]
    pure = [t for t in toks if t.lower() in ("mlkem512", "mlkem768", "mlkem1024")]
    classic = [t for t in toks if t not in hybrid and t not in pure]
    if (hybrid or pure) and not classic:
        return "pqonly"
    if hybrid or pure:
        return "ok"
    if any(CLASSIC_GROUP.match(t) or re.match(r"(?i)^(?:curve|x25519|p\d{3}|secp)", t) for t in classic):
        return "pinned"
    return None


def cipher_verdict(value):
    """Return (static_rsa_token, dhe_token) found in an OpenSSL-style or IANA cipher list."""
    srsa = dhe = None
    for t in re.split(r"[:,\s]+", value or ""):
        t = t.strip(" '\";")
        if not t or t[0] in "!-":
            continue
        t2 = t.lstrip("+@")
        if t2 in ("kRSA", "RSA") or t2.startswith("TLS_RSA_WITH") or re.match(r"^(?:AES|CAMELLIA|DES-CBC3|SEED|IDEA|RC4|ARIA)\d*[-_]", t2):
            srsa = srsa or t2
        if re.match(r"^(?:DHE|EDH)[-_]|^(?:kEDH|kDHE|EDH|DHE)$|^TLS_DHE_", t2):
            dhe = dhe or t2
    return srsa, dhe


def emit_group(col, rel, ln, line, value, asset=None):
    v = group_verdict(value)
    a = asset or TLSP
    if v == "pinned":
        col.add("KEX-TLS-PINNED", rel, ln, line, dict(a, parameter=value.strip()[:60]))
    elif v in ("ok", "pqonly"):
        groups = {name.lower(): name for name in GROUPS.values() if "MLKEM" in name}
        alg = next((groups[t.lower()] for t in re.findall(r"[\w-]+", value) if t.lower() in groups), None)
        col.add("OK-PQ-KEX" if v == "ok" else "PQ-ONLY", rel, ln, line,
                dict(PQK, kind="protocol", algorithm=alg, parameter=value.strip()[:60]))


def emit_ciphers(col, rel, ln, line, value):
    srsa, dhe = cipher_verdict(value)
    if srsa:
        col.add("KEX-TLS-STATIC-RSA", rel, ln, line, _a("RSA", "RSA", "pke", "kex", "protocol", srsa))
    if dhe:
        col.add("KEX-TLS-DHE", rel, ln, line, _a("DHE", "FFDH", "key-agree", "kex", "protocol", dhe))


CODE_PINS = [
    re.compile(r"\becdhCurve\s*:\s*['\"`]([^'\"`]+)['\"`]"),
    re.compile(r"\bSSL(?:_CTX)?_set1_(?:groups|curves)_list\s*\(\s*[^,]+,\s*\"([^\"]*)\""),
    re.compile(r"\bjdk\.tls\.namedGroups\s*[=,]\s*\"?([^\"\n)]+)"),
    re.compile(r"\bsetNamedGroups\s*\(\s*(?:new\s+String\s*\[\s*\]\s*)?\{?([^)}]*)"),
    re.compile(r"\bcurl\b[^\n]*--curves\s+['\"]?([^\s'\"]+)"),
    re.compile(r"\bopenssl\s+s_(?:client|server)\b[^\n]*\s-(?:groups|curves)\s+['\"]?([^\s'\"]+)"),
    re.compile(r"\bset1_groups_list\s*\(\s*\"([^\"]*)\""),
]
CODE_CIPHERS = re.compile(r"\bSSL(?:_CTX)?_set_cipher_list\s*\(\s*[^,]+,\s*\"([^\"]*)\"|\bciphers\s*:\s*['\"]([^'\"]+)['\"]")


GO_CURVEPREF = re.compile(r"\bCurvePreferences\s*[:=]")
RS_KX = re.compile(r"\bkx_groups\b")
SSH_KEX_MINUS = re.compile(r"(?i)KexAlgorithms\s+-")
SSHKEYGEN_DSA = re.compile(r"\bssh-keygen\b[^\n]*-t\s+dsa\b")
PY_DOC = re.compile(r"^[rRuUbBfF]{0,2}(\"\"\"|\'\'\')")

# Literal prefilter. For every rule regex we derive lowercase literals such that any match must contain one of
# them. A file whose lowercased text has none of a rule's literals cannot match it, so that rule is skipped for
# the file. The literals come from the regex itself; when they cannot be derived the rule always runs, so the
# prefilter can only make a scan faster, never change its result (tests/test_tools.py checks this).
try:
    try:
        import re._parser as _sre  # Python 3.11+
    except ImportError:
        import sre_parse as _sre   # Python 3.8 - 3.10
except Exception:  # pragma: no cover - no parser available: run every rule on every file
    _sre = None
_NEEDLES = {}
_FOLD_ODDITIES = ("\u017f", "\u212a", "\u0130", "\u0131")   # characters re.IGNORECASE folds to ASCII s, k, i


def _better(a, b):
    if not a:
        return b
    if not b:
        return a
    ka, kb = (min(len(x) for x in a), -len(a)), (min(len(x) for x in b), -len(b))
    return b if kb > ka else a


def _required(sub):
    """Literals one of which every match of this parsed pattern must contain, or None when unknown."""
    best, run = None, []
    for op, av in list(sub) + [(None, None)]:
        if op is _sre.LITERAL:
            run.append(chr(av).lower())
            continue
        if run:
            best = _better(best, ["".join(run)])
            run = []
        cand = None
        if op is _sre.SUBPATTERN:
            cand = _required(av[-1])
        elif op is _sre.BRANCH:
            parts = [_required(x) for x in av[1]]
            cand = None if any(x is None for x in parts) else [y for x in parts for y in x]
        elif op in (_sre.MAX_REPEAT, _sre.MIN_REPEAT, getattr(_sre, "POSSESSIVE_REPEAT", -1)):
            if av[0] >= 1:
                cand = _required(av[2])
        elif op is getattr(_sre, "ATOMIC_GROUP", -1):
            cand = _required(av)
        best = _better(best, cand)
    return best


def needles(rx):
    if rx not in _NEEDLES:
        nd = None
        if _sre is not None:
            try:
                nd = _required(_sre.parse(rx.pattern, rx.flags & ~re.UNICODE if isinstance(rx.pattern, str) else rx.flags))
                if nd and min(len(x) for x in nd) < 2:
                    nd = None
            except Exception:
                nd = None
        _NEEDLES[rx] = tuple(sorted(set(nd))) if nd else None
    return _NEEDLES[rx]


def lowered(text, opts):
    """Lowercased text for the prefilter, or None to run every rule (prefilter off or not provably exact)."""
    if _sre is None or opts.get("no_prefilter") or os.environ.get("PQSHIFT_NO_PREFILTER"):
        return None
    for ch in _FOLD_ODDITIES:
        if ch in text:
            return None
    return text.lower()


def could_match(rx, low):
    if low is None:
        return True
    nd = needles(rx)
    if nd is None:
        return True
    for x in nd:
        if x in low:
            return True
    return False


def scan_text_lines(col, rel, lines, lang, opts, low=None):
    include_comments = opts.get("include_comments")
    rules = [t for t in _compiled(lang) if could_match(t[1], low)]
    shell = [t for t in _SHELL_C if could_match(t[1], low)]
    generic = [t for t in _GENERIC_C if could_match(t[1], low)]
    pins = [rx for rx in CODE_PINS if could_match(rx, low)]
    ciphers = lang in ("c", "js") and could_match(CODE_CIPHERS, low)
    go_cp = lang == "go" and could_match(GO_CURVEPREF, low)
    rs_kx = lang == "rs" and could_match(RS_KX, low)
    ok_kex = lang not in ("conf", "ini", "toml") and could_match(OK_KEX, low)
    ok_sig = could_match(OK_SIG, low)
    weak = [rx for rx in WEAK_BITS if could_match(rx, low)]
    dh = could_match(DH_BITS, low)
    dsa = could_match(SSHKEYGEN_DSA, low)
    sshlit = lang in CODE_LANGS and could_match(SSH_KEX_LIT, low)
    if not (rules or shell or generic or pins or ciphers or go_cp or rs_kx or ok_kex or ok_sig or weak or dh or dsa or sshlit):
        return
    n = len(lines)
    doc = None        # delimiter of the Python docstring we are inside
    prev_code = None  # last non-blank, non-comment line (to tell a docstring from an ordinary string)
    last_ssh = -10
    for i, line in enumerate(lines):
        if len(line) > 4000:
            col.nc(rel, "code matching skips lines longer than 4000 characters")
            continue
        stripped = line.strip()
        if not stripped:
            continue
        ln = i + 1
        comment = is_comment_line(stripped, lang)
        if lang == "py":
            if doc:
                comment = True
                if doc in stripped:
                    doc = None
            elif not comment:
                m = PY_DOC.match(stripped)
                if m and (prev_code is None or prev_code.endswith(":")):
                    comment = True
                    if stripped.count(m.group(1)) < 2:
                        doc = m.group(1)
        if not comment:
            prev_code = stripped
        if comment and not include_comments:
            continue
        ctx = "comment" if comment else None
        for (rule, rx, asset) in rules:
            if rx.search(line):
                if rule == "KEX-TLS-PINNED" and MLKEM_IN.search(line):
                    col.add("OK-PQ-KEX", rel, ln, line, PQK, context=ctx)
                    continue
                col.add(rule, rel, ln, line, asset, context=ctx)
        for (rule, rx, asset) in shell:
            if rx.search(line):
                col.add(rule, rel, ln, line, asset, context=ctx)
        for (rule, rx, asset) in generic:
            if rx.search(line):
                col.add(rule, rel, ln, line, asset, context=ctx)
        # pinned group lists in code and command lines
        for rx in pins:
            m = rx.search(line)
            if m:
                emit_group(col, rel, ln, line, m.group(1))
        if ciphers:
            m = CODE_CIPHERS.search(line)
            if m:
                emit_ciphers(col, rel, ln, line, m.group(1) or m.group(2))
        if go_cp and GO_CURVEPREF.search(line):
            block = line
            j = i
            while "}" not in block and j + 1 < n and j - i < 10:
                j += 1
                block += " " + lines[j]
            inner = block[block.find("{") + 1: block.find("}")] if "{" in block else ""
            if MLKEM_IN.search(inner):
                col.add("OK-PQ-KEX", rel, ln, line, dict(PQK, kind="protocol", algorithm="X25519MLKEM768"), context=ctx)
            elif inner.strip():
                col.add("KEX-TLS-PINNED", rel, ln, line, dict(TLSP, parameter=" ".join(inner.split())[:60]), context=ctx)
        if rs_kx and RS_KX.search(line):
            block = " ".join(lines[i:i + 6])
            if MLKEM_IN.search(block):
                col.add("OK-PQ-KEX", rel, ln, line, PQK, context=ctx)
            else:
                col.add("KEX-TLS-PINNED", rel, ln, line, TLSP, context=ctx)
        # classic SSH key-exchange names written into code (a client or server library pinned in code)
        if sshlit and SSH_KEX_LIT.search(line) and not NEGATED.search(line):
            if i - last_ssh > 3 and not SSH_PQ_NAME.search(" ".join(lines[max(0, i - 8):i + 9])):
                col.add("KEX-SSH-PINNED", rel, ln, line, _a("ECDH", "ECC", "key-agree", "kex", "protocol"), context=ctx,
                        confidence="medium")
            last_ssh = i
        # positives (config files report these through their own handlers)
        if ok_kex and not SSH_KEX_MINUS.search(line) and OK_KEX.search(line) and not re.search(r"(?i)kyber", line):
            col.add("OK-PQ-KEX", rel, ln, line, PQK, context=ctx)
        if ok_sig and OK_SIG.search(line):
            col.add("OK-PQ-SIG", rel, ln, line, PQS, context=ctx)
        # small keys / small DH
        for rx in weak:
            m = rx.search(line)
            if not m:
                continue
            bits = int([g for g in m.groups() if g][0])
            win = " ".join(lines[max(0, i - 4):i + 2])
            names_rsa = re.search(r"(?i)rsa|modulusLength", line)
            # A size on a line that names another algorithm (bits: 256 next to 'ecdsa') is not an RSA size.
            other = NOT_RSA_BITS.search(line) and not names_rsa
            if bits < 2048 and not other and (names_rsa or re.search(r"(?i)rsa|modulusLength|genrsa|RSACryptoServiceProvider", win)):
                col.add("WEAK-RSA-SMALL", rel, ln, line, _a("RSA", "RSA", None, "keygen", "key", str(bits)), context=ctx,
                        confidence="high" if names_rsa else "medium")
            break
        if dh:
            m = DH_BITS.search(line)
            if m:
                bits = int([g for g in m.groups() if g][0])
                if bits < 2048:
                    col.add("WEAK-DH-SMALL", rel, ln, line, _a("DH", "FFDH", "key-agree", "kex", "key", str(bits)), context=ctx)
                else:
                    col.add("KEX-TLS-DHE", rel, ln, line, _a("DH", "FFDH", "key-agree", "kex", "key", str(bits)), context=ctx)
        if dsa and SSHKEYGEN_DSA.search(line):
            col.add("WEAK-SIG-SHA1", rel, ln, line, _a("DSA", "DSA", "signature", "keygen", "key"), context=ctx)
        # PEM blocks embedded in code are handled by the key parser


# ---------------------------------------------------------------------------------------------------------------
# Config files (A.2)
# ---------------------------------------------------------------------------------------------------------------

def _clines(lines, prefixes=("#",)):
    for i, line in enumerate(lines):
        s = line.strip()
        if not s or any(s.startswith(p) for p in prefixes):
            continue
        yield i + 1, line, s


def tls_protocols(col, rel, ln, line, value, style="nginx"):
    v = value
    toks = [t for t in re.split(r"[\s,:]+", v) if t]
    low = [t.lower() for t in toks]
    if style == "apache":
        has13 = any(t.lstrip("+") == "tlsv1.3" for t in low) or ("all" in low and "-tlsv1.3" not in low)
        no13 = "-tlsv1.3" in low or not has13
        old = [t for t in toks if t.lower().lstrip("+") in ("tlsv1", "tlsv1.0", "tlsv1.1", "sslv3", "sslv2")
               and not t.startswith("-")]
    else:
        no13 = not any(t in ("tlsv1.3", "tls1.3", "tls1_3", "tlsv1_3") for t in low)
        old = [t for t in toks if t.lower() in ("tlsv1", "tlsv1.0", "tlsv1.1", "sslv3", "sslv2", "tls1.0", "tls1.1",
                                                 "tlsv1_0", "tlsv1_1", "tls1", "tls1_1")]
    if no13:
        col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
    if old:
        col.add("WEAK-TLS-OLD", rel, ln, line, dict(TLSP, parameter=",".join(old)))


def cfg_nginx(col, rel, lines, text):
    has_cert = None
    has_groups = False
    for ln, line, s in _clines(lines):
        m = re.match(r"(?:proxy_)?ssl_ecdh_curve\s+([^;]+);?", s)
        if m:
            has_groups = True
            emit_group(col, rel, ln, line, m.group(1))
        m = re.match(r"(?:proxy_)?ssl_conf_command\s+(?:Groups|Curves)\s+([^;]+);?", s)
        if m:
            has_groups = True
            emit_group(col, rel, ln, line, m.group(1))
        m = re.match(r"(?:proxy_)?ssl_protocols\s+([^;]+);?", s)
        if m:
            tls_protocols(col, rel, ln, line, m.group(1))
        m = re.match(r"(?:proxy_)?ssl_ciphers\s+['\"]?([^;'\"]+)", s)
        if m:
            emit_ciphers(col, rel, ln, line, m.group(1))
        if re.match(r"ssl_dhparam\s+", s):
            col.add("KEX-TLS-DHE", rel, ln, line, _a("DHE", "FFDH", "key-agree", "kex", "protocol"))
        if re.match(r"ssl_certificate\s+", s) and has_cert is None:
            has_cert = (ln, line)
    if has_cert and not has_groups:
        col.add("KEX-TLS-DEFAULT", rel, has_cert[0], has_cert[1], TLSP, needs=["probe"])


def cfg_apache(col, rel, lines, text):
    cert = None
    groups = False
    for ln, line, s in _clines(lines):
        m = re.match(r"(?i)SSLOpenSSLConfCmd\s+(?:Curves|Groups|ECDHParameters)\s+(\S+)", s)
        if m:
            groups = True
            emit_group(col, rel, ln, line, m.group(1))
        m = re.match(r"(?i)(?:SSL|SSLProxy)Protocol\s+(.+)", s)
        if m:
            tls_protocols(col, rel, ln, line, m.group(1), style="apache")
        m = re.match(r"(?i)(?:SSL|SSLProxy)CipherSuite\s+(?:TLSv1\.3\s+)?['\"]?([^'\"]+)", s)
        if m:
            emit_ciphers(col, rel, ln, line, m.group(1))
        if re.match(r"(?i)SSLOpenSSLConfCmd\s+DHParameters\s+", s):
            col.add("KEX-TLS-DHE", rel, ln, line, _a("DHE", "FFDH", "key-agree", "kex", "protocol"))
        if re.match(r"(?i)SSLCertificateFile\s+", s) and not cert:
            cert = (ln, line)
    if cert and not groups:
        col.add("KEX-TLS-DEFAULT", rel, cert[0], cert[1], TLSP, needs=["probe"])


def cfg_haproxy(col, rel, lines, text):
    for ln, line, s in _clines(lines):
        m = re.search(r"\bssl-default-(?:bind|server)-curves\s+(\S+)|\bcurves\s+(\S+)", s)
        if m:
            emit_group(col, rel, ln, line, m.group(1) or m.group(2))
        if re.search(r"\bssl-max-ver\s+TLSv1\.[0-2]\b|\bno-tlsv13\b|\bforce-tlsv12\b", s):
            col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
        if re.search(r"\bssl-min-ver\s+(?:TLSv1\.[01]|SSLv3)\b|\bforce-(?:tlsv10|tlsv11|sslv3)\b", s):
            col.add("WEAK-TLS-OLD", rel, ln, line, TLSP)
        m = re.search(r"\bssl-default-(?:bind|server)-ciphers\s+(\S+)|\bciphers\s+(\S+)", s)
        if m:
            emit_ciphers(col, rel, ln, line, m.group(1) or m.group(2))


def cfg_caddy(col, rel, lines, text):
    for ln, line, s in _clines(lines):
        m = re.match(r"curves\s+(.+)", s)
        if m:
            emit_group(col, rel, ln, line, m.group(1))
        m = re.match(r"protocols\s+(\S+)(?:\s+(\S+))?", s)
        if m:
            lo, hi = m.group(1), m.group(2) or "tls1.3"
            if hi == "tls1.2":
                col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
            if lo in ("tls1.0", "tls1.1"):
                col.add("WEAK-TLS-OLD", rel, ln, line, TLSP)
        m = re.match(r"ciphers\s+(.+)", s)
        if m:
            emit_ciphers(col, rel, ln, line, m.group(1))


KV_GROUP = re.compile(r"""^\s*-?\s*["']?(ecdh_curves|ecdhCurves|curvePreferences|curve_preferences|ssl-ecdh-curve|ssl_ecdh_curve|
    named_groups|namedGroups|tls_groups|tlsGroups|ssl_groups|ssl_curve_list|tls_eecdh_auto_curves|ecdh_curve|curves|groups|Groups|Curves|tls-groups)["']?\s*[:=]\s*(.*)$""", re.X)
KV_MAXV = re.compile(r"""(?i)^\s*["']?(?:maxVersion|max_version|tls_maximum_protocol_version|ssl_max_protocol_version|MaxProtocol|maxTLSVersion|max_tls_version)["']?\s*[:=]\s*["']?(VersionTLS12|TLSv1_2|TLSv1\.2|1\.2|TLS12|TLS1_2)["']?""")
KV_MINV = re.compile(r"""(?i)^\s*["']?(?:minVersion|min_version|tls_minimum_protocol_version|ssl_min_protocol_version|ssl_min_protocol|MinProtocol|minTLSVersion|min_tls_version|minimum_protocol_version|tls-version-min)["']?\s*[:=]?\s*["']?(VersionTLS10|VersionTLS11|TLSv1_0|TLSv1_1|TLSv1|TLSv1\.0|TLSv1\.1|1\.0|1\.1|TLS1_0|TLS1_1|TLSv1_2016|TLSv1\.1_2016|SSLv3)["']?\s*$""")
KV_PROTO = re.compile(r"""(?i)^\s*["']?(?:ssl-protocols|ssl_protocols|smtpd_tls_protocols|smtp_tls_protocols|smtpd_tls_mandatory_protocols|tls_version|protocols)["']?\s*[:=]\s*["']?([^"'#]+)""")
KV_CIPH = re.compile(r"""(?i)^\s*["']?(?:ssl-ciphers|ssl_ciphers|cipherString|CipherString|cipher_suites|tls_ciphers|smtpd_tls_mandatory_ciphers|ssl_cipher_list)["']?\s*[:=]\s*["']?([^"'#]+)""")


def cfg_kv(col, rel, lines, text, kind="kv"):
    """Envoy, Traefik, ingress, Istio, Postfix, Dovecot, PostgreSQL, MySQL, openssl.cnf: key/value settings."""
    n = len(lines)
    for ln, line, s in _clines(lines, ("#", ";", "//")):
        m = KV_GROUP.match(line)
        if m:
            key, val = m.group(1), m.group(2).strip().rstrip(",")
            if key in ("curves", "groups") and kind not in ("cnf", "kv"):
                pass
            if not val or val in ("|", ">", "[") or val.endswith("["):
                # YAML/JSON list on the following lines
                items = []
                j = ln
                while j < n and len(items) < 12:
                    nxt = lines[j].strip()
                    if not nxt:
                        j += 1
                        continue
                    if nxt.startswith("-") or (val.endswith("[") and not nxt.startswith("]")):
                        items.append(nxt.lstrip("- ").strip("\"',"))
                        j += 1
                        continue
                    break
                val = ",".join(items)
            if val:
                emit_group(col, rel, ln, line, val)
        if KV_MAXV.match(line):
            col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
        if KV_MINV.match(line):
            col.add("WEAK-TLS-OLD", rel, ln, line, TLSP)
        m = KV_PROTO.match(line)
        if m:
            v = m.group(1)
            if re.search(r"(?i)tlsv?1\.?[0-3]|sslv3", v):
                if re.search(r"!", v):
                    # Postfix exclusion syntax: !SSLv2, !TLSv1
                    if not re.search(r"(?i)!\s*TLSv1(?![._]\d)", v) and re.search(r"(?i)\bTLSv1\b", v) is None:
                        pass
                    if re.search(r"(?i)!\s*TLSv1\.3", v):
                        col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
                else:
                    tls_protocols(col, rel, ln, line, v.replace(",", " "))
        m = KV_CIPH.match(line)
        if m:
            emit_ciphers(col, rel, ln, line, m.group(1))
        m = re.match(r"(?i)^\s*default_bits\s*=\s*(\d+)", line)
        if m and int(m.group(1)) < 2048:
            col.add("WEAK-RSA-SMALL", rel, ln, line, _a("RSA", "RSA", None, "keygen", "key", m.group(1)))
        m = re.match(r"(?i)^\s*default_md\s*=\s*(sha1|md5)\b", line)
        if m:
            col.add("WEAK-SIG-SHA1", rel, ln, line, _a(m.group(1).upper(), None, "signature", "sign"))
        # Cloud load-balancer policies
        m = re.search(r"""(?i)\b(?:ssl_policy|SslPolicy|sslPolicy|ssl-policy)["']?\s*[:=]\s*["']?(ELBSecurityPolicy-[\w.-]+)""", line)
        if m and "PQ" not in m.group(1).upper():
            col.add("KEX-LB-POLICY", rel, ln, line, dict(TLSP, parameter=m.group(1)))
        elif m:
            col.add("OK-PQ-KEX", rel, ln, line, dict(PQK, kind="protocol", parameter=m.group(1)))
        # IaC key specs
        if re.search(r"""(?i)\b(?:customer_master_key_spec|key_spec|KeySpec)["']?\s*[:=]\s*["']?(?:RSA_\d+|ECC_\w+)""", line) or \
           re.search(r"""\bkey_algorithm\s*=\s*"(?:RSA_\d+|EC_\w+)\"""", line) or \
           re.search(r"""\bkey_type\s*=\s*"(?:RSA|EC)(?:-HSM)?\"""", line) or \
           re.search(r"""\balgorithm\s*=\s*"(?:RSA_SIGN_|RSA_DECRYPT_|EC_SIGN_)\w*\"""", line) or \
           re.search(r"""\balgorithm\s*=\s*"(?:RSA|ECDSA|ED25519)\"""", line):
            col.add("KEY-GEN", rel, ln, line, KEYGEN)
        m = re.search(r"""\brsa_bits\s*=\s*(\d+)""", line)
        if m and int(m.group(1)) < 2048:
            col.add("WEAK-RSA-SMALL", rel, ln, line, _a("RSA", "RSA", None, "keygen", "key", m.group(1)))
        if re.search(r"""(?i)\b(?:ML_DSA_(?:44|65|87)|ML_KEM_(?:512|768|1024)|PQ_SIGN_\w+)\b""", line):
            col.add("OK-PQ-SIG" if "DSA" in line or "SIGN" in line else "OK-PQ-KEX", rel, ln, line, PQS)
    # cert-manager Certificate: privateKey: algorithm: RSA|ECDSA|Ed25519
    if re.search(r"(?m)^\s*kind:\s*Certificate\b", text) or "privateKey:" in text:
        in_pk = False
        for i, line in enumerate(lines):
            if re.match(r"^\s*privateKey:\s*$", line):
                in_pk = True
                continue
            if in_pk:
                m = re.match(r"^\s*algorithm:\s*['\"]?(RSA|ECDSA|Ed25519)['\"]?\s*$", line)
                if m:
                    col.add("KEY-GEN", rel, i + 1, line, KEYGEN)
                    in_pk = False
                m = re.match(r"^\s*size:\s*(\d+)", line)
                if m and int(m.group(1)) < 2048 and "RSA" in "".join(lines[max(0, i - 3):i + 3]):
                    col.add("WEAK-RSA-SMALL", rel, i + 1, line, _a("RSA", "RSA", None, "keygen", "key", m.group(1)))
                if line.strip() and not line.startswith(" " * 4) and not re.match(r"^\s+", line):
                    in_pk = False


PQ_SSH = ("mlkem768x25519-sha256", "sntrup761x25519-sha512", "sntrup761x25519-sha512@openssh.com",
          "mlkem768nistp256-sha256", "mlkem1024nistp384-sha384")


def cfg_ssh(col, rel, lines, text, is_server):
    has_kex = False
    for ln, line, s in _clines(lines):
        m = re.match(r"(?i)KexAlgorithms\s+(\S+)", s)
        if m:
            has_kex = True
            v = m.group(1)
            names = [x for x in v.lstrip("+-^").split(",") if x]
            pq = [x for x in names if x in PQ_SSH]
            if v[0] in "+^":
                if pq:
                    col.add("OK-PQ-KEX", rel, ln, line, dict(PQK, kind="protocol", algorithm=pq[0]))
            elif v[0] == "-":
                if any(fnmatch.fnmatchcase(alg, pattern) for pattern in names for alg in PQ_SSH):
                    col.add("KEX-SSH-PINNED", rel, ln, line, _a("ECDH", "ECC", "key-agree", "kex", "protocol", v[:60]))
            else:
                if pq:
                    col.add("OK-PQ-KEX", rel, ln, line, dict(PQK, kind="protocol", algorithm=pq[0]))
                else:
                    col.add("KEX-SSH-PINNED", rel, ln, line, _a("ECDH", "ECC", "key-agree", "kex", "protocol", v[:60]))
            if v[0] != "-":
                if "diffie-hellman-group1-sha1" in names:
                    col.add("WEAK-DH-SMALL", rel, ln, line, _a("DH", "FFDH", "key-agree", "kex", "protocol", "group1"))
                if any(x in names for x in ("diffie-hellman-group14-sha1", "diffie-hellman-group-exchange-sha1")):
                    col.add("WEAK-SIG-SHA1", rel, ln, line, _a("DH-SHA1", "FFDH", "key-agree", "kex", "protocol"))
        m = re.match(r"(?i)(HostKeyAlgorithms|PubkeyAcceptedAlgorithms|PubkeyAcceptedKeyTypes|CASignatureAlgorithms|HostbasedAcceptedAlgorithms)\s+(\S+)", s)
        if m:
            v = m.group(2)
            names = [x for x in v.lstrip("+-^").split(",") if x]
            if v[0] != "-" and any(x in ("ssh-rsa", "ssh-dss", "ssh-rsa-cert-v01@openssh.com", "ssh-dss-cert-v01@openssh.com") for x in names):
                col.add("WEAK-SIG-SHA1", rel, ln, line, _a("ssh-rsa (SHA-1)", "RSA", "signature", "sign", "protocol"))
            else:
                col.add("SIG-SSH-ALGS", rel, ln, line, _a(None, None, "signature", "sign", "protocol", v[:60]))
        if re.match(r"(?i)HostKey\s+\S+", s):
            col.add("SIG-SSH-ALGS", rel, ln, line, _a(None, None, "signature", "sign", "key"))
    if is_server and not has_kex:
        col.add("KEX-SSH-DEFAULT", rel, 1, "no KexAlgorithms line (uses the OpenSSH version's default)", TLSP,
                needs=["probe", "runtime"], file_level=True)


def cfg_wireguard(col, rel, lines, text):
    blocks = []
    cur = None
    for i, line in enumerate(lines):
        s = line.strip()
        if s.lower() == "[peer]":
            cur = {"line": i + 1, "psk": False, "name": ""}
            blocks.append(cur)
        elif s.startswith("[") and s.endswith("]"):
            cur = None
        elif cur is not None:
            psk = re.match(r"(?i)PresharedKey\s*=\s*([^#\s]*)", s)
            if psk:
                value = psk.group(1)
                cur["psk"] = bool(value) and value != base64.b64encode(bytes(32)).decode("ascii")
            if s.startswith("#") and not cur["name"]:
                cur["name"] = s.lstrip("# ")[:40]
    for b in blocks:
        if not b["psk"]:
            col.add("KEX-VPN-WG-NOPSK", rel, b["line"], "[Peer] " + b["name"], _a("X25519", "ECC", "key-agree", "kex", "protocol"))


def cfg_openvpn(col, rel, lines, text):
    crypt = re.search(r"(?m)^\s*(?:tls-crypt|tls-crypt-v2)\b|<tls-crypt", text)
    grp = None
    anchor = None
    for ln, line, s in _clines(lines, ("#", ";")):
        m = re.match(r"(?:tls-groups|ecdh-curve)\s+(\S+)", s)
        if m:
            grp = (ln, line, m.group(1))
        m = re.match(r"dh\s+(\S+)", s)
        if m and m.group(1) != "none":
            col.add("KEX-TLS-DHE", rel, ln, line, _a("DH", "FFDH", "key-agree", "kex", "protocol"))
        if re.match(r"tls-version-min\s+1\.[01]\b", s):
            col.add("WEAK-TLS-OLD", rel, ln, line, TLSP)
        if re.match(r"tls-version-max\s+1\.2\b", s):
            col.add("KEX-TLS-NO13", rel, ln, line, TLSP)
        if anchor is None and re.match(r"(?:remote|server|client|dev)\b", s):
            anchor = (ln, line)
    pqg = grp and MLKEM_IN.search(grp[2])
    if pqg:
        col.add("OK-PQ-KEX", rel, grp[0], grp[1], PQK)
    else:
        a = anchor or (1, "")
        col.add("KEX-VPN-OVPN", rel, a[0], a[1], _a("ECDH", "ECC", "key-agree", "kex", "protocol"),
                severity="medium" if crypt else None, file_level=True)


def cfg_ike(col, rel, lines, text):
    has_ppk = re.search(r"(?m)^\s*(?:ppk_id|ppk_required)\b", text)
    for ln, line, s in _clines(lines):
        m = re.match(r"(?:proposals|esp_proposals|ike|esp)\s*=\s*(\S+)", s)
        if not m:
            continue
        v = m.group(1).lower()
        classic = re.search(r"modp\d+|ecp\d+|curve25519|x25519|curve448|x448|ecp\d+bp", v)
        pq = re.search(r"(?:^|[-,])(?:ke[1-7]_)?mlkem(?:512|768|1024)(?=$|[-,])", v)
        if pq:
            col.add("OK-PQ-KEX", rel, ln, line, PQK)
        elif classic:
            col.add("KEX-VPN-IKE", rel, ln, line, _a("ECDH", "ECC", "key-agree", "kex", "protocol", v[:60]),
                    confidence="medium" if has_ppk else "high",
                    extra={"note": "Check whether this connection requires a strong PPK on both peers."} if has_ppk else None)
        if re.search(r"modp(?:768|1024|1536)\b", v):
            col.add("WEAK-DH-SMALL", rel, ln, line, _a("DH", "FFDH", "key-agree", "kex", "protocol"))


def detect_configs(rel, name, ext, text):
    """Return a list of (handler, kwargs) for the config formats this file looks like."""
    out = []
    lname = name.lower()
    if "nginx" in rel.lower() or re.search(r"(?m)^\s*(?:ssl_certificate|ssl_protocols|ssl_ciphers|ssl_ecdh_curve)\s", text) or \
            re.search(r"(?m)^\s*listen\s+[^;]*\bssl\b", text):
        if re.search(r"(?m)^\s*(?:ssl_|proxy_ssl_|listen|server\s*\{|http\s*\{)", text):
            out.append((cfg_nginx, {}))
    if re.search(r"(?im)^\s*(?:SSLEngine|SSLProtocol|SSLCipherSuite|SSLOpenSSLConfCmd|SSLCertificateFile)\b", text):
        out.append((cfg_apache, {}))
    if "haproxy" in lname or (re.search(r"(?m)^\s*(?:frontend|backend|global|defaults)\b", text) and
                              re.search(r"\bbind\b[^\n]*\bssl\b|ssl-default-bind", text)):
        out.append((cfg_haproxy, {}))
    if lname.startswith("caddyfile"):
        out.append((cfg_caddy, {}))
    sshish = lname.startswith("sshd_config") or lname.startswith("ssh_config") or lname == "config" and "/.ssh/" in "/" + rel or \
        "/sshd_config.d/" in "/" + rel or re.search(r"(?im)^\s*(?:KexAlgorithms|HostKeyAlgorithms|PubkeyAcceptedAlgorithms|PermitRootLogin|HostKey)\s", text)
    if sshish and not re.search(r"(?m)^\s*\[", text):
        out.append((cfg_ssh, {"is_server": lname.startswith("sshd") or "/sshd_config.d/" in "/" + rel}))
    if re.search(r"(?im)^\s*\[Interface\]", text) and re.search(r"(?im)^\s*PrivateKey\s*=", text):
        out.append((cfg_wireguard, {}))
    if ext == ".ovpn" or (re.search(r"(?m)^\s*dev\s+(?:tun|tap)", text) and re.search(r"(?m)^\s*(?:remote|server|client)\b", text)):
        out.append((cfg_openvpn, {}))
    if lname in ("swanctl.conf", "ipsec.conf") or re.search(r"(?m)^\s*(?:proposals|esp_proposals)\s*=", text) or \
            re.search(r"(?m)^\s*(?:ike|esp)\s*=\s*\S+", text) and re.search(r"(?m)^\s*conn\s", text):
        out.append((cfg_ike, {}))
    if ext in (".yml", ".yaml", ".json", ".toml", ".conf", ".cnf", ".cfg", ".ini", ".tf", ".tfvars", ".properties", "") or \
            lname in ("main.cf", "postgresql.conf", "my.cnf", "openssl.cnf"):
        out.append((cfg_kv, {"kind": "cnf" if ext == ".cnf" else "kv"}))
    return out


# ---------------------------------------------------------------------------------------------------------------
# Keys and certificates (A.3): a minimal DER walker. Reads type and size only; never outputs key fields.
# ---------------------------------------------------------------------------------------------------------------

OIDS = {
    "1.2.840.113549.1.1.1": ("RSA", "RSA", None),
    "1.2.840.113549.1.1.10": ("RSASSA-PSS", "RSA", None),
    "1.2.840.10045.2.1": ("EC", "ECC", None),
    "1.3.101.110": ("X25519", "ECC", 256), "1.3.101.111": ("X448", "ECC", 448),
    "1.3.101.112": ("Ed25519", "ECC", 256), "1.3.101.113": ("Ed448", "ECC", 448),
    "1.2.840.10040.4.1": ("DSA", "DSA", None),
    "1.2.840.113549.1.3.1": ("DH", "FFDH", None), "1.2.840.10046.2.1": ("DH", "FFDH", None),
    "2.16.840.1.101.3.4.4.1": ("ML-KEM-512", "ML-KEM", 512), "2.16.840.1.101.3.4.4.2": ("ML-KEM-768", "ML-KEM", 768),
    "2.16.840.1.101.3.4.4.3": ("ML-KEM-1024", "ML-KEM", 1024),
    "2.16.840.1.101.3.4.3.17": ("ML-DSA-44", "ML-DSA", 44), "2.16.840.1.101.3.4.3.18": ("ML-DSA-65", "ML-DSA", 65),
    "2.16.840.1.101.3.4.3.19": ("ML-DSA-87", "ML-DSA", 87),
}
for _i, _n in enumerate(["SHA2-128s", "SHA2-128f", "SHA2-192s", "SHA2-192f", "SHA2-256s", "SHA2-256f",
                         "SHAKE-128s", "SHAKE-128f", "SHAKE-192s", "SHAKE-192f", "SHAKE-256s", "SHAKE-256f"]):
    OIDS["2.16.840.1.101.3.4.3.%d" % (20 + _i)] = ("SLH-DSA-" + _n, "SLH-DSA", None)
CURVES = {"1.2.840.10045.3.1.7": "P-256", "1.3.132.0.34": "P-384", "1.3.132.0.35": "P-521", "1.3.132.0.10": "secp256k1",
          "1.2.840.10045.3.1.1": "P-192", "1.3.132.0.33": "P-224"}
CURVE_BITS = {"P-256": 256, "P-384": 384, "P-521": 521, "secp256k1": 256, "P-192": 192, "P-224": 224}
SIGALGS = {
    "1.2.840.113549.1.1.4": "md5WithRSAEncryption", "1.2.840.113549.1.1.5": "sha1WithRSAEncryption",
    "1.2.840.113549.1.1.11": "sha256WithRSAEncryption", "1.2.840.113549.1.1.12": "sha384WithRSAEncryption",
    "1.2.840.113549.1.1.13": "sha512WithRSAEncryption", "1.2.840.113549.1.1.10": "RSASSA-PSS",
    "1.2.840.10045.4.1": "ecdsa-with-SHA1", "1.2.840.10045.4.3.2": "ecdsa-with-SHA256",
    "1.2.840.10045.4.3.3": "ecdsa-with-SHA384", "1.2.840.10045.4.3.4": "ecdsa-with-SHA512",
    "1.3.101.112": "Ed25519", "1.3.101.113": "Ed448", "1.2.840.10040.4.3": "dsa-with-SHA1",
    "2.16.840.1.101.3.4.3.2": "dsa-with-SHA256",
}
CLASSIC_LEVEL = {("RSA", 2048): 112, ("RSA", 3072): 128, ("RSA", 4096): 128, ("ECC", 256): 128, ("ECC", 384): 192,
                 ("ECC", 521): 256, ("ECC", 448): 224}


class DERError(Exception):
    pass


def der_tlv(b, i):
    if i + 2 > len(b):
        raise DERError("truncated")
    tag = b[i]
    ln = b[i + 1]
    j = i + 2
    if ln & 0x80:
        n = ln & 0x7F
        if n == 0 or n > 4 or j + n > len(b):
            raise DERError("bad length")
        ln = int(binascii.hexlify(b[j:j + n]), 16)
        j += n
    if j + ln > len(b):
        raise DERError("truncated value")
    return tag, j, j + ln


def der_kids(b, start, end):
    out = []
    i = start
    while i < end:
        t, s, e = der_tlv(b, i)
        out.append((t, s, e))
        i = e
    return out


def der_oid(v):
    if not v:
        return ""
    first = v[0]
    parts = [str(first // 40) if first < 80 else "2", str(first % 40) if first < 80 else str(first - 80)]
    n = 0
    for c in v[1:]:
        n = (n << 7) | (c & 0x7F)
        if not c & 0x80:
            parts.append(str(n))
            n = 0
    return ".".join(parts)


def int_bits(v):
    v = v.lstrip(b"\x00")
    if not v:
        return 0
    return (len(v) - 1) * 8 + v[0].bit_length()


def der_time(t, v):
    s = v.decode("ascii", "replace")
    try:
        if t == 0x17:
            yy = int(s[:2])
            year = 1900 + yy if yy >= 50 else 2000 + yy
            return "%04d-%s-%sT%s:%s:%sZ" % (year, s[2:4], s[4:6], s[6:8], s[8:10], s[10:12])
        return "%s-%s-%sT%s:%s:%sZ" % (s[:4], s[4:6], s[6:8], s[8:10], s[10:12], s[12:14])
    except Exception:
        return None


def der_cn(b, s, e):
    try:
        for (_t, ss, se) in der_kids(b, s, e):          # SET
            for (_t2, as_, ae) in der_kids(b, ss, se):   # SEQ
                k = der_kids(b, as_, ae)
                if len(k) >= 2 and k[0][0] == 6 and der_oid(b[k[0][1]:k[0][2]]) == "2.5.4.3":
                    return b[k[1][1]:k[1][2]].decode("utf-8", "replace")
    except DERError:
        pass
    return None


def algid(b, s, e):
    k = der_kids(b, s, e)
    oid = der_oid(b[k[0][1]:k[0][2]]) if k and k[0][0] == 6 else ""
    params = None
    if len(k) > 1 and k[1][0] == 6:
        params = der_oid(b[k[1][1]:k[1][2]])
    return oid, params, k


def spki_info(b, s, e):
    """SubjectPublicKeyInfo -> dict(algorithm, family, size, oid, pq)."""
    k = der_kids(b, s, e)
    oid, params, ak = algid(b, k[0][1], k[0][2])
    name, fam, size = OIDS.get(oid, (oid or "unknown", None, None))
    info = {"algorithm": name, "family": fam, "size": size, "oid": oid,
            "pq": fam in ("ML-KEM", "ML-DSA", "SLH-DSA")}
    if fam == "RSA" and len(k) > 1:
        bs = b[k[1][1] + 1:k[1][2]]
        try:
            rk = der_kids(bs, *der_tlv(bs, 0)[1:])
            info["size"] = int_bits(bs[rk[0][1]:rk[0][2]])
        except DERError:
            pass
        info["algorithm"] = "RSA-%s" % info["size"]
    elif fam == "ECC" and name == "EC":
        c = CURVES.get(params or "", params or "unknown curve")
        info["algorithm"] = "EC " + c
        info["size"] = CURVE_BITS.get(c)
        info["curve"] = c
    elif fam == "DSA" and len(ak) > 1 and ak[1][0] == 0x30:
        try:
            pk = der_kids(b, ak[1][1], ak[1][2])
            info["size"] = int_bits(b[pk[0][1]:pk[0][2]])
        except DERError:
            pass
    return info


def parse_cert(b):
    _t, s, e = der_tlv(b, 0)
    top = der_kids(b, s, e)
    tbs = der_kids(b, top[0][1], top[0][2])
    i = 0
    if tbs[0][0] == 0xA0:
        i = 1
    sig_oid = der_oid(b[der_kids(b, top[1][1], top[1][2])[0][1]:der_kids(b, top[1][1], top[1][2])[0][2]])
    issuer = tbs[i + 2]
    validity = der_kids(b, tbs[i + 3][1], tbs[i + 3][2])
    subject = tbs[i + 4]
    spki = tbs[i + 5]
    info = {"type": "certificate", "subject": der_cn(b, subject[1], subject[2]), "issuer": der_cn(b, issuer[1], issuer[2]),
            "not_before": der_time(validity[0][0], b[validity[0][1]:validity[0][2]]),
            "not_after": der_time(validity[1][0], b[validity[1][1]:validity[1][2]]),
            "sig_oid": sig_oid, "sig_alg": SIGALGS.get(sig_oid, OIDS.get(sig_oid, (sig_oid,))[0]),
            "key": spki_info(b, spki[1], spki[2]), "ca": False,
            "sha256": hashlib.sha256(b[:e]).hexdigest()}
    info["self_signed"] = info["subject"] == info["issuer"]
    for (t, xs, xe) in tbs[i + 6:]:
        if t != 0xA3:
            continue
        for (_t, es, ee) in der_kids(b, *der_tlv(b, xs)[1:]):
            ek = der_kids(b, es, ee)
            if ek and der_oid(b[ek[0][1]:ek[0][2]]) == "2.5.29.19":
                oct_ = ek[-1]
                inner = b[oct_[1]:oct_[2]]
                try:
                    bc = der_kids(inner, *der_tlv(inner, 0)[1:])
                    if bc and bc[0][0] == 1 and inner[bc[0][1]:bc[0][2]] != b"\x00":
                        info["ca"] = True
                except DERError:
                    pass
    return info


def parse_csr(b):
    _t, s, e = der_tlv(b, 0)
    top = der_kids(b, s, e)
    cri = der_kids(b, top[0][1], top[0][2])
    sk = der_kids(b, top[1][1], top[1][2])
    sig_oid = der_oid(b[sk[0][1]:sk[0][2]])
    return {"type": "csr", "subject": der_cn(b, cri[1][1], cri[1][2]), "key": spki_info(b, cri[2][1], cri[2][2]),
            "sig_oid": sig_oid, "sig_alg": SIGALGS.get(sig_oid, sig_oid)}


def parse_private(label, b):
    _t, s, e = der_tlv(b, 0)
    k = der_kids(b, s, e)
    if label == "RSA PRIVATE KEY":
        return {"algorithm": "RSA-%d" % int_bits(b[k[1][1]:k[1][2]]), "family": "RSA", "size": int_bits(b[k[1][1]:k[1][2]])}
    if label == "EC PRIVATE KEY":
        curve = None
        for (t, ss, se) in k[2:]:
            if t == 0xA0:
                it, is_, ie = der_tlv(b, ss)
                curve = CURVES.get(der_oid(b[is_:ie]), der_oid(b[is_:ie]))
        return {"algorithm": "EC " + (curve or "?"), "family": "ECC", "size": CURVE_BITS.get(curve or "")}
    if label == "DSA PRIVATE KEY":
        return {"algorithm": "DSA", "family": "DSA", "size": int_bits(b[k[1][1]:k[1][2]])}
    # PKCS#8
    oid, params, _ak = algid(b, k[1][1], k[1][2])
    name, fam, size = OIDS.get(oid, (oid, None, None))
    info = {"algorithm": name, "family": fam, "size": size, "oid": oid, "pq": fam in ("ML-KEM", "ML-DSA", "SLH-DSA")}
    if fam == "RSA":
        inner = b[k[2][1]:k[2][2]]
        try:
            ik = der_kids(inner, *der_tlv(inner, 0)[1:])
            info["size"] = int_bits(inner[ik[1][1]:ik[1][2]])
            info["algorithm"] = "RSA-%d" % info["size"]
        except DERError:
            pass
    elif name == "EC":
        c = CURVES.get(params or "", params)
        info.update(algorithm="EC " + (c or "?"), size=CURVE_BITS.get(c or ""))
    return info


def ssh_blob_info(blob):
    def rd(i):
        n = struct.unpack(">I", blob[i:i + 4])[0]
        return blob[i + 4:i + 4 + n], i + 4 + n
    typ, i = rd(0)
    typ = typ.decode("ascii", "replace")
    info = {"algorithm": typ, "family": None, "size": None}
    if typ.startswith("ssh-rsa") or typ.startswith("rsa-"):
        _e, i = rd(i)
        n, i = rd(i)
        info.update(family="RSA", size=int_bits(n), algorithm="ssh-rsa %d-bit" % int_bits(n))
    elif "ecdsa" in typ:
        info.update(family="ECC", size=int(re.findall(r"nistp(\d+)", typ)[0]) if "nistp" in typ else None)
    elif typ == "ssh-mldsa44-ed25519":
        info.update(family="ML-DSA", pq=True)
    elif "ed25519" in typ:
        info.update(family="ECC", size=256)
    elif "ed448" in typ:
        info.update(family="ECC", size=448)
    elif typ == "ssh-dss":
        info.update(family="DSA")
    elif "mlkem" in typ or "mldsa" in typ:
        info.update(family="ML-DSA", pq=True)
    return info


PEM_RX = re.compile(r"-----BEGIN ([A-Z0-9 .]+)-----\s*(.*?)-----END \1-----", re.S)
SSH_PUB_RX = re.compile(r"(?:^|\s)(ssh-rsa|ssh-dss|ecdsa-sha2-nistp(?:256|384|521)|ssh-mldsa44-ed25519|ssh-ed25519|ssh-ed448|"
                        r"sk-ecdsa-sha2-nistp256@openssh\.com|sk-ssh-ed25519@openssh\.com)\s+(AAAA[A-Za-z0-9+/]+=*)")


def _pem_body(body):
    lines = [l for l in body.strip().splitlines() if ":" not in l]
    return base64.b64decode("".join(l.strip() for l in lines))


def horizon_past(not_after, horizon):
    return bool(not_after) and not_after[:10] > horizon


def key_findings(col, rel, ln, label, info, evidence, kind="key"):
    fam = info.get("family")
    size = info.get("size")
    asset = {"kind": kind, "algorithm": info.get("algorithm"), "family": fam, "parameter": str(size) if size else None,
             "oid": info.get("oid"), "primitive": None, "usage": "unknown", "quantum_safe": bool(info.get("pq"))}
    if info.get("pq"):
        col.add("OK-PQ-KEX" if fam == "ML-KEM" else "OK-PQ-SIG", rel, ln, evidence, asset)
        return
    col.add("KEY-FILE", rel, ln, evidence, asset)
    if fam == "RSA" and size and size < 2048:
        col.add("WEAK-RSA-SMALL", rel, ln, evidence, asset)
    if fam == "DSA":
        col.add("WEAK-SIG-SHA1", rel, ln, evidence, asset)


def cert_findings(col, rel, ln, info, evidence):
    k = info["key"]
    asset = {"kind": "certificate", "algorithm": k.get("algorithm"), "family": k.get("family"),
             "parameter": str(k.get("size")) if k.get("size") else None, "oid": k.get("oid"),
             "primitive": "signature", "usage": "verify", "quantum_safe": bool(k.get("pq")),
             "subject": info.get("subject"), "issuer": info.get("issuer"), "not_after": info.get("not_after"),
             "not_before": info.get("not_before"), "sig_alg": info.get("sig_alg"), "ca": info.get("ca"),
             "sha256": info.get("sha256")}
    ev = "%s %s %s %s until %s" % ("CA" if info.get("ca") else info["type"],
                                   "CN=%s" % info["subject"] if info.get("subject") else "(no common name)",
                                   k.get("algorithm"), info.get("sig_alg"), (info.get("not_after") or "?")[:10])
    if k.get("pq"):
        col.add("OK-PQ-SIG", rel, ln, ev, asset)
    else:
        if info["type"] == "certificate" and info.get("ca") and horizon_past(info.get("not_after"), col.horizon):
            col.add("CRT-CA-HORIZON", rel, ln, ev, asset)
        else:
            past = info["type"] == "csr" or horizon_past(info.get("not_after"), col.horizon)
            col.add("CRT-CLASSIC", rel, ln, ev, asset, severity="medium" if past else "low")
    if k.get("family") == "RSA" and k.get("size") and k["size"] < 2048:
        col.add("WEAK-RSA-SMALL", rel, ln, ev, asset)
    sa = (info.get("sig_alg") or "").lower()
    if "sha1" in sa or "md5" in sa or sa.startswith("dsa"):
        col.add("WEAK-SIG-SHA1", rel, ln, ev, asset)
    if k.get("family") == "DSA":
        col.add("WEAK-SIG-SHA1", rel, ln, ev, asset)


def scan_pem(col, rel, text):
    for m in PEM_RX.finditer(text):
        label = m.group(1).strip()
        ln = text.count("\n", 0, m.start()) + 1
        # Evidence names the block type without the PEM armour, so findings files never look like key files
        # to secret scanners.
        head = "PEM block: %s" % label.lower()
        try:
            if label in ("ENCRYPTED PRIVATE KEY",) or "PGP" in label:
                col.nc(rel, "%s: passphrase-protected or PGP block; check its type with your key tool" % label)
                continue
            if label == "OPENSSH PRIVATE KEY":
                raw = _pem_body(m.group(2))
                if not raw.startswith(b"openssh-key-v1\x00"):
                    raise DERError("not openssh-key-v1")
                i = len(b"openssh-key-v1\x00")
                for _ in range(3):
                    n = struct.unpack(">I", raw[i:i + 4])[0]
                    i += 4 + n
                i += 4
                n = struct.unpack(">I", raw[i:i + 4])[0]
                info = ssh_blob_info(raw[i + 4:i + 4 + n])
                key_findings(col, rel, ln, label, info, head + " " + (info.get("algorithm") or ""))
                continue
            if label in ("SSH2 PUBLIC KEY",):
                continue
            der = _pem_body(m.group(2))
            if label in ("CERTIFICATE", "TRUSTED CERTIFICATE", "X509 CERTIFICATE"):
                cert_findings(col, rel, ln, parse_cert(der), head)
            elif label in ("CERTIFICATE REQUEST", "NEW CERTIFICATE REQUEST"):
                cert_findings(col, rel, ln, parse_csr(der), head)
            elif label in ("PUBLIC KEY",):
                _t, s, e = der_tlv(der, 0)
                info = spki_info(der, s, e)
                key_findings(col, rel, ln, label, info, head + " " + str(info.get("algorithm")))
            elif label == "RSA PUBLIC KEY":
                _t, s, e = der_tlv(der, 0)
                k = der_kids(der, s, e)
                bits = int_bits(der[k[0][1]:k[0][2]])
                key_findings(col, rel, ln, label, {"algorithm": "RSA-%d" % bits, "family": "RSA", "size": bits},
                             head + " RSA-%d" % bits)
            elif label.endswith("PRIVATE KEY"):
                info = parse_private(label, der)
                key_findings(col, rel, ln, label, info, head + " " + str(info.get("algorithm")))
            elif label in ("DH PARAMETERS", "X9.42 DH PARAMETERS"):
                _t, s, e = der_tlv(der, 0)
                k = der_kids(der, s, e)
                bits = int_bits(der[k[0][1]:k[0][2]])
                a = _a("DH", "FFDH", "key-agree", "kex", "key", str(bits))
                if bits < 2048:
                    col.add("WEAK-DH-SMALL", rel, ln, head + " %d-bit" % bits, a)
                else:
                    col.add("KEX-TLS-DHE", rel, ln, head + " %d-bit" % bits, a)
            elif label in ("EC PARAMETERS",):
                continue
            else:
                col.nc(rel, "%s block not parsed" % label)
        except (DERError, IndexError, ValueError, binascii.Error, struct.error) as ex:
            col.errors.append({"path": rel, "line": ln, "error": "could not parse %s: %s" % (label, ex)})


def scan_ssh_pub(col, rel, text):
    for i, line in enumerate(text.splitlines()):
        m = SSH_PUB_RX.search(line)
        if not m:
            continue
        try:
            info = ssh_blob_info(base64.b64decode(m.group(2)))
        except Exception:
            info = {"algorithm": m.group(1), "family": None, "size": None}
        ev = line[:m.start(2)] + "<key>" + line[m.end(2):]
        key_findings(col, rel, i + 1, None, info, ev.strip() + "  (" + str(info.get("algorithm")) + ")")


def scan_binary_key(col, rel, data, ext):
    if ext in (".p12", ".pfx", ".jks", ".keystore", ".bks"):
        col.nc(rel, "password-protected key store; list it with keytool -list or openssl pkcs12 -info")
        return
    try:
        info = parse_cert(data)
        cert_findings(col, rel, 1, info, "DER certificate")
        return
    except (DERError, IndexError, ValueError):
        pass
    try:
        _t, s, e = der_tlv(data, 0)
        info = spki_info(data, s, e)
        if info.get("family"):
            key_findings(col, rel, 1, "DER", info, "DER public key " + str(info.get("algorithm")))
            return
    except (DERError, IndexError, ValueError):
        pass
    col.nc(rel, "binary key or certificate file not recognised; inspect with openssl")


# ---------------------------------------------------------------------------------------------------------------
# Dependencies and runtimes (A.4)
# ---------------------------------------------------------------------------------------------------------------

PY_LIBS = {"cryptography", "pycryptodome", "pycryptodomex", "pyopenssl", "paramiko", "pyjwt", "python-jose", "rsa", "ecdsa",
           "pynacl", "jwcrypto", "josepy", "authlib", "liboqs-python", "asyncssh", "fido2", "pgpy", "python-gnupg"}
JS_LIBS = {"jsonwebtoken", "jose", "node-forge", "node-rsa", "jsencrypt", "tweetnacl", "elliptic", "@noble/curves",
           "@noble/ed25519", "@noble/secp256k1", "openpgp", "ssh2", "@noble/post-quantum", "jwk-to-pem", "crypto-js",
           "libsodium-wrappers", "eccrypto", "secp256k1", "@peculiar/webcrypto", "pkijs", "@panva/hkdf"}
GO_LIBS = ("golang.org/x/crypto", "github.com/golang-jwt/jwt", "github.com/cloudflare/circl", "filippo.io/age",
           "github.com/lestrrat-go/jwx", "github.com/go-jose/go-jose", "github.com/open-quantum-safe/liboqs-go")
RS_LIBS = {"rsa", "x25519-dalek", "ed25519-dalek", "ring", "openssl", "p256", "p384", "k256", "jsonwebtoken", "rustls",
           "aws-lc-rs", "ml-kem", "ml-dsa", "pqcrypto", "oqs", "ecdsa", "sodiumoxide", "josekit", "rcgen", "x509-parser"}
JAVA_LIBS = ("bcprov", "bcpkix", "bctls", "jjwt", "nimbus-jose-jwt", "java-jwt", "jose4j", "tink", "conscrypt")
CS_LIBS = ("System.IdentityModel.Tokens.Jwt", "Microsoft.IdentityModel.Tokens", "BouncyCastle", "Portable.BouncyCastle",
           "NSec.Cryptography", "jose-jwt", "Sodium.Core")
BASE_IMAGES = re.compile(r"(?i)^(?:debian:(?:buster|bullseye|bookworm)|ubuntu:(?:18|20|22|24)\.04|alpine:3\.(?:1\d|20|21)\b|"
                         r"centos|(?:registry\.access\.redhat\.com/)?ubi[789]|node:(?:1\d|20|22)\b|python:3\.(?:[89]|1[0-3])\b|"
                         r"golang:1\.(?:1\d|2[0-3])\b|eclipse-temurin:(?:8|11|17|21)\b|openjdk:(?:8|11|17|21)\b|"
                         r"mcr\.microsoft\.com/dotnet/(?:aspnet|runtime|sdk):[5-9]\.)")


def _line_of(lines, needle):
    for i, l in enumerate(lines):
        if needle in l:
            return i + 1, l
    return 1, needle


BUILD_TARGET_NOTE = " This line is a build target: the runtime that actually runs the service may be newer. Check it where it runs."


def dep_old(col, rel, ln, line, comp, found, note=None, confidence="high"):
    th = THRESH.get(comp)
    if not th or not found:
        return
    minimum = (24, 5) if comp == "node" and found[0] in (23, 24) else th[0]
    if comp == "node" and len(found) == 1 and found[0] in (22, 24):
        return  # A major-only pin can resolve to a supported minor.
    if vlt(found, minimum):
        col.add("DEP-RUNTIME-OLD", rel, ln, line, {"kind": "library", "algorithm": None, "family": None,
                                                    "parameter": ".".join(str(x) for x in found), "library": comp},
                extra={"note": note or th[1]}, confidence=confidence)


def node_range_top(spec):
    """Highest Node.js version a package.json `engines.node` range allows, or None when it has no upper end.
    '>=12' only says "12 or newer", so it tells us nothing about the version in use and is not reported."""
    tops = []
    for part in str(spec).split("||"):
        part = part.strip()
        if not part or part in ("*", "x", "X", "latest"):
            return None
        hi = re.findall(r"<=?\s*v?(\d+(?:\.\d+)*)", part)
        if hi:
            tops.append(max(vtuple(x) for x in hi))
        elif part.startswith(">"):
            return None
        else:
            m = re.search(r"\d+(?:\.\d+)*", part)
            if not m:
                return None
            tops.append(vtuple(m.group(0)))
    return max(tops) if tops else None


def dep_lib(col, rel, ln, line, name, version=None):
    a = {"kind": "library", "algorithm": None, "family": None, "parameter": version, "library": name}
    if re.search(r"(?i)post-quantum|ml-kem|ml-dsa|liboqs|pqcrypto|\boqs\b", name):
        col.add("OK-PQ-KEX", rel, ln, line, dict(PQK, kind="library", library=name))
    else:
        col.add("DEP-CRYPTO-LIB", rel, ln, line, a)


def scan_deps(col, rel, name, ext, text, lines):
    lname = name.lower()
    if re.match(r"(?:requirements|constraints)[\w.-]*\.(?:txt|in)$", lname) or lname == "pyproject.toml" or lname == "setup.cfg":
        for i, line in enumerate(lines):
            m = re.match(r"""^\s*["']?([A-Za-z0-9_.\-]+)(?:\[[^\]]*\])?\s*(?:(==|>=|~=|\^|=)\s*["']?\s*\^?([\d.]+))?""", line)
            if not m or line.strip().startswith("#"):
                continue
            pkg = m.group(1).lower()
            if pkg in PY_LIBS:
                dep_lib(col, rel, i + 1, line, pkg, m.group(3))
                if pkg == "cryptography" and m.group(3) and m.group(2) in ("==", "=", "~=", "^"):
                    dep_old(col, rel, i + 1, line, "cryptography", vtuple(m.group(3)))
        m = re.search(r"""(?m)^\s*requires-python\s*=\s*["']([^"']+)""", text)
    elif lname == "poetry.lock":
        for m in re.finditer(r'name = "cryptography"\s*\n\s*version = "([\d.]+)"', text):
            ln = text.count("\n", 0, m.start()) + 1
            dep_old(col, rel, ln, "cryptography " + m.group(1), "cryptography", vtuple(m.group(1)))
    elif lname == "package.json":
        try:
            pj = json.loads(text)
        except ValueError:
            col.nc(rel, "invalid package.json; dependency versions not checked")
            return
        if not isinstance(pj, dict):
            col.nc(rel, "package.json must contain an object")
            return
        engines = pj.get("engines")
        eng = engines.get("node") if isinstance(engines, dict) else None
        top = node_range_top(eng) if eng else None
        if top and (top[0] < 22 or re.fullmatch(r"v?\d+\.\d+\.\d+", str(eng).strip())):
            ln, l = _line_of(lines, '"node"')
            dep_old(col, rel, ln, l, "node", top)
        for sect in ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies"):
            deps = pj.get(sect, {})
            if not isinstance(deps, dict):
                col.nc(rel, "%s must contain an object" % sect)
                continue
            for dep, ver in deps.items():
                if dep in JS_LIBS:
                    ln, l = _line_of(lines, '"%s"' % dep)
                    dep_lib(col, rel, ln, l, dep, str(ver))
    elif lname in (".nvmrc", ".node-version"):
        dep_old(col, rel, 1, text.strip(), "node", vtuple(text.strip()))
    elif lname == "go.mod":
        for i, line in enumerate(lines):
            m = re.match(r"^\s*go\s+(\d+\.\d+)", line)
            if m:
                dep_old(col, rel, i + 1, line, "go", vtuple(m.group(1)))
            m = re.match(r"^\s*toolchain\s+go(\d+\.\d+)", line)
            if m:
                dep_old(col, rel, i + 1, line, "go", vtuple(m.group(1)))
            for lib in GO_LIBS:
                if lib in line and not line.strip().startswith("//"):
                    v = re.search(r"\sv([\d.]+)", line)
                    dep_lib(col, rel, i + 1, line, lib, v.group(1) if v else None)
    elif lname == "cargo.toml":
        sect = ""
        for i, line in enumerate(lines):
            s = line.strip()
            if s.startswith("["):
                sect = s
                continue
            m = re.match(r"^([A-Za-z0-9_-]+)\s*=", s)
            if m and "dependencies" in sect and m.group(1) in RS_LIBS:
                v = re.search(r'"([\d.]+)"', s)
                dep_lib(col, rel, i + 1, line, m.group(1), v.group(1) if v else None)
    elif lname == "pom.xml":
        for i, line in enumerate(lines):
            m = re.search(r"<(?:maven\.compiler\.(?:release|source|target)|java\.version|release)>\s*(?:1\.)?(\d+)\s*<", line)
            if m:
                dep_old(col, rel, i + 1, line, "java", (int(m.group(1)),), THRESH["java"][1] + BUILD_TARGET_NOTE, "medium")
            m = re.search(r"<artifactId>\s*([\w.-]+)\s*</artifactId>", line)
            if m and any(m.group(1).startswith(x) for x in JAVA_LIBS):
                ver = None
                for j in range(i, min(i + 4, len(lines))):
                    v = re.search(r"<version>\s*([\d.]+)\s*</version>", lines[j])
                    if v:
                        ver = v.group(1)
                        break
                dep_lib(col, rel, i + 1, line, m.group(1), ver)
                if m.group(1).startswith("bcprov") and ver:
                    dep_old(col, rel, i + 1, line, "bcprov", vtuple(ver))
    elif lname in ("build.gradle", "build.gradle.kts"):
        for i, line in enumerate(lines):
            m = re.search(r"(?:sourceCompatibility|targetCompatibility)\s*=\s*['\"]?(?:JavaVersion\.VERSION_)?(?:1[._])?(\d+)|"
                          r"jvmToolchain\s*\(\s*(\d+)|JavaLanguageVersion\.of\s*\(\s*(\d+)", line)
            if m:
                dep_old(col, rel, i + 1, line, "java", (int([g for g in m.groups() if g][0]),),
                        THRESH["java"][1] + BUILD_TARGET_NOTE, "medium")
            m = re.search(r"['\"]org\.bouncycastle:(bcprov[\w-]*):([\d.]+)['\"]", line)
            if m:
                dep_lib(col, rel, i + 1, line, m.group(1), m.group(2))
                dep_old(col, rel, i + 1, line, "bcprov", vtuple(m.group(2)))
    elif ext in (".csproj", ".fsproj", ".vbproj") or lname == "directory.build.props":
        for i, line in enumerate(lines):
            m = re.search(r"<TargetFrameworks?>\s*([^<]+)<", line)
            if m:
                vs = [vtuple(x.replace("net", "")) for x in re.findall(r"net(\d+\.\d+)", m.group(1))]
                if vs:
                    dep_old(col, rel, i + 1, line, "dotnet", max(vs), THRESH["dotnet"][1] + BUILD_TARGET_NOTE)
            m = re.search(r'<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?', line)
            if m and any(m.group(1).startswith(x) for x in CS_LIBS):
                dep_lib(col, rel, i + 1, line, m.group(1), m.group(2))
    elif lname in ("gemfile.lock", "composer.json", "composer.lock"):
        for i, line in enumerate(lines):
            m = re.search(r"(?:^\s{4}(jwt|rbnacl|ed25519|x25519|openssl|net-ssh)\s+\(([\d.]+)\))|\"(firebase/php-jwt|phpseclib/phpseclib|"
                          r"lcobucci/jwt|web-token/[\w-]+|paragonie/sodium_compat)\"", line)
            if m:
                dep_lib(col, rel, i + 1, line, m.group(1) or m.group(3), m.group(2))
    elif lname == ".tool-versions":
        for i, line in enumerate(lines):
            m = re.match(r"^\s*(nodejs|golang|java|dotnet)\s+\S*?(\d[\d.]*)", line)
            if m:
                comp = {"nodejs": "node", "golang": "go", "java": "java", "dotnet": "dotnet"}[m.group(1)]
                dep_old(col, rel, i + 1, line, comp, vtuple(m.group(2)))
    if lname.startswith("dockerfile") or lname.endswith(".dockerfile") or lname.startswith("containerfile"):
        for i, line in enumerate(lines):
            m = re.match(r"(?i)^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)", line)
            if m and BASE_IMAGES.search(m.group(1)):
                col.add("DEP-BASE-IMAGE", rel, i + 1, line, {"kind": "library", "algorithm": None, "family": None,
                                                              "parameter": m.group(1), "library": "base image"},
                        needs=["runtime"], extra={"note": "Likely ships OpenSSL older than 3.5: run `openssl version` inside the image."})


RUNTIME_CMDS = [
    ("openssl", ["openssl", "version"], r"OpenSSL\s+(\d+\.\d+\.\d+)"),
    ("openssh", ["ssh", "-V"], r"OpenSSH_(?:for_Windows_)?(\d+\.\d+)"),
    ("node", ["node", "-p", "process.version+' '+process.versions.openssl"], r"v(\d+\.\d+\.\d+)"),
    ("node-openssl", ["node", "-p", "process.versions.openssl"], r"(\d+\.\d+\.\d+)"),
    ("python-ssl", [sys.executable, "-I", "-c", "import ssl;print(ssl.OPENSSL_VERSION)"], r"OpenSSL\s+(\d+\.\d+\.\d+)"),
    ("go", ["go", "version"], r"go(\d+\.\d+)"),
    ("java", ["java", "-version"], r"version \"(?:1\.)?(\d+)"),
    ("dotnet", ["dotnet", "--version"], r"(\d+\.\d+)"),
    ("nginx", ["nginx", "-V"], r"built with OpenSSL (\d+\.\d+\.\d+)"),
    ("haproxy", ["haproxy", "-vv"], r"OpenSSL (\d+\.\d+\.\d+)"),
    ("apache", ["apache2", "-V"], r"Server version: (\S+)"),
]
RT_COMP = {"openssl": "openssl", "openssh": "openssh", "node-openssl": "openssl", "python-ssl": "openssl",
           "go": "go", "java": "java", "dotnet": "dotnet", "nginx": "openssl", "haproxy": "openssl"}


def installed_tool(name):
    if os.path.isabs(name):
        return name
    # A repository-local executable must not win the implicit Windows current-directory search.
    cwd = os.path.normcase(os.path.realpath(os.getcwd()))
    for directory in os.get_exec_path():
        if os.path.isabs(directory) and os.path.normcase(os.path.realpath(directory)) != cwd:
            exe = shutil.which(os.path.join(directory, name + ".exe" if os.name == "nt" else name))
            if exe:
                return exe
    raise FileNotFoundError(name)


def run_runtime_command(cmd, **kwargs):
    env = dict(os.environ, GOTOOLCHAIN="local", GOTELEMETRY="off", DOTNET_CLI_TELEMETRY_OPTOUT="1")
    with tempfile.TemporaryDirectory(prefix="pqshift-runtime-") as directory:
        return subprocess.run([installed_tool(cmd[0])] + cmd[1:], cwd=directory, env=env, **kwargs)


def scan_runtime(col):
    out = []
    for name, cmd, rx in RUNTIME_CMDS:
        try:
            p = run_runtime_command(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, stdin=subprocess.DEVNULL)
            txt = p.stdout.decode("utf-8", "replace")
        except (OSError, subprocess.SubprocessError):
            col.nc("runtime: " + name, "command not found: " + " ".join(cmd[:2]))
            continue
        m = re.search(rx, txt)
        if not m:
            col.nc("runtime: " + name, "version not recognised")
            continue
        ver = m.group(1)
        out.append({"component": name, "version": ver})
        comp = RT_COMP.get(name)
        ep = "runtime:" + name
        th = THRESH.get(comp)
        a = {"kind": "library", "algorithm": None, "family": None, "parameter": ver, "library": name}
        if th and vlt(vtuple(ver), th[0]):
            col.add("DEP-RUNTIME-OLD", None, None, "%s %s" % (name, ver), a, endpoint=ep, context="prod",
                    extra={"note": th[1]})
        else:
            col.add("DEP-CRYPTO-LIB", None, None, "%s %s" % (name, ver), a, endpoint=ep, context="prod")
    return out


# ---------------------------------------------------------------------------------------------------------------
# Walker and scan command
# ---------------------------------------------------------------------------------------------------------------

IGNORE_RX = re.compile(r"pqshift:ignore\s+([A-Z][A-Z0-9-]+)(?:\s+(.+))?")


def lang_for(name, ext, head):
    lname = name.lower()
    if ext in LANG:
        return LANG[ext]
    if lname.startswith("dockerfile") or lname.startswith("containerfile") or lname in ("makefile", "gnumakefile", "justfile",
                                                                                         "jenkinsfile", "procfile", "pre-commit"):
        return "sh"
    if lname.startswith("caddyfile") or lname.startswith("sshd_config") or lname.startswith("ssh_config") or \
            lname in ("config", "known_hosts", "authorized_keys"):
        return "conf"
    if head.startswith("#!"):
        return "py" if "python" in head.split("\n")[0] else "sh"
    if not ext:
        return "conf"
    return None


def path_is_link(path):
    if os.path.islink(path):
        return True
    if os.name == "nt":
        # Python 3.8 through 3.11 have no os.path.isjunction.
        return bool(os.lstat(path).st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT)
    return False


def load_ignore_globs(root):
    globs = []
    p = os.path.join(root, ".pqshiftignore")
    if os.path.isfile(p) and not path_is_link(p):
        with open(p, "r", encoding="utf-8", errors="replace") as fh:
            for line in fh:
                s = line.strip()
                if s and not s.startswith("#"):
                    globs.append(s)
    return globs


def glob_match(rel, globs):
    for g in globs:
        g2 = g.rstrip("/")
        if fnmatch.fnmatch(rel, g2) or fnmatch.fnmatch(rel, g2 + "/*") or fnmatch.fnmatch(rel, "*/" + g2) or \
                fnmatch.fnmatch(rel, "*/" + g2 + "/*") or rel.startswith(g2.replace("**", "").rstrip("/*") + "/") and "*" in g2:
            return True
    return False


def iter_files(root, opts):
    if path_is_link(root):
        raise UsageError("scan root %s is a link or junction; name the intended directory or file explicitly" % root)
    ignore = load_ignore_globs(root) if os.path.isdir(root) else []
    if ignore:
        opts.setdefault("_ignore_files", {})[root] = ignore
    excl = list(opts.get("exclude") or []) + ignore
    vend = opts.get("include_vendored")
    built = opts.get("include_build")
    skipped = opts.setdefault("_skipped", {})     # folder name -> how many were skipped, reported under not_checked
    if os.path.isfile(root):
        yield os.path.basename(root), root
        return
    base_depth = os.path.abspath(root).rstrip("\\/").count(os.sep)
    if not os.path.isdir(root):
        raise UsageError("scan root %s is not a regular file or directory" % root)

    def walk_error(ex):
        opts.setdefault("_walk_errors", []).append({"path": ex.filename, "error": ex.strerror})

    for dp, dns, fns in os.walk(root, topdown=True, followlinks=False, onerror=walk_error):
        keep = []
        too_deep = os.path.abspath(dp).count(os.sep) - base_depth >= MAX_DEPTH
        for d in dns:
            full = os.path.join(dp, d)
            if path_is_link(full):
                skipped["symbolic links"] = skipped.get("symbolic links", 0) + 1
                continue
            if d == ".git":
                continue
            if too_deep:
                skipped["folders deeper than %d levels" % MAX_DEPTH] = skipped.get("folders deeper than %d levels" % MAX_DEPTH, 0) + 1
                continue
            if d in SKIP_DIRS and not (vend and d in VENDOR_DIRS) and not (built and d in BUILD_DIRS):
                if d in VENDOR_DIRS or d in BUILD_DIRS:
                    skipped[d] = skipped.get(d, 0) + 1
                continue
            reld = os.path.relpath(full, root).replace("\\", "/")
            if excl and glob_match(reld, excl):
                continue
            keep.append(d)
        dns[:] = sorted(keep)
        for fn in sorted(fns):
            full = os.path.join(dp, fn)
            if path_is_link(full):
                skipped["symbolic links"] = skipped.get("symbolic links", 0) + 1
                continue
            rel = os.path.relpath(full, root).replace("\\", "/")
            if excl and glob_match(rel, excl):
                continue
            yield rel, full


def decode_text(data):
    """Bytes -> text for the common encodings. Returns None for binary data.
    Handles UTF-8 (with or without a byte-order mark) and UTF-16, which Windows tools such as PowerShell
    still write. Line endings are normalised so CRLF files give the same line numbers and matches."""
    if data[:3] == b"\xef\xbb\xbf":
        text = data[3:].decode("utf-8", "replace")
    elif data[:2] in (b"\xff\xfe", b"\xfe\xff"):
        try:
            text = data.decode("utf-16")
        except UnicodeDecodeError:
            return None
    else:
        head = data[:4096]
        if b"\x00" in head:
            # UTF-16 without a byte-order mark: every other byte is zero for ASCII-range text.
            even, odd = head[0::2].count(b"\x00"), head[1::2].count(b"\x00")
            half = max(1, len(head) // 2)
            if odd > half * 0.6 and even < half * 0.05:
                enc = "utf-16-le"
            elif even > half * 0.6 and odd < half * 0.05:
                enc = "utf-16-be"
            else:
                return None
            try:
                text = data.decode(enc)
            except UnicodeDecodeError:
                return None
        else:
            text = data.decode("utf-8", "replace")
    if "\r" in text:
        text = text.replace("\r\n", "\n").replace("\r", "\n")
    return text


def is_own_file(lname, head):
    """True for PQ Shift itself and the files it writes (findings, CBOM, SARIF, policy, rule and support lists).
    They are full of algorithm names, so scanning them would bury the real inventory and break before/after diffs."""
    if lname == "pqshift.py":
        return b"PQ Shift" in head and b"zirkomirko.com/tools/pq-shift" in head
    if lname.endswith((".json", ".sarif")):
        if b'"tool": "pqshift"' in head or b'"schema": "pqshift.' in head:
            return True
        if b'"CycloneDX"' in head and b'"name": "pqshift"' in head:
            return True
        if b'"name": "PQ Shift"' in head and b'"runs"' in head:
            return True
        if lname == "support.json" and b'"hybrid_kex"' in head:
            return True
        if lname == "rules.json" and b'"exposure"' in head and b'"severity"' in head:
            return True
    return False


def scan_file(col, rel, full, opts, data=None):
    name = os.path.basename(rel)
    lname = name.lower()
    ext = os.path.splitext(lname)[1]
    if ext in (".gz", ".zip", ".tar", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".woff", ".woff2", ".ttf",
               ".mp4", ".mp3", ".wasm", ".exe", ".dll", ".so", ".dylib", ".class", ".jar", ".pyc", ".lock") and \
            lname not in ("poetry.lock", "cargo.lock", "gemfile.lock", "composer.lock"):
        return False
    try:
        limit = opts.get("max_size", 2 * 1024 * 1024)
        if data is None:
            info = os.stat(full, follow_symlinks=False)
            if not stat.S_ISREG(info.st_mode):
                col.nc(rel, "not a regular file")
                return False
            if info.st_size > limit:
                col.nc(rel, "larger than --max-file-size")
                return False
            with open(full, "rb") as fh:
                data = fh.read(limit + 1)
        if len(data) > limit:
            col.nc(rel, "larger than --max-file-size")
            return False
    except OSError as ex:
        col.errors.append({"path": rel, "error": str(ex)})
        return False
    if is_own_file(lname, data[:1500]):
        opts.setdefault("_own", []).append(rel)
        return False
    only = opts.get("only")
    keyish = ext in KEY_EXT or lname in KEY_NAMES or lname.startswith("ssh_host_") or data[:11] == b"-----BEGIN "
    text = decode_text(data)
    binary = text is None
    if keyish:
        if only and "keys" not in only:
            return True
        if binary or (ext in (".der", ".cer", ".p12", ".pfx", ".jks", ".keystore") and not text.lstrip().startswith("-----")):
            scan_binary_key(col, rel, data, ext)
            return True
        if text.startswith("PuTTY-User-Key-File"):
            typ = text.split("\n", 1)[0].split(":", 1)[1].strip()
            key_findings(col, rel, 1, None, {"algorithm": typ, "family": "RSA" if "rsa" in typ else "ECC"}, "PuTTY key " + typ)
            return True
        if "-----BEGIN" in text:
            scan_pem(col, rel, text)
        scan_ssh_pub(col, rel, text)
        if ext in (".pem", ".crt", ".cer", ".key", ".pub", ".csr", ".params", ".dh") or lname in KEY_NAMES or lname.startswith("ssh_host_"):
            return True
    if binary:
        return False
    if ext in DOC_EXT:
        if "-----BEGIN" in text and (not only or "keys" in only):
            scan_pem(col, rel, text)
        if re.match(r"(?:requirements|constraints)[\w.-]*\.(?:txt|in)$", lname) and (not only or "deps" in only):
            scan_deps(col, rel, name, ext, text, text.split("\n"))
        return True
    head = text[:200]
    lang = lang_for(name, ext, head)
    if lang is None:
        return False
    lines = text.split("\n")
    for i, line in enumerate(lines):
        if "pqshift:ignore" in line:
            m = IGNORE_RX.search(line)
            if m:
                if not (m.group(2) or "").strip():
                    col.errors.append({"path": rel, "line": i + 1, "error": "pqshift:ignore needs a reason; not honoured"})
                else:
                    col.ignores.setdefault(rel, []).append((i + 1, m.group(1), m.group(2).strip()))
    if not only or "code" in only:
        scan_text_lines(col, rel, lines, lang, opts, lowered(text, opts))
    # Server-config readers look at the shape of a file (a line starting with HostKey, ssl_protocols ...). Source
    # code can have the same shape by accident (`hostkey = None`), so they are not run on programming languages.
    if (not only or "config" in only) and lang not in CODE_LANGS:
        for fn, kw in detect_configs(rel, name, ext, text):
            fn(col, rel, lines, text, **kw)
    if not only or "deps" in only:
        scan_deps(col, rel, name, ext, text, lines)
    if "-----BEGIN" in text and (not only or "keys" in only):
        scan_pem(col, rel, text)
    return True


def run_scan(paths, opts):
    t0 = time.time()
    root = paths[0] if len(paths) == 1 else "."
    col = Collector(root.replace("\\", "/"), opts.get("horizon") or DEFAULT_HORIZON)
    scanned = skipped = 0
    for p in paths:
        base = p if os.path.isdir(p) else os.path.dirname(p) or "."
        for rel, full in iter_files(p, opts):
            if len(paths) > 1:
                rel = os.path.relpath(full, ".").replace("\\", "/")
            if scan_file(col, rel, full, opts):
                scanned += 1
            else:
                skipped += 1
    runtime = None
    if opts.get("runtime"):
        runtime = scan_runtime(col)
    sk = opts.get("_skipped") or {}
    vend = sorted((k, v) for k, v in sk.items() if k in VENDOR_DIRS)
    bld = sorted((k, v) for k, v in sk.items() if k in BUILD_DIRS)
    if vend:
        col.nc("third-party folders: " + ", ".join("%s (%d)" % kv for kv in vend),
               "skipped by default; add --include-vendored to scan the libraries you ship")
    if bld:
        col.nc("build output folders: " + ", ".join("%s (%d)" % kv for kv in bld),
               "skipped by default; add --include-build if what you deploy is only in these folders")
    own = opts.get("_own") or []
    if own:
        col.nc("PQ Shift's own files (%d): %s%s" % (len(own), ", ".join(own[:4]), " ..." if len(own) > 4 else ""),
               "the tool, its rule lists and its earlier output are not part of your system")
    for k, v in sorted(sk.items()):
        if k not in VENDOR_DIRS and k not in BUILD_DIRS:
            col.nc("%s (%d)" % (k, v), "not followed, so a loop or a link out of the project cannot be scanned by accident")
    col.nc("symmetric ciphers and hash functions", "out of scope: post-quantum migration concerns public-key cryptography")
    # drop comment-context findings unless asked; drop context-only duplicates
    scope = {"paths": sorted(os.path.normpath(p).replace("\\", "/") for p in paths),
             "only": sorted(opts.get("only") or []), "exclude": sorted(opts.get("exclude") or []),
             "ignore_files": opts.get("_ignore_files", {}),
             "max_size": opts.get("max_size", 2 * 1024 * 1024), "horizon": col.horizon}
    for key in ("runtime", "include_vendored", "include_build", "include_comments"):
        scope[key] = bool(opts.get(key))
    col.errors.extend(opts.get("_walk_errors", []))
    res = summarize(col, scanned, skipped, time.time() - t0, "scan", {"scope": scope})
    if runtime is not None:
        res["runtime"] = runtime
    if opts.get("baseline"):
        baseline = read_json(opts["baseline"], "baseline file")
        if not isinstance(baseline, dict) or not isinstance(baseline.get("findings"), list) or not all(
                isinstance(f, dict) and isinstance(f.get("id"), str) for f in baseline["findings"]):
            raise UsageError("baseline must be a scan findings JSON file")
        base_ids = {f["id"] for f in baseline["findings"]}
        kept = [f for f in res["findings"] if f["id"] not in base_ids]
        res["baseline_removed"] = len(res["findings"]) - len(kept)
        res["findings"] = kept
        res = resummarize(res)
    return res


def resummarize(res):
    bys = dict((s, 0) for s in SEVERITIES)
    bye = {}
    pq = 0
    for f in res["findings"]:
        bys[f["severity"]] += 1
        bye[f["exposure"]] = bye.get(f["exposure"], 0) + 1
        if f["rule"].startswith("OK-") or f["rule"] == "PQ-ONLY":
            pq += 1
    res["summary"]["by_severity"] = bys
    res["summary"]["by_exposure"] = bye
    res["summary"]["pq_present"] = pq
    return res


def write_json(obj, dest):
    txt = json.dumps(obj, indent=2, ensure_ascii=False)
    if dest == "-":
        sys.stdout.write(txt + "\n")
    else:
        write_text(dest, txt + "\n")


def write_text(dest, txt):
    try:
        d = os.path.dirname(dest)
        if d and not os.path.isdir(d):
            os.makedirs(d)
        with open(dest, "w", encoding="utf-8", newline="\n") as fh:
            fh.write(txt)
    except OSError as ex:
        raise UsageError("cannot write %s: %s" % (dest, ex.strerror or ex))


# ---------------------------------------------------------------------------------------------------------------
# SARIF 2.1.0 (OASIS). The format GitHub code scanning, GitLab, Azure DevOps and most code-review tools read.
# ---------------------------------------------------------------------------------------------------------------

SARIF_LEVEL = {"critical": "error", "high": "error", "medium": "warning", "low": "note", "info": "none"}


def to_sarif(findings, command="scan"):
    used = []
    for f in findings:
        if f["rule"] in RULES and f["rule"] not in used:
            used.append(f["rule"])
    used.sort()
    rules = []
    for rid in used:
        r = RULES[rid]
        text = r["why"] + (" Replace with: " + r["replace"] if r["replace"] else "")
        rule = {"id": rid, "name": "".join(w.capitalize() for w in rid.split("-")),
                "shortDescription": {"text": r["title"]},
                "fullDescription": {"text": r["why"]},
                "help": {"text": text + " " + FOOTER},
                "helpUri": HOME + (r["recipe"] or "#s6"),
                "defaultConfiguration": {"level": SARIF_LEVEL[r["severity"]]},
                "properties": {"tags": ["security", "cryptography", "post-quantum", r["category"]],
                               "pqshift:severity": r["severity"], "pqshift:exposure": r["exposure"]}}
        rules.append(rule)
    results = []
    for f in findings:
        if f["rule"] not in RULES:
            continue
        loc = f.get("location") or {}
        positive = f["rule"].startswith("OK-") or f["rule"] == "PQ-ONLY"
        res = {"ruleId": f["rule"], "ruleIndex": used.index(f["rule"]),
               "kind": "pass" if positive else ("informational" if f["severity"] == "info" else "fail"),
               "level": "none" if positive else SARIF_LEVEL[f["severity"]],
               "message": {"text": "%s: %s" % (f.get("title") or RULES[f["rule"]]["title"], f.get("evidence") or "")},
               "properties": {"pqshift:severity": f["severity"], "pqshift:exposure": f.get("exposure"),
                              "pqshift:confidence": f.get("confidence"), "pqshift:context": f.get("context")}}
        if f.get("id"):
            res["partialFingerprints"] = {"pqshiftFindingId/v1": f["id"]}
        if loc.get("path"):
            phys = {"artifactLocation": {"uri": _uri(loc["path"]), "uriBaseId": "%SRCROOT%"}}
            if loc.get("line"):
                phys["region"] = {"startLine": int(loc["line"])}
            res["locations"] = [{"physicalLocation": phys}]
        elif loc.get("endpoint"):
            res["locations"] = [{"logicalLocations": [{"name": loc["endpoint"], "kind": "resource"}]}]
        results.append(res)
    return {"$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json",
            "version": "2.1.0",
            "runs": [{"tool": {"driver": {"name": "PQ Shift", "version": VERSION, "semanticVersion": VERSION,
                                          "informationUri": HOME, "rules": rules}},
                      "automationDetails": {"id": "pqshift/" + command},
                      "results": results}]}


def _uri(path):
    from urllib.parse import quote
    return quote(path.replace("\\", "/"), safe="/")


def sev_at_least(sev, floor):
    return SEVERITIES.index(sev) <= SEVERITIES.index(floor)


# ---------------------------------------------------------------------------------------------------------------
# probe: live endpoints. TLS: a ClientHello with an empty key_share makes a TLS 1.3 server name the group it
# selects in a HelloRetryRequest (RFC 8446 4.1.4, 4.2.8). No post-quantum maths needed on our side.
# ---------------------------------------------------------------------------------------------------------------

GROUPS = {0x11EC: "X25519MLKEM768", 0x11EB: "SecP256r1MLKEM768", 0x11ED: "SecP384r1MLKEM1024", 0x001D: "x25519",
          0x0017: "secp256r1", 0x0018: "secp384r1", 0x0019: "secp521r1", 0x001E: "x448", 0x0100: "ffdhe2048",
          0x0101: "ffdhe3072", 0x0200: "MLKEM512", 0x0201: "MLKEM768", 0x0202: "MLKEM1024", 0x6399: "X25519Kyber768Draft00"}
HYBRIDS = (0x11EC, 0x11EB, 0x11ED)
HRR_RANDOM = binascii.unhexlify("cf21ad74e59a6111be1d8c021e65b891c2a211167abb8c5e079e09e2c8a8339c")
SUITES12 = [0xC02B, 0xC02F, 0xC02C, 0xC030, 0xCCA9, 0xCCA8, 0x009E, 0x009F, 0x009C, 0x009D, 0x002F, 0x0035, 0x003C, 0x003D, 0x00FF]
SUITE_NAMES = {0xC02B: "ECDHE-ECDSA-AES128-GCM-SHA256", 0xC02F: "ECDHE-RSA-AES128-GCM-SHA256", 0xC02C: "ECDHE-ECDSA-AES256-GCM-SHA384",
               0xC030: "ECDHE-RSA-AES256-GCM-SHA384", 0xCCA9: "ECDHE-ECDSA-CHACHA20-POLY1305", 0xCCA8: "ECDHE-RSA-CHACHA20-POLY1305",
               0x009E: "DHE-RSA-AES128-GCM-SHA256", 0x009F: "DHE-RSA-AES256-GCM-SHA384", 0x009C: "AES128-GCM-SHA256",
               0x009D: "AES256-GCM-SHA384", 0x002F: "AES128-SHA", 0x0035: "AES256-SHA", 0x003C: "AES128-SHA256",
               0x003D: "AES256-SHA256", 0x1301: "TLS_AES_128_GCM_SHA256", 0x1302: "TLS_AES_256_GCM_SHA384",
               0x1303: "TLS_CHACHA20_POLY1305_SHA256"}


def suite_kex(code):
    if code in (0xC02B, 0xC02F, 0xC02C, 0xC030, 0xCCA9, 0xCCA8):
        return "ECDHE"
    if code in (0x009E, 0x009F):
        return "DHE"
    if code in (0x009C, 0x009D, 0x002F, 0x0035, 0x003C, 0x003D):
        return "RSA"
    return "TLS1.3"


def _u16(n):
    return struct.pack(">H", n)


def _ext(t, data):
    return _u16(t) + _u16(len(data)) + data


def client_hello(sni, groups, tls13=True, suites=None):
    rnd = os.urandom(32)
    sid = os.urandom(32)
    suites = suites or ([0x1301, 0x1302, 0x1303] if tls13 else SUITES12)
    ext = b""
    if sni and ":" not in sni and not re.fullmatch(r"[\d.]+", sni):
        name = sni.encode("idna")
        entry = b"\x00" + _u16(len(name)) + name
        ext += _ext(0x0000, _u16(len(entry)) + entry)
    if tls13:
        ext += _ext(0x002B, b"\x02\x03\x04")
    g = b"".join(_u16(x) for x in groups)
    ext += _ext(0x000A, _u16(len(g)) + g)
    sa = b"".join(_u16(x) for x in [0x0403, 0x0804, 0x0401, 0x0503, 0x0805, 0x0806, 0x0807, 0x0501, 0x0601, 0x0201])
    ext += _ext(0x000D, _u16(len(sa)) + sa)
    if tls13:
        ext += _ext(0x0033, b"\x00\x00")
        ext += _ext(0x002D, b"\x01\x01")
    else:
        ext += _ext(0x000B, b"\x01\x00") + _ext(0x0017, b"") + _ext(0xFF01, b"\x00")
    cs = b"".join(_u16(x) for x in suites)
    body = b"\x03\x03" + rnd + bytes([len(sid)]) + sid + _u16(len(cs)) + cs + b"\x01\x00" + _u16(len(ext)) + ext
    hs = b"\x01" + struct.pack(">I", len(body))[1:] + body
    return b"\x16\x03\x01" + _u16(len(hs)) + hs


def _recv_exact(sock, n):
    buf = b""
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            raise ConnectionError("connection closed")
        buf += chunk
    return buf


def parse_server_hello(body):
    """Return dict for a ServerHello / HelloRetryRequest body."""
    i = 2
    rnd = body[i:i + 32]
    i += 32
    sl = body[i]
    i += 1 + sl
    suite = struct.unpack(">H", body[i:i + 2])[0]
    i += 3
    out = {"hrr": rnd == HRR_RANDOM, "suite": suite, "version": 0x0303, "group": None}
    if i + 2 <= len(body):
        el = struct.unpack(">H", body[i:i + 2])[0]
        i += 2
        end = i + el
        while i + 4 <= end:
            t, l = struct.unpack(">HH", body[i:i + 4])
            d = body[i + 4:i + 4 + l]
            if t == 0x002B and l >= 2:
                out["version"] = struct.unpack(">H", d[:2])[0]
            if t == 0x0033 and l >= 2:
                out["group"] = struct.unpack(">H", d[:2])[0]
            i += 4 + l
    return out


def tls_try(host, port, sni, groups, timeout, tls13=True, suites=None):
    """One connection. Returns {'kind': 'hrr'|'sh13'|'sh12'|'alert'|'error', ...}."""
    try:
        sock = socket.create_connection((host, port), timeout=timeout)
    except (OSError, socket.timeout) as ex:
        return {"kind": "error", "error": "connect: %s" % ex}
    try:
        sock.settimeout(timeout)
        sock.sendall(client_hello(sni, groups, tls13, suites))
        buf = b""
        for _ in range(8):
            hdr = _recv_exact(sock, 5)
            ctype, _ver, ln = hdr[0], hdr[1:3], struct.unpack(">H", hdr[3:5])[0]
            if ln > 1 << 15:
                return {"kind": "error", "error": "record too long"}
            rec = _recv_exact(sock, ln)
            if ctype == 21:
                return {"kind": "alert", "level": rec[0], "alert": rec[1] if len(rec) > 1 else None}
            if ctype == 20:
                continue
            if ctype != 22:
                return {"kind": "error", "error": "unexpected record type %d" % ctype}
            buf += rec
            if len(buf) >= 4:
                mt = buf[0]
                ml = struct.unpack(">I", b"\x00" + buf[1:4])[0]
                if len(buf) >= 4 + ml:
                    if mt != 2:
                        return {"kind": "error", "error": "unexpected handshake type %d" % mt}
                    sh = parse_server_hello(buf[4:4 + ml])
                    if sh["hrr"]:
                        sh["kind"] = "hrr"
                    else:
                        sh["kind"] = "sh13" if sh["version"] == 0x0304 else "sh12"
                    return sh
        return {"kind": "error", "error": "no ServerHello"}
    except (OSError, ValueError, UnicodeError, struct.error, IndexError) as ex:
        return {"kind": "error", "error": str(ex) or ex.__class__.__name__}
    finally:
        try:
            sock.close()
        except OSError:
            pass


def fetch_cert(host, port, sni, timeout):
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE  # inspection only: we read the certificate, we do not trust it
    try:
        with socket.create_connection((host, port), timeout=timeout) as s:
            with ctx.wrap_socket(s, server_hostname=sni if sni and ":" not in sni and not re.fullmatch(r"[\d.]+", sni) else None) as t:
                der = t.getpeercert(binary_form=True)
                return parse_cert(der) if der else None
    except Exception as ex:
        return {"error": str(ex)}


def _tool_version(cmd, rx):
    try:
        p = run_runtime_command(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, stdin=subprocess.DEVNULL)
        m = re.search(rx, p.stdout.decode("utf-8", "replace"))
        return m.group(1) if m else None
    except (OSError, subprocess.SubprocessError):
        return None


NODE_CONFIRM = r"""
const tls=require('tls');const [h,p,s]=process.argv.slice(1);
const c=tls.connect({host:h,port:+p,servername:s||undefined,ecdhCurve:'X25519MLKEM768',rejectUnauthorized:false,
 minVersion:'TLSv1.3'},()=>{console.log('OK '+c.getProtocol()+' '+process.versions.openssl);c.end();});
c.setTimeout(8000,()=>{console.log('ERR timeout');c.destroy();});
c.on('error',e=>{console.log('ERR '+(e.code||e.message));});
"""


def confirm_handshake(host, port, sni):
    nv = _tool_version(["node", "-p", "process.versions.openssl"], r"(\d+\.\d+\.\d+)")
    if nv and not vlt(vtuple(nv), (3, 5)):
        try:
            sn = "" if not sni or ":" in sni or re.fullmatch(r"[\d.]+", sni) else sni
            p = run_runtime_command(["node", "-e", NODE_CONFIRM, host, str(port), sn], stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE, timeout=15, stdin=subprocess.DEVNULL)
            out = p.stdout.decode("utf-8", "replace").strip()
        except (OSError, subprocess.SubprocessError) as ex:
            return {"done": False, "reason": "node failed: %s" % ex}
        if out.startswith("OK"):
            return {"done": True, "via": "node %s / OpenSSL %s, hybrid-only offer (X25519MLKEM768)" % (
                _tool_version(["node", "--version"], r"v([\d.]+)") or "?", nv)}
        return {"done": False, "reason": "hybrid-only handshake failed: " + out[:80]}
    ov = _tool_version(["openssl", "version"], r"OpenSSL\s+(\d+\.\d+\.\d+)")
    if ov and not vlt(vtuple(ov), (3, 5)):
        try:
            address = ("[%s]:%d" if ":" in host else "%s:%d") % (host, port)
            servername = ["-servername", sni] if sni and ":" not in sni and not re.fullmatch(r"[\d.]+", sni) else ["-noservername"]
            p = run_runtime_command(["openssl", "s_client", "-connect", address] + servername +
                               ["-tls1_3", "-groups", "X25519MLKEM768", "-brief"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                               timeout=15, input=b"")
            out = p.stdout.decode("utf-8", "replace")
        except (OSError, subprocess.SubprocessError) as ex:
            return {"done": False, "reason": "openssl failed: %s" % ex}
        if p.returncode == 0 and re.search(r"(?m)^Protocol version: TLSv1\.3\s*$", out):
            return {"done": True, "via": "openssl %s s_client -groups X25519MLKEM768" % ov}
        return {"done": False, "reason": "hybrid-only handshake failed"}
    return {"done": False, "attempted": False, "reason": "no OpenSSL 3.5+ found (node or openssl); selection shown by HelloRetryRequest only"}


def ssh_probe(host, port, timeout):
    try:
        sock = socket.create_connection((host, port), timeout=timeout)
    except OSError as ex:
        return {"error": "connect: %s" % ex}
    try:
        sock.settimeout(timeout)
        banner = b""
        total = 0
        while True:
            line = b""
            while not line.endswith(b"\n"):
                c = sock.recv(1)
                if not c:
                    raise ConnectionError("closed")
                line += c
                total += 1
                if total > 8192:
                    raise ConnectionError("banner too long")
            if line.startswith(b"SSH-"):
                banner = line.strip()
                break
        sock.sendall(b"SSH-2.0-pqshift_1.0\r\n")
        plen = struct.unpack(">I", _recv_exact(sock, 4))[0]
        if plen > 256 * 1024:
            raise ConnectionError("packet too long")
        pkt = _recv_exact(sock, plen)
        pad = pkt[0]
        payload = pkt[1:plen - pad]
        if payload[0] != 20:
            raise ConnectionError("expected KEXINIT")
        i = 17
        lists = []
        for _ in range(10):
            n = struct.unpack(">I", payload[i:i + 4])[0]
            lists.append(payload[i + 4:i + 4 + n].decode("ascii", "replace").split(","))
            i += 4 + n
        return {"banner": banner.decode("ascii", "replace"), "kex": lists[0], "hostkey": lists[1]}
    except (OSError, ConnectionError, struct.error, IndexError) as ex:
        return {"error": str(ex) or ex.__class__.__name__}
    finally:
        try:
            sock.close()
        except OSError:
            pass


def is_private_target(host):
    """(private, first_ip). private is None when the name does not resolve."""
    import ipaddress
    try:
        infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
    except (OSError, UnicodeError):
        return None, None
    ranges = tuple(ipaddress.ip_network(cidr) for cidr in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"))
    ips = []
    local = True
    for _, _, _, _, addr in infos:
        ip = addr[0]
        a = ipaddress.ip_address(ip.split("%")[0])
        if len(addr) == 4 and addr[3] and "%" not in ip:
            ip += "%%%d" % addr[3]
        ips.append(ip)
        if not (a.is_loopback or any(a in net for net in ranges)):
            local = False
    return (local, ips[0]) if ips else (None, None)


def split_target(t, mode=None):
    """'host', 'host:port', '[v6]:port', 'https://host/path' or 'ssh://host' -> (host, port, protocol)."""
    raw = t.strip()
    t = raw
    scheme = None
    m = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*)://", t)
    if m:
        scheme = m.group(1).lower()
        t = t[m.end():]
        if scheme not in ("https", "ssh", "tls", "wss"):
            raise UsageError("probe: %s is not a TLS or SSH address. Give host[:port], for example example.com:443" % raw)
    t = t.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0]
    if "@" in t:
        t = t.rsplit("@", 1)[1]
    port = None
    if t.startswith("["):
        host, bracket, rest = t[1:].partition("]")
        if not bracket or (rest and not re.fullmatch(r":[0-9]+", rest)):
            raise UsageError("probe: invalid bracketed address; use [IPv6]:port")
        ptxt = rest[1:]
    elif t.count(":") == 1:
        host, ptxt = t.split(":")
    else:
        host, ptxt = t, ""           # a bare IPv6 address has several colons and no port
    if ptxt:
        if not re.fullmatch(r"[0-9]{1,5}", ptxt) or not 0 < int(ptxt) < 65536:
            raise UsageError("probe: %r is not a port number in %s. Give host[:port], for example example.com:443" % (ptxt, raw))
        port = int(ptxt)
    if not host or re.search(r"\s", host):
        raise UsageError("probe: cannot read a host name from %r. Give host[:port], for example example.com:443" % raw)
    proto = mode or ("ssh" if scheme == "ssh" or (scheme is None and port == 22) else "tls")
    if port is None:
        port = 22 if proto == "ssh" else 443
    return host, port, proto


def probe_endpoint(col, target, opts, ip):
    host, port, proto = split_target(target, opts.get("mode"))
    timeout = opts.get("timeout", 8)
    delay = opts.get("delay", 0.5)
    sni = opts.get("sni") or host
    ep = ("[%s]:%d" if ":" in host else "%s:%d") % (host, port)
    res = {"endpoint": ep, "ip": ip, "sni": sni if proto == "tls" else None, "protocol": proto}
    if ip is None:
        res["error"] = "the name %s does not resolve to an address. Check the spelling and your DNS." % host
        col.errors.append({"endpoint": ep, "error": res["error"]})
        return res
    if proto == "ssh":
        r = ssh_probe(ip, port, timeout)
        res["connections_used"] = 1
        if "error" in r:
            res["error"] = r["error"]
            col.errors.append({"endpoint": ep, "error": r["error"]})
            return res
        res.update(banner=r["banner"], kex_algorithms=r["kex"], server_host_key_algorithms=r["hostkey"])
        pq = [k for k in r["kex"] if k in PQ_SSH]
        res["pq"] = {"offered": pq, "first": r["kex"][0] if r["kex"] else None, "preferred": bool(r["kex"]) and r["kex"][0] in pq}
        if pq:
            col.add("OK-PQ-KEX", None, None, "SSH kex offers " + ",".join(pq), dict(PQK, kind="protocol", algorithm=pq[0]), endpoint=ep)
        else:
            col.add("KEX-ENDPOINT-SSH-NO-PQ", None, None, "SSH kex: " + ",".join(r["kex"][:4]), _a("ECDH", "ECC", "key-agree", "kex", "protocol"),
                    endpoint=ep)
        if any("kyber" in k for k in r["kex"]):
            col.add("OBS-PQ-DRAFT", None, None, "SSH kex offers a Kyber draft", None, endpoint=ep)
        if any(k in ("diffie-hellman-group1-sha1",) for k in r["kex"]):
            col.add("WEAK-DH-SMALL", None, None, "SSH kex offers diffie-hellman-group1-sha1", None, endpoint=ep)
        if any(k in ("ssh-rsa", "ssh-dss") for k in r["hostkey"]):
            col.add("WEAK-SIG-SHA1", None, None, "SSH host key algorithms include ssh-rsa/ssh-dss (SHA-1)", None, endpoint=ep)
        return res
    used = 0

    def attempt(groups, tls13=True, suites=None):
        r = tls_try(ip, port, sni, groups, timeout, tls13, suites)
        time.sleep(delay)
        return r

    r1 = attempt([0x11EC, 0x11EB, 0x11ED, 0x001D, 0x0017, 0x0018])
    used += 1
    res["tls13"] = r1["kind"] in ("hrr", "sh13")
    pq = {"selected_for_pq_client": None, "code": None, "method": "HelloRetryRequest", "supported_hybrids": [], "preferred": False}
    if r1["kind"] == "error":
        res["connections_used"] = used
        res["error"] = r1["error"]
        col.errors.append({"endpoint": ep, "error": r1["error"]})
        return res
    if r1["kind"] == "hrr" and r1["group"] in HYBRIDS:
        pq.update(selected_for_pq_client=GROUPS[r1["group"]], code="0x%04X" % r1["group"], supported_hybrids=[GROUPS[r1["group"]]],
                  preferred=True)
    else:
        r2 = attempt([0x11EC, 0x11EB, 0x11ED])
        used += 1
        if r1["kind"] == "hrr":
            pq["selected_for_pq_client"] = GROUPS.get(r1["group"], "0x%04X" % (r1["group"] or 0))
            pq["code"] = "0x%04X" % (r1["group"] or 0)
        if r2["kind"] == "hrr" and r2["group"] in HYBRIDS:
            res["tls13"] = True
            pq["supported_hybrids"] = [GROUPS[r2["group"]]]
    res["pq"] = pq
    r3 = attempt([0x001D, 0x0017, 0x0018])
    used += 1
    res["classic"] = {"accepted": r3["kind"] in ("hrr", "sh13", "sh12"),
                      "selected": GROUPS.get(r3.get("group"), None) if r3["kind"] == "hrr" else None}
    r4 = attempt([0x001D, 0x0017, 0x0018], tls13=False)
    used += 1
    t12 = {"accepted": r4["kind"] == "sh12", "suite": None, "kex": None, "static_rsa": None}
    if r4["kind"] == "sh12":
        t12["suite"] = SUITE_NAMES.get(r4["suite"], "0x%04X" % r4["suite"])
        t12["kex"] = suite_kex(r4["suite"])
    res["tls12"] = t12
    if opts.get("deep"):
        r6 = attempt([0x001D, 0x0017], tls13=False, suites=[0x009C, 0x009D, 0x002F, 0x0035, 0x00FF])
        used += 1
        t12["static_rsa"] = r6["kind"] == "sh12"
        r7 = attempt([0x0201, 0x0202])
        used += 1
        res["pure_mlkem"] = GROUPS.get(r7.get("group")) if r7["kind"] == "hrr" else None
        if used + 1 + bool(opts.get("confirm")) < 8:
            r8 = attempt([0x6399])
            used += 1
            res["draft_kyber"] = r8["kind"] == "hrr" and r8.get("group") == 0x6399
        else:
            col.nc(ep + " draft Kyber", "connection reserved for the requested handshake confirmation")
    cert = fetch_cert(ip, port, sni, timeout)
    used += 1
    if cert and "error" not in cert:
        k = cert["key"]
        res["certificate"] = {"subject": cert.get("subject"), "issuer": cert.get("issuer"), "sig_alg": cert.get("sig_alg"),
                              "key": k.get("algorithm"), "not_after": cert.get("not_after"), "sha256": cert.get("sha256")}
    elif cert:
        res["certificate"] = {"error": cert["error"]}
    if opts.get("confirm"):
        time.sleep(delay)
        res["handshake_confirmed"] = confirm_handshake(ip, port, sni)
        used += int(res["handshake_confirmed"].get("attempted", True))
    else:
        res["handshake_confirmed"] = {"done": False, "reason": "not requested (--confirm-handshake)"}
    res["connections_used"] = used
    # findings
    tlsasset = _a("ECDH", "ECC", "key-agree", "kex", "protocol")
    if pq["supported_hybrids"] and pq["preferred"]:
        col.add("OK-PQ-KEX", None, None, "selects %s for a client that offers it" % pq["selected_for_pq_client"],
                dict(PQK, kind="protocol", algorithm=pq["selected_for_pq_client"]), endpoint=ep)
    elif pq["supported_hybrids"] and pq["selected_for_pq_client"]:
        col.add("KEX-ENDPOINT-NOT-PREFERRED", None, None, "hybrid %s supported, but %s chosen when both are offered" % (
            pq["supported_hybrids"][0], pq["selected_for_pq_client"]), tlsasset, endpoint=ep)
    elif not pq["supported_hybrids"] and r2["kind"] == "alert" and (
            pq["selected_for_pq_client"] or (r1.get("alert") == 70 and t12["accepted"])):
        why = "classic exchange observed; the hybrid-only offer received TLS alert %s" % r2.get("alert")
        col.add("KEX-ENDPOINT-NO-PQ", None, None, why, tlsasset, endpoint=ep)
    else:
        reason = "TLS responses did not establish hybrid preference or rejection"
        res["pq"]["inconclusive"] = reason
        col.nc(ep, reason)
    if t12["accepted"]:
        col.add("ENDPOINT-TLS12", None, None, "TLS 1.2 accepted (%s)" % t12["suite"], tlsasset, endpoint=ep)
        if t12["kex"] == "RSA" or t12.get("static_rsa"):
            col.add("KEX-TLS-STATIC-RSA", None, None, "TLS 1.2 accepts RSA key transport (%s)" % t12["suite"], tlsasset, endpoint=ep)
        if t12["kex"] == "DHE":
            col.add("KEX-TLS-DHE", None, None, "TLS 1.2 selects DHE (%s)" % t12["suite"], tlsasset, endpoint=ep)
    if res.get("draft_kyber"):
        col.add("OBS-PQ-DRAFT", None, None, "accepts X25519Kyber768Draft00", None, endpoint=ep)
    c = res.get("certificate") or {}
    if c.get("key") and "error" not in c:
        if not re.search(r"ML-DSA|SLH-DSA", c["key"]):
            past = horizon_past(c.get("not_after"), col.horizon)
            col.add("ENDPOINT-CERT-CLASSIC", None, None, "%s %s until %s" % (c["key"], c.get("sig_alg"), (c.get("not_after") or "?")[:10]),
                    {"kind": "certificate", "algorithm": c["key"], "family": None}, severity="medium" if past else "low", endpoint=ep)
        if re.match(r"RSA-(\d+)", c["key"]) and int(re.match(r"RSA-(\d+)", c["key"]).group(1)) < 2048:
            col.add("WEAK-RSA-SMALL", None, None, "served certificate key " + c["key"], None, endpoint=ep)
        if re.search(r"(?i)sha1|md5", c.get("sig_alg") or ""):
            col.add("WEAK-SIG-SHA1", None, None, "served certificate signed with " + c["sig_alg"], None, endpoint=ep)
    return res


TLS_NOT_CHECKED = ["STARTTLS services", "QUIC / HTTP/3", "client-certificate endpoints",
                   "the hop behind a CDN or load balancer (only the edge answers)", "other IP addresses behind this name"]


def run_probe(targets, opts):
    t0 = time.time()
    col = Collector(".", opts.get("horizon") or DEFAULT_HORIZON)
    eps = []
    if len(targets) > 50:
        raise UsageError("probe: at most 50 endpoints per run (got %d). Split the list." % len(targets))
    resolved = []
    for key, default in (("timeout", 8), ("delay", 0.5)):
        value = opts.get(key, default)
        if not math.isfinite(value) or value < 0 or (key == "timeout" and value == 0):
            raise UsageError("probe: invalid --%s, give a finite %s number of seconds" %
                             (key, "positive" if key == "timeout" else "non-negative"))
    for t in targets:
        host, _port, _proto = split_target(t, opts.get("mode"))
        private, ip = is_private_target(host)
        if private is False and not opts.get("authorized"):
            raise UsageError("Probe only systems you own or are authorized to test. %s is outside loopback and RFC 1918: "
                             "add --authorized to confirm you may test it. Nothing was contacted." % host)
        if private is None and not opts.get("authorized"):
            raise UsageError("%s does not resolve to an address from this computer, so it cannot be confirmed as local. "
                             "Check the spelling. If it is a system you own, add --authorized. Nothing was contacted." % host)
        resolved.append((t, ip))
    for t, ip in resolved:
        eps.append(probe_endpoint(col, t, opts, ip))
    if any(e.get("protocol") == "tls" for e in eps):
        for x in TLS_NOT_CHECKED:
            col.nc(x, "not reachable by this probe")
    return summarize(col, 0, 0, time.time() - t0, "probe", {"endpoints": eps, "checked": now_iso()})


# ---------------------------------------------------------------------------------------------------------------
# report: priority, waves, plan.md, CycloneDX CBOM, before/after diff
# ---------------------------------------------------------------------------------------------------------------

BASE = {"critical": 100, "high": 70, "medium": 40, "low": 15, "info": 0}
EXPO = {"hndl": 20, "trust-anchor": 15, "blocker": 5}
LIFE = {"<1y": -10, "1-5y": 0, "5-10y": 10, ">10y": 20, "unknown": 10}
REACH = {"internet": 10, "internal": 0, "isolated": -10, "unknown": 0}
CTXP = {"test": -30, "example": -30, "docs": -30, "comment": -30, "vendored": -20}


def load_findings(paths):
    merged = {"findings": [], "not_checked": [], "sources": [], "horizon": DEFAULT_HORIZON, "endpoints": [],
              "coverage": [], "errors": [], "suppressed": []}
    seen = set()
    for p in paths:
        d = read_json(p, "findings file")
        if not isinstance(d, dict) or not isinstance(d.get("findings"), list):
            raise UsageError("%s is not a PQ Shift findings file. Make one with: python pqshift.py scan . --json %s" % (p, p))
        if any(not isinstance(f, dict) or not isinstance(f.get("id"), str) or
               f.get("rule") not in RULES or f.get("severity") not in SEVERITIES or
               not isinstance(f.get("location"), dict) or not isinstance(f.get("asset"), dict) or
               not all(k in f for k in ("evidence", "context", "exposure", "category", "title", "why", "replace", "recipe"))
               for f in d["findings"]):
            raise UsageError("invalid finding in %s; provide the JSON written by scan or probe" % p)
        merged["sources"].append(p)
        merged["coverage"].append((d.get("command"), d.get("root"), d.get("scope"), d.get("baseline_removed")))
        merged["errors"].extend(d.get("errors") or [])
        merged["suppressed"].extend(d.get("suppressed") or [])
        merged["horizon"] = d.get("horizon", merged["horizon"])
        merged["endpoints"] += d.get("endpoints", [])
        for f in d.get("findings", []):
            if f["id"] not in seen:
                seen.add(f["id"])
                merged["findings"].append(f)
        for n in d.get("not_checked", []):
            if n not in merged["not_checked"]:
                merged["not_checked"].append(n)
    return merged


MANUAL_ASK = ("Ask whoever runs it which key exchange and signature algorithms it uses, and when the "
              "post-quantum hybrid will be available. Record the answer and the date.")


def check_answers(answers, path):
    """Validate the triage answers and turn short manual items into full findings. Raises UsageError with the fix."""
    systems = answers.get("systems") or []
    if not isinstance(systems, list):
        raise UsageError("%s: \"systems\" must be a list" % path)
    for sy in systems:
        if not isinstance(sy, dict) or not sy.get("name"):
            raise UsageError("%s: every entry in \"systems\" needs a \"name\"" % path)
        if sy.get("data_lifetime", "unknown") not in LIFE:
            raise UsageError("%s: system %s has data_lifetime %r. Use one of: %s" % (
                path, sy["name"], sy.get("data_lifetime"), ", ".join(sorted(LIFE))))
        if sy.get("reach", "unknown") not in REACH:
            raise UsageError("%s: system %s has reach %r. Use one of: %s" % (
                path, sy["name"], sy.get("reach"), ", ".join(sorted(REACH))))
        for k in ("paths", "endpoints"):
            if not isinstance(sy.get(k, []), list):
                raise UsageError("%s: system %s: \"%s\" must be a list" % (path, sy["name"], k))
    for x in answers.get("false_positives") or []:
        if not isinstance(x, dict) or not x.get("id") or not x.get("reason"):
            raise UsageError("%s: every false_positives entry needs an \"id\" and a \"reason\"" % path)
    out = []
    for m in answers.get("manual_findings") or []:
        if not isinstance(m, dict):
            raise UsageError("%s: manual_findings entries must be objects, for example "
                             "{\"what\": \"CDN in front of www\", \"system\": \"website\"}" % path)
        if m.get("location") and m.get("severity") and m.get("id"):
            out.append(m)                 # already a full finding
            continue
        what = m.get("what") or m.get("title")
        if not what:
            raise UsageError("%s: a manual_findings entry needs \"what\" (one line saying what it is)" % path)
        sev = m.get("severity", "medium")
        if sev not in SEVERITIES:
            raise UsageError("%s: manual finding %r has severity %r. Use one of: %s" % (path, what, sev, ", ".join(SEVERITIES)))
        expo = m.get("exposure", "unknown")
        out.append({"id": "M-" + hashlib.sha256(what.encode("utf-8")).hexdigest()[:8], "rule": "MANUAL", "title": what,
                    "severity": sev, "exposure": expo, "category": "manual", "context": "prod", "confidence": "reported",
                    "system": m.get("system"), "evidence": what, "replace": m.get("ask") or MANUAL_ASK,
                    "location": {"path": None, "line": None, "col": None, "endpoint": m.get("where") or what}})
    answers["manual_findings"] = out
    return answers


def count(n, word):
    """'1 finding', '2 findings'."""
    return "%d %s%s" % (n, word, "" if n == 1 else "s")


def system_for(f, answers):
    loc = f.get("location") or {}
    if f.get("system"):
        for s in (answers or {}).get("systems", []):
            if s.get("name") == f["system"]:
                return s
    for s in (answers or {}).get("systems", []):
        if loc.get("endpoint") and loc["endpoint"] in s.get("endpoints", []):
            return s
        if loc.get("path") and any(fnmatch.fnmatch(loc["path"], g) for g in s.get("paths", [])):
            return s
    return None


def score(f, answers):
    s = system_for(f, answers)
    parts = {"base": BASE[f["severity"]], "exposure": EXPO.get(f["exposure"], 0), "lifetime": 0, "reach": 0,
             "context": CTXP.get(f.get("context"), 0)}
    if f["exposure"] == "hndl":
        parts["lifetime"] = LIFE.get((s or {}).get("data_lifetime", "unknown"), 10)
    parts["reach"] = REACH.get((s or {}).get("reach", "unknown"), 0)
    total = sum(parts.values())
    if f["severity"] == "critical":
        wave = 0
    elif total >= 90:
        wave = 1
    elif total >= 70:
        wave = 2
    elif total >= 40:
        wave = 3
    else:
        wave = 4
    return total, parts, wave, (s or {}).get("name") or f.get("system") or "unassigned"


WAVE_TITLES = {0: "Wave 0: weak with ordinary computers (fix now, unrelated to quantum)",
               1: "Wave 1: key exchange and encryption that is internet-facing or guards long-lived data",
               2: "Wave 2: remaining key exchange and encryption, trust anchors",
               3: "Wave 3: signatures, tokens, certificates",
               4: "Wave 4: hygiene and items waiting on a fact"}
PROOF = {"config": "re-scan + probe", "endpoint": "re-scan + probe", "code": "re-scan + tests", "token": "re-scan + tests",
         "key": "re-scan", "cert": "re-scan", "dependency": "re-scan + tests", "runtime": "re-scan"}


def build_plan(data, answers, today):
    fp = set(x["id"] for x in (answers or {}).get("false_positives", []))
    rows = {}
    for f in data["findings"] + (answers or {}).get("manual_findings", []):
        if f["severity"] == "info" or f["id"] in fp or f["exposure"] == "none":
            continue
        total, parts, wave, sysname = score(f, answers)
        key = (wave, f["rule"], sysname)
        if f["rule"] == "MANUAL":
            key = (wave, f["id"], sysname)       # one row per thing the human told us about
        r = rows.setdefault(key, {"wave": wave, "rule": f["rule"], "system": sysname, "ids": [], "paths": [],
                                  "score": total, "parts": parts, "category": f.get("category"),
                                  "title": f.get("title") if f["rule"] == "MANUAL" else None,
                                  "replace": f.get("replace") if f["rule"] == "MANUAL" else None})
        r["ids"].append(f["id"])
        where = (f.get("location") or {}).get("endpoint") or (f.get("location") or {}).get("path") or "?"
        ln = (f.get("location") or {}).get("line")
        r["paths"].append(where + (":%d" % ln if ln else ""))
        r["score"] = max(r["score"], total)
    out = sorted(rows.values(), key=lambda r: (r["wave"], -r["score"], r["rule"], r["system"]))
    return out


def plan_md(data, answers, rows):
    nf = [f for f in data["findings"]]
    bys = {}
    for f in nf:
        bys[f["severity"]] = bys.get(f["severity"], 0) + 1
    L = []
    L.append("# PQ Shift plan")
    L.append("")
    L.append("Generated %s by pqshift %s from %s. Horizon %s (a policy date, not a prediction)." % (
        now_iso()[:10], VERSION, ", ".join(data["sources"]), data["horizon"]))
    L.append("")
    L.append("Findings: " + " | ".join("%d %s" % (bys.get(s, 0), s) for s in SEVERITIES))
    L.append("")
    L.append("A finding means \"uses an algorithm the guidance says to migrate\", not \"exploitable today\" "
             "(critical items are the exception: they are weak with ordinary computers). A clean scan is not an audit.")
    L.append("")
    L.append("Score = base (critical 100, high 70, medium 40, low 15) + exposure (recorded-now-read-later +20, trust anchor +15, "
             "blocker +5) + data lifetime (key exchange only: <1y -10, 1-5y 0, 5-10y +10, >10y +20, unknown +10) + reach "
             "(internet +10, isolated -10) + context (test/example/docs -30, vendored -20).")
    L.append("")
    n = 0
    for w in range(5):
        wr = [r for r in rows if r["wave"] == w]
        if not wr:
            continue
        L.append("## " + WAVE_TITLES[w])
        L.append("")
        L.append("| # | Finding ids | System | What | Change | Owner | Proof | Status |")
        L.append("|---|---|---|---|---|---|---|---|")
        for r in wr:
            n += 1
            rule = RULES.get(r["rule"], {"title": r["rule"], "replace": "", "recipe": ""})
            if r["rule"] == "MANUAL":
                rule = {"title": "Not visible in the repository: %s" % (r.get("title") or "manual item"),
                        "replace": r.get("replace") or MANUAL_ASK, "recipe": ""}
            ids = ", ".join(r["ids"][:6]) + (" +%d" % (len(r["ids"]) - 6) if len(r["ids"]) > 6 else "")
            where = "; ".join(r["paths"][:4]) + (" +%d more" % (len(r["paths"]) - 4) if len(r["paths"]) > 4 else "")
            what = "%s (%s) score %d: %s" % (rule["title"], r["rule"], r["score"], where)
            change = rule["replace"] + (" See %s." % rule["recipe"] if rule.get("recipe") else "")
            L.append("| %d | %s | %s | %s | %s |  | %s | PLANNED |" % (
                n, ids, r["system"], what.replace("|", "/"), change.replace("|", "/"),
                PROOF.get(r["category"], "the owner's written answer" if r["rule"] == "MANUAL" else "re-scan")))
        L.append("")
    L.append("## Not checked")
    L.append("")
    for x in data["not_checked"]:
        L.append("- %s: %s" % (x["what"], x["why"]))
    L.append("")
    L.append("Status words: PROVEN | CHANGED, NOT PROVEN HERE | PLANNED | BLOCKED: <what> | VENDOR: <who, asked on date> | "
             "ACCEPTED: <owner, until date> | NOT APPLICABLE: <reason>.")
    L.append("")
    return "\n".join(L)


NQL = {"ML-KEM-512": 1, "ML-KEM-768": 3, "ML-KEM-1024": 5, "ML-DSA-44": 2, "ML-DSA-65": 3, "ML-DSA-87": 5}


def _slug(s):
    return re.sub(r"[^a-z0-9.+-]+", "-", (s or "unknown").lower()).strip("-")


def build_cbom(data, rootname):
    comps = {}
    deps = []

    def add(ref, comp, occ):
        c = comps.get(ref)
        if not c:
            c = comp
            c["bom-ref"] = ref
            comps[ref] = c
        if occ:
            ev = c.setdefault("evidence", {"occurrences": []})
            if occ not in ev["occurrences"] and len(ev["occurrences"]) < 50:
                ev["occurrences"].append(occ)
        return ref

    for f in data["findings"]:
        a = f.get("asset") or {}
        loc = f.get("location") or {}
        occ = None
        if loc.get("path"):
            occ = {"location": loc["path"]}
            if loc.get("line"):
                occ["line"] = loc["line"]
        elif loc.get("endpoint"):
            occ = {"location": loc["endpoint"]}
        props = [{"name": "pqshift:rule", "value": f["rule"]}, {"name": "pqshift:severity", "value": f["severity"]},
                 {"name": "pqshift:exposure", "value": f["exposure"]}]
        kind = a.get("kind") or "algorithm"
        if kind == "library":
            name = a.get("library") or "library"
            ver = a.get("parameter")
            ref = "lib/%s@%s" % (_slug(name), ver or "unknown")
            comp = {"type": "library", "name": name}
            if ver:
                comp["version"] = ver
            add(ref, comp, None)
            deps.append(ref)
            continue
        if kind == "certificate":
            sha = a.get("sha256") or hashlib.sha256(json.dumps(loc).encode()).hexdigest()
            alg_ref = "crypto/algorithm/" + _slug(a.get("sig_alg") or "unknown-signature")
            add(alg_ref, {"type": "cryptographic-asset", "name": a.get("sig_alg") or "unknown",
                          "cryptoProperties": {"assetType": "algorithm", "algorithmProperties": {"primitive": "signature",
                                                                                                "cryptoFunctions": ["sign", "verify"]}}}, None)
            key_ref = "crypto/algorithm/" + _slug(a.get("algorithm"))
            add(key_ref, {"type": "cryptographic-asset", "name": a.get("algorithm") or "unknown",
                          "cryptoProperties": {"assetType": "algorithm", "algorithmProperties": {"primitive": "signature"}}}, None)
            subj = "CN=%s" % a["subject"] if a.get("subject") else "(no common name)"
            cp = {"assetType": "certificate", "certificateProperties": {
                "subjectName": subj, "issuerName": "CN=%s" % a["issuer"] if a.get("issuer") else "(no common name)",
                "signatureAlgorithmRef": alg_ref, "subjectPublicKeyRef": key_ref, "certificateFormat": "X.509"}}
            if a.get("not_before"):
                cp["certificateProperties"]["notValidBefore"] = a["not_before"]
            if a.get("not_after"):
                cp["certificateProperties"]["notValidAfter"] = a["not_after"]
            ref = add("crypto/certificate/" + sha[:16], {"type": "cryptographic-asset", "name": subj,
                                                          "cryptoProperties": cp, "properties": props}, occ)
            deps.append(ref)
            continue
        if kind == "key":
            alg = a.get("algorithm") or "unknown"
            alg_ref = "crypto/algorithm/" + _slug(alg)
            add(alg_ref, {"type": "cryptographic-asset", "name": alg, "cryptoProperties": {"assetType": "algorithm"}}, None)
            path = loc.get("path") or loc.get("endpoint") or "?"
            ev_l = (f.get("evidence") or "").lower()
            rcm = {"type": "private-key" if "private" in ev_l else "public-key",
                   "algorithmRef": alg_ref, "format": "PEM" if "pem block" in ev_l else "unknown"}
            if a.get("parameter") and str(a.get("parameter")).isdigit():
                rcm["size"] = int(a["parameter"])
            ref = add("crypto/key/" + hashlib.sha256((path + str(loc.get("line"))).encode()).hexdigest()[:16],
                      {"type": "cryptographic-asset", "name": path,
                       "cryptoProperties": {"assetType": "related-crypto-material", "relatedCryptoMaterialProperties": rcm},
                       "properties": props}, occ)
            deps.append(ref)
            continue
        if kind == "protocol":
            alg = a.get("algorithm") or "ECDH"
            alg_ref = "crypto/algorithm/" + _slug(alg)
            add(alg_ref, {"type": "cryptographic-asset", "name": alg,
                          "cryptoProperties": {"assetType": "algorithm", "algorithmProperties": {
                              "primitive": "kem" if "MLKEM" in alg.upper() or "ML-KEM" in alg.upper() else "key-agree"}}}, None)
            where = loc.get("path") or loc.get("endpoint") or "?"
            endpoint_proto = next((ep.get("protocol") for ep in data.get("endpoints", [])
                                   if ep.get("endpoint") == where), None)
            if f["rule"] == "KEX-VPN-WG-NOPSK":
                proto, label = "other", "WireGuard"
            elif f["rule"] == "KEX-VPN-IKE":
                proto, label = "ike", "IKE"
            elif f["rule"] == "KEX-VPN-OVPN":
                proto, label = "tls", "OpenVPN control channel"
            elif endpoint_proto == "ssh" or "SSH" in f["rule"] or alg in PQ_SSH:
                proto, label = "ssh", "SSH"
            else:
                proto, label = "tls", "TLS"
            ref = add("crypto/protocol/%s@%s" % (proto, where),
                      {"type": "cryptographic-asset", "name": label, "cryptoProperties": {
                          "assetType": "protocol", "protocolProperties": {"type": proto, "cryptoRefArray": []}},
                       "properties": props}, occ)
            alg_refs = comps[ref]["cryptoProperties"]["protocolProperties"]["cryptoRefArray"]
            if alg_ref not in alg_refs:
                alg_refs.append(alg_ref)
            deps.append(ref)
            continue
        alg = a.get("algorithm") or RULES.get(f["rule"], {}).get("title", f["rule"])
        param = a.get("parameter")
        name = alg + ("-" + str(param) if param and str(param) not in alg else "")
        ap = {"primitive": a.get("primitive") or "other"}
        if a.get("usage") and a["usage"] != "unknown":
            # CycloneDX 1.6 has no "key agreement" function: a KEM encapsulates, classic (EC)DH derives a shared key.
            kexfn = ["keygen", "encapsulate", "decapsulate"] if a.get("primitive") == "kem" else ["keygen", "keyderive"]
            ap["cryptoFunctions"] = {"kex": kexfn, "encrypt": ["encrypt", "decrypt"], "sign": ["sign", "verify"],
                                     "verify": ["verify"], "keygen": ["keygen"]}.get(a["usage"], ["other"])
        if param:
            ap["parameterSetIdentifier"] = str(param)
        fam = a.get("family")
        if fam in ("RSA", "ECC", "FFDH", "DSA"):
            ap["nistQuantumSecurityLevel"] = 0
            try:
                lvl = CLASSIC_LEVEL.get((fam, int(param)))
                if lvl:
                    ap["classicalSecurityLevel"] = lvl
            except (TypeError, ValueError):
                pass
        if NQL.get(alg):
            ap["nistQuantumSecurityLevel"] = NQL[alg]
        cp = {"assetType": "algorithm", "algorithmProperties": ap}
        if a.get("oid"):
            cp["oid"] = a["oid"]
        ref = add("crypto/algorithm/%s/%s" % (_slug(name), f["rule"].lower()),
                  {"type": "cryptographic-asset", "name": name, "cryptoProperties": cp, "properties": props}, occ)
        deps.append(ref)
    bom = {"bomFormat": "CycloneDX", "specVersion": "1.6", "serialNumber": "urn:uuid:" + str(uuid.uuid4()), "version": 1,
           "metadata": {"timestamp": now_iso(),
                        "tools": {"components": [{"type": "application", "name": "pqshift", "version": VERSION}]},
                        "component": {"type": "application", "name": rootname, "bom-ref": "root"}},
           "components": list(comps.values()),
           "dependencies": [{"ref": "root", "dependsOn": sorted(set(deps))}]}
    return bom


def run_report(args):
    if args.expect_closed and not args.diff:
        raise UsageError("--expect-closed requires --diff with the before findings")
    data = load_findings(args.findings)
    answers = None
    if args.answers:
        answers = read_json(args.answers, "answers file")
        if not isinstance(answers, dict):
            raise UsageError("answers file %s must be a JSON object (see agent.md, phase 2)" % args.answers)
        answers = check_answers(answers, args.answers)
        unknown_fp = [x["id"] for x in answers.get("false_positives") or [] if x["id"] not in set(f["id"] for f in data["findings"])]
        if unknown_fp:
            raise UsageError("%s: false_positives lists ids that are not in the findings: %s" % (args.answers, ", ".join(unknown_fp)))
    rows = build_plan(data, answers, now_iso()[:10])
    rc = 0
    out = sys.stderr if args.json == "-" else sys.stdout
    counts = {}
    for r in rows:
        counts[r["wave"]] = counts.get(r["wave"], 0) + len(r["ids"])
    n_manual = len((answers or {}).get("manual_findings") or [])
    out.write("PQ Shift %s  report  %s from %s%s\n" % (
        VERSION, count(len(data["findings"]), "finding"), ", ".join(data["sources"]),
        (" + %d you reported in %s" % (n_manual, args.answers)) if n_manual else ""))
    for w in range(5):
        if counts.get(w):
            out.write("  wave %d  %3d %-8s  %s\n" % (w, counts[w], "finding" if counts[w] == 1 else "findings",
                                                    WAVE_TITLES[w].split(": ", 1)[1]))
    if args.plan:
        write_text(args.plan, plan_md(data, answers, rows))
        out.write("  plan  -> %s\n" % args.plan)
    if args.cbom:
        scan_root = next((item[1] for item in data["coverage"] if item[0] == "scan" and item[1]), None)
        root = os.path.basename(os.path.normpath(scan_root)) if scan_root else None
        root = root if root and root != "." else "project"
        write_json(build_cbom(data, root), args.cbom)
        out.write("  cbom  -> %s (CycloneDX 1.6)\n" % args.cbom)
    if args.diff:
        before = load_findings([args.diff])
        bids = dict((f["id"], f) for f in before["findings"])
        aids = dict((f["id"], f) for f in data["findings"])
        closed = [i for i in bids if i not in aids]
        remaining = [i for i in bids if i in aids]
        new = [i for i in aids if i not in bids]
        # A new "already post-quantum" line is the good news of a migration, not a new problem: list it apart.
        gained = [i for i in new if aids[i]["rule"].startswith("OK-") or aids[i]["rule"] == "PQ-ONLY"]
        new = [i for i in new if i not in gained]
        out.write("  diff  closed %d | remaining %d | new %d | post-quantum added %d\n" % (
            len(closed), len(remaining), len(new), len(gained)))
        for i in gained:
            f = aids[i]
            out.write("    added   %s %s %s\n" % (i, f["rule"], (f["location"].get("path") or f["location"].get("endpoint") or "")))
        for i in closed:
            f = bids[i]
            out.write("    closed  %s %s %s\n" % (i, f["rule"], (f["location"].get("path") or f["location"].get("endpoint") or "")))
        for i in new:
            f = aids[i]
            out.write("    new     %s %s %s %s\n" % (i, f["severity"], f["rule"], (f["location"].get("path") or f["location"].get("endpoint") or "")))
        if args.expect_closed:
            want = [x.strip() for x in ",".join(args.expect_closed).split(",") if x.strip()]
            if not want:
                raise UsageError("--expect-closed requires at least one finding id")
            suppressed = {f.get("id") for f in data["suppressed"]}
            missed = {n["what"] for n in data["not_checked"]}
            gaps = []
            for i in want:
                loc = bids.get(i, {}).get("location", {})
                endpoint = loc.get("endpoint")
                if i in suppressed or loc.get("path") in missed or endpoint in missed or (endpoint and endpoint.startswith("runtime:")
                        and endpoint.replace("runtime:", "runtime: ", 1) in missed):
                    gaps.append(i)
                if endpoint and not endpoint.startswith("runtime:") and not any(
                        ep.get("endpoint") == endpoint and not ep.get("error") for ep in data["endpoints"]):
                    gaps.append(i)
            # Each before scope needs a corresponding complete after run. Older files lack full option metadata.
            def comparable(old):
                return any(old[:2] == now[:2] and (old[2] is None or now[2] == old[2]) and
                           now[3] is None for now in data["coverage"])
            expected_locs = {bids[i]["location"].get("path") or bids[i]["location"].get("endpoint")
                             for i in want if i in bids}
            incomplete = any(err not in before["errors"] or (err.get("path") or err.get("endpoint")) in expected_locs
                             for err in data["errors"])
            if incomplete or gaps or not all(comparable(old) for old in before["coverage"]):
                out.write("  FAIL  incomplete or different after coverage; repeat the same scan/probe, check errors "
                          "and remove suppressions for the expected ids.\n")
                rc = 1
            unknown = [i for i in want if i not in bids]
            if unknown:
                # An id that was never in the 'before' file cannot be "closed": most often a typo.
                rc = 1
                out.write("  FAIL  not in the before file (check the ids): %s\n" % ", ".join(unknown))
            still = [i for i in want if i in aids]
            bad_new = [i for i in new if aids[i]["severity"] in ("critical", "high")]
            if still or bad_new:
                rc = 1
                if still:
                    out.write("  FAIL  still present: %s\n" % ", ".join(still))
                if bad_new:
                    out.write("  FAIL  new high/critical: %s\n" % ", ".join(bad_new))
            elif rc == 0:
                out.write("  PASS  %s closed, no new high/critical\n" % (
                    "the expected finding" if len(want) == 1 else "all %d expected findings" % len(want)))
    if args.json:
        write_json({"schema": "pqshift.report/1", "rows": rows}, args.json)
    return rc


# ---------------------------------------------------------------------------------------------------------------
# guard: new work starts on current standards
# ---------------------------------------------------------------------------------------------------------------

DEFAULT_POLICY = {"schema": "pqshift.policy/1", "horizon": DEFAULT_HORIZON, "fail_on": ["hndl", "weak-today", "obsolete-pq"],
                  "warn_on": ["forgery", "trust-anchor", "blocker", "unknown"], "exclude": [], "allow": []}



def git(args, cwd, binary=False):
    try:
        p = subprocess.run([installed_tool("git"), "-c", "core.quotepath=false"] + args, cwd=cwd, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)
    except OSError:
        raise UsageError("guard needs git for --staged and --diff, and git was not found. "
                         "Outside git use: pqshift.py guard --baseline FILE")
    if p.returncode != 0:
        err = p.stderr.decode("utf-8", "replace").strip()
        if "not a git repository" in err:
            raise UsageError("guard --staged and --diff need a git repository, and %s is not inside one. "
                             "Outside git use: pqshift.py guard --baseline FILE" % os.path.abspath(cwd))
        if "unknown revision" in err or "bad revision" in err or "ambiguous argument" in err:
            raise UsageError("guard --diff: git does not know that branch or commit. In CI, fetch it first "
                             "(for example: git fetch origin main). git said: %s" % err.splitlines()[0])
        raise UsageError("git %s failed: %s" % (" ".join(args), err))
    return p.stdout if binary else p.stdout.decode("utf-8", "backslashreplace")


def changed_blobs(raw):
    """Yield the before and after Git objects with the destination path for each diff entry."""
    fields = iter(raw.rstrip("\0").split("\0"))
    for header in fields:
        if not header:
            continue
        old_mode, new_mode, old_oid, new_oid, status = header.lstrip(":").split()
        path = next(fields)
        if status[0] in "RC":
            path = next(fields)
        yield path, old_mode, new_mode, old_oid, new_oid, status[0]


def guard_blob(top, path, oid, opts):
    size = int(git(["cat-file", "-s", oid], top))
    if size > opts.get("max_size", 2 * 1024 * 1024):
        sys.stderr.write("pqshift guard: skipped %s (larger than the scan limit)\n" % path)
        return []
    data = git(["cat-file", "blob", oid], top, binary=True)
    col = Collector(top, opts["horizon"])
    scan_file(col, path, None, opts, data=data)
    if col.errors:
        raise UsageError("guard: could not fully check %s: %s" % (path, col.errors[0]["error"]))
    return col.findings


def load_policy(path, root, revision=None):
    pol = dict(DEFAULT_POLICY)
    p = path or os.path.join(root, ".pqshift.json")
    if path and not os.path.isfile(path):
        raise UsageError("policy file not found: %s" % path)
    if revision is not None and not path:
        args = ["ls-files", "--stage"] if revision == ":" else ["ls-tree", revision]
        entry = git(args + ["--", ".pqshift.json"], root)
        d = {}
        if entry:
            if not entry.startswith("100") or len(entry.splitlines()) != 1:
                raise UsageError("guard: .pqshift.json must be a regular, resolved file")
            ref = (":" if revision == ":" else revision + ":") + ".pqshift.json"
            try:
                d = json.loads(git(["cat-file", "blob", ref], root, binary=True).decode("utf-8-sig"))
            except ValueError as ex:
                raise UsageError("invalid .pqshift.json in the checked revision: %s" % ex)
    else:
        d = read_json(p, "policy file") if os.path.isfile(p) else {}
    if not isinstance(d, dict):
        raise UsageError("policy file %s must be a JSON object (see guard/pqshift.policy.example.json)" % p)
    pol.update(d)
    for key in ("fail_on", "warn_on", "exclude"):
        if not isinstance(pol[key], list) or any(not isinstance(v, str) for v in pol[key]):
            raise UsageError("policy %s must be a list of strings" % key)
    if not isinstance(pol["allow"], list):
        raise UsageError("policy allow must be a list of dated exceptions")
    for entry in pol["allow"]:
        if not isinstance(entry, dict) or not isinstance(entry.get("rule"), str) or not isinstance(entry.get("path", "*"), str):
            raise UsageError("each policy exception needs a rule and a valid path pattern")
        try:
            date = _dt.date.fromisoformat(entry["until"])
            if date.isoformat() != entry["until"]:
                raise ValueError()
        except (KeyError, ValueError, TypeError):
            raise UsageError("each policy exception needs an until date in YYYY-MM-DD format")
        if not isinstance(entry.get("reason"), str) or not entry["reason"].strip():
            raise UsageError("each policy exception needs a nonempty reason")
    return pol


def run_guard(args):
    root = args.path or "."
    if not os.path.isdir(root):
        raise UsageError("guard: %s is not a folder" % root)
    top = root if args.baseline else git(["rev-parse", "--show-toplevel"], root).strip()
    pol = load_policy(args.policy, top, None if args.baseline else (":" if args.staged else "HEAD"))
    today = _dt.date.today().isoformat()
    opts = {"horizon": pol.get("horizon", DEFAULT_HORIZON), "exclude": pol.get("exclude", [])}
    viol = []
    if args.baseline:
        read_json(args.baseline, "baseline file")     # a missing baseline must stop the run, not pass everything
        opts["baseline"] = args.baseline
        res = run_scan([root], opts)
        cand = res["findings"]
    else:
        if args.diff and args.diff.startswith("-"):
            raise UsageError("guard --diff needs a base branch or commit")
        revs = ["--cached"] if args.staged else ["%s...HEAD" % args.diff]
        raw = git(["diff", "--raw", "-z", "--no-abbrev", "--no-ext-diff", "--no-textconv",
                   "--diff-filter=ACMRT"] + revs + ["--"], top)
        cand = []
        for name, old_mode, new_mode, old_oid, new_oid, status in changed_blobs(raw):
            if glob_match(name, opts["exclude"]) or not new_mode.startswith("100"):
                continue
            # Compare the index/commit objects, including binary changes and findings caused by deletions.
            # Use the destination name for both scans so that moving a file alone does not create a finding.
            current = guard_blob(top, name, new_oid, opts)
            previous = set()
            if current and old_mode.startswith("100") and status != "C":
                previous = {f["id"] for f in guard_blob(top, name, old_oid, opts)}
            cand.extend(f for f in current if f["id"] not in previous)
    fails, warns, allowed = [], [], []
    for a in pol.get("allow", []):
        if not a.get("reason") or not a.get("until"):
            viol.append(("POLICY", "allow entry for %s needs reason and until" % a.get("rule")))
        elif a["until"] < today:
            fails.append({"rule": "POLICY-EXPIRED", "severity": "high", "location": {"path": ".pqshift.json", "line": None},
                          "evidence": "allow %s %s expired %s (%s)" % (a.get("rule"), a.get("path", "*"), a["until"], a.get("reason")),
                          "replace": RULES["POLICY-EXPIRED"]["replace"]})
    for f in cand:
        if f["exposure"] == "none" or f["severity"] == "info":
            continue
        ok = None
        for a in pol.get("allow", []):
            if a.get("until", "") >= today and a.get("reason") and a.get("rule") in (f["rule"], "*") and \
                    fnmatch.fnmatch(f["location"]["path"] or "", a.get("path", "*")):
                ok = a
        if ok:
            allowed.append(f)
            continue
        if f["exposure"] in pol.get("fail_on", []):
            fails.append(f)
        elif f["exposure"] in pol.get("warn_on", []):
            warns.append(f)
    out = sys.stderr if args.json == "-" or getattr(args, "sarif", None) == "-" else sys.stdout
    for f in fails:
        loc = f["location"]
        out.write("FAIL  %s%s  %s  %s  %s  | fix: %s\n" % (loc["path"], ":%d" % loc["line"] if loc.get("line") else "",
                                                          f["rule"], f["severity"], f["evidence"][:80], f.get("replace", "")))
    for f in warns:
        loc = f["location"]
        out.write("warn  %s%s  %s  %s  %s\n" % (loc["path"], ":%d" % loc["line"] if loc.get("line") else "", f["rule"],
                                              f["severity"], f["evidence"][:80]))
    for v in viol:
        out.write("FAIL  %s\n" % v[1])
    out.write("pqshift guard: %d failing, %s, %d allowed by policy\n" % (len(fails) + len(viol), count(len(warns), "warning"), len(allowed)))
    if args.json:
        write_json({"schema": "pqshift.guard/1", "fail": fails, "warn": warns, "allowed": [f["id"] for f in allowed]}, args.json)
    if getattr(args, "sarif", None):
        write_json(to_sarif([f for f in fails + warns if f.get("id")], "guard"), args.sarif)
    if fails or viol:
        out.write("How to clear a failure: add the hybrid next to the classic algorithm (python pqshift.py explain RULE), "
                  "or record a dated exception in .pqshift.json (see guard/pqshift.policy.example.json).\n")
    return 1 if (fails or viol) else 0


# ---------------------------------------------------------------------------------------------------------------
# mcp: stdio JSON-RPC 2.0 wrapper (newline-delimited). Tools map 1:1 to the CLI and return the same JSON.
# ---------------------------------------------------------------------------------------------------------------

MCP_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
MCP_TOOLS = [
    {"name": "pq_scan", "description": "Read-only inventory of RSA, elliptic-curve and classic Diffie-Hellman use in local files "
                                       "(code, configs, keys, certificates, dependencies). Returns pqshift.findings/1 JSON.",
     "inputSchema": {"type": "object", "properties": {
         "paths": {"type": "array", "items": {"type": "string"}, "description": "Folders or files to scan."},
         "only": {"type": "array", "items": {"type": "string", "enum": ["code", "config", "keys", "deps"]}},
         "runtime": {"type": "boolean", "description": "Also read local tool versions (openssl, ssh, node...)."},
         "horizon": {"type": "string", "description": "Policy date, YYYY-MM-DD. Default 2030-01-01."},
         "include_vendored": {"type": "boolean"}, "include_build": {"type": "boolean"},
         "out": {"type": "string", "description": "Write the full JSON to this file and return only the summary. "
                                                  "Use it on large projects: without it at most 150 findings are returned."}},
         "required": ["paths"]}},
    {"name": "pq_probe", "description": "Check which TLS key-exchange group (or SSH key exchange) live endpoints select. Use only on "
                                        "hosts the human has confirmed they own or may test; set authorized=true only after that "
                                        "confirmation. TLS uses at most 6 connections per endpoint (8 with deep), SSH one.",
     "inputSchema": {"type": "object", "properties": {
         "targets": {"type": "array", "items": {"type": "string"}}, "authorized": {"type": "boolean"},
         "deep": {"type": "boolean"}, "confirm_handshake": {"type": "boolean"}}, "required": ["targets", "authorized"]}},
    {"name": "pq_report", "description": "Rank findings into waves 0-4 and optionally write plan.md, a CycloneDX 1.6 CBOM, and a "
                                         "before/after diff (the proof). Paths are local files.",
     "inputSchema": {"type": "object", "properties": {
         "findings": {"type": "array", "items": {"type": "string"}}, "answers": {"type": "string"}, "plan": {"type": "string"},
         "cbom": {"type": "string"}, "diff": {"type": "string"}, "expect_closed": {"type": "array", "items": {"type": "string"}}},
         "required": ["findings"]}},
    {"name": "pq_guard", "description": "Fail new classic-only key exchange or encryption in staged changes, a diff against a base "
                                        "branch, or a full scan minus a baseline.",
     "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "mode": {"type": "string", "enum": ["staged", "diff", "baseline"]},
                                                      "base": {"type": "string"}}, "required": ["path", "mode"]}},
    {"name": "pq_explain", "description": "Why a rule matters, what to replace it with, and the migration recipe file.",
     "inputSchema": {"type": "object", "properties": {"rule": {"type": "string"}}, "required": ["rule"]}},
]


MCP_MAX_FINDINGS = 150


class _NS(object):
    def __init__(self, **kw):
        self.__dict__.update(kw)


def _capture(fn, *a):
    import io
    old = sys.stdout
    buf = io.StringIO()
    sys.stdout = buf
    try:
        rc = fn(*a)
    except UsageError as ex:
        rc = EXIT_USAGE
        buf.write("pqshift: %s\n" % ex)
    except SystemExit as ex:
        rc = ex.code if isinstance(ex.code, int) else 2
        if ex.code and not isinstance(ex.code, int):
            buf.write(str(ex.code) + "\n")
    finally:
        sys.stdout = old
    return rc, buf.getvalue()


def mcp_call(name, a):
    schema = next(t["inputSchema"] for t in MCP_TOOLS if t["name"] == name)
    for key in schema["required"]:
        if key not in a:
            return "Missing required argument: " + key, True
    for key, value in a.items():
        prop = schema["properties"].get(key)
        if not prop:
            return "Unknown argument: " + key, True
        typ = prop["type"]
        if typ == "boolean" and not isinstance(value, bool):
            return key + " must be a boolean", True
        if typ == "string" and (not isinstance(value, str) or not value.strip() or value not in prop.get("enum", [value])):
            return "Invalid value for " + key, True
        if typ == "array" and (not isinstance(value, list) or not value or any(
                not isinstance(v, str) or not v.strip() or v not in prop["items"].get("enum", [v]) for v in value)):
            return key + " must be a nonempty list of valid strings", True
    if name == "pq_scan":
        if a.get("out") == "-":
            return "Omit out to receive findings in the MCP response, or supply a file path.", True
        if "horizon" in a:
            _date_arg(a["horizon"])
        paths = a["paths"]
        for pth in paths:
            if not os.path.exists(pth):
                return "no such path: %s" % pth, True
        res = run_scan(paths, {"only": a.get("only"), "runtime": a.get("runtime"), "horizon": a.get("horizon"),
                               "include_vendored": a.get("include_vendored"), "include_build": a.get("include_build")})
        total = len(res["findings"])
        if a.get("out"):
            write_json(res, a["out"])
            res = dict(res, findings=[], note="%d findings written to %s. Next: pq_report with findings=[%r]." % (
                total, a["out"], a["out"]))
        elif total > MCP_MAX_FINDINGS:
            res = dict(res, findings=res["findings"][:MCP_MAX_FINDINGS],
                       note="Showing the %d highest-priority of %d findings. Call again with out=FILE to save all of them." % (
                           MCP_MAX_FINDINGS, total))
        return json.dumps(res, indent=1), False
    if name == "pq_probe":
        if a.get("authorized") is not True:
            return "Refused: probe only systems the human confirmed they own or may test, then call again with authorized=true.", True
        res = run_probe(a["targets"], {"authorized": True, "deep": a.get("deep"), "confirm": a.get("confirm_handshake"),
                                       "timeout": 8, "delay": 0.5})
        return json.dumps(res, indent=1), all(ep.get("error") for ep in res["endpoints"])
    if name == "pq_report":
        ns = _NS(findings=a.get("findings") or [], answers=a.get("answers"), plan=a.get("plan"), cbom=a.get("cbom"),
                 diff=a.get("diff"), expect_closed=a.get("expect_closed"), json=None)
        rc, txt = _capture(run_report, ns)
        return txt + ("exit %d\n" % rc), rc != 0
    if name == "pq_guard":
        mode = a["mode"]
        if mode != "staged" and not a.get("base"):
            return "The selected guard mode requires base.", True
        ns = _NS(path=a.get("path") or ".", staged=mode == "staged", diff=a.get("base") if mode == "diff" else None,
                 baseline=a.get("base") if mode == "baseline" else None, policy=None, json=None, sarif=None)
        rc, txt = _capture(run_guard, ns)
        return txt + ("exit %d\n" % rc), rc != 0
    if name == "pq_explain":
        txt = explain_text(a.get("rule", ""))
        return txt, txt.startswith("Unknown rule")
    return "unknown tool %r. Tools: %s" % (name, ", ".join(t["name"] for t in MCP_TOOLS)), True


def mcp_error(mid, code, message, data=None):
    error = {"code": code, "message": message}
    if data is not None:
        error["data"] = data
    print(json.dumps({"jsonrpc": "2.0", "id": mid, "error": error}), flush=True)


def run_mcp():
    if hasattr(sys.stdin, "reconfigure"):
        sys.stdin.reconfigure(encoding="utf-8")
    for raw in sys.stdin:
        raw = raw.strip()
        if not raw:
            continue
        try:
            msg = json.loads(raw)
        except ValueError:
            sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}) + "\n")
            sys.stdout.flush()
            continue
        if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0" or not isinstance(msg.get("method"), str):
            mcp_error(None, -32600, "invalid JSON-RPC request")
            continue
        if "id" not in msg:
            continue  # notification
        mid = msg["id"]
        if type(mid) not in (int, str):
            mcp_error(None, -32600, "invalid request id")
            continue
        method = msg["method"]
        params = msg.get("params", {})
        if not isinstance(params, dict) or not isinstance(params.get("_meta", {}), dict):
            mcp_error(mid, -32602, "params and _meta must be objects")
            continue
        meta = params.get("_meta", {})
        modern = meta.get("io.modelcontextprotocol/protocolVersion")
        if modern is not None and modern != MCP_VERSIONS[0]:
            mcp_error(mid, -32022, "Unsupported protocol version", {"supported": MCP_VERSIONS, "requested": modern})
            continue
        if modern and (not isinstance(meta.get("io.modelcontextprotocol/clientInfo"), dict) or
                       not isinstance(meta.get("io.modelcontextprotocol/clientCapabilities"), dict)):
            mcp_error(mid, -32602, "missing clientInfo or clientCapabilities in _meta")
            continue
        try:
            if method == "server/discover":
                if not modern:
                    mcp_error(mid, -32602, "server/discover requires the protocol version in _meta")
                    continue
                result = {"supportedVersions": MCP_VERSIONS, "capabilities": {"tools": {}},
                          "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "pqshift", "version": VERSION}}}
            elif method == "initialize" and not modern:
                want = params.get("protocolVersion")
                result = {"protocolVersion": want if want in MCP_VERSIONS[1:] else MCP_VERSIONS[1],
                          "capabilities": {"tools": {"listChanged": False}},
                          "serverInfo": {"name": "pqshift", "version": VERSION},
                          "instructions": "PQ Shift: read-only inventory of classic public-key cryptography, ranking, CBOM and "
                                          "proof. Protocol for agents: " + HOME + "agent.md"}
            elif method == "ping":
                result = {}
            elif method == "tools/list":
                result = {"tools": MCP_TOOLS}
            elif method == "tools/call":
                name, arguments = params.get("name"), params.get("arguments", {})
                if name not in [t["name"] for t in MCP_TOOLS] or not isinstance(arguments, dict):
                    mcp_error(mid, -32602, "unknown tool name or invalid arguments object")
                    continue
                try:
                    txt, err = mcp_call(name, arguments)
                except (UsageError, argparse.ArgumentTypeError, OSError) as ex:
                    txt, err = str(ex), True
                result = {"content": [{"type": "text", "text": txt}], "isError": bool(err)}
            else:
                sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "method not found"}}) + "\n")
                sys.stdout.flush()
                continue
            if modern:
                result["resultType"] = "complete"
            sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, "result": result}) + "\n")
        except Exception as ex:
            mcp_error(mid, -32603, "internal error: %s" % ex)
        sys.stdout.flush()
    return 0


# ---------------------------------------------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------------------------------------------

def explain_text(rule):
    r = RULES.get((rule or "").strip().upper())
    if not r:
        near = [k for k in sorted(RULES) if (rule or "").strip().upper() in k][:6]
        return "Unknown rule %s.%s List them all with: python pqshift.py rules\n" % (
            rule, " Did you mean: %s?" % ", ".join(near) if near and rule else "")
    return "%s  %s  (%s, exposure %s)\nWhy: %s\nReplace with: %s\nRecipe: %s%s\nRefs: %s\n" % (
        r["id"], r["title"], r["severity"], r["exposure"], r["why"], r["replace"] or "-", HOME if r["recipe"] else "",
        r["recipe"] or "-", ", ".join(r["refs"]) or "-")


def rules_list():
    out = []
    for r in _R:
        x = RULES[r[0]]
        out.append({k: x[k] for k in ("id", "title", "severity", "exposure", "category", "why", "replace", "recipe", "refs")})
    return out


EPILOG = """\
commands (run `pqshift.py COMMAND --help` for the options of one):
  scan     list where files use RSA, elliptic-curve or classic Diffie-Hellman      read-only
  probe    ask a server you own which key exchange it picks                        read-only, a few connections
  report   rank findings into waves, write a plan and a CBOM, diff before/after    writes only the files you name
  guard    fail a commit or CI run that adds new classic-only key exchange          read-only
  explain  why one rule matters and what to replace it with
  rules    list every rule            support  which libraries and servers have ML-KEM / ML-DSA
  mcp      run as an MCP server on stdio for an AI agent

first run:
  python pqshift.py scan . --json pq/before.json
  python pqshift.py report pq/before.json --plan pq/plan.md --cbom pq/cbom.json

exit codes (the same for every command):
  0    finished; nothing failed a check you asked for
  1    finished, and a check failed: scan --fail-on, guard, or report --expect-closed
  2    could not run: wrong arguments, a missing or unreadable file, git not available, probe not authorized
  130  stopped with Ctrl+C

Severity is migration priority, not "exploitable today". A clean scan is a first inventory, not an audit.
Docs: %sagent.md
""" % HOME


def _date_arg(v):
    try:
        _dt.datetime.strptime(v, "%Y-%m-%d")
    except ValueError:
        raise argparse.ArgumentTypeError("%r is not a date. Use YYYY-MM-DD, for example %s" % (v, DEFAULT_HORIZON))
    return v


def _size_arg(v):
    m = re.match(r"^(\d+(?:\.\d+)?)\s*([KMG]?)B?$", v.strip().upper())
    if not m:
        raise argparse.ArgumentTypeError("%r is not a size. Use a number with K, M or G, for example 2M" % v)
    return int(float(m.group(1)) * {"": 1, "K": 1024, "M": 1024 ** 2, "G": 1024 ** 3}[m.group(2)])


def build_parser():
    F = argparse.RawDescriptionHelpFormatter
    ap = argparse.ArgumentParser(
        prog="pqshift", formatter_class=F, epilog=EPILOG,
        description="PQ Shift %s: find where your code and servers use RSA, elliptic-curve and classic Diffie-Hellman "
                    "cryptography, rank what to move first, and prove each move to the NIST post-quantum standards." % VERSION)
    ap.add_argument("--version", action="version", version="pqshift " + VERSION)
    sub = ap.add_subparsers(dest="cmd", metavar="COMMAND")

    s = sub.add_parser("scan", formatter_class=F, help="read-only inventory of files",
                       description="List where files use RSA, elliptic-curve or classic Diffie-Hellman: source code, server and "
                                   "SSH configs, VPN configs, keys, certificates and dependency files. Nothing is changed and "
                                   "nothing leaves this computer.",
                       epilog="examples:\n  python pqshift.py scan . --json pq/before.json\n"
                              "  python pqshift.py scan services/api --only config,keys\n"
                              "  python pqshift.py scan . --sarif pq/pqshift.sarif --fail-on high\n\n"
                              "Skipped by default: .git, node_modules, vendor, virtualenvs, dist, build, out, target.\n"
                              "A file named .pqshiftignore (one glob per line) excludes more.\n"
                              "To accept one line, add a comment on it:  pqshift:ignore RULE-ID reason\n"
                              "exit codes: 0 done | 1 --fail-on matched | 2 could not run")
    s.add_argument("paths", nargs="*", default=["."], help="folders or files to scan (default: the current folder)")
    s.add_argument("--json", metavar="FILE|-", help="write all findings as JSON to FILE; '-' prints JSON only")
    s.add_argument("--sarif", metavar="FILE", help="also write SARIF 2.1.0 for code-scanning tools (GitHub, GitLab, Azure DevOps)")
    s.add_argument("--only", metavar="LIST", help="comma list of what to look at: code,config,keys,deps (default: all)")
    s.add_argument("--runtime", action="store_true", help="also read installed tool versions (openssl, ssh, node, go, java...)")
    s.add_argument("--horizon", type=_date_arg, default=DEFAULT_HORIZON, metavar="YYYY-MM-DD",
                   help="policy date: keys and certificates valid past it rank higher (default %(default)s; not a prediction)")
    s.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="skip paths matching GLOB (repeatable)")
    s.add_argument("--include-vendored", action="store_true", help="also scan node_modules, vendor, third_party, site-packages")
    s.add_argument("--include-build", action="store_true", help="also scan build output: dist, build, out, target, .next")
    s.add_argument("--include-comments", action="store_true", help="also report matches inside comments and docstrings")
    s.add_argument("--max-file-size", type=_size_arg, default="2M", metavar="SIZE",
                   help="skip larger files and list them as not checked (default 2M)")
    s.add_argument("--baseline", metavar="FILE", help="hide findings already in this earlier scan JSON (show only new ones)")
    s.add_argument("--fail-on", choices=SEVERITIES, metavar="LEVEL",
                   help="exit 1 if any finding is at or above LEVEL: critical, high, medium, low or info")
    s.add_argument("--limit", type=int, default=200, metavar="N", help="rows to print on screen (default 200; --json has all)")

    p = sub.add_parser("probe", formatter_class=F, help="check which key exchange a live TLS or SSH server selects",
                       description="Open a few ordinary connections to a server and report which key-exchange group it picks "
                                   "when a client offers the post-quantum hybrid. Needs no post-quantum library. "
                                   "Probe only systems you own or are authorized to test.",
                       epilog="examples:\n  python pqshift.py probe 127.0.0.1:8443\n"
                              "  python pqshift.py probe api.example.com --authorized --confirm-handshake --json pq/probe.json\n"
                              "  python pqshift.py probe git.example.com:22 --authorized\n\n"
                              "TLS uses at most 6 connections per endpoint (8 with --deep); SSH uses 1.\n"
                              "exit codes: 0 done (read the result) | 2 could not run or not authorized")
    p.add_argument("targets", nargs="*", metavar="HOST[:PORT]", help="server to test; port 443 unless given, port 22 means SSH")
    p.add_argument("--authorized", action="store_true", help="confirm you own or may test these public addresses (required for them)")
    p.add_argument("--targets", dest="targets_file", metavar="FILE", help="read targets from FILE, one per line")
    g = p.add_mutually_exclusive_group()
    g.add_argument("--ssh", action="store_const", dest="mode", const="ssh", help="treat every target as SSH")
    g.add_argument("--tls", action="store_const", dest="mode", const="tls", help="treat every target as TLS")
    p.add_argument("--sni", metavar="NAME", help="server name to send, if it differs from the host")
    p.add_argument("--deep", action="store_true", help="also test static RSA, pure ML-KEM and the old Kyber draft (2-3 more connections)")
    p.add_argument("--confirm-handshake", action="store_true",
                   help="also complete a full hybrid handshake with openssl or node, if OpenSSL 3.5+ is installed")
    p.add_argument("--timeout", type=float, default=8, metavar="SECONDS", help="per connection (default 8)")
    p.add_argument("--delay", type=float, default=0.5, metavar="SECONDS", help="pause between connections (default 0.5)")
    p.add_argument("--horizon", type=_date_arg, default=DEFAULT_HORIZON, metavar="YYYY-MM-DD", help="policy date (default %(default)s)")
    p.add_argument("--json", metavar="FILE|-", help="write the result as JSON to FILE; '-' prints JSON only")

    r = sub.add_parser("report", formatter_class=F, help="plan, CBOM and before/after proof from scan or probe JSON",
                       description="Turn findings into a ranked plan (waves 0-4, key exchange first), a CycloneDX 1.6 CBOM "
                                   "(a machine-readable list of the cryptography in use) and a before/after diff.",
                       epilog="examples:\n  python pqshift.py report pq/before.json --plan pq/plan.md --cbom pq/cbom.json\n"
                              "  python pqshift.py report pq/after.json --diff pq/before.json --expect-closed F-3a9c1e7b02\n\n"
                              "exit codes: 0 done | 1 --expect-closed failed (an id is still open, unknown, or a new high/critical "
                              "finding appeared) | 2 could not run")
    r.add_argument("findings", nargs="+", metavar="FINDINGS.json", help="one or more JSON files written by scan or probe")
    r.add_argument("--answers", metavar="FILE", help="triage answers JSON: how long data must stay secret, what faces the internet")
    r.add_argument("--plan", metavar="FILE", help="write the ranked plan as Markdown")
    r.add_argument("--cbom", metavar="FILE", help="write a CycloneDX 1.6 cryptography bill of materials (JSON)")
    r.add_argument("--diff", metavar="BEFORE.json", help="compare against an earlier scan: what closed, what is new")
    r.add_argument("--expect-closed", action="append", metavar="IDS",
                   help="with --diff: comma list of finding ids that must be gone; exit 1 otherwise")
    r.add_argument("--json", metavar="FILE", help="write the ranked rows as JSON")

    gd = sub.add_parser("guard", formatter_class=F, help="fail new classic-only crypto in a commit or CI diff",
                        description="Check only what is new, so old findings do not block today's work. Fails on new "
                                    "classic-only key exchange or public-key encryption and on anything weak today; warns on the rest.",
                        epilog="examples:\n  python pqshift.py guard --staged                 # pre-commit hook\n"
                               "  python pqshift.py guard --diff origin/main       # CI on a pull request\n"
                               "  python pqshift.py guard --baseline pq/before.json  # no git: full scan minus known findings\n\n"
                               "Policy and dated exceptions live in .pqshift.json (see guard/pqshift.policy.example.json).\n"
                               "exit codes: 0 nothing new fails | 1 a new finding fails the policy | 2 could not run")
    gd.add_argument("path", nargs="?", default=".", help="project folder (default: the current folder)")
    m = gd.add_mutually_exclusive_group(required=True)
    m.add_argument("--staged", action="store_true", help="check the changes staged for the next git commit")
    m.add_argument("--diff", metavar="BASE", help="check commits on this branch that are not on BASE (for example origin/main)")
    m.add_argument("--baseline", metavar="FILE", help="scan everything and ignore findings listed in this earlier scan JSON")
    gd.add_argument("--policy", metavar="FILE", help="policy file (default: .pqshift.json in the project folder, if present)")
    gd.add_argument("--json", metavar="FILE", help="write failures and warnings as JSON")
    gd.add_argument("--sarif", metavar="FILE", help="write failures and warnings as SARIF 2.1.0")

    sub.add_parser("mcp", help="run as an MCP server on stdio (for AI agents)",
                   description="Speak the Model Context Protocol on standard input and output. Tools: pq_scan, pq_probe, "
                               "pq_report, pq_guard, pq_explain. Start it from your agent's MCP settings, not by hand.")
    e = sub.add_parser("explain", help="explain one rule", description="Why a rule matters, what to replace it with, and the recipe.")
    e.add_argument("rule", metavar="RULE-ID", help="for example KEX-TLS-PINNED")
    rl = sub.add_parser("rules", help="list every rule", description="List every detection rule with its priority.")
    rl.add_argument("--json", action="store_true", help="print as JSON")
    sp = sub.add_parser("support", help="which libraries and servers have ML-KEM / ML-DSA",
                        description="Versions that added the post-quantum algorithms, each with a source and a check date.")
    sp.add_argument("--json", action="store_true", help="print as JSON")
    return ap


def main(argv=None):
    for stream in (sys.stdout, sys.stderr):
        if hasattr(stream, "reconfigure"):
            try:
                stream.reconfigure(errors="replace")
            except Exception:
                pass
    try:
        return _main(argv)
    except UsageError as ex:
        sys.stderr.write("pqshift: %s\n" % ex)
        return EXIT_USAGE
    except KeyboardInterrupt:
        sys.stderr.write("\npqshift: stopped (Ctrl+C). Check any requested output files.\n")
        return 130
    except BrokenPipeError:
        # The reader went away (`pqshift.py scan . | head`). Not an error.
        try:
            sys.stdout = open(os.devnull, "w")
        except OSError:
            pass
        return EXIT_OK


def _main(argv=None):
    ap = build_parser()
    a = ap.parse_args(argv)
    if getattr(a, "sarif", None) == "-" and getattr(a, "json", None) == "-":
        raise UsageError("choose one output format for stdout and give the other a file path")
    if a.cmd == "scan":
        size = a.max_file_size if isinstance(a.max_file_size, int) else _size_arg(a.max_file_size)
        only = None
        if a.only:
            only = [x.strip().lower() for x in a.only.split(",") if x.strip()]
            bad = [x for x in only if x not in ("code", "config", "keys", "deps")]
            if bad:
                raise UsageError("--only: unknown value %s. Choose from: code, config, keys, deps" % ", ".join(bad))
        opts = {"only": only, "runtime": a.runtime, "horizon": a.horizon,
                "exclude": a.exclude, "include_vendored": a.include_vendored, "include_comments": a.include_comments,
                "include_build": a.include_build, "max_size": size, "baseline": a.baseline}
        for pth in a.paths:
            if not os.path.exists(pth):
                raise UsageError("no such file or folder: %s" % pth)
        if a.baseline:
            read_json(a.baseline, "baseline file")
        res = run_scan(a.paths, opts)
        if a.json:
            write_json(res, a.json)
        if a.sarif:
            write_json(to_sarif(res["findings"], "scan"), a.sarif)
        if a.json != "-" and a.sarif != "-":
            print_console(res, " ".join(a.paths), limit=a.limit)
            if a.json:
                d = os.path.dirname(a.json).replace("\\", "/")
                d = d + "/" if d else ""
                print("Next: python pqshift.py report %s --plan %splan.md --cbom %scbom.json" % (a.json, d, d))
            elif res["findings"]:
                print("Next: add --json pq/before.json to save this, then: python pqshift.py report pq/before.json --plan pq/plan.md")
        if a.fail_on and any(sev_at_least(f["severity"], a.fail_on) for f in res["findings"]):
            return EXIT_FINDINGS
        return EXIT_OK
    if a.cmd == "probe":
        targets = list(a.targets)
        if a.targets_file:
            try:
                with open(a.targets_file, "r", encoding="utf-8-sig") as fh:
                    targets += [l.strip() for l in fh if l.strip() and not l.lstrip().startswith("#")]
            except OSError as ex:
                raise UsageError("cannot read targets file %s: %s" % (a.targets_file, ex.strerror or ex))
        if not targets:
            raise UsageError("probe: give at least one HOST[:PORT], for example: python pqshift.py probe 127.0.0.1:8443")
        res = run_probe(targets, {"authorized": a.authorized, "mode": a.mode, "sni": a.sni, "deep": a.deep,
                                  "confirm": a.confirm_handshake, "timeout": a.timeout, "delay": a.delay, "horizon": a.horizon})
        if a.json:
            write_json(res, a.json)
        if a.json != "-":
            print_probe(res)
        eps = res.get("endpoints") or []
        if eps and all(e.get("error") for e in eps):
            sys.stderr.write("pqshift: no endpoint could be reached, so nothing was measured (see the error above).\n")
            return EXIT_USAGE
        return EXIT_OK
    if a.cmd == "report":
        return run_report(a)
    if a.cmd == "guard":
        return run_guard(a)
    if a.cmd == "mcp":
        return run_mcp()
    if a.cmd == "explain":
        txt = explain_text(a.rule)
        if txt.startswith("Unknown rule"):
            raise UsageError(txt.strip())
        sys.stdout.write(txt)
        return EXIT_OK
    if a.cmd == "rules":
        if a.json:
            write_json(rules_list(), "-")
        else:
            for r in rules_list():
                print("%-26s %-8s %-12s %s" % (r["id"], r["severity"], r["exposure"], r["title"]))
        return EXIT_OK
    if a.cmd == "support":
        if a.json:
            write_json(SUPPORT, "-")
        else:
            for row in SUPPORT:
                print("%-22s ML-KEM %-14s hybrid %-30s ML-DSA %-12s [%s]" % (row.get("component"), row.get("mlkem") or "-",
                                                                           (row.get("hybrid_kex") or "-")[:30], row.get("mldsa") or "-",
                                                                           row.get("status")))
        return EXIT_OK
    ap.print_help()
    return EXIT_OK


def print_probe(res):
    w = sys.stdout.write
    w("PQ Shift %s  probe  %s\n" % (VERSION, res.get("checked")))
    for e in res["endpoints"]:
        if e.get("error"):
            w("%-28s error: %s\n" % (e["endpoint"], e["error"]))
            continue
        if e["protocol"] == "ssh":
            w("%-28s SSH  %s  kex first: %s  post-quantum offered: %s\n" % (e["endpoint"], e.get("banner"), e["pq"]["first"],
                                                                            ", ".join(e["pq"]["offered"]) or "none"))
            continue
        pq = e.get("pq") or {}
        w("%-28s TLS 1.3 %s  hybrid-first client gets: %s  hybrids accepted: %s\n" % (
            e["endpoint"], "observed" if e.get("tls13") else "not observed", pq.get("selected_for_pq_client"), ", ".join(pq.get("supported_hybrids") or []) or "none observed"))
        c = e.get("classic") or {}
        t = e.get("tls12") or {}
        w("%-28s classic-only client gets: %s  TLS 1.2: %s\n" % ("", c.get("selected"), (t.get("suite") or "refused") if t else "-"))
        cert = e.get("certificate") or {}
        if cert.get("key"):
            w("%-28s certificate: %s, %s, until %s\n" % ("", cert["key"], cert.get("sig_alg"), (cert.get("not_after") or "?")[:10]))
        hc = e.get("handshake_confirmed") or {}
        w("%-28s handshake with hybrid only: %s\n" % ("", ("confirmed via " + hc["via"]) if hc.get("done") else hc.get("reason")))
    s = res["summary"]["by_severity"]
    w("%d critical | %d high | %d medium | %d low | %d info\n" % (s["critical"], s["high"], s["medium"], s["low"], s["info"]))
    w("Not checked: %s\n" % "; ".join(x["what"] for x in res["not_checked"]))


if __name__ == "__main__":
    sys.exit(main())
