PQ Step 0: Inventory

The zeroth step in moving TLS authentication and encryption to a post-quantum (PQ) state is knowing what you have.

Certificate management platforms do not analyse TLS key exchange groups today. They can find an endpoint, and they can tell you whether it accepts a protocol version older than TLS 1.3. A TLS 1.2 or older endpoint cannot use a PQ key exchange together with a traditional certificate, because hybrid key exchange groups exist only in TLS 1.3. That is useful, but it does not answer the question that matters for harvest-now-decrypt-later (HNDL) risk.

Two TLS 1.3 endpoints can look identical in an inventory. One negotiates classical X25519. The other negotiates X25519MLKEM768. The certificate management platform sees the same TLS version and the same certificate type for both. The difference is in the key exchange group, and you need to probe for it.

"""
Scan a subnet for TLS endpoints and report their post-quantum (PQ) posture.

Status:
  Fully PQ : leaf certificate public key is a PQ signature (ML-DSA, SLH-DSA, XMSS, LMS).
  Hybrid   : classical certificate and the endpoint accepts a group in PQ_HYBRID_GROUPS.
  No PQ    : classical certificate and no group in PQ_HYBRID_GROUPS is accepted.

Standard library only. TLS versions 1.0-1.3 are probed with raw ClientHellos. Key exchange
groups are probed with TLS 1.3 ClientHellos that offer one group and an empty key_share; a
server that supports the group replies with a HelloRetryRequest selecting it, otherwise it
replies with an alert. Hybrid PQ groups only exist in TLS 1.3, so TLS 1.2-only endpoints
are never hybrid.

Ports in STARTTLS_PORTS (RDP, PostgreSQL, MariaDB) begin in plain text, so the protocol's
upgrade step runs before the TLS probes. SQL Server (TDS) runs a PRELOGIN exchange and then
carries the TLS handshake inside TDS packets. Oracle TCPS is plain TLS on its own port (2484
by convention, or any port configured for TCPS). Ports that do not answer TLS are reported as
non-TLS, with whatever plain-text banner they send (for example the SSH banner on port 22).
All TLS and non-TLS results go to one CSV file.
"""
import contextlib
import csv
import ipaddress
import secrets
import socket
import ssl
import struct
from concurrent.futures import ThreadPoolExecutor, as_completed

# ---------------- Configuration ----------------
SUBNET = "10.1.2.0"
CLASS_PREFIX = 24  # CIDR prefix length
PORTS = [22, 443, 1433, 1521, 2484, 3306, 3389, 5432, 8443, 9443]
PQ_HYBRID_GROUPS = [
    "X25519MLKEM768",
    "SecP256r1MLKEM768",
    "SecP384r1MLKEM1024",
]
# Substrings that mark an SSH key exchange name as post-quantum (e.g. mlkem768x25519-sha256).
SSH_PQ_KEX_MARKERS = ("mlkem", "sntrup", "kyber")
TIMEOUT_SECONDS = 3
MAX_WORKERS = 64
OUTPUT_CSV = "pq_scan_results.csv"

# Ports whose protocol starts in plain text and upgrades to TLS (name per _starttls).
STARTTLS_PORTS = {3389: "rdp", 5432: "postgresql", 3306: "mariadb", 1433: "mssql"}

# Key exchange groups probed on every TLS endpoint (name -> IANA code point).
KEX_GROUPS = {
    "secp256r1": 0x0017,
    "secp384r1": 0x0018,
    "secp521r1": 0x0019,
    "x25519": 0x001D,
    "x448": 0x001E,
    "ffdhe2048": 0x0100,
    "ffdhe3072": 0x0101,
    "X25519Kyber768Draft00": 0x6399,
    "SecP256r1MLKEM768": 0x11EB,
    "X25519MLKEM768": 0x11EC,
    "SecP384r1MLKEM1024": 0x11ED,
    "MLKEM512": 0x0200,
    "MLKEM768": 0x0201,
    "MLKEM1024": 0x0202,
}

# ---------------- Constants ----------------
CIPHER_SUITES = [0x1301, 0x1302, 0x1303, 0xC02B, 0xC02F, 0xC02C, 0xC030, 0xCCA9, 0xCCA8]
LEGACY_CIPHER_SUITES = [0xC02F, 0xC030, 0xC02B, 0xC02C, 0xC013, 0xC014, 0xC009, 0xC00A,
                        0x009C, 0x009D, 0x002F, 0x0035, 0x000A, 0x0005]
LEGACY_GROUPS = [0x0017, 0x0018, 0x0019, 0x001D]
SIGNATURE_ALGORITHMS = [0x0403, 0x0503, 0x0603, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601, 0x0807]
TLS_HRR_RANDOM = bytes.fromhex("CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C")
TLS_VERSION_NAMES = {0x0301: "1.0", 0x0302: "1.1", 0x0303: "1.2", 0x0304: "1.3"}
LEGACY_VERSIONS = (0x0301, 0x0302, 0x0303)
PQ_SIGNATURE_OIDS = {
    "1.2.840.113549.1.9.16.3.17": "LMS (hash-based)",
    "1.3.6.1.5.5.7.6.34": "XMSS (hash-based)",
    "1.3.6.1.5.5.7.6.35": "XMSS-MT (hash-based)",
}
CLASSICAL_KEY_OIDS = {
    "1.2.840.113549.1.1.1": "RSA",
    "1.2.840.10045.2.1": "EC",
    "1.3.101.112": "Ed25519",
    "1.3.101.113": "Ed448",
}
NIST_SIG_ARC = "2.16.840.1.101.3.4.3."
CN_OID = "2.5.4.3"
# X.224 connection request with RDP_NEG_REQ asking for TLS (1) or CredSSP/hybrid (2).
RDP_CONNECTION_REQUEST = bytes.fromhex("03000013" + "0EE00000000000" + "0100080003000000")
TDS_PRELOGIN = 0x12
TDS_MAX_PAYLOAD = 4088  # default TDS packet size (4096) minus the 8-byte header
TDS_ENCRYPTION_NAMES = {0x00: "off", 0x01: "on", 0x02: "not supported", 0x03: "required"}
TDS_ENCRYPT_NOT_SUPPORTED = 0x02


# ---------------- ClientHello / probing ----------------
def _u16(value):
    return struct.pack("!H", value)


def _u24(value):
    return struct.pack("!I", value)[1:]


def _extension(ext_type, data):
    return _u16(ext_type) + _u16(len(data)) + data


def _signature_algorithms_extension():
    sig_data = b"".join(_u16(s) for s in SIGNATURE_ALGORITHMS)
    return _extension(0x000D, _u16(len(sig_data)) + sig_data)


def _groups_extension(groups):
    groups_data = b"".join(_u16(g) for g in groups)
    return _extension(0x000A, _u16(len(groups_data)) + groups_data)


def _hello_message(legacy_version, cipher_suites, extensions):
    cipher_data = b"".join(_u16(c) for c in cipher_suites)
    extension_data = b"".join(extensions)
    body = (_u16(legacy_version) + secrets.token_bytes(32) + b"\x00"
            + _u16(len(cipher_data)) + cipher_data
            + b"\x01\x00"
            + _u16(len(extension_data)) + extension_data)
    handshake = b"\x01" + _u24(len(body)) + body
    return b"\x16\x03\x01" + _u16(len(handshake)) + handshake


def _client_hello_tls13(groups):
    extensions = [
        _extension(0x002B, b"\x02\x03\x04"),     # supported_versions: TLS 1.3
        _groups_extension(groups),
        _signature_algorithms_extension(),
        _extension(0x0033, _u16(0)),             # key_share: empty -> forces HRR
        _extension(0x002D, b"\x01\x01"),         # psk_key_exchange_modes
    ]
    return _hello_message(0x0303, CIPHER_SUITES, extensions)


def _client_hello_legacy(version):
    extensions = [
        _groups_extension(LEGACY_GROUPS),
        _extension(0x000B, b"\x01\x00"),         # ec_point_formats: uncompressed
        _signature_algorithms_extension(),
    ]
    return _hello_message(version, LEGACY_CIPHER_SUITES, extensions)


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


def _parse_server_hello(message):
    """Return (kind, selected_group, negotiated_version) from a ServerHello or HelloRetryRequest."""
    body = message[4:]
    server_version = struct.unpack("!H", body[:2])[0]
    is_hrr = body[2:34] == TLS_HRR_RANDOM
    pos = 35 + body[34] + 3  # skip session id, cipher suite, compression
    ext_len = struct.unpack("!H", body[pos:pos + 2])[0]
    pos += 2
    extensions = body[pos:pos + ext_len]
    selected_version = server_version
    selected_group = None
    p = 0
    while p + 4 <= len(extensions):
        ext_type, length = struct.unpack("!HH", extensions[p:p + 4])
        data = extensions[p + 4:p + 4 + length]
        if ext_type == 0x002B:
            selected_version = struct.unpack("!H", data[:2])[0]
        elif ext_type == 0x0033 and is_hrr:
            selected_group = struct.unpack("!H", data[:2])[0]
        p += 4 + length
    return ("hrr" if is_hrr else "server_hello"), selected_group, selected_version


def _tds_packet(payload):
    """Wrap payload in one TDS packet of type PRELOGIN (0x12), which also carries TLS handshake records."""
    return struct.pack("!BBHHBB", TDS_PRELOGIN, 0x01, 8 + len(payload), 0, 1, 0) + payload


def _read_tds_payload(sock):
    header = _read_exact(sock, 8)
    return _read_exact(sock, struct.unpack("!H", header[2:4])[0] - 8)


def _tds_prelogin(sock):
    """Send a TDS PRELOGIN and return the server's ENCRYPTION option value."""
    options = (b"\x00" + _u16(11) + _u16(6)      # VERSION: offset 11, length 6
               + b"\x01" + _u16(17) + _u16(1)    # ENCRYPTION: offset 17, length 1
               + b"\xff"
               + b"\x0e\x00\x00\x00\x00\x00"     # client version
               + b"\x01")                        # ENCRYPT_ON
    sock.sendall(_tds_packet(options))
    reply = _read_tds_payload(sock)
    pos = 0
    while reply[pos] != 0xFF:
        if reply[pos] == 0x01:
            return reply[struct.unpack("!H", reply[pos + 1:pos + 3])[0]]
        pos += 5
    raise ConnectionError("TDS PRELOGIN reply has no ENCRYPTION option")


class _TdsStream:
    """Socket-like wrapper that carries TLS records inside TDS packets, as SQL Server does."""

    def __init__(self, sock):
        self._sock = sock
        self._buffer = b""

    def sendall(self, data):
        for start in range(0, len(data), TDS_MAX_PAYLOAD):
            self._sock.sendall(_tds_packet(data[start:start + TDS_MAX_PAYLOAD]))

    def recv(self, count):
        while not self._buffer:
            self._buffer = _read_tds_payload(self._sock)
        chunk, self._buffer = self._buffer[:count], self._buffer[count:]
        return chunk


def _handshake_over_tds(stream, ctx):
    """Complete a TLS handshake over a _TdsStream and return the leaf certificate in DER form."""
    incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO()
    tls = ctx.wrap_bio(incoming, outgoing)
    done = False
    while not done:
        try:
            tls.do_handshake()
            done = True
        except ssl.SSLWantReadError:
            pass
        if outgoing.pending:
            stream.sendall(outgoing.read())
        if not done:
            incoming.write(stream.recv(65536))
    return tls.getpeercert(binary_form=True)


def _starttls(sock, port):
    """Run the plain-text upgrade for STARTTLS_PORTS; raise ConnectionError if TLS is refused."""
    protocol = STARTTLS_PORTS.get(port)
    if protocol == "rdp":
        sock.sendall(RDP_CONNECTION_REQUEST)
        header = _read_exact(sock, 4)
        payload = _read_exact(sock, struct.unpack("!H", header[2:4])[0] - 4)
        neg_response = payload[-8:]
        if len(neg_response) != 8 or neg_response[0] != 0x02:
            raise ConnectionError("RDP did not select TLS")
        if struct.unpack("<I", neg_response[4:8])[0] not in (0x1, 0x2):
            raise ConnectionError("RDP selected a non-TLS protocol")
    elif protocol == "postgresql":
        sock.sendall(struct.pack("!II", 8, 80877103))  # SSLRequest
        if _read_exact(sock, 1) != b"S":
            raise ConnectionError("PostgreSQL refused SSL")
    elif protocol == "mariadb":
        greeting_header = _read_exact(sock, 4)
        _read_exact(sock, int.from_bytes(greeting_header[:3], "little"))
        body = struct.pack("<IIB", 0x0200 | 0x0800, 16777215, 33) + b"\x00" * 23  # CLIENT_SSL
        sock.sendall(len(body).to_bytes(3, "little") + b"\x01" + body)
    elif protocol == "mssql":
        if _tds_prelogin(sock) == TDS_ENCRYPT_NOT_SUPPORTED:
            raise ConnectionError("SQL Server refused encryption")


@contextlib.contextmanager
def _open(ip, port):
    sock = socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS)
    try:
        _starttls(sock, port)
        yield _TdsStream(sock) if STARTTLS_PORTS.get(port) == "mssql" else sock
    finally:
        sock.close()


def _send_hello(ip, port, hello):
    """Return (kind, selected_group, negotiated_version); kind is 'hrr', 'server_hello', 'alert' or 'none'."""
    with _open(ip, port) as sock:
        sock.sendall(hello)
        for _ in range(5):
            header = _read_exact(sock, 5)
            content_type = header[0]
            if content_type not in (0x14, 0x15, 0x16):
                return ("none", None, None)
            payload = _read_exact(sock, struct.unpack("!H", header[3:5])[0])
            if content_type == 0x15:
                return ("alert", None, None)
            if content_type == 0x16 and payload[0] == 0x02:
                return _parse_server_hello(payload)
    return ("none", None, None)


PROBE_ERRORS = (OSError, IndexError, struct.error)  # malformed replies from old devices


def _offer(ip, port, hello):
    """Return (answered, negotiated_version). answered is False if the port gave no TLS response."""
    try:
        kind, _, version = _send_hello(ip, port, hello)
    except PROBE_ERRORS:
        return False, None
    return kind != "none", version


def _group_supported(ip, port, code):
    try:
        kind, selected, _ = _send_hello(ip, port, _client_hello_tls13([code]))
    except PROBE_ERRORS:
        return False
    return kind == "hrr" and selected == code


# ---------------- Certificate handling ----------------
def _fetch_leaf_certificate(ip, port):
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    ctx.minimum_version = ssl.TLSVersion.TLSv1
    ctx.set_ciphers("ALL:@SECLEVEL=0")  # lets legacy TLS 1.0/1.1 endpoints complete the handshake
    try:
        with _open(ip, port) as stream:
            if isinstance(stream, _TdsStream):
                return _handshake_over_tds(stream, ctx)
            with ctx.wrap_socket(stream) as tls:
                return tls.getpeercert(binary_form=True)
    except (ValueError,) + PROBE_ERRORS:
        return None


def _tls_remediation(accepted):
    """Return a priority-prefixed remediation note (HIGH, MEDIUM, LOW) or '' if none is needed."""
    if not accepted:
        return "REVIEW: no known TLS version negotiated"
    if max(accepted) < 0x0303:
        return "HIGH: retire, TLS 1.1 or lower only"
    if accepted & {0x0301, 0x0302}:
        return "MEDIUM: disable TLS 1.0/1.1"
    if 0x0303 in accepted:
        if 0x0304 in accepted:
            return "LOW: disable TLS 1.2 fallback"
        return "LOW: upgrade to TLS 1.3 (required for hybrid PQ)"
    return ""


def _der_tlv(buf, pos):
    """Return (tag, content_start, content_length) for the DER element at pos."""
    tag = buf[pos]
    length = buf[pos + 1]
    pos += 2
    if length & 0x80:
        count = length & 0x7F
        length = int.from_bytes(buf[pos:pos + count], "big")
        pos += count
    return tag, pos, length


def _der_children(buf, start, length):
    children = []
    pos = start
    end = start + length
    while pos < end:
        tag, content_start, content_len = _der_tlv(buf, pos)
        children.append((tag, content_start, content_len))
        pos = content_start + content_len
    return children


def _oid_to_str(data):
    arcs = []
    value = 0
    for byte in data:
        value = (value << 7) | (byte & 0x7F)
        if not byte & 0x80:
            arcs.append(value)
            value = 0
    first = arcs[0]
    head = [first // 40, first % 40] if first < 80 else [2, first - 80]
    return ".".join(str(a) for a in head + arcs[1:])


def _algorithm_oid(der, start, length):
    _, oid_start, oid_len = _der_children(der, start, length)[0]
    return _oid_to_str(der[oid_start:oid_start + oid_len])


def _common_name(der, start, length):
    for _, rdn_start, rdn_len in _der_children(der, start, length):
        for _, atv_start, atv_len in _der_children(der, rdn_start, rdn_len):
            oid_tlv, value_tlv = _der_children(der, atv_start, atv_len)[:2]
            if _oid_to_str(der[oid_tlv[1]:oid_tlv[1] + oid_tlv[2]]) == CN_OID:
                return der[value_tlv[1]:value_tlv[1] + value_tlv[2]].decode("utf-8", errors="replace")
    return None


def _certificate_fields(der):
    """Return public key OID, signature OID, subject CN and issuer CN of a DER X.509 certificate."""
    _, cert_start, cert_len = _der_tlv(der, 0)
    cert_children = _der_children(der, cert_start, cert_len)
    _, tbs_start, tbs_len = cert_children[0]
    tbs_children = _der_children(der, tbs_start, tbs_len)
    # tbsCertificate: [version] serial signature issuer validity subject subjectPublicKeyInfo
    offset = 1 if tbs_children[0][0] == 0xA0 else 0
    _, issuer_start, issuer_len = tbs_children[offset + 2]
    _, subject_start, subject_len = tbs_children[offset + 4]
    _, spki_start, spki_len = tbs_children[offset + 5]
    _, spki_alg_start, spki_alg_len = _der_children(der, spki_start, spki_len)[0]
    _, sig_start, sig_len = cert_children[1]
    return {
        "public_key_oid": _algorithm_oid(der, spki_alg_start, spki_alg_len),
        "signature_oid": _algorithm_oid(der, sig_start, sig_len),
        "subject_cn": _common_name(der, subject_start, subject_len) or "",
        "issuer_cn": _common_name(der, issuer_start, issuer_len) or "",
    }


def _nist_sig_number(oid):
    """Return N for OIDs of the form 2.16.840.1.101.3.4.3.N, otherwise None."""
    if not oid.startswith(NIST_SIG_ARC):
        return None
    suffix = oid[len(NIST_SIG_ARC):]
    return int(suffix) if suffix.isdigit() else None


def _is_pq_oid(oid):
    if oid in PQ_SIGNATURE_OIDS:
        return True
    number = _nist_sig_number(oid)
    return number is not None and 17 <= number <= 31


def _describe_oid(oid):
    if oid in PQ_SIGNATURE_OIDS:
        return PQ_SIGNATURE_OIDS[oid]
    if oid in CLASSICAL_KEY_OIDS:
        return CLASSICAL_KEY_OIDS[oid]
    number = _nist_sig_number(oid)
    if number is not None and 17 <= number <= 19:
        return f"ML-DSA ({oid})"
    if number is not None and 20 <= number <= 31:
        return f"SLH-DSA ({oid})"
    return oid


# ---------------- Endpoint scan ----------------
def _probe_plain(ip, port):
    """Return the printable text the port sends without TLS, or None if the port is closed."""
    try:
        with socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS) as sock:
            try:
                data = sock.recv(256)
            except socket.timeout:
                data = b""
    except OSError:
        return None
    return "".join(chr(b) if 32 <= b < 127 else "." for b in data).strip()


def _tds_encryption_banner(ip, port):
    """Describe SQL Server's PRELOGIN encryption setting; None if closed, '' if no PRELOGIN reply."""
    try:
        sock = socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS)
    except OSError:
        return None
    with sock:
        try:
            return "TDS prelogin: encryption " + TDS_ENCRYPTION_NAMES.get(_tds_prelogin(sock), "unknown")
        except PROBE_ERRORS:
            return ""


def _ssh_kex_algorithms(ip, port):
    """Return the key exchange algorithms the SSH server advertises (KEXINIT is sent before encryption)."""
    with socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS) as sock:
        sock.sendall(b"SSH-2.0-pqscanner\r\n")
        line = b""
        while not line.endswith(b"\n"):
            line += _read_exact(sock, 1)
        for _ in range(10):
            packet_length = struct.unpack("!I", _read_exact(sock, 4))[0]
            body = _read_exact(sock, packet_length)
            payload = body[1:packet_length - body[0]]
            if payload[:1] == b"\x14":  # SSH_MSG_KEXINIT
                name_len = struct.unpack("!I", payload[17:21])[0]
                return payload[21:21 + name_len].decode("ascii", errors="replace").split(",")
    raise ConnectionError("no SSH_MSG_KEXINIT received")


def _ssh_kex_status(kex_names):
    if any(marker in name for name in kex_names for marker in SSH_PQ_KEX_MARKERS):
        return "Hybrid (PQ kex offered)"
    return "No PQ (no PQ kex offered)"


def scan_endpoint(ip, port):
    """Return ("tls", record), ("non_tls", record) for an open port without TLS, or None if closed."""
    accepted = set()
    tls13_answered, tls13_version = _offer(ip, port, _client_hello_tls13(list(KEX_GROUPS.values())))
    answered = tls13_answered
    if tls13_version == 0x0304:
        accepted.add(0x0304)
    for version in LEGACY_VERSIONS:
        legacy_answered, negotiated = _offer(ip, port, _client_hello_legacy(version))
        answered = answered or legacy_answered
        if negotiated == version:
            accepted.add(version)
    if not answered:
        if STARTTLS_PORTS.get(port) == "mssql":
            banner = _tds_encryption_banner(ip, port)
        else:
            banner = _probe_plain(ip, port)
        if banner is None:
            return None
        record = {
            "ip": ip,
            "port": port,
            "transport": "non-TLS",
            "banner": banner,
            "pq_status": "N/A (no TLS)",
        }
        if banner.startswith("SSH-"):
            try:
                kex_names = _ssh_kex_algorithms(ip, port)
                record["ssh_kex_algorithms"] = ";".join(kex_names)
                record["pq_status"] = _ssh_kex_status(kex_names)
            except PROBE_ERRORS:
                record["ssh_kex_algorithms"] = "unavailable"
        return "non_tls", record

    supported = []
    if 0x0304 in accepted:
        supported = [name for name, code in KEX_GROUPS.items() if _group_supported(ip, port, code)]
    hybrid = [g for g in supported if g in PQ_HYBRID_GROUPS]

    der = _fetch_leaf_certificate(ip, port)

    cert_key = cert_sig = subject_cn = issuer_cn = "unavailable"
    cert_is_pq = False
    if der is not None:
        fields = _certificate_fields(der)
        cert_key = _describe_oid(fields["public_key_oid"])
        cert_sig = _describe_oid(fields["signature_oid"])
        subject_cn = fields["subject_cn"]
        issuer_cn = fields["issuer_cn"]
        cert_is_pq = _is_pq_oid(fields["public_key_oid"])

    if cert_is_pq:
        status = "Fully PQ"
    elif hybrid:
        status = "Hybrid"
    elif der is None:
        status = "Unknown (certificate not retrieved)"
    else:
        status = "No PQ"

    max_version = max(accepted) if accepted else None
    return "tls", {
        "ip": ip,
        "port": port,
        "transport": "TLS",
        "banner": "",
        "tls_max_version": TLS_VERSION_NAMES.get(max_version, "none"),
        "tls_versions_accepted": ";".join(TLS_VERSION_NAMES[v] for v in sorted(accepted)),
        "tls_remediation": _tls_remediation(accepted),
        "subject_cn": subject_cn,
        "issuer_ca_cn": issuer_cn,
        "cert_key": cert_key,
        "cert_signature": cert_sig,
        "kex_groups": ";".join(supported),
        "pq_hybrid_groups": ";".join(hybrid),
        "pq_status": status,
    }


def _validate_config():
    """Fail fast on bad settings instead of partway through a scan."""
    ipaddress.ip_network(f"{SUBNET}/{CLASS_PREFIX}", strict=False)
    if len(set(PORTS)) != len(PORTS):
        raise ValueError(f"PORTS contains duplicates: {PORTS}")
    invalid = [p for p in PORTS if not 1 <= p <= 65535]
    if invalid:
        raise ValueError(f"PORTS outside 1-65535: {invalid}")
    unknown = [g for g in PQ_HYBRID_GROUPS if g not in KEX_GROUPS]
    if unknown:
        raise ValueError(f"PQ_HYBRID_GROUPS names not in KEX_GROUPS: {unknown}")


def _write_results(rows):
    rows.sort(key=lambda r: (ipaddress.ip_address(r["ip"]), r["port"]))
    fieldnames = ["ip", "port", "transport", "pq_status", "banner",
                  "tls_max_version", "tls_versions_accepted", "tls_remediation",
                  "subject_cn", "issuer_ca_cn", "cert_key", "cert_signature",
                  "kex_groups", "pq_hybrid_groups", "ssh_kex_algorithms"]
    with open(OUTPUT_CSV, "w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fieldnames, restval="")
        writer.writeheader()
        writer.writerows(rows)
    tls_count = sum(1 for r in rows if r["transport"] == "TLS")
    error_count = sum(1 for r in rows if r["transport"] == "error")
    print(f"\n{tls_count} TLS endpoints, {len(rows) - tls_count - error_count} non-TLS open ports, "
          f"{error_count} errors. Results written to {OUTPUT_CSV}")


def main():
    _validate_config()
    network = ipaddress.ip_network(f"{SUBNET}/{CLASS_PREFIX}", strict=False)
    hosts = list(network.hosts()) or list(network)
    targets = [(str(ip), port) for ip in hosts for port in PORTS]
    print(f"Scanning {network} on ports {PORTS} ({len(targets)} endpoints)")

    rows = []
    pool = ThreadPoolExecutor(max_workers=MAX_WORKERS)
    futures = {pool.submit(scan_endpoint, ip, port): (ip, port) for ip, port in targets}
    try:
        for future in as_completed(futures):
            ip, port = futures[future]
            try:
                result = future.result()
            except Exception as exc:
                rows.append({"ip": ip, "port": port, "transport": "error", "pq_status": f"Error: {exc}"})
                print(f"{ip}:{port}  error: {exc}")
                continue
            if result is None:
                continue
            kind, record = result
            rows.append(record)
            if kind == "tls":
                print(f"{ip}:{port}  TLS [{record['tls_versions_accepted']}]  CN={record['subject_cn']}  "
                      f"CA={record['issuer_ca_cn']}  cert={record['cert_key']}  "
                      f"kex=[{record['kex_groups']}]  => {record['pq_status']}"
                      + (f"  ** {record['tls_remediation']}" if record["tls_remediation"] else ""))
            else:
                print(f"{ip}:{port}  open, non-TLS  banner={record['banner'] or '(none)'}"
                      + (f"  kex=[{record['ssh_kex_algorithms']}]  => {record['pq_status']}"
                         if "ssh_kex_algorithms" in record else ""))
    except KeyboardInterrupt:
        print("\nInterrupted: cancelling queued probes and saving partial results.")
        for future in futures:
            future.cancel()
    finally:
        pool.shutdown(wait=True)
        _write_results(rows)


if __name__ == "__main__":
    main()

What the scanner does

scanSubnetAndReportPQStatus.py is a standard-library Python script. It needs no OpenSSL command-line tool. For each IP in a subnet and each port in a list, it:

  1. Checks whether the port speaks TLS. Ports that do not are reported as non-TLS with their plain-text banner. Ports such as RDP, PostgreSQL, MariaDB and SQL Server start in plain text and are upgraded with each protocol’s own handshake before the TLS probes run.
  2. Probes each TLS version from 1.0 to 1.3 with raw handshakes, so you see what the server accepts, not what the client library prefers.
  3. Probes each TLS 1.3 key exchange group separately, and records every group the server accepts.
  4. Reads the leaf certificate’s key and signature algorithm, subject CN and issuer CN.
  5. Classifies the endpoint and flags the remediation priority.

For SSH on port 22, it reads the key exchange list the server advertises in its plain-text KEXINIT message. That list shows what the server accepts. The client’s preference decides what is negotiated.

Configuration and usage

The subnet, port list and hybrid group list are variables at the top of the script. The repository README covers setup, configuration and usage: [link to repo README].

The script writes one line per open port as it runs, and a CSV file with one row per open port. Example lines:

Reading the results

Each TLS row gets one pq_status:

StatusMeaning
Fully PQThe leaf certificate uses a PQ signature. The script recognises ML-DSA, SLH-DSA, XMSS and LMS.
HybridThe certificate is classical and the endpoint accepts at least one hybrid group.
No PQThe certificate is classical and no hybrid group is accepted.
UnknownThe endpoint answered TLS but the certificate could not be fetched.

Use tls_remediation alongside it:

PriorityConditionAction
HIGHOnly TLS 1.1 or lowerRetire or replace the device.
MEDIUMTLS 1.0 or 1.1 accepted with a higher versionDisable 1.0 and 1.1.
LOWTLS 1.2 acceptedDisable the 1.2 fallback if 1.3 is also accepted. If 1.2 is the only version, plan an upgrade.
REVIEWNo known version answeredCheck the endpoint by hand.

Two things to keep in mind when reading the output:

  • A Hybrid result means the endpoint offers a hybrid group. It does not mean every client negotiates one. Check a real client to confirm.
  • A TLS 1.2 endpoint is never Hybrid. It is a remediation item regardless of what its certificate or cipher suites look like.

First steps

The scan gives you a list. Work through it in this order.

1. Disable legacy TLS. Start with the HIGH and MEDIUM rows. TLS 1.0 and 1.1 have no PQ path at all. Disabling them is a configuration change on most servers, and it closes the weakest entry points first. Test each change, because some old clients will break.

2. Remove TLS 1.2 fallbacks where 1.3 works. If an endpoint accepts both 1.2 and 1.3, clients that can use 1.3 will do so. Disabling 1.2 removes a path that can never carry a hybrid group. Where 1.2 is the only version, schedule an upgrade.

3. Upgrade the software, where the vendor has shipped PQ support. The scan shows what is deployed. Upgrading is what changes the result. Two examples from the current research:

  • RHEL 9.7 adds an opt-in PQ crypto policy with hybrid ML-KEM. Apply it with update-crypto-policies --set DEFAULT:PQ. OpenSSH on RHEL 9.7 still has no ML-KEM key exchange, so SSH on those hosts stays classical.
  • Windows 11 and Windows Server 2025 offer hybrid TLS groups in Schannel from the July 2026 updates. Check Microsoft’s release notes for your build before rollout.

4. Put non-upgradeable devices behind a proxy. If a device cannot speak hybrid TLS and cannot be retired yet, put it behind an Apache httpd or NGINX reverse proxy that offers hybrid groups to users, and restrict the device to accept only the proxy’s address. This protects the user-facing channel. The proxy-to-device hop stays classical, and the device still needs replacing. Treat the proxy as a stopgap.

5. Record the SSH state, even if you do not change it yet. The scanner lists SSH key exchange algorithms the server accepts. Many SSH servers still offer only classical names. Keep that list as the baseline for the client-side work.

What comes next

Phase 0 gives you the list. Phase 1 covers the classical endpoints that the scan found and how to decide which ones to fix first.

Post-Quantum TLS, Background: Why Key Exchange Matters Now

Most of the internet’s encryption rests on two kinds of public-key math: RSA and elliptic curve cryptography (ECC). They protect the key exchange that sets up a session, and the certificates that prove who you are talking to. Both rely on problems that a classical computer cannot solve in a practical time. A large, fault-tolerant quantum computer running Shor’s algorithm could solve them efficiently. No such computer exists today, but the risk shapes what we need to do now.

The problem: harvest now, decrypt later

Attackers do not need a quantum computer to steal encrypted traffic. They can record it today and store it until they have the capability to break it. This is harvest now, decrypt later (HNDL).

The risk depends on how long the data must stay confidential. Medical records, government files, trade secrets, and personal data may need protection for decades. If a session’s key exchange can be broken later, every recorded session becomes readable at that point.

Authentication has a different risk. A quantum computer that can break a certificate’s signature could forge certificates going forward. That is a problem for the future, not for recorded traffic, because a signature only proves identity at the moment it is checked. Even so, the migration takes years, so the work has to start now.

What a key exchange does

Two parties need a shared secret to encrypt their session, and they cannot send that secret across an open network. A key exchange solves this. Each side generates a temporary (ephemeral) key pair, sends its public half to the other, and combines its private half with the other’s public half. Both arrive at the same shared secret. An eavesdropper sees the public halves but cannot compute the secret without solving the underlying hard problem.

In TLS 1.3, this exchange happens in the first messages of the handshake. The key exchange is what protects the session’s traffic, so it is the part that HNDL targets.

Key exchange groups

A key exchange group is a named algorithm that the two sides agree to use. TLS identifies each group with a code point. The client lists the groups it supports and sends a key share for one or more of them. The server picks one, and the two sides complete the exchange with it.

Classical groups include:

  • X25519: elliptic curve Diffie-Hellman on Curve25519. Fast and widely used. Broken by a sufficiently large quantum computer.
  • secp256r1 (P-256): a NIST elliptic curve group. Also broken by a quantum computer.
  • ffdhe2048 and similar finite-field groups: classical Diffie-Hellman, also broken by a quantum computer.

Post-quantum groups use a key encapsulation mechanism (KEM) instead. ML-KEM, standardised by NIST as FIPS 203, is the main example. It is designed to resist known quantum attacks. Pure ML-KEM groups exist, but most deployments use hybrid groups.

Hybrid: good, but not the end state

A hybrid group runs a classical exchange and a PQ exchange at the same time, then combines the two shared secrets into one key. Common examples are X25519MLKEM768 and SecP256r1MLKEM768. The session key stays secret as long as at least one of the two components holds. If ML-KEM turns out to have a flaw, the classical part still protects the session against today’s attacks. If a quantum computer arrives, the ML-KEM part still protects it.

That is why hybrid is the recommended first step. It protects against HNDL now, and it protects against a weakness in either algorithm, without betting everything on one new algorithm.

Hybrid is not the finish line, for three reasons:

  1. Certificates are still classical. Most certificates use RSA or ECDSA signatures. Hybrid protects the key exchange, not the identity check. Post-quantum signatures such as ML-DSA (FIPS 204) exist, but they are larger, and they require updates to certificate authorities, clients, and tooling.
  2. The protocol does not cover everything. TLS hybrid groups are standardised, but the exact code points and drafts still move. Some implementations offer hybrid groups only as preview or experimental features. Check what your stack actually ships.
  3. Negotiation is not guaranteed. An endpoint can offer a hybrid group and still negotiate a classical one, depending on the client. Offering a group is not the same as using it in every session.

SSH has a similar split. OpenSSH offers hybrid key exchange methods such as mlkem768x25519-sha256, but its host keys are still classical. Hybrid protects the session from HNDL. It does not protect the host identity from a future forgery.

What comes next

Before fixing anything, you need to know what your endpoints offer. Most certificate platforms only show the certificate and the TLS version. They do not show which key exchange groups an endpoint accepts. The next post covers how to find that out, and what the results mean.

P’s and Q’s

It’s pretty wild that this summer the messaging was “plan on getting to post-quantum certificates by roughly 2030, maybe 2035” and by December we’ve got “you probably should have post-quantum encryption already” It’s like the old saying about planting a fruit tree. The best time was years ago. The second-best time is now.

There was a recent claim by an Anthropic researcher that they used Claude to produce a proof of the Riemann Hypothesis that has since been mechanically verified in Lean. While proving the Riemann Hypothesis would not suddenly render modern cryptography useless (if for no other reason than cryptographers have generally operated under the assumption that it *is* true, even if we cannot *prove* it, for decades), it does demonstrate mathematical reasoning capabilities far beyond what many people expected from AI systems in the near term.

I don’t know whether that has anything to do with the timing of the NSA guidance, but it does seem relevant to the broader risk discussion. If AI systems are becoming useful collaborators in advanced mathematical research, it is reasonable to expect they may also accelerate work in areas such as lattice cryptanalysis, number theory, protocol analysis, implementation attacks, and side-channel research. That doesn’t mean any of those problems have been solved, but it may compress timelines in ways that were not being seriously considered a few years ago. Not that there is a *current* and *known* exploit, but that we reasonably expect breakthroughs in the near future thus recommend you secure against those advances before the crypto version of a Babel fish is released.

What I think is getting mixed together in the guidance is that there are really three separate efforts underway:

     * Inventory and automation - know where your cryptography is used and automate certificate and software deployment.
     * Protection against harvest-now/decrypt-later attacks - move TLS to post-quantum-capable key establishment, typically using hybrid key exchange.
     * Post-quantum certificates and PKI - move certificates, trust chains, code signing, and identity systems to PQ algorithms.

The first item is essentially a prerequisite. Inventory what you’ve got, identify crypto dependencies, automate deployment and renewal, and get current systems patched. If you don’t know what you have, you cannot do anything.

The second item seems to get lost in the discussion about post-quantum certificates. Looking at current TLS deployments, there are already production sites negotiating hybrid post-quantum key exchange. For example, my personal site negotiates X25519MLKEM768, which combines a traditional elliptic-curve exchange with ML-KEM-768. That means the session keys used to protect traffic today have protection against the classic “harvest now, decrypt later” scenario, even though the certificates themselves are still conventional certificates. I think of it as “post-quantum encryption with classical identity”. The NSA advisory specifically calls out enabling PQ settings in TLS 1.3 and using hybrid key exchange where available – this seems like the most immediately actionable advice because it provides tangible protection today against harvest-now/decrypt-later attacks without requiring the entire certificate ecosystem, operating system ecosystem, browser ecosystem, and customer device ecosystem to complete their own transitions first.

The third item, post-quantum certificates, is where things are much less mature. The major public certificate ecosystem is still transitioning. Let’s Encrypt’s roadmap, for example, is still focused on testing and rollout of PQ-capable certificate infrastructure. Sectigo opened signups for their PQ Lab over the summer, but platform is specifically designated as non-prod. Cloudflare is looking to be PQ-capable by 1Q2027. There are more than zero providers, but it’s not like you can ring up your current certificate provider and say “I’d like to add this product!”.

I’m surprised “upgrade” appears as item five in the NSA guidance. In practice, a lot of the success of the certificate transition depends on being on current platforms. RHEL9 (9.6 with optional config, but it’s 10.1 before it’s on by default). Windows 11 and Windows Server 2025. Internally that’s a significant undertaking, but a manageable one. Externally, we still have customers running Windows 10, old mobile operating systems, embedded devices, and other legacy platforms. We are not going to stop customers from paying bills because they don’t have a device that supports the latest post-quantum certificate ecosystem.

I suspect the industry spends several years in a hybrid state. Hybrid TLS key exchange seems deployable today and provides immediate protection against harvest-now/decrypt-later attacks. Hybrid certificates and PQ certificate chains provide a migration path for authentication and trust. The end goal is fully post-quantum infrastructure, but we’re clearly still in the “make today’s systems safer while preserving compatibility” phase rather than the “flip a switch and require PQ everywhere” phase.

Headwind Device Owner setup without a reset

Enable developer mode, enable USB debugging in developer options

set “ADB=%LOCALAPPDATA%\Android\Sdk\platform-tools\adb.exe”

“%ADB%” devices -l
“%ADB%” shell dpm list-owners
“%ADB%” shell pm list users
“%ADB%” shell dpm set-device-owner com.hmdm.launcher/.AdminReceiver
“%ADB%” shell dpm list-owners

 

Before the change, the phone had no Device Owner, one Android user, and no accounts. The command succeeded without a reset; the final check showed Headwind as DeviceOwner.

Headwind MDM: Restrictions

Android 13’s restriction keys—the actual values to enter in Headwind’s comma-separated Restrictions field. Some depend on device-owner status, Android version, or manufacturer behavior; test each one. Android 13 source

Network and connectivity

Apps and device access

Accounts, users, and profiles

Settings, display, and privacy

Calls, media, and other features

Android also defines hidden or internal keys, including no_camera and no_record_audio; they aren’t necessarily usable through Headwind’s restriction field.

Be careful with no_debugging_features, no_safe_boot, and no_factory_reset: they can make recovery harder. Also avoid assuming no_install_apps lets MDM deployments through—Android documents that it can block those too.

PIP – Where in the world are my binaries!?!?

If I run pip as root (and, yeah, I know you shouldn’t do that), I get happy functional binaries in /usr/bin. When I do the right thing, I (of course) cannot write to that bin folder. I cannot find my binaries! Running updatedb and using locate doesn’t help. Still got no files.

I ended up tracing an operation to find these things. They’re in my user home directory? And, of course, the locate command (and its database via updatedb) often excludes user home directories by default due to privacy and security concerns. So it looked like nothing was getting written to disk during the pip install.

Once I found the missing binaries in my ~/.local/bin folder, I was able to find that this is all well documented:

“Currently if user is installing their own tools with installers like (pip), they will be installed inside ~/.local/bin or ~/bin but if the same CLI tools are installed at system level the user would not be able to use his own tools because the system one would be picked instead. This happens because .bashrc file adds user PATH to the end instead of the top of PATH list variable.”

 

Of course, I go through all this research and learning to actually find the binary … only to discover that home assistant literally has something hard coded to require that you use a virtual environment. Not just do a pip install as your application user. I really wish people would explain why in their documentation. https://fedoraproject.org/wiki/Home_Assistant just says to type these commands. Which is nice if you don’t know what you are doing. But explaining why a virtual environment is being used would have saved me a lot of trouble just to bash up against another brick wall. Sigh. On the up side, I learned something new about Linux.

We didn’t think that should or would happen

“We didn’t think that should or would happen.” Duffy on the air traffic outage.

This seems like a fairly reasonable assertion to anyone who doesn’t actually implement changes to things that impact other people. What dude here fails to appreciate is that there aren’t many changes where we *expect* to take everything down. Most systems have redundancies. I can literally update and reboot one server in the system without anyone noticing. The difference between what we expect to happen and what DOES happen is why work is done during maintenance windows. Publicized so anyone who happens to be working at 2am knows who to call if things don’t look right.

I worked at a company that was planning an electrical upgrade at their data center. The electrician opened a floor panel to look at what he’d be doing. Literally just look. Somehow, dude dropped the quarter inch sheet metal cover into the opening, shorting some stuff out and dropping half of the servers that weren’t high enough priority for redundant power (also identified a few where redundancy power both went to the same place), had to take an ambulance to the hospital (he recovered and was fine). The data center ops guy – the one who declined all changes that weren’t in a maintenance window or accompanied by an emergency change and a critical issue ticket – kept that metal plate in his office as a reminder of why there were no exceptions. No matter how much someone might plead and assure him their change was so trivial.
Worked another place where they had a team removing the unused fiber. Contractors paid hourly, and the rate was higher for nights and weekends. Of course they wanted to save money and do this at 2 in the afternoon instead of 2 in the morning. And they found every poorly documented fiber connection into SAN shelves.
These changes were approved by immature change management structures who took “Nothing should happen, we’re just removing the unused fiber” as a 100% accurate depiction of reality. That took “I’m just opening this panel and looking over some wiring” as  immune to any accidents. In both companies, changes were made. The criterion for approving a change outside of the agreed upon maintenance window became much stricter. The “no impact expected” checkbox meant very little in deciding if the change would be approved or not.

For any organization that is approving non-critical changes during peak usage, hopefully this is a prompt to make some changes without having to take out dozens of your own systems. For the rest of us, though, it’s a good reminder why change management exists. Why it is a good thing someone is rejecting your change and requesting it be rescheduled during a maintenance window. To have some appreciation for the folks to review these changes for impact and handle end user notification. I think most of us who have worked in IT for a while know the feeling the guy who plugged in the Gear of Doom had. Having a couple extra people check your plan is a wonderful contribution to never feeling that again.

None is not 0

W3Schools documents the default number of digits for the python round function as 0

Except that’s not actually how the function works — if you don’t supply a value, you get an integer. No decimal places. If you supply a zero, you get the same value but with a decimal point. The float representation of that rounded value.

The default, per Python’s documentation at https://docs.python.org/3.11/library/functions.html#round :

round(number, ndigits=None)
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

The default value is None, not 0.

Blender – Making a Part Thicker

We are modifying a mount that lets you attach your cell phone to a microscope – one of the problems with the original design is that it’s not particularly sturdy. We lengthened the arms to accommodate larger cell phones, but that made the arms even flimsier. Anya showed us how to use s – z – 0 which flattens the selection to the average z height of the selected faces. Starting with a curved surface, I selected all of the faces. Then typed the letter s, the letter z, and 0

This flattens the object – the difference between the z location of all faces is zero. You can keep the curve but make it smaller by using a fractional number instead of zero. You can exaggerate the difference by using a number greater than 1. A negative number inverts the curve – the high part becomes low, and the low part becomes high.

Once the faces were on a single plane, we used G Z {number} to move the selected faces. The number is an offset from the plane where the faces are currently – so if you are at 4 and want the object to be 5mm thick, you use G Z 1. Using G Z 5 (which makes sense to move them to z of 5) actually makes the object 9mm thick!

The perpendicular faces are magically extruded so the faces you moved are not floating out there in space. The two arms that have already been increased, you can see that the perpendicular faces have been extended to meet the new face height. Obviously, if you want all three arms to be the same height you should select all of the top faces and adjust them simultaneously.

 

One other thing we learned in this adventure is how to select a bunch of faces between the faces you’ve already got selected and where you want to be. Shift will let you individually click faces, but I don’t want to click all of those little triangles along the curved side.

Selecting a few faces and then holding ctrl will select everything along the shortest path from where you already selected to where you click — here, selecting all the faces on the top of this arm. You can also use alt for a loop select — Anya finds that very functional, but it didn’t work for me!

On outages

What causes all the recent outages? I cannot rule out that there were AI driven cyber attacks. I cannot rule out that they were attacks from “enemy” countries. I also cannot rule out space aliens. But there were over a thousand MS patches this month, last month, etc. There are dozens of Linux patches most nights. We’ll get the Oracle patches of the month in a few days. In the rush to get things patched (absolutely the right thing to do), testing is either fully automated or getting less robust.

My expectation is that fully automated regression testing is going to be pushed hard in the near future. I’ve got Selenium scripts that run after the monthly Windows patch & reboot. Get a ping at dark o’clock that something doesn’t look right rather than a flood of calls at 7:30 AM.