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.

Leave a Reply

Your email address will not be published. Required fields are marked *