{"id":12742,"date":"2026-12-04T23:08:08","date_gmt":"2026-12-05T04:08:08","guid":{"rendered":"https:\/\/www.rushworth.us\/lisa\/?p=12742"},"modified":"2026-12-04T23:08:09","modified_gmt":"2026-12-05T04:08:09","slug":"pq-step-0-inventory","status":"publish","type":"post","link":"https:\/\/www.rushworth.us\/lisa\/?p=12742","title":{"rendered":"PQ Step 0: Inventory"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The zeroth step in moving TLS authentication and encryption to a post-quantum (PQ) state is knowing what you have.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two TLS 1.3 endpoints can look identical in an inventory. One negotiates classical X25519. The other negotiates&nbsp;<code>X25519MLKEM768<\/code>. 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.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; notranslate\">\n&quot;&quot;&quot;\nScan a subnet for TLS endpoints and report their post-quantum (PQ) posture.\n\nStatus:\n  Fully PQ : leaf certificate public key is a PQ signature (ML-DSA, SLH-DSA, XMSS, LMS).\n  Hybrid   : classical certificate and the endpoint accepts a group in PQ_HYBRID_GROUPS.\n  No PQ    : classical certificate and no group in PQ_HYBRID_GROUPS is accepted.\n\nStandard library only. TLS versions 1.0-1.3 are probed with raw ClientHellos. Key exchange\ngroups are probed with TLS 1.3 ClientHellos that offer one group and an empty key_share; a\nserver that supports the group replies with a HelloRetryRequest selecting it, otherwise it\nreplies with an alert. Hybrid PQ groups only exist in TLS 1.3, so TLS 1.2-only endpoints\nare never hybrid.\n\nPorts in STARTTLS_PORTS (RDP, PostgreSQL, MariaDB) begin in plain text, so the protocol&#039;s\nupgrade step runs before the TLS probes. SQL Server (TDS) runs a PRELOGIN exchange and then\ncarries the TLS handshake inside TDS packets. Oracle TCPS is plain TLS on its own port (2484\nby convention, or any port configured for TCPS). Ports that do not answer TLS are reported as\nnon-TLS, with whatever plain-text banner they send (for example the SSH banner on port 22).\nAll TLS and non-TLS results go to one CSV file.\n&quot;&quot;&quot;\nimport contextlib\nimport csv\nimport ipaddress\nimport secrets\nimport socket\nimport ssl\nimport struct\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\n# ---------------- Configuration ----------------\nSUBNET = &quot;10.1.2.0&quot;\nCLASS_PREFIX = 24  # CIDR prefix length\nPORTS = &#x5B;22, 443, 1433, 1521, 2484, 3306, 3389, 5432, 8443, 9443]\nPQ_HYBRID_GROUPS = &#x5B;\n    &quot;X25519MLKEM768&quot;,\n    &quot;SecP256r1MLKEM768&quot;,\n    &quot;SecP384r1MLKEM1024&quot;,\n]\n# Substrings that mark an SSH key exchange name as post-quantum (e.g. mlkem768x25519-sha256).\nSSH_PQ_KEX_MARKERS = (&quot;mlkem&quot;, &quot;sntrup&quot;, &quot;kyber&quot;)\nTIMEOUT_SECONDS = 3\nMAX_WORKERS = 64\nOUTPUT_CSV = &quot;pq_scan_results.csv&quot;\n\n# Ports whose protocol starts in plain text and upgrades to TLS (name per _starttls).\nSTARTTLS_PORTS = {3389: &quot;rdp&quot;, 5432: &quot;postgresql&quot;, 3306: &quot;mariadb&quot;, 1433: &quot;mssql&quot;}\n\n# Key exchange groups probed on every TLS endpoint (name -&gt; IANA code point).\nKEX_GROUPS = {\n    &quot;secp256r1&quot;: 0x0017,\n    &quot;secp384r1&quot;: 0x0018,\n    &quot;secp521r1&quot;: 0x0019,\n    &quot;x25519&quot;: 0x001D,\n    &quot;x448&quot;: 0x001E,\n    &quot;ffdhe2048&quot;: 0x0100,\n    &quot;ffdhe3072&quot;: 0x0101,\n    &quot;X25519Kyber768Draft00&quot;: 0x6399,\n    &quot;SecP256r1MLKEM768&quot;: 0x11EB,\n    &quot;X25519MLKEM768&quot;: 0x11EC,\n    &quot;SecP384r1MLKEM1024&quot;: 0x11ED,\n    &quot;MLKEM512&quot;: 0x0200,\n    &quot;MLKEM768&quot;: 0x0201,\n    &quot;MLKEM1024&quot;: 0x0202,\n}\n\n# ---------------- Constants ----------------\nCIPHER_SUITES = &#x5B;0x1301, 0x1302, 0x1303, 0xC02B, 0xC02F, 0xC02C, 0xC030, 0xCCA9, 0xCCA8]\nLEGACY_CIPHER_SUITES = &#x5B;0xC02F, 0xC030, 0xC02B, 0xC02C, 0xC013, 0xC014, 0xC009, 0xC00A,\n                        0x009C, 0x009D, 0x002F, 0x0035, 0x000A, 0x0005]\nLEGACY_GROUPS = &#x5B;0x0017, 0x0018, 0x0019, 0x001D]\nSIGNATURE_ALGORITHMS = &#x5B;0x0403, 0x0503, 0x0603, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601, 0x0807]\nTLS_HRR_RANDOM = bytes.fromhex(&quot;CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C&quot;)\nTLS_VERSION_NAMES = {0x0301: &quot;1.0&quot;, 0x0302: &quot;1.1&quot;, 0x0303: &quot;1.2&quot;, 0x0304: &quot;1.3&quot;}\nLEGACY_VERSIONS = (0x0301, 0x0302, 0x0303)\nPQ_SIGNATURE_OIDS = {\n    &quot;1.2.840.113549.1.9.16.3.17&quot;: &quot;LMS (hash-based)&quot;,\n    &quot;1.3.6.1.5.5.7.6.34&quot;: &quot;XMSS (hash-based)&quot;,\n    &quot;1.3.6.1.5.5.7.6.35&quot;: &quot;XMSS-MT (hash-based)&quot;,\n}\nCLASSICAL_KEY_OIDS = {\n    &quot;1.2.840.113549.1.1.1&quot;: &quot;RSA&quot;,\n    &quot;1.2.840.10045.2.1&quot;: &quot;EC&quot;,\n    &quot;1.3.101.112&quot;: &quot;Ed25519&quot;,\n    &quot;1.3.101.113&quot;: &quot;Ed448&quot;,\n}\nNIST_SIG_ARC = &quot;2.16.840.1.101.3.4.3.&quot;\nCN_OID = &quot;2.5.4.3&quot;\n# X.224 connection request with RDP_NEG_REQ asking for TLS (1) or CredSSP\/hybrid (2).\nRDP_CONNECTION_REQUEST = bytes.fromhex(&quot;03000013&quot; + &quot;0EE00000000000&quot; + &quot;0100080003000000&quot;)\nTDS_PRELOGIN = 0x12\nTDS_MAX_PAYLOAD = 4088  # default TDS packet size (4096) minus the 8-byte header\nTDS_ENCRYPTION_NAMES = {0x00: &quot;off&quot;, 0x01: &quot;on&quot;, 0x02: &quot;not supported&quot;, 0x03: &quot;required&quot;}\nTDS_ENCRYPT_NOT_SUPPORTED = 0x02\n\n\n# ---------------- ClientHello \/ probing ----------------\ndef _u16(value):\n    return struct.pack(&quot;!H&quot;, value)\n\n\ndef _u24(value):\n    return struct.pack(&quot;!I&quot;, value)&#x5B;1:]\n\n\ndef _extension(ext_type, data):\n    return _u16(ext_type) + _u16(len(data)) + data\n\n\ndef _signature_algorithms_extension():\n    sig_data = b&quot;&quot;.join(_u16(s) for s in SIGNATURE_ALGORITHMS)\n    return _extension(0x000D, _u16(len(sig_data)) + sig_data)\n\n\ndef _groups_extension(groups):\n    groups_data = b&quot;&quot;.join(_u16(g) for g in groups)\n    return _extension(0x000A, _u16(len(groups_data)) + groups_data)\n\n\ndef _hello_message(legacy_version, cipher_suites, extensions):\n    cipher_data = b&quot;&quot;.join(_u16(c) for c in cipher_suites)\n    extension_data = b&quot;&quot;.join(extensions)\n    body = (_u16(legacy_version) + secrets.token_bytes(32) + b&quot;\\x00&quot;\n            + _u16(len(cipher_data)) + cipher_data\n            + b&quot;\\x01\\x00&quot;\n            + _u16(len(extension_data)) + extension_data)\n    handshake = b&quot;\\x01&quot; + _u24(len(body)) + body\n    return b&quot;\\x16\\x03\\x01&quot; + _u16(len(handshake)) + handshake\n\n\ndef _client_hello_tls13(groups):\n    extensions = &#x5B;\n        _extension(0x002B, b&quot;\\x02\\x03\\x04&quot;),     # supported_versions: TLS 1.3\n        _groups_extension(groups),\n        _signature_algorithms_extension(),\n        _extension(0x0033, _u16(0)),             # key_share: empty -&gt; forces HRR\n        _extension(0x002D, b&quot;\\x01\\x01&quot;),         # psk_key_exchange_modes\n    ]\n    return _hello_message(0x0303, CIPHER_SUITES, extensions)\n\n\ndef _client_hello_legacy(version):\n    extensions = &#x5B;\n        _groups_extension(LEGACY_GROUPS),\n        _extension(0x000B, b&quot;\\x01\\x00&quot;),         # ec_point_formats: uncompressed\n        _signature_algorithms_extension(),\n    ]\n    return _hello_message(version, LEGACY_CIPHER_SUITES, extensions)\n\n\ndef _read_exact(sock, count):\n    buf = b&quot;&quot;\n    while len(buf) &lt; count:\n        chunk = sock.recv(count - len(buf))\n        if not chunk:\n            raise ConnectionError(&quot;connection closed&quot;)\n        buf += chunk\n    return buf\n\n\ndef _parse_server_hello(message):\n    &quot;&quot;&quot;Return (kind, selected_group, negotiated_version) from a ServerHello or HelloRetryRequest.&quot;&quot;&quot;\n    body = message&#x5B;4:]\n    server_version = struct.unpack(&quot;!H&quot;, body&#x5B;:2])&#x5B;0]\n    is_hrr = body&#x5B;2:34] == TLS_HRR_RANDOM\n    pos = 35 + body&#x5B;34] + 3  # skip session id, cipher suite, compression\n    ext_len = struct.unpack(&quot;!H&quot;, body&#x5B;pos:pos + 2])&#x5B;0]\n    pos += 2\n    extensions = body&#x5B;pos:pos + ext_len]\n    selected_version = server_version\n    selected_group = None\n    p = 0\n    while p + 4 &lt;= len(extensions):\n        ext_type, length = struct.unpack(&quot;!HH&quot;, extensions&#x5B;p:p + 4])\n        data = extensions&#x5B;p + 4:p + 4 + length]\n        if ext_type == 0x002B:\n            selected_version = struct.unpack(&quot;!H&quot;, data&#x5B;:2])&#x5B;0]\n        elif ext_type == 0x0033 and is_hrr:\n            selected_group = struct.unpack(&quot;!H&quot;, data&#x5B;:2])&#x5B;0]\n        p += 4 + length\n    return (&quot;hrr&quot; if is_hrr else &quot;server_hello&quot;), selected_group, selected_version\n\n\ndef _tds_packet(payload):\n    &quot;&quot;&quot;Wrap payload in one TDS packet of type PRELOGIN (0x12), which also carries TLS handshake records.&quot;&quot;&quot;\n    return struct.pack(&quot;!BBHHBB&quot;, TDS_PRELOGIN, 0x01, 8 + len(payload), 0, 1, 0) + payload\n\n\ndef _read_tds_payload(sock):\n    header = _read_exact(sock, 8)\n    return _read_exact(sock, struct.unpack(&quot;!H&quot;, header&#x5B;2:4])&#x5B;0] - 8)\n\n\ndef _tds_prelogin(sock):\n    &quot;&quot;&quot;Send a TDS PRELOGIN and return the server&#039;s ENCRYPTION option value.&quot;&quot;&quot;\n    options = (b&quot;\\x00&quot; + _u16(11) + _u16(6)      # VERSION: offset 11, length 6\n               + b&quot;\\x01&quot; + _u16(17) + _u16(1)    # ENCRYPTION: offset 17, length 1\n               + b&quot;\\xff&quot;\n               + b&quot;\\x0e\\x00\\x00\\x00\\x00\\x00&quot;     # client version\n               + b&quot;\\x01&quot;)                        # ENCRYPT_ON\n    sock.sendall(_tds_packet(options))\n    reply = _read_tds_payload(sock)\n    pos = 0\n    while reply&#x5B;pos] != 0xFF:\n        if reply&#x5B;pos] == 0x01:\n            return reply&#x5B;struct.unpack(&quot;!H&quot;, reply&#x5B;pos + 1:pos + 3])&#x5B;0]]\n        pos += 5\n    raise ConnectionError(&quot;TDS PRELOGIN reply has no ENCRYPTION option&quot;)\n\n\nclass _TdsStream:\n    &quot;&quot;&quot;Socket-like wrapper that carries TLS records inside TDS packets, as SQL Server does.&quot;&quot;&quot;\n\n    def __init__(self, sock):\n        self._sock = sock\n        self._buffer = b&quot;&quot;\n\n    def sendall(self, data):\n        for start in range(0, len(data), TDS_MAX_PAYLOAD):\n            self._sock.sendall(_tds_packet(data&#x5B;start:start + TDS_MAX_PAYLOAD]))\n\n    def recv(self, count):\n        while not self._buffer:\n            self._buffer = _read_tds_payload(self._sock)\n        chunk, self._buffer = self._buffer&#x5B;:count], self._buffer&#x5B;count:]\n        return chunk\n\n\ndef _handshake_over_tds(stream, ctx):\n    &quot;&quot;&quot;Complete a TLS handshake over a _TdsStream and return the leaf certificate in DER form.&quot;&quot;&quot;\n    incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO()\n    tls = ctx.wrap_bio(incoming, outgoing)\n    done = False\n    while not done:\n        try:\n            tls.do_handshake()\n            done = True\n        except ssl.SSLWantReadError:\n            pass\n        if outgoing.pending:\n            stream.sendall(outgoing.read())\n        if not done:\n            incoming.write(stream.recv(65536))\n    return tls.getpeercert(binary_form=True)\n\n\ndef _starttls(sock, port):\n    &quot;&quot;&quot;Run the plain-text upgrade for STARTTLS_PORTS; raise ConnectionError if TLS is refused.&quot;&quot;&quot;\n    protocol = STARTTLS_PORTS.get(port)\n    if protocol == &quot;rdp&quot;:\n        sock.sendall(RDP_CONNECTION_REQUEST)\n        header = _read_exact(sock, 4)\n        payload = _read_exact(sock, struct.unpack(&quot;!H&quot;, header&#x5B;2:4])&#x5B;0] - 4)\n        neg_response = payload&#x5B;-8:]\n        if len(neg_response) != 8 or neg_response&#x5B;0] != 0x02:\n            raise ConnectionError(&quot;RDP did not select TLS&quot;)\n        if struct.unpack(&quot;&lt;I&quot;, neg_response&#x5B;4:8])&#x5B;0] not in (0x1, 0x2):\n            raise ConnectionError(&quot;RDP selected a non-TLS protocol&quot;)\n    elif protocol == &quot;postgresql&quot;:\n        sock.sendall(struct.pack(&quot;!II&quot;, 8, 80877103))  # SSLRequest\n        if _read_exact(sock, 1) != b&quot;S&quot;:\n            raise ConnectionError(&quot;PostgreSQL refused SSL&quot;)\n    elif protocol == &quot;mariadb&quot;:\n        greeting_header = _read_exact(sock, 4)\n        _read_exact(sock, int.from_bytes(greeting_header&#x5B;:3], &quot;little&quot;))\n        body = struct.pack(&quot;&lt;IIB&quot;, 0x0200 | 0x0800, 16777215, 33) + b&quot;\\x00&quot; * 23  # CLIENT_SSL\n        sock.sendall(len(body).to_bytes(3, &quot;little&quot;) + b&quot;\\x01&quot; + body)\n    elif protocol == &quot;mssql&quot;:\n        if _tds_prelogin(sock) == TDS_ENCRYPT_NOT_SUPPORTED:\n            raise ConnectionError(&quot;SQL Server refused encryption&quot;)\n\n\n@contextlib.contextmanager\ndef _open(ip, port):\n    sock = socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS)\n    try:\n        _starttls(sock, port)\n        yield _TdsStream(sock) if STARTTLS_PORTS.get(port) == &quot;mssql&quot; else sock\n    finally:\n        sock.close()\n\n\ndef _send_hello(ip, port, hello):\n    &quot;&quot;&quot;Return (kind, selected_group, negotiated_version); kind is &#039;hrr&#039;, &#039;server_hello&#039;, &#039;alert&#039; or &#039;none&#039;.&quot;&quot;&quot;\n    with _open(ip, port) as sock:\n        sock.sendall(hello)\n        for _ in range(5):\n            header = _read_exact(sock, 5)\n            content_type = header&#x5B;0]\n            if content_type not in (0x14, 0x15, 0x16):\n                return (&quot;none&quot;, None, None)\n            payload = _read_exact(sock, struct.unpack(&quot;!H&quot;, header&#x5B;3:5])&#x5B;0])\n            if content_type == 0x15:\n                return (&quot;alert&quot;, None, None)\n            if content_type == 0x16 and payload&#x5B;0] == 0x02:\n                return _parse_server_hello(payload)\n    return (&quot;none&quot;, None, None)\n\n\nPROBE_ERRORS = (OSError, IndexError, struct.error)  # malformed replies from old devices\n\n\ndef _offer(ip, port, hello):\n    &quot;&quot;&quot;Return (answered, negotiated_version). answered is False if the port gave no TLS response.&quot;&quot;&quot;\n    try:\n        kind, _, version = _send_hello(ip, port, hello)\n    except PROBE_ERRORS:\n        return False, None\n    return kind != &quot;none&quot;, version\n\n\ndef _group_supported(ip, port, code):\n    try:\n        kind, selected, _ = _send_hello(ip, port, _client_hello_tls13(&#x5B;code]))\n    except PROBE_ERRORS:\n        return False\n    return kind == &quot;hrr&quot; and selected == code\n\n\n# ---------------- Certificate handling ----------------\ndef _fetch_leaf_certificate(ip, port):\n    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n    ctx.check_hostname = False\n    ctx.verify_mode = ssl.CERT_NONE\n    ctx.minimum_version = ssl.TLSVersion.TLSv1\n    ctx.set_ciphers(&quot;ALL:@SECLEVEL=0&quot;)  # lets legacy TLS 1.0\/1.1 endpoints complete the handshake\n    try:\n        with _open(ip, port) as stream:\n            if isinstance(stream, _TdsStream):\n                return _handshake_over_tds(stream, ctx)\n            with ctx.wrap_socket(stream) as tls:\n                return tls.getpeercert(binary_form=True)\n    except (ValueError,) + PROBE_ERRORS:\n        return None\n\n\ndef _tls_remediation(accepted):\n    &quot;&quot;&quot;Return a priority-prefixed remediation note (HIGH, MEDIUM, LOW) or &#039;&#039; if none is needed.&quot;&quot;&quot;\n    if not accepted:\n        return &quot;REVIEW: no known TLS version negotiated&quot;\n    if max(accepted) &lt; 0x0303:\n        return &quot;HIGH: retire, TLS 1.1 or lower only&quot;\n    if accepted &amp; {0x0301, 0x0302}:\n        return &quot;MEDIUM: disable TLS 1.0\/1.1&quot;\n    if 0x0303 in accepted:\n        if 0x0304 in accepted:\n            return &quot;LOW: disable TLS 1.2 fallback&quot;\n        return &quot;LOW: upgrade to TLS 1.3 (required for hybrid PQ)&quot;\n    return &quot;&quot;\n\n\ndef _der_tlv(buf, pos):\n    &quot;&quot;&quot;Return (tag, content_start, content_length) for the DER element at pos.&quot;&quot;&quot;\n    tag = buf&#x5B;pos]\n    length = buf&#x5B;pos + 1]\n    pos += 2\n    if length &amp; 0x80:\n        count = length &amp; 0x7F\n        length = int.from_bytes(buf&#x5B;pos:pos + count], &quot;big&quot;)\n        pos += count\n    return tag, pos, length\n\n\ndef _der_children(buf, start, length):\n    children = &#x5B;]\n    pos = start\n    end = start + length\n    while pos &lt; end:\n        tag, content_start, content_len = _der_tlv(buf, pos)\n        children.append((tag, content_start, content_len))\n        pos = content_start + content_len\n    return children\n\n\ndef _oid_to_str(data):\n    arcs = &#x5B;]\n    value = 0\n    for byte in data:\n        value = (value &lt;&lt; 7) | (byte &amp; 0x7F)\n        if not byte &amp; 0x80:\n            arcs.append(value)\n            value = 0\n    first = arcs&#x5B;0]\n    head = &#x5B;first \/\/ 40, first % 40] if first &lt; 80 else &#x5B;2, first - 80]\n    return &quot;.&quot;.join(str(a) for a in head + arcs&#x5B;1:])\n\n\ndef _algorithm_oid(der, start, length):\n    _, oid_start, oid_len = _der_children(der, start, length)&#x5B;0]\n    return _oid_to_str(der&#x5B;oid_start:oid_start + oid_len])\n\n\ndef _common_name(der, start, length):\n    for _, rdn_start, rdn_len in _der_children(der, start, length):\n        for _, atv_start, atv_len in _der_children(der, rdn_start, rdn_len):\n            oid_tlv, value_tlv = _der_children(der, atv_start, atv_len)&#x5B;:2]\n            if _oid_to_str(der&#x5B;oid_tlv&#x5B;1]:oid_tlv&#x5B;1] + oid_tlv&#x5B;2]]) == CN_OID:\n                return der&#x5B;value_tlv&#x5B;1]:value_tlv&#x5B;1] + value_tlv&#x5B;2]].decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)\n    return None\n\n\ndef _certificate_fields(der):\n    &quot;&quot;&quot;Return public key OID, signature OID, subject CN and issuer CN of a DER X.509 certificate.&quot;&quot;&quot;\n    _, cert_start, cert_len = _der_tlv(der, 0)\n    cert_children = _der_children(der, cert_start, cert_len)\n    _, tbs_start, tbs_len = cert_children&#x5B;0]\n    tbs_children = _der_children(der, tbs_start, tbs_len)\n    # tbsCertificate: &#x5B;version] serial signature issuer validity subject subjectPublicKeyInfo\n    offset = 1 if tbs_children&#x5B;0]&#x5B;0] == 0xA0 else 0\n    _, issuer_start, issuer_len = tbs_children&#x5B;offset + 2]\n    _, subject_start, subject_len = tbs_children&#x5B;offset + 4]\n    _, spki_start, spki_len = tbs_children&#x5B;offset + 5]\n    _, spki_alg_start, spki_alg_len = _der_children(der, spki_start, spki_len)&#x5B;0]\n    _, sig_start, sig_len = cert_children&#x5B;1]\n    return {\n        &quot;public_key_oid&quot;: _algorithm_oid(der, spki_alg_start, spki_alg_len),\n        &quot;signature_oid&quot;: _algorithm_oid(der, sig_start, sig_len),\n        &quot;subject_cn&quot;: _common_name(der, subject_start, subject_len) or &quot;&quot;,\n        &quot;issuer_cn&quot;: _common_name(der, issuer_start, issuer_len) or &quot;&quot;,\n    }\n\n\ndef _nist_sig_number(oid):\n    &quot;&quot;&quot;Return N for OIDs of the form 2.16.840.1.101.3.4.3.N, otherwise None.&quot;&quot;&quot;\n    if not oid.startswith(NIST_SIG_ARC):\n        return None\n    suffix = oid&#x5B;len(NIST_SIG_ARC):]\n    return int(suffix) if suffix.isdigit() else None\n\n\ndef _is_pq_oid(oid):\n    if oid in PQ_SIGNATURE_OIDS:\n        return True\n    number = _nist_sig_number(oid)\n    return number is not None and 17 &lt;= number &lt;= 31\n\n\ndef _describe_oid(oid):\n    if oid in PQ_SIGNATURE_OIDS:\n        return PQ_SIGNATURE_OIDS&#x5B;oid]\n    if oid in CLASSICAL_KEY_OIDS:\n        return CLASSICAL_KEY_OIDS&#x5B;oid]\n    number = _nist_sig_number(oid)\n    if number is not None and 17 &lt;= number &lt;= 19:\n        return f&quot;ML-DSA ({oid})&quot;\n    if number is not None and 20 &lt;= number &lt;= 31:\n        return f&quot;SLH-DSA ({oid})&quot;\n    return oid\n\n\n# ---------------- Endpoint scan ----------------\ndef _probe_plain(ip, port):\n    &quot;&quot;&quot;Return the printable text the port sends without TLS, or None if the port is closed.&quot;&quot;&quot;\n    try:\n        with socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS) as sock:\n            try:\n                data = sock.recv(256)\n            except socket.timeout:\n                data = b&quot;&quot;\n    except OSError:\n        return None\n    return &quot;&quot;.join(chr(b) if 32 &lt;= b &lt; 127 else &quot;.&quot; for b in data).strip()\n\n\ndef _tds_encryption_banner(ip, port):\n    &quot;&quot;&quot;Describe SQL Server&#039;s PRELOGIN encryption setting; None if closed, &#039;&#039; if no PRELOGIN reply.&quot;&quot;&quot;\n    try:\n        sock = socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS)\n    except OSError:\n        return None\n    with sock:\n        try:\n            return &quot;TDS prelogin: encryption &quot; + TDS_ENCRYPTION_NAMES.get(_tds_prelogin(sock), &quot;unknown&quot;)\n        except PROBE_ERRORS:\n            return &quot;&quot;\n\n\ndef _ssh_kex_algorithms(ip, port):\n    &quot;&quot;&quot;Return the key exchange algorithms the SSH server advertises (KEXINIT is sent before encryption).&quot;&quot;&quot;\n    with socket.create_connection((ip, port), timeout=TIMEOUT_SECONDS) as sock:\n        sock.sendall(b&quot;SSH-2.0-pqscanner\\r\\n&quot;)\n        line = b&quot;&quot;\n        while not line.endswith(b&quot;\\n&quot;):\n            line += _read_exact(sock, 1)\n        for _ in range(10):\n            packet_length = struct.unpack(&quot;!I&quot;, _read_exact(sock, 4))&#x5B;0]\n            body = _read_exact(sock, packet_length)\n            payload = body&#x5B;1:packet_length - body&#x5B;0]]\n            if payload&#x5B;:1] == b&quot;\\x14&quot;:  # SSH_MSG_KEXINIT\n                name_len = struct.unpack(&quot;!I&quot;, payload&#x5B;17:21])&#x5B;0]\n                return payload&#x5B;21:21 + name_len].decode(&quot;ascii&quot;, errors=&quot;replace&quot;).split(&quot;,&quot;)\n    raise ConnectionError(&quot;no SSH_MSG_KEXINIT received&quot;)\n\n\ndef _ssh_kex_status(kex_names):\n    if any(marker in name for name in kex_names for marker in SSH_PQ_KEX_MARKERS):\n        return &quot;Hybrid (PQ kex offered)&quot;\n    return &quot;No PQ (no PQ kex offered)&quot;\n\n\ndef scan_endpoint(ip, port):\n    &quot;&quot;&quot;Return (&quot;tls&quot;, record), (&quot;non_tls&quot;, record) for an open port without TLS, or None if closed.&quot;&quot;&quot;\n    accepted = set()\n    tls13_answered, tls13_version = _offer(ip, port, _client_hello_tls13(list(KEX_GROUPS.values())))\n    answered = tls13_answered\n    if tls13_version == 0x0304:\n        accepted.add(0x0304)\n    for version in LEGACY_VERSIONS:\n        legacy_answered, negotiated = _offer(ip, port, _client_hello_legacy(version))\n        answered = answered or legacy_answered\n        if negotiated == version:\n            accepted.add(version)\n    if not answered:\n        if STARTTLS_PORTS.get(port) == &quot;mssql&quot;:\n            banner = _tds_encryption_banner(ip, port)\n        else:\n            banner = _probe_plain(ip, port)\n        if banner is None:\n            return None\n        record = {\n            &quot;ip&quot;: ip,\n            &quot;port&quot;: port,\n            &quot;transport&quot;: &quot;non-TLS&quot;,\n            &quot;banner&quot;: banner,\n            &quot;pq_status&quot;: &quot;N\/A (no TLS)&quot;,\n        }\n        if banner.startswith(&quot;SSH-&quot;):\n            try:\n                kex_names = _ssh_kex_algorithms(ip, port)\n                record&#x5B;&quot;ssh_kex_algorithms&quot;] = &quot;;&quot;.join(kex_names)\n                record&#x5B;&quot;pq_status&quot;] = _ssh_kex_status(kex_names)\n            except PROBE_ERRORS:\n                record&#x5B;&quot;ssh_kex_algorithms&quot;] = &quot;unavailable&quot;\n        return &quot;non_tls&quot;, record\n\n    supported = &#x5B;]\n    if 0x0304 in accepted:\n        supported = &#x5B;name for name, code in KEX_GROUPS.items() if _group_supported(ip, port, code)]\n    hybrid = &#x5B;g for g in supported if g in PQ_HYBRID_GROUPS]\n\n    der = _fetch_leaf_certificate(ip, port)\n\n    cert_key = cert_sig = subject_cn = issuer_cn = &quot;unavailable&quot;\n    cert_is_pq = False\n    if der is not None:\n        fields = _certificate_fields(der)\n        cert_key = _describe_oid(fields&#x5B;&quot;public_key_oid&quot;])\n        cert_sig = _describe_oid(fields&#x5B;&quot;signature_oid&quot;])\n        subject_cn = fields&#x5B;&quot;subject_cn&quot;]\n        issuer_cn = fields&#x5B;&quot;issuer_cn&quot;]\n        cert_is_pq = _is_pq_oid(fields&#x5B;&quot;public_key_oid&quot;])\n\n    if cert_is_pq:\n        status = &quot;Fully PQ&quot;\n    elif hybrid:\n        status = &quot;Hybrid&quot;\n    elif der is None:\n        status = &quot;Unknown (certificate not retrieved)&quot;\n    else:\n        status = &quot;No PQ&quot;\n\n    max_version = max(accepted) if accepted else None\n    return &quot;tls&quot;, {\n        &quot;ip&quot;: ip,\n        &quot;port&quot;: port,\n        &quot;transport&quot;: &quot;TLS&quot;,\n        &quot;banner&quot;: &quot;&quot;,\n        &quot;tls_max_version&quot;: TLS_VERSION_NAMES.get(max_version, &quot;none&quot;),\n        &quot;tls_versions_accepted&quot;: &quot;;&quot;.join(TLS_VERSION_NAMES&#x5B;v] for v in sorted(accepted)),\n        &quot;tls_remediation&quot;: _tls_remediation(accepted),\n        &quot;subject_cn&quot;: subject_cn,\n        &quot;issuer_ca_cn&quot;: issuer_cn,\n        &quot;cert_key&quot;: cert_key,\n        &quot;cert_signature&quot;: cert_sig,\n        &quot;kex_groups&quot;: &quot;;&quot;.join(supported),\n        &quot;pq_hybrid_groups&quot;: &quot;;&quot;.join(hybrid),\n        &quot;pq_status&quot;: status,\n    }\n\n\ndef _validate_config():\n    &quot;&quot;&quot;Fail fast on bad settings instead of partway through a scan.&quot;&quot;&quot;\n    ipaddress.ip_network(f&quot;{SUBNET}\/{CLASS_PREFIX}&quot;, strict=False)\n    if len(set(PORTS)) != len(PORTS):\n        raise ValueError(f&quot;PORTS contains duplicates: {PORTS}&quot;)\n    invalid = &#x5B;p for p in PORTS if not 1 &lt;= p &lt;= 65535]\n    if invalid:\n        raise ValueError(f&quot;PORTS outside 1-65535: {invalid}&quot;)\n    unknown = &#x5B;g for g in PQ_HYBRID_GROUPS if g not in KEX_GROUPS]\n    if unknown:\n        raise ValueError(f&quot;PQ_HYBRID_GROUPS names not in KEX_GROUPS: {unknown}&quot;)\n\n\ndef _write_results(rows):\n    rows.sort(key=lambda r: (ipaddress.ip_address(r&#x5B;&quot;ip&quot;]), r&#x5B;&quot;port&quot;]))\n    fieldnames = &#x5B;&quot;ip&quot;, &quot;port&quot;, &quot;transport&quot;, &quot;pq_status&quot;, &quot;banner&quot;,\n                  &quot;tls_max_version&quot;, &quot;tls_versions_accepted&quot;, &quot;tls_remediation&quot;,\n                  &quot;subject_cn&quot;, &quot;issuer_ca_cn&quot;, &quot;cert_key&quot;, &quot;cert_signature&quot;,\n                  &quot;kex_groups&quot;, &quot;pq_hybrid_groups&quot;, &quot;ssh_kex_algorithms&quot;]\n    with open(OUTPUT_CSV, &quot;w&quot;, newline=&quot;&quot;, encoding=&quot;utf-8&quot;) as handle:\n        writer = csv.DictWriter(handle, fieldnames=fieldnames, restval=&quot;&quot;)\n        writer.writeheader()\n        writer.writerows(rows)\n    tls_count = sum(1 for r in rows if r&#x5B;&quot;transport&quot;] == &quot;TLS&quot;)\n    error_count = sum(1 for r in rows if r&#x5B;&quot;transport&quot;] == &quot;error&quot;)\n    print(f&quot;\\n{tls_count} TLS endpoints, {len(rows) - tls_count - error_count} non-TLS open ports, &quot;\n          f&quot;{error_count} errors. Results written to {OUTPUT_CSV}&quot;)\n\n\ndef main():\n    _validate_config()\n    network = ipaddress.ip_network(f&quot;{SUBNET}\/{CLASS_PREFIX}&quot;, strict=False)\n    hosts = list(network.hosts()) or list(network)\n    targets = &#x5B;(str(ip), port) for ip in hosts for port in PORTS]\n    print(f&quot;Scanning {network} on ports {PORTS} ({len(targets)} endpoints)&quot;)\n\n    rows = &#x5B;]\n    pool = ThreadPoolExecutor(max_workers=MAX_WORKERS)\n    futures = {pool.submit(scan_endpoint, ip, port): (ip, port) for ip, port in targets}\n    try:\n        for future in as_completed(futures):\n            ip, port = futures&#x5B;future]\n            try:\n                result = future.result()\n            except Exception as exc:\n                rows.append({&quot;ip&quot;: ip, &quot;port&quot;: port, &quot;transport&quot;: &quot;error&quot;, &quot;pq_status&quot;: f&quot;Error: {exc}&quot;})\n                print(f&quot;{ip}:{port}  error: {exc}&quot;)\n                continue\n            if result is None:\n                continue\n            kind, record = result\n            rows.append(record)\n            if kind == &quot;tls&quot;:\n                print(f&quot;{ip}:{port}  TLS &#x5B;{record&#x5B;&#039;tls_versions_accepted&#039;]}]  CN={record&#x5B;&#039;subject_cn&#039;]}  &quot;\n                      f&quot;CA={record&#x5B;&#039;issuer_ca_cn&#039;]}  cert={record&#x5B;&#039;cert_key&#039;]}  &quot;\n                      f&quot;kex=&#x5B;{record&#x5B;&#039;kex_groups&#039;]}]  =&gt; {record&#x5B;&#039;pq_status&#039;]}&quot;\n                      + (f&quot;  ** {record&#x5B;&#039;tls_remediation&#039;]}&quot; if record&#x5B;&quot;tls_remediation&quot;] else &quot;&quot;))\n            else:\n                print(f&quot;{ip}:{port}  open, non-TLS  banner={record&#x5B;&#039;banner&#039;] or &#039;(none)&#039;}&quot;\n                      + (f&quot;  kex=&#x5B;{record&#x5B;&#039;ssh_kex_algorithms&#039;]}]  =&gt; {record&#x5B;&#039;pq_status&#039;]}&quot;\n                         if &quot;ssh_kex_algorithms&quot; in record else &quot;&quot;))\n    except KeyboardInterrupt:\n        print(&quot;\\nInterrupted: cancelling queued probes and saving partial results.&quot;)\n        for future in futures:\n            future.cancel()\n    finally:\n        pool.shutdown(wait=True)\n        _write_results(rows)\n\n\nif __name__ == &quot;__main__&quot;:\n    main()\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">What the scanner does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>scanSubnetAndReportPQStatus.py<\/code>&nbsp;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:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>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&#8217;s own handshake before the TLS probes run.<\/li>\n\n\n\n<li>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.<\/li>\n\n\n\n<li>Probes each TLS 1.3 key exchange group separately, and records every group the server accepts.<\/li>\n\n\n\n<li>Reads the leaf certificate&#8217;s key and signature algorithm, subject CN and issuer CN.<\/li>\n\n\n\n<li>Classifies the endpoint and flags the remediation priority.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">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&#8217;s preference decides what is negotiated.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Configuration and usage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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].<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The script writes one line per open port as it runs, and a CSV file with one row per open port. Example lines:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Reading the results<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Each TLS row gets one&nbsp;<code>pq_status<\/code>:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Status<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td><strong>Fully PQ<\/strong><\/td><td>The leaf certificate uses a PQ signature. The script recognises ML-DSA, SLH-DSA, XMSS and LMS.<\/td><\/tr><tr><td><strong>Hybrid<\/strong><\/td><td>The certificate is classical and the endpoint accepts at least one hybrid group.<\/td><\/tr><tr><td><strong>No PQ<\/strong><\/td><td>The certificate is classical and no hybrid group is accepted.<\/td><\/tr><tr><td><strong>Unknown<\/strong><\/td><td>The endpoint answered TLS but the certificate could not be fetched.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Use&nbsp;<code>tls_remediation<\/code>&nbsp;alongside it:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Priority<\/th><th>Condition<\/th><th>Action<\/th><\/tr><\/thead><tbody><tr><td><strong>HIGH<\/strong><\/td><td>Only TLS 1.1 or lower<\/td><td>Retire or replace the device.<\/td><\/tr><tr><td><strong>MEDIUM<\/strong><\/td><td>TLS 1.0 or 1.1 accepted with a higher version<\/td><td>Disable 1.0 and 1.1.<\/td><\/tr><tr><td><strong>LOW<\/strong><\/td><td>TLS 1.2 accepted<\/td><td>Disable the 1.2 fallback if 1.3 is also accepted. If 1.2 is the only version, plan an upgrade.<\/td><\/tr><tr><td><strong>REVIEW<\/strong><\/td><td>No known version answered<\/td><td>Check the endpoint by hand.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Two things to keep in mind when reading the output:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>A\u00a0<code>Hybrid<\/code>\u00a0result means the endpoint offers a hybrid group.<\/strong>\u00a0It does not mean every client negotiates one. Check a real client to confirm.<\/li>\n\n\n\n<li><strong>A TLS 1.2 endpoint is never\u00a0<code>Hybrid<\/code>.<\/strong>\u00a0It is a remediation item regardless of what its certificate or cipher suites look like.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">First steps<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The scan gives you a list. Work through it in this order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>1. Disable legacy TLS.<\/strong>&nbsp;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>2. Remove TLS 1.2 fallbacks where 1.3 works.<\/strong>&nbsp;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>3. Upgrade the software, where the vendor has shipped PQ support.<\/strong>&nbsp;The scan shows what is deployed. Upgrading is what changes the result. Two examples from the current research:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>RHEL 9.7<\/strong>\u00a0adds an opt-in\u00a0<code>PQ<\/code>\u00a0crypto policy with hybrid ML-KEM. Apply it with\u00a0<code>update-crypto-policies --set DEFAULT:PQ<\/code>. OpenSSH on RHEL 9.7 still has no ML-KEM key exchange, so SSH on those hosts stays classical.<\/li>\n\n\n\n<li><strong>Windows 11 and Windows Server 2025<\/strong>\u00a0offer hybrid TLS groups in Schannel from the July 2026 updates. Check Microsoft&#8217;s release notes for your build before rollout.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>4. Put non-upgradeable devices behind a proxy.<\/strong>&nbsp;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&#8217;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>5. Record the SSH state, even if you do not change it yet.<\/strong>&nbsp;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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What comes next<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2253],"tags":[2254,2265,2264,236,395],"class_list":["post-12742","post","type-post","status-publish","format-standard","hentry","category-pki","tag-pki","tag-post-quantum-computing","tag-pqc","tag-ssl","tag-tls"],"_links":{"self":[{"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/posts\/12742","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=12742"}],"version-history":[{"count":2,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/posts\/12742\/revisions"}],"predecessor-version":[{"id":12744,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=\/wp\/v2\/posts\/12742\/revisions\/12744"}],"wp:attachment":[{"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=12742"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=12742"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.rushworth.us\/lisa\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=12742"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}