How to Turn On Post-Quantum Key Exchange in nginx and Prove It: Read the Negotiated Group With OpenSSL 3.5, Handle Fallbacks and Oversized Hellos, and Check Every Host in CI
A hands-on nginx 1.30.8 and OpenSSL 3.5 lab with nine key-exchange policies shows who gets X25519MLKEM768 and who falls back, reads the handshake bytes, simulates a firewall that drops the bigger...
Every HTTPS connection starts with two machines agreeing on a fresh secret key over a wire that anyone may be listening to. Someone recording that traffic today can keep it for years, and if a large enough quantum computer is ever built, the elliptic-curve math behind today’s key agreement is the part that would let the recording be opened. Post-quantum key exchange closes that door in advance. For a web server it is a TLS setting rather than a new certificate: the visitor and your server agree on a secret that needs an elliptic-curve exchange and a lattice-based one (ML-KEM) to be broken together.
Table Of Content
- The idea in plain words
- Two jobs in every handshake
- Groups, key shares and the guess
- What “hybrid” means
- What you need before you start
- Step 1: Check that your tools can speak post-quantum at all
- Step 2: Download nginx and make a throwaway certificate
- Step 3: Start a lab with nine key-exchange policies
- What nginx does with the value
- Test a value before you reload nginx
- Step 4: Ask one server which group it picked
- Save the probe library
- Step 5: Look at the bytes
- Step 6: Run the client-by-server matrix
- Rows that behave the way you want
- Rows that should worry you
- Step 7: Tuples, key shares and the extra round trip
- Who decides, the client or the server?
- Step 8: Turn the probes into a checker
- Step 9: Count what real clients negotiate with $ssl_curve
- Step 10: When a firewall chokes on the bigger ClientHello
- Step 11: Test the checker, then break it on purpose
- Step 12: Check real hosts
- A mistake the survey caught
- Common mistakes
- Testing with a client that cannot speak post-quantum
- Believing that a connection proves protection
- Testing the wrong hop
- Making the server post-quantum only
- A classical-first list with server preference
- Forgetting that TLS 1.2 and certificates stay classical
- A configuration that loads on one machine only
- A probe that is narrower than the clients it imitates
- Check that everything works end to end
- Where to go next
- What I tested, and what I did not
- Sources
This tutorial shows how to turn that on in nginx and, more importantly, how to prove it is on. You will run a private copy of nginx 1.30.8 with nine different key-exchange policies, connect five kinds of client to it with OpenSSL 3.5, and read the answers in a table and in the raw bytes of the handshake. You will write a Python checker, pqcheck.py, that gives any host one of six plain labels and an exit status for CI, with 43 tests and 14 planted bugs that the tests catch. You will see a Hello Retry Request, a simulated firewall that chokes on the larger ClientHello, nginx’s $ssl_curve log variable, and a dated check of 14 public hosts. Along the way you will meet a mistake in the first version of the checker, found by pointing it at a real government site.
The topic is current: Anthropic published four lattice-cryptography papers on November 30, and we covered what those papers say about ML-KEM and ML-DSA and the title-hash episode that preceded them. Nothing below depends on how that research turns out, because the group you will enable keeps X25519 in the exchange: you add a layer rather than swap one. For the federal timetable around all of this, see our report on NIST’s final transition report.
The idea in plain words
Two jobs in every handshake
A TLS handshake does two separate jobs. Key exchange is the two ends agreeing on a secret that nobody watching can compute. Authentication is the server proving, with a certificate and a signature, that it really is the site you meant to reach. Post-quantum key exchange changes only the first job. The certificate in this lab is an ordinary ECDSA P-256 one, and that is deliberate: recorded traffic is protected by keeping its key secret, so the key exchange is what has to resist a future computer, while a signature has to be broken while the connection is still open. Post-quantum certificates and signatures are a separate migration with their own timeline.
Groups, key shares and the guess
The math a key exchange uses is called a group. X25519 and secp256r1 are classical groups. In TLS 1.3 the client does not wait to be told which one to use. It lists every group it supports, then guesses one or two and sends its public value for each inside the ClientHello; those public values are called key shares. The server picks a group, answers with its own key share, and both sides compute the same secret. If the server wants a group that the client supports but sent no key share for, it replies with a Hello Retry Request (HRR) and the client starts again, which costs one extra round trip. Step 5 shows all of this in bytes.
What “hybrid” means
X25519MLKEM768 is one group made of two: an X25519 exchange and an ML-KEM-768 exchange (ML-KEM is the lattice-based mechanism standardized in NIST’s FIPS 203). The client sends both public values glued together, the server answers with both, and the TLS key schedule receives both secrets. RFC 10024 defines it, and says that the shared secret is “the concatenation of the ML-KEM shared secret and the X25519 shared secret.” That is the point of a hybrid: ML-KEM is new, X25519 has years of scrutiny behind it, and the session key depends on both.
The price is bytes. The same RFC puts the client’s share at 1216 bytes (1184 for ML-KEM and 32 for X25519) and the server’s at 1120 bytes (1088 for ML-KEM and 32 for X25519), against 32 bytes each for X25519 alone. These are the three hybrid groups you will meet:
| OpenSSL name | IANA value | Made of | Marked “Recommended” |
|---|---|---|---|
X25519MLKEM768 |
4588 (0x11EC) |
X25519 and ML-KEM-768 | Yes |
SecP256r1MLKEM768 |
4587 (0x11EB) |
P-256 and ML-KEM-768 | No |
SecP384r1MLKEM1024 |
4589 (0x11ED) |
P-384 and ML-KEM-1024 | No |
The values and the Recommended column come from IANA’s TLS Supported Groups registry as I fetched it on December 1, 2026, and all three rows cite RFC 10024. This tutorial uses X25519MLKEM768, the one the registry marks Recommended. The registry also lists pure ML-KEM groups (MLKEM512, MLKEM768 and MLKEM1024, values 512 to 514), which I did not test. One oddity worth knowing: the name says X25519 first, but on the wire the ML-KEM part comes first. RFC 10024 puts it this way: the client’s key exchange value is “the concatenation of the client’s ML-KEM-768 encapsulation key and the client’s X25519 ephemeral share,” and a note in the RFC calls the reversed order a matter of “historical reasons.”
What you need before you start
- A Windows 11 PC with Git for Windows, so that the commands run in Git Bash. I tested on Windows only. The lab scripts call the Windows
nginx.exe, so on Linux you can still usepqcheck.py(Steps 1, 8 and 12) against your own servers, but not the lab itself. - OpenSSL 3.5 or newer as the client. The OpenSSL that comes with Git Bash on my test machine is 3.5.7. OpenSSL 3.5 is the release that brought post-quantum support; its announcement lists “Support for PQC algorithms (ML-KEM, ML-DSA and SLH-DSA).”
- Python 3.13 (I used 3.13.14). The scripts use only the standard library; the tests need
pytest. - About 10 MB of disk and ports 9441 to 9451 free on 127.0.0.1.
- Comfort with a terminal. No TLS knowledge is assumed.
Step 1: Check that your tools can speak post-quantum at all
The most common mistake in this whole area is testing with a client that cannot offer a post-quantum group, which makes every server look classical. So start by asking your tools. Run these in Git Bash:
openssl version
openssl list -tls-groups -tls1_3
OpenSSL 3.5.7 9 Jun 2026 (Library: OpenSSL 3.5.7 9 Jun 2026)
secp256r1:secp384r1:secp521r1:x25519:x448:brainpoolP256r1tls13:brainpoolP384r1tls13:brainpoolP512r1tls13:ffdhe2048:ffdhe3072:ffdhe4096:ffdhe6144:ffdhe8192:MLKEM512:MLKEM768:MLKEM1024:SecP256r1MLKEM768:X25519MLKEM768:SecP384r1MLKEM1024
The first line is the version; the second is every group this OpenSSL can offer in TLS 1.3, separated by colons. You are looking for X25519MLKEM768 in that list. If it is missing, your OpenSSL is too old and nothing below will work as shown; pqcheck.py, which you will write in Step 8, refuses to run in that case instead of reporting wrong answers.
Now ask Python. The standard library’s ssl module uses whatever OpenSSL your Python was built with, which is often older than the one in Git Bash. The -u flag keeps the output lines in order:
python --version
python -u -c "import ssl; print(ssl.OPENSSL_VERSION); ssl.create_default_context().set_ecdh_curve('X25519MLKEM768')" 2>&1 | grep -E 'OpenSSL|ValueError'
Python 3.13.14
OpenSSL 3.0.21 9 Jun 2026
ValueError: unknown elliptic curve name 'X25519MLKEM768'
On this machine Python 3.13.14 is linked against OpenSSL 3.0.21, which has never heard of X25519MLKEM768, so a checker written with the ssl module would call every server classical. That is why pqcheck.py drives the OpenSSL command-line program instead. Your Python may differ, so run the check; it takes a second.
Step 2: Download nginx and make a throwaway certificate
Create an empty folder for the lab and keep every file from this tutorial in it. Put the file below there and run it. It downloads the Windows build of nginx 1.30.8 from nginx.org, unpacks it next to the script, and makes a self-signed certificate for localhost that is valid for two days.
# setup_pq.py
"""setup_pq.py: unpack the Windows build of nginx 1.30.8 next to this script and make a throwaway ECDSA certificate.
Run it once from the lab folder: python setup_pq.py
"""
import hashlib
import io
import pathlib
import shutil
import subprocess
import urllib.request
import zipfile
HERE = pathlib.Path(__file__).resolve().parent
URL = "https://nginx.org/download/nginx-1.30.8.zip"
OPENSSL = shutil.which("openssl") or "C:/Program Files/Git/usr/bin/openssl.exe"
if (HERE / "nginx-1.30.8").exists():
print("already unpacked: nginx-1.30.8")
else:
request = urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0"})
data = urllib.request.urlopen(request, timeout=90).read()
print(f"downloaded {len(data):,} bytes, sha256 {hashlib.sha256(data).hexdigest()}")
zipfile.ZipFile(io.BytesIO(data)).extractall(HERE)
print("unpacked: nginx-1.30.8")
if (HERE / "cert.pem").exists():
print("certificate already exists")
else:
subprocess.run(
[OPENSSL, "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes",
"-keyout", str(HERE / "key.pem"), "-out", str(HERE / "cert.pem"), "-days", "2",
"-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"],
check=True, capture_output=True,
)
print("wrote cert.pem and key.pem (ECDSA P-256, valid 2 days)")
python setup_pq.py
downloaded 2,775,867 bytes, sha256 ccd0c03ff665d4534e6595e455624ededc9eeb11a81a6a128920fcc928be1151
unpacked: nginx-1.30.8
wrote cert.pem and key.pem (ECDSA P-256, valid 2 days)
The certificate uses an ECDSA P-256 key, a classical one, on purpose. Remember the two jobs: this tutorial changes how the secret is agreed, not how the server proves who it is. Now ask the nginx you just unpacked which OpenSSL it carries:
./nginx-1.30.8/nginx.exe -V 2>&1 | head -3
nginx version: nginx/1.30.8
built by cl 19.44.35211 for x86
built with OpenSSL 3.5.9 29 Sep 2026
The line to read is “built with OpenSSL”. The Windows build bundles its own copy, here 3.5.9. On Linux, nginx normally uses the system’s OpenSSL, so run nginx -V and openssl version there; you need 3.5 or newer for ML-KEM.
Step 3: Start a lab with nine key-exchange policies
The next file writes an nginx configuration with nine servers on nine ports. Each one has a different ssl_ecdh_curve line, which is the nginx directive that sets the groups the server will accept for key exchange. The file also has helpers to start and stop nginx.
# servers.py
"""servers.py: the nine nginx servers of the lab, one ssl_ecdh_curve policy each, plus start and stop helpers.
usage: python servers.py conf print the generated nginx.conf
python servers.py start test the config and start nginx in the background
python servers.py stop stop it
"""
import pathlib
import socket
import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
NGINX_DIR = HERE / "nginx-1.30.8"
NGINX = str(NGINX_DIR / "nginx.exe")
# name -> (port, directives for that server block)
SERVERS = {
"auto": (9441, "ssl_ecdh_curve auto;"),
"hybrid_first": (9442, "ssl_ecdh_curve X25519MLKEM768:X25519:prime256v1;"),
"classical": (9443, "ssl_ecdh_curve X25519:prime256v1;"),
"pq_only": (9444, "ssl_ecdh_curve X25519MLKEM768;"),
"tuples": (9445, "ssl_ecdh_curve X25519MLKEM768/X25519:prime256v1;"),
"classical_first": (9446, "ssl_ecdh_curve X25519:X25519MLKEM768;"),
"server_pref": (9447, "ssl_ecdh_curve X25519:X25519MLKEM768; ssl_prefer_server_ciphers on;"),
"x25519_only": (9448, "ssl_ecdh_curve X25519;"),
"optional_hybrid": (9449, "ssl_ecdh_curve ?X25519MLKEM768:X25519:prime256v1;"),
}
CONF = """worker_processes 1;
error_log logs/pq_error.log notice;
pid logs/pq.pid;
events {{ worker_connections 128; }}
http {{
log_format pq '$server_port $ssl_protocol $ssl_curve';
access_log logs/pq_access.log pq;
ssl_certificate {cert};
ssl_certificate_key {key};
ssl_protocols TLSv1.2 TLSv1.3;
{servers}}}
"""
SERVER = """ server {{
listen 127.0.0.1:{port} ssl;
server_name localhost;
{directives}
location / {{ default_type text/plain; return 200 "{name}\\n"; }}
}}
"""
def write_conf():
blocks = "".join(SERVER.format(port=p, directives=d, name=n) for n, (p, d) in SERVERS.items())
text = CONF.format(cert=(HERE / "cert.pem").as_posix(), key=(HERE / "key.pem").as_posix(), servers=blocks)
(NGINX_DIR / "conf" / "pq.conf").write_text(text, encoding="utf-8", newline="\n")
return text
def nginx(*args):
return subprocess.run([NGINX, "-p", str(NGINX_DIR), "-c", "conf/pq.conf", *args],
cwd=NGINX_DIR, capture_output=True, text=True)
def running():
try:
socket.create_connection(("127.0.0.1", next(iter(SERVERS.values()))[0]), timeout=0.5).close()
return True
except OSError:
return False
def start():
"""Start nginx with the lab config. Returns True if this call started it, False if it was already running."""
if running():
return False
write_conf()
check = nginx("-t")
if check.returncode != 0:
raise RuntimeError("nginx -t failed:\n" + check.stderr)
subprocess.Popen([NGINX, "-p", str(NGINX_DIR), "-c", "conf/pq.conf"], cwd=NGINX_DIR,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _, (port, _) in SERVERS.items():
for _ in range(50):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.5).close()
break
except OSError:
time.sleep(0.1)
else:
raise RuntimeError(f"port {port} never opened")
return True
def stop():
nginx("-s", "stop")
time.sleep(0.5)
if __name__ == "__main__":
action = sys.argv[1] if len(sys.argv) > 1 else "conf"
if action == "start":
print("started" if start() else "already running")
elif action == "stop":
stop()
print("stopped")
else:
print(write_conf())
python servers.py start
started
Here are the first lines of the file it generated, with the folder name shortened. Two servers are shown; the other seven repeat the pattern with their own port and directive.
worker_processes 1;
error_log logs/pq_error.log notice;
pid logs/pq.pid;
events { worker_connections 128; }
http {
log_format pq '$server_port $ssl_protocol $ssl_curve';
access_log logs/pq_access.log pq;
ssl_certificate <lab>/cert.pem;
ssl_certificate_key <lab>/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
server {
listen 127.0.0.1:9441 ssl;
server_name localhost;
ssl_ecdh_curve auto;
location / { default_type text/plain; return 200 "auto\n"; }
}
server {
listen 127.0.0.1:9442 ssl;
server_name localhost;
ssl_ecdh_curve X25519MLKEM768:X25519:prime256v1;
location / { default_type text/plain; return 200 "hybrid_first\n"; }
}
The nine policies, and what each will teach you:
| Name | Port | ssl_ecdh_curve value |
What it shows |
|---|---|---|---|
auto |
9441 | auto |
nginx’s default |
hybrid_first |
9442 | X25519MLKEM768:X25519:prime256v1 |
post-quantum preferred, classical fallback |
classical |
9443 | X25519:prime256v1 |
no post-quantum group |
pq_only |
9444 | X25519MLKEM768 |
post-quantum or nothing |
tuples |
9445 | X25519MLKEM768/X25519:prime256v1 |
the / splits groups into ranked tuples |
classical_first |
9446 | X25519:X25519MLKEM768 |
classical listed first |
server_pref |
9447 | same, plus ssl_prefer_server_ciphers on |
who decides, client or server |
x25519_only |
9448 | X25519 |
a P-256 certificate with no P-256 group |
optional_hybrid |
9449 | ?X25519MLKEM768:X25519:prime256v1 |
the ? makes the post-quantum group optional |
What nginx does with the value
The nginx documentation for ssl_ecdh_curve says: “The special value auto (1.11.0) instructs nginx to use a list built into the OpenSSL library when using OpenSSL 1.0.2 or higher.” It also says: “When using OpenSSL 1.0.2 or higher, this directive sets the list of curves supported by the server.” The source agrees and shows how little nginx does. In ngx_event_openssl.c at the release-1.30.8 tag, the value auto returns before any group list is set, and any other value goes to SSL_CTX_set1_curves_list unchanged. So auto means “whatever your OpenSSL prefers”, and with OpenSSL 3.5 underneath that already includes the hybrid group, as the first row of the matrix in Step 6 will show. It also means anything OpenSSL accepts in a group list works in nginx, including the /, * and ? characters you will meet in Steps 7 and 10.
Test a value before you reload nginx
You do not have to start a server to find out whether nginx accepts a value. The helper below builds a trial copy of the configuration with one value swapped in and runs nginx -t on it.
# try_group.py
"""try_group.py: ask nginx to parse one ssl_ecdh_curve value, without starting anything.
usage: python try_group.py "X25519MLKEM768:X25519"
"""
import pathlib
import subprocess
import sys
import servers
value = sys.argv[1]
text = servers.write_conf().replace("ssl_ecdh_curve auto;", f"ssl_ecdh_curve {value};", 1)
trial = servers.NGINX_DIR / "conf" / "pq_try.conf"
trial.write_text(text, encoding="utf-8", newline="\n")
run = subprocess.run([servers.NGINX, "-p", str(servers.NGINX_DIR), "-c", "conf/pq_try.conf", "-t"],
cwd=servers.NGINX_DIR, capture_output=True, text=True)
trial.unlink()
print(f"ssl_ecdh_curve {value};")
for line in run.stderr.strip().splitlines():
print(" " + line.replace(str(servers.NGINX_DIR), "nginx-1.30.8"))
python try_group.py 'X25519MLKEM768:X25519:prime256v1'
python try_group.py 'X25519MLKEM9999:X25519'
python try_group.py '?X25519MLKEM9999:X25519'
ssl_ecdh_curve X25519MLKEM768:X25519:prime256v1;
nginx: the configuration file nginx-1.30.8/conf/pq_try.conf syntax is ok
nginx: configuration file nginx-1.30.8/conf/pq_try.conf test is successful
ssl_ecdh_curve X25519MLKEM9999:X25519;
nginx: [emerg] SSL_CTX_set1_curves_list("X25519MLKEM9999:X25519") failed
nginx: configuration file nginx-1.30.8/conf/pq_try.conf test failed
ssl_ecdh_curve ?X25519MLKEM9999:X25519;
nginx: the configuration file nginx-1.30.8/conf/pq_try.conf syntax is ok
nginx: configuration file nginx-1.30.8/conf/pq_try.conf test is successful
The first value is fine. The second names a group that does not exist, and nginx refuses to start with the line SSL_CTX_set1_curves_list(...) failed. The third puts a ? in front of the bad name and passes. The OpenSSL 3.5 documentation explains the character: “If a group name is prefixed with the ? character, it will be ignored if an implementation is missing.” I used a made-up name because both nginx builds I had link OpenSSL 3.5. An nginx linked against an OpenSSL without ML-KEM should treat X25519MLKEM768 the same way, as an unknown name, but I could not test that here. The practical lesson is a config line that loads on every machine: write ?X25519MLKEM768:X25519:prime256v1, which is the ninth server above. If that inference holds, one file then works on builds with and without ML-KEM.
Step 4: Ask one server which group it picked
With the lab running, connect to the first server and read the answer. echo | gives the program a blank line as input, so it closes right after the handshake. -servername sends the name localhost (SNI, the field that tells a server which site you want). -brief prints a short summary.
echo | openssl s_client -connect 127.0.0.1:9441 -servername localhost -brief 2>&1
Connecting to 127.0.0.1
depth=0 CN=localhost
verify error:num=18:self-signed certificate
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: CN=localhost
Hash used: SHA256
Signature type: ecdsa_secp256r1_sha256
Verification error: self-signed certificate
Negotiated TLS1.3 group: X25519MLKEM768
DONE
The verify error lines are expected: nobody trusts our throwaway certificate, and that does not matter for this test. The line you came for is Negotiated TLS1.3 group: X25519MLKEM768. This default OpenSSL 3.5.7 client offered the hybrid group, and nginx accepted it. Now the same server with a client that knows no post-quantum group, then one that insists on it:
echo | openssl s_client -connect 127.0.0.1:9441 -servername localhost -groups X25519 -brief 2>&1 | grep -E 'Negotiated|Peer Temp Key'
echo | openssl s_client -connect 127.0.0.1:9441 -servername localhost -groups X25519MLKEM768 -brief 2>&1 | grep -E 'Negotiated|Peer Temp Key'
Peer Temp Key: X25519, 253 bits
Negotiated TLS1.3 group: X25519MLKEM768
For a classical group this OpenSSL prints Peer Temp Key: X25519, 253 bits instead of the Negotiated line, so a script has to look for both. And here is what a refusal looks like, a client that insists on post-quantum talking to the server that has none (port 9443, the classical policy):
echo | openssl s_client -connect 127.0.0.1:9443 -servername localhost -groups X25519MLKEM768 -brief 2>&1 | grep -o 'alert handshake failure.*'
alert handshake failure:../openssl-3.5.7/ssl/record/rec_layer_s3.c:918:SSL alert number 40
Alert 40 is handshake_failure: no group in common, so no connection. Notice the lesson hiding in these four runs. The default client connected to everything and the picky clients did not. A browser behaves like the default client, so “the page loads” tells you nothing about post-quantum protection. You have to ask which group was chosen.
Save the probe library
Three of the scripts that follow reuse the same few lines, the ones that run openssl s_client and read its answer. Save them now as pqcheck.py. Step 8 explains how the file turns three probes into a label; for now you need its probe function, which runs one handshake and returns a small dictionary with the group, the protocol, the hello sizes and any error.
# pqcheck.py
"""pqcheck.py: ask TLS servers which key-exchange group they pick and say whether post-quantum key exchange is on.
Needs OpenSSL 3.5 or newer on PATH (Git for Windows ships one in Git Bash). Standard library only.
Exit status: 0 every target meets --require, 1 at least one does not, 2 the tool itself cannot run.
"""
import argparse
import ipaddress
import json
import re
import shutil
import subprocess
import sys
OPENSSL = shutil.which("openssl") or "C:/Program Files/Git/usr/bin/openssl.exe"
DEFAULT_PORT = 443
PQ_GROUP = "X25519MLKEM768"
CLASSICAL_GROUPS = "X25519:secp256r1:secp384r1" # what a client without post-quantum support offers
ALERTS = {40: "handshake_failure", 47: "illegal_parameter", 70: "protocol_version", 80: "internal_error"}
HELLO = re.compile(r"^>>> TLS 1\.\d, Handshake \[length ([0-9a-f]{4})\], ClientHello", re.M)
SERVER_HELLO = re.compile(r"^<<< TLS 1\.\d, Handshake \[length ([0-9a-f]{4})\], ServerHello", re.M)
NOTES = {
"pq-preferred": "a default client gets post-quantum key exchange, a classical-only client still connects",
"pq-only": "post-quantum works but a client with only classical groups is refused",
"pq-available": "supported, but a default client is given a classical group",
"classical-only": "no post-quantum group accepted",
"default-fails": "the default handshake fails while a smaller one works: look for a ClientHello size problem",
"unreachable": "no handshake completed",
}
def is_pq(group):
"""True for any group whose name carries ML-KEM (X25519MLKEM768, SecP256r1MLKEM768, MLKEM1024, ...)."""
return bool(group) and "MLKEM" in group.upper()
def is_ip(host):
try:
ipaddress.ip_address(host)
return True
except ValueError:
return False
def parse_target(text):
"""'example.com' -> ('example.com', 443); 'example.com:8443'; '[::1]:8443'."""
if text.startswith("["):
host, _, rest = text[1:].partition("]")
return host, int(rest[1:]) if rest.startswith(":") else DEFAULT_PORT
if text.count(":") == 1:
host, port = text.split(":")
return host, int(port)
return text, DEFAULT_PORT
def parse_output(text):
"""Turn the text printed by `openssl s_client -brief -msg` into a small dict."""
group = None
found = re.search(r"Negotiated TLS1\.3 group:\s*(\S+)", text)
if found:
group = found.group(1)
else:
found = re.search(r"(?:Peer|Server) Temp Key:\s*(.+)", text)
if found:
parts = [p.strip() for p in found.group(1).split(",")]
group = parts[1] if parts[0] == "ECDH" and len(parts) > 1 else parts[0]
protocol = re.search(r"Protocol version:\s*(\S+)", text)
hellos = [int(x, 16) for x in HELLO.findall(text)]
servers = [int(x, 16) for x in SERVER_HELLO.findall(text)]
ok = "CONNECTION ESTABLISHED" in text and protocol is not None
error = None
if not ok:
alert = re.search(r"SSL alert number (\d+)", text)
if alert:
error = ALERTS.get(int(alert.group(1)), "alert " + alert.group(1))
elif re.search(r"errno=|Connection refused|Connect call failed", text):
error = "connect failed"
else:
error = "no handshake"
return {
"ok": ok,
"protocol": protocol.group(1) if protocol else None,
"group": group if ok else None,
"client_hello": hellos[0] if hellos else None,
"server_hello": servers[-1] if servers else None,
"hello_retry": len(hellos) > 1,
"error": error,
}
def run_s_client(host, port=DEFAULT_PORT, groups=None, tls12=False, timeout=15):
"""Run one handshake with `openssl s_client` and return everything it printed. Raises TimeoutExpired."""
cmd = [OPENSSL, "s_client", "-connect", f"{host}:{port}", "-brief", "-msg"]
if not is_ip(host):
cmd += ["-servername", host]
if groups:
cmd += ["-groups", groups]
if tls12:
cmd += ["-tls1_2"]
run = subprocess.run(cmd, input="", capture_output=True, text=True, timeout=timeout, errors="replace")
return run.stdout + run.stderr
def probe(host, port=DEFAULT_PORT, groups=None, tls12=False, timeout=15):
"""One handshake, parsed. groups is an OpenSSL group list such as 'X25519' (None = the client's defaults)."""
try:
return parse_output(run_s_client(host, port, groups, tls12, timeout))
except subprocess.TimeoutExpired:
return {"ok": False, "protocol": None, "group": None, "client_hello": None, "server_hello": None,
"hello_retry": False, "error": "timeout"}
def classify(default, pq, classical):
"""Name what the three probes say. default = client defaults, pq = only X25519MLKEM768, classical = only classical groups."""
if not default["ok"]:
return "default-fails" if (pq["ok"] or classical["ok"]) else "unreachable"
if is_pq(default["group"]):
return "pq-preferred" if classical["ok"] else "pq-only"
return "pq-available" if pq["ok"] else "classical-only"
def meets(label, requirement):
if requirement == "pq-preferred":
return label == "pq-preferred"
return label in ("pq-preferred", "pq-only", "pq-available")
def check(host, port=DEFAULT_PORT, timeout=15):
default = probe(host, port, timeout=timeout)
pq = probe(host, port, groups=PQ_GROUP, timeout=timeout)
classical = probe(host, port, groups=CLASSICAL_GROUPS, timeout=timeout)
return {"host": host, "port": port, "label": classify(default, pq, classical),
"default": default, "pq": pq, "classical": classical}
def tool_problem():
"""None when this OpenSSL can offer X25519MLKEM768, else a sentence saying why not."""
try:
run = subprocess.run([OPENSSL, "list", "-tls-groups", "-tls1_3"], capture_output=True, text=True, timeout=20)
except (OSError, subprocess.TimeoutExpired) as exc:
return f"cannot run openssl: {exc}"
if PQ_GROUP.lower() not in run.stdout.lower():
return "this OpenSSL has no X25519MLKEM768 group (needs OpenSSL 3.5 or newer), so every server would look classical"
return None
def main(argv=None):
parser = argparse.ArgumentParser(description="Check post-quantum key exchange on TLS servers.")
parser.add_argument("targets", nargs="+", help="host, host:port or [ipv6]:port")
parser.add_argument("--require", choices=["pq-preferred", "pq-available"], default="pq-preferred")
parser.add_argument("--json", action="store_true", help="print the full probe results as JSON")
parser.add_argument("--timeout", type=float, default=15)
args = parser.parse_args(argv)
problem = tool_problem()
if problem:
print("pqcheck: " + problem, file=sys.stderr)
return 2
results = [check(*parse_target(t), timeout=args.timeout) for t in args.targets]
failed = [r for r in results if not meets(r["label"], args.require)]
if args.json:
print(json.dumps(results, indent=2))
else:
for r in results:
d = r["default"]
print(f"{r['host'] + ':' + str(r['port']):28} {r['label']:15} {str(d['group'] or d['error']):16} "
f"hello={d['client_hello'] or '-':<5} {NOTES[r['label']]}")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
Step 5: Look at the bytes
The -msg option makes s_client print every handshake message in hex. The script below reads the ClientHello and ServerHello out of that dump and lists the groups and key shares inside them, so you can see the sizes the RFC describes.
# wire.py
"""wire.py: list the groups and key shares inside the hello messages that `openssl s_client -msg` prints.
usage: python wire.py HOST:PORT [openssl -groups value]
"""
import re
import struct
import subprocess
import sys
from pqcheck import OPENSSL, parse_target
GROUP_NAMES = {
0x0017: "secp256r1", 0x0018: "secp384r1", 0x0019: "secp521r1", 0x001D: "X25519", 0x001E: "X448",
0x0100: "ffdhe2048", 0x0101: "ffdhe3072", 0x0102: "ffdhe4096", 0x0103: "ffdhe6144", 0x0104: "ffdhe8192",
0x0200: "MLKEM512", 0x0201: "MLKEM768", 0x0202: "MLKEM1024",
0x11EB: "SecP256r1MLKEM768", 0x11EC: "X25519MLKEM768", 0x11ED: "SecP384r1MLKEM1024",
}
SUPPORTED_GROUPS, KEY_SHARE = 0x000A, 0x0033
HEADER = re.compile(r"^(>>>|<<<) TLS 1\.\d, Handshake \[length ([0-9a-f]{4})\], (ClientHello|ServerHello)")
def name(group_id):
return GROUP_NAMES.get(group_id, f"0x{group_id:04x}")
def messages(text):
"""Yield (direction, kind, bytes) for each ClientHello or ServerHello in the -msg output."""
lines = text.splitlines()
for i, line in enumerate(lines):
found = HEADER.match(line)
if not found:
continue
hex_text = ""
for follow in lines[i + 1:]:
if not re.fullmatch(r"\s+([0-9a-f]{2} ?)+", follow):
break
hex_text += follow
yield found.group(1), found.group(3), bytes.fromhex(hex_text.replace(" ", ""))
def extensions(message, is_server):
pos = 4 + 2 + 32 # handshake header, legacy version, random
pos += 1 + message[pos] # legacy session id
if is_server:
pos += 2 + 1 # chosen cipher suite, compression method
else:
pos += 2 + struct.unpack(">H", message[pos:pos + 2])[0] # cipher suites
pos += 1 + message[pos] # compression methods
end = pos + 2 + struct.unpack(">H", message[pos:pos + 2])[0]
pos += 2
found = {}
while pos < end:
kind, size = struct.unpack(">HH", message[pos:pos + 4])
found[kind] = message[pos + 4:pos + 4 + size]
pos += 4 + size
return found
def describe(kind, message):
is_server = kind == "ServerHello"
exts = extensions(message, is_server)
lines = [f"{kind} {len(message)} bytes"]
if SUPPORTED_GROUPS in exts:
data = exts[SUPPORTED_GROUPS][2:]
ids = [struct.unpack(">H", data[i:i + 2])[0] for i in range(0, len(data), 2)]
lines.append(" supported_groups: " + ", ".join(name(g) for g in ids))
share = exts.get(KEY_SHARE, b"")
if is_server and len(share) == 2:
lines.append(f" key_share: HelloRetryRequest, server asks for {name(struct.unpack('>H', share)[0])}")
elif is_server:
group, size = struct.unpack(">HH", share[:4])
lines.append(f" key_share: {name(group)} ({size} bytes)")
elif share:
data, entries, pos = share[2:], [], 0
while pos < len(data):
group, size = struct.unpack(">HH", data[pos:pos + 4])
entries.append(f"{name(group)} ({size} bytes)")
pos += 4 + size
lines.append(" key_share: " + ", ".join(entries))
return "\n".join(lines)
def main(target, groups=None):
host, port = parse_target(target)
cmd = [OPENSSL, "s_client", "-connect", f"{host}:{port}", "-brief", "-msg", "-servername", "localhost"]
if groups:
cmd += ["-groups", groups]
run = subprocess.run(cmd, input="", capture_output=True, text=True, timeout=20, errors="replace")
for direction, kind, message in messages(run.stdout + run.stderr):
print(("client -> server " if direction == ">>>" else "server -> client ") + describe(kind, message).replace("\n", "\n" + " " * 18))
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
python wire.py 127.0.0.1:9441
python wire.py 127.0.0.1:9441 X25519
client -> server ClientHello 1544 bytes
supported_groups: X25519MLKEM768, X25519, secp256r1, X448, secp384r1, secp521r1, ffdhe2048, ffdhe3072
key_share: X25519MLKEM768 (1216 bytes), X25519 (32 bytes)
server -> client ServerHello 1210 bytes
key_share: X25519MLKEM768 (1120 bytes)
client -> server ClientHello 310 bytes
supported_groups: X25519
key_share: X25519 (32 bytes)
server -> client ServerHello 122 bytes
key_share: X25519 (32 bytes)
Read the first block from the top. The default client lists eight groups in preference order, with X25519MLKEM768 first, and sends two key shares: 1216 bytes for the hybrid and 32 for X25519. The whole ClientHello is 1544 bytes. The server answers with a 1210-byte ServerHello whose key share is 1120 bytes. Those three numbers, 1216, 32 and 1120, are the ones RFC 10024 gives: the client share is “1216 bytes (1184 bytes for the ML-KEM part and 32 bytes for X25519),” and the server share is “1120 bytes (1088 bytes for the ML-KEM part and 32 bytes for X25519).” The second block is the classical client: a 310-byte ClientHello and a 122-byte ServerHello.
Two details matter later. First, the ClientHello grows by about 1.2 KB. A typical Ethernet connection carries at most 1460 bytes of TCP payload per segment (1500 minus 40 bytes of IPv4 and TCP headers), so a post-quantum ClientHello no longer fits in one segment. Second, the exact size depends on the name you send in SNI: the probes in pqcheck.py connect to IP addresses in the lab and send no SNI, so their hello is 1526 bytes instead of 1544.
Step 6: Run the client-by-server matrix
One handshake tells you little. The script below connects five kinds of client to every server in the lab and prints a table. It uses the probe function from pqcheck.py, the file you saved at the end of Step 4. Save this one next to the others.
# matrix.py
"""matrix.py: connect five kinds of client to the lab servers and print which group each pair ends up with.
Start the servers first: python servers.py start
"""
import servers
from pqcheck import probe
CLIENTS = {
"default": {},
"classical": {"groups": "X25519"},
"pq_only": {"groups": "X25519MLKEM768"},
"pq_noshare": {"groups": "X25519MLKEM768:*X25519"},
"tls12": {"tls12": True},
}
def cell(result):
if not result["ok"]:
return "REFUSED"
text = result["group"] or "?"
return text + (" +HRR" if result["hello_retry"] else "")
def main():
print(f"{'server':17}" + "".join(f"{name:22}" for name in CLIENTS))
for name, (port, _) in servers.SERVERS.items():
row = [cell(probe("127.0.0.1", port, **opts)) for opts in CLIENTS.values()]
print(f"{name:17}" + "".join(f"{c:22}" for c in row))
if __name__ == "__main__":
main()
python matrix.py
server default classical pq_only pq_noshare tls12
auto X25519MLKEM768 X25519 X25519MLKEM768 X25519MLKEM768 +HRR X25519
hybrid_first X25519MLKEM768 X25519 X25519MLKEM768 X25519 X25519
classical X25519 X25519 REFUSED X25519 X25519
pq_only X25519MLKEM768 REFUSED X25519MLKEM768 X25519MLKEM768 +HRR REFUSED
tuples X25519MLKEM768 X25519 X25519MLKEM768 X25519MLKEM768 +HRR X25519
classical_first X25519MLKEM768 X25519 X25519MLKEM768 X25519 X25519
server_pref X25519 X25519 X25519MLKEM768 X25519 X25519
x25519_only X25519 X25519 REFUSED X25519 X25519
optional_hybrid X25519MLKEM768 X25519 X25519MLKEM768 X25519 X25519
The columns are the clients. default is the OpenSSL 3.5.7 client with its built-in list. classical offers X25519 only, like a client with no post-quantum support. pq_only offers only X25519MLKEM768. pq_noshare lists X25519MLKEM768 and X25519 but sends a key share only for X25519; that is what -groups X25519MLKEM768:*X25519 means, because the * marks the groups to send shares for. tls12 forces TLS 1.2. A cell shows the group that was negotiated, +HRR if a Hello Retry Request cost an extra round trip, or REFUSED if the handshake failed.
Rows that behave the way you want
Look at auto, nginx’s default. The default client gets X25519MLKEM768 and the classical client still connects with X25519. With a current OpenSSL underneath, post-quantum key exchange may already be on for you without anyone having asked for it. The tls12 column shows X25519 everywhere it connects: the hybrid groups belong to TLS 1.3, and the abstract of RFC 10024 says it “defines three hybrid key agreement mechanisms for TLS 1.3,” so a client held to TLS 1.2 never gets them.
Row hybrid_first is the graceful setup: post-quantum first, classical groups behind it in the same list. Row optional_hybrid behaves the same, which confirms that the ? prefix costs nothing when the group exists.
Rows that should worry you
Row classical shows the silent fallback. The default client falls back to X25519 without a word, and only the client that insists on post-quantum (pq_only) is refused. That is by design, so that old and new clients can share a server, and it is exactly why a connecting browser proves nothing.
Row pq_only shows the opposite mistake. The classical client and the TLS 1.2 client are both refused, so every visitor whose software lacks post-quantum support is locked out. Unless you control every client, that is an outage rather than a security upgrade.
Row x25519_only is a loose end from the nginx documentation, which warns: “Thus, in order for ECDSA certificates to work, it is important to include the curves used in the certificates.” Our certificate is ECDSA P-256 and this server lists only X25519, yet the default, classical, pq_noshare and TLS 1.2 clients all connected. I could not reproduce a failure with this OpenSSL, but I still list prime256v1 in the other policies because the documentation asks for it and I did not test every client.
Step 7: Tuples, key shares and the extra round trip
Compare the pq_noshare column for rows hybrid_first and tuples. Both servers prefer X25519MLKEM768, yet the first gives this client X25519 and the second gives it the post-quantum group, at the cost of a retry. The difference is one character in the configuration: a colon versus a slash. The OpenSSL 3.5 documentation explains it. Groups separated by : belong to one tuple, and “a more expressive syntax supports definition of group tuples of comparable security by separating them from each other with / characters.” The server then walks its tuples in order and stops at the first tuple that has any group in common with the client. If the client sent a key share for a group in that tuple, the server answers at once. If the client only lists a group from that tuple as supported, the server sends a Hello Retry Request. In the documentation’s words: “if a client supports a group in a server group tuple, but does not send a key share for this group, a Hello Retry Request (HRR) is triggered, asking the client to send a new Hello message with a more preferred keyshare.”
Watch it happen with the tuples server and the client that predicts only X25519:
python wire.py 127.0.0.1:9445 'X25519MLKEM768:*X25519'
client -> server ClientHello 312 bytes
supported_groups: X25519MLKEM768, X25519
key_share: X25519 (32 bytes)
server -> client ServerHello 88 bytes
key_share: HelloRetryRequest, server asks for X25519MLKEM768
client -> server ClientHello 1496 bytes
supported_groups: X25519MLKEM768, X25519
key_share: X25519MLKEM768 (1216 bytes)
server -> client ServerHello 1210 bytes
key_share: X25519MLKEM768 (1120 bytes)
The first ClientHello is small (312 bytes) because it carries only the X25519 share. The server’s reply is an 88-byte message whose key share contains just a group name: “send me X25519MLKEM768.” The client then sends a second, large ClientHello (1496 bytes) with the 1216-byte share, and the handshake finishes. With one tuple (hybrid_first) the server would have accepted the X25519 share it already had and skipped the retry, but that client would then be protected by classical math only.
So the choice is a trade. A single tuple avoids the round trip whenever the client’s key share is for any group in the list, and it gives post-quantum protection to every client that sends a post-quantum key share. Separate tuples force post-quantum on clients that support it but did not predict it, and those clients pay a round trip. Clients that send the hybrid share, which includes the default OpenSSL client in the first column, never pay.
Who decides, the client or the server?
Rows classical_first and server_pref have the same group list, X25519 first and the hybrid second. The default client gets the hybrid from the first and plain X25519 from the second. The only difference is ssl_prefer_server_ciphers on in the second. By default OpenSSL follows the client’s preference. The OpenSSL documentation says: “Server preference can be enforced by setting SSL_OP_CIPHER_SERVER_PREFERENCE using SSL_set_options (default: client preference).” nginx sets that option when you turn ssl_prefer_server_ciphers on, and a comment in its own source says what it does to key exchange: “By default a curve preferred by the client will be used for key exchange. The SSL_OP_CIPHER_SERVER_PREFERENCE option can be used to prefer server curves instead, similar to what it does for ciphers.” So a classical-first list plus server preference quietly takes post-quantum away from clients that asked for it. If you use ssl_prefer_server_ciphers on, list the hybrid group first.
Step 8: Turn the probes into a checker
Typing openssl s_client commands does not scale. The pqcheck.py you saved at the end of Step 4 already holds the other half: a small tool built on the same probe. For each host it makes three handshakes and names what they show:
- default: the client’s own defaults, a stand-in for an up-to-date client.
- pq: a client that offers only
X25519MLKEM768, to learn whether the server accepts it at all. - classical: a client that offers only classical groups (X25519, P-256 and P-384), to learn whether older clients still connect.
The three results decide one of six labels:
| Label | What the probes showed | Exit status with the default requirement |
|---|---|---|
pq-preferred |
the default client negotiated a post-quantum group and the classical client also connected | 0 |
pq-only |
post-quantum works, but the classical client was refused | 1 |
pq-available |
the default client was given a classical group, yet the post-quantum client connected | 1 (0 with --require pq-available) |
classical-only |
no post-quantum group accepted | 1 |
default-fails |
the default handshake failed while a smaller one worked | 1 |
unreachable |
nothing completed | 1 |
The exit status is the useful part: 0 means every host met the requirement, 1 means at least one did not, and 2 means the tool itself could not run. That last case matters. Before probing anything, the tool asks OpenSSL for its group list and stops with status 2 if X25519MLKEM768 is missing, because an old OpenSSL would otherwise make every host look classical and the failure would go unnoticed.
The functions that decide this are classify and meets, and the exit status comes from main. Each is a few lines, so read them in the file with this explanation beside it. Now run it against the lab. Each line shows the host and port, the label, the group the default client got (or the error), the size of its ClientHello, and a plain-language note:
python pqcheck.py 127.0.0.1:9441 127.0.0.1:9442 127.0.0.1:9443 127.0.0.1:9444 127.0.0.1:9445 127.0.0.1:9446 127.0.0.1:9447 127.0.0.1:9448 127.0.0.1:9449
echo "exit status: $?"
127.0.0.1:9441 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
127.0.0.1:9442 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
127.0.0.1:9443 classical-only X25519 hello=1526 no post-quantum group accepted
127.0.0.1:9444 pq-only X25519MLKEM768 hello=1526 post-quantum works but a client with only classical groups is refused
127.0.0.1:9445 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
127.0.0.1:9446 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
127.0.0.1:9447 pq-available X25519 hello=1526 supported, but a default client is given a classical group
127.0.0.1:9448 classical-only X25519 hello=1526 no post-quantum group accepted
127.0.0.1:9449 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
exit status: 1
The labels follow the matrix. auto, hybrid_first, tuples, classical_first and optional_hybrid are pq-preferred. pq_only is pq-only. server_pref is pq-available, the server that accepts post-quantum but hands a default client X25519. classical and x25519_only are classical-only. The exit status is 1 because several of them failed the requirement. To gate a deployment, name only the hosts that must pass:
python pqcheck.py --require pq-preferred 127.0.0.1:9441 127.0.0.1:9443
echo "exit status: $?"
127.0.0.1:9441 pq-preferred X25519MLKEM768 hello=1526 a default client gets post-quantum key exchange, a classical-only client still connects
127.0.0.1:9443 classical-only X25519 hello=1526 no post-quantum group accepted
exit status: 1
One passes and one does not, so the run fails with status 1, which is what a scheduler or CI job needs. The --json option prints every probe in full for dashboards.
Step 9: Count what real clients negotiate with $ssl_curve
A probe tells you what your server can do. Your logs tell you what your visitors actually get. nginx exposes the negotiated group in a variable; its documentation says: “$ssl_curve returns the negotiated curve used for SSL handshake key exchange process (1.21.5).” It adds: “The variable is supported only when using OpenSSL version 3.0 or higher. With older versions, the variable value will be an empty string.” The lab configuration already contains the two lines that use it, a log_format and an access_log (look back at the generated file in Step 3). The script below sends ten requests through the first server with three kinds of client, then counts what nginx wrote.
# curve_log.py
"""curve_log.py: send ten HTTPS requests with three kinds of client, then count which key-exchange group nginx logged.
Start the servers first: python servers.py start
nginx writes one line per request: $server_port $ssl_protocol $ssl_curve (see log_format in servers.py).
"""
import collections
import subprocess
import time
import servers
from pqcheck import OPENSSL
LOG = servers.NGINX_DIR / "logs" / "pq_access.log"
REQUEST = b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
TRAFFIC = [ # (how many requests, extra s_client options)
(5, []), # a default OpenSSL 3.5 client
(3, ["-groups", "X25519"]), # a client that knows no post-quantum group
(2, ["-tls1_2"]), # an old client limited to TLS 1.2
]
def send(port, options):
subprocess.run([OPENSSL, "s_client", "-connect", f"127.0.0.1:{port}", "-servername", "localhost", "-quiet", *options],
input=REQUEST, capture_output=True, timeout=20)
def main():
port = servers.SERVERS["auto"][0]
before = len(LOG.read_text().splitlines()) if LOG.exists() else 0
for count, options in TRAFFIC:
for _ in range(count):
send(port, options)
time.sleep(0.5)
lines = LOG.read_text().splitlines()[before:]
total = sum(count for count, _ in TRAFFIC)
print(f"requests sent: {total}, lines logged: {len(lines)}")
counts = collections.Counter(tuple(line.split()[1:3]) for line in lines)
print("count protocol curve")
for (protocol, curve), number in counts.most_common():
print(f"{number:5} {protocol:8} {curve}")
if __name__ == "__main__":
main()
python curve_log.py
requests sent: 10, lines logged: 10
count protocol curve
5 TLSv1.3 X25519MLKEM768
3 TLSv1.3 X25519
2 TLSv1.2 X25519
Five default clients negotiated the hybrid group, three classical clients and two TLS 1.2 clients got X25519. To count your own traffic, a plain shell pipeline over the log is enough. This one counts the second and third fields, the protocol and the group, over the lab’s log:
awk '{print $2, $3}' nginx-1.30.8/logs/pq_access.log | sort | uniq -c | sort -rn
7 TLSv1.3 X25519MLKEM768
4 TLSv1.3 X25519
2 TLSv1.2 X25519
The counts are larger than the script’s because the log holds three more lines, from the Step 4 probes: the blank line that echo | sends appears to count as a request. Those three handshakes were one hybrid, one classical TLS 1.3 and one hybrid again, in that order, which is the order of the three Step 4 commands.
On a real server, add the same log_format line, point an access_log at a file, and run the same pipeline daily. The share of lines with X25519MLKEM768 is the share of your requests that were protected by post-quantum key exchange, which is a better number to report than “we enabled it.”
Step 10: When a firewall chokes on the bigger ClientHello
You saw in Step 5 that a post-quantum ClientHello is about 1.5 KB. The OpenSSL documentation warns about what that can do: “The DEFAULT list selects X25519MLKEM768 as one of the predicted keyshares. In rare cases this can lead to failures or timeouts because the resulting larger TLS Client Hello message may no longer fit in a single TCP segment and firewall software may erroneously disrupt the TLS handshake.” The symptom is a handshake that hangs while a smaller one works. To make this concrete without a broken appliance, the script below imitates one: a tiny TCP proxy that reads the first TLS record of each connection and goes silent if it is larger than 1460 bytes. This is a simulation of the failure the documentation describes, not a measurement of any real product.
# firewall.py
"""firewall.py: imitate a middlebox that only looks at the first TCP segment and drops hellos that do not fit.
usage: python firewall.py LISTEN_PORT UPSTREAM_PORT [LIMIT_BYTES]
It listens on 127.0.0.1:LISTEN_PORT. If the first TLS record is larger than LIMIT_BYTES (default 1460, a common
TCP segment size) it goes silent, like a device that cannot reassemble the message. Otherwise it relays traffic.
This is a simulation of the failure OpenSSL's documentation warns about, not a measurement of any real product.
"""
import socket
import socketserver
import sys
import threading
import time
LIMIT = 1460
def pump(src, dst):
try:
while True:
data = src.recv(65536)
if not data:
break
dst.sendall(data)
except OSError:
pass
finally:
for sock in (src, dst):
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
class Handler(socketserver.BaseRequestHandler):
def handle(self):
client = self.request
first = client.recv(65536)
if len(first) >= 5 and 5 + int.from_bytes(first[3:5], "big") > self.server.limit:
time.sleep(30) # silent drop: no answer, no reset
return
upstream = socket.create_connection(("127.0.0.1", self.server.upstream))
upstream.sendall(first)
threading.Thread(target=pump, args=(upstream, client), daemon=True).start()
pump(client, upstream)
class Server(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
def serve(listen_port, upstream_port, limit=LIMIT):
server = Server(("127.0.0.1", listen_port), Handler)
server.upstream, server.limit = upstream_port, limit
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
if __name__ == "__main__":
serve(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) if len(sys.argv) > 3 else LIMIT)
time.sleep(3600)
Now put two lab servers behind it and compare what pqcheck.py and a gentler client see. The documentation offers the gentler client’s recipe: “prepending ?X25519MLKEM768: without a * prefix leads to its occurrence in the default list to be ignored as a duplicate, and along with that also the keyshare prediction.” In OpenSSL’s -groups syntax that is ?X25519MLKEM768:DEFAULT: the client still lists the hybrid group but sends no share for it.
# fw_demo.py
"""fw_demo.py: put two lab servers behind a firewall that drops big hellos, then compare what pqcheck and a gentler client see.
Start the servers first: python servers.py start
"""
import firewall
from pqcheck import main, probe
HYBRID_FIRST, TUPLES = 9442, 9445
default = probe("127.0.0.1", HYBRID_FIRST)
print(f"a default ClientHello is {default['client_hello']} bytes (the firewall's limit is {firewall.LIMIT} for the whole record)")
front_single = firewall.serve(9450, HYBRID_FIRST) # in front of one group tuple: PQ and X25519 are equals
front_tuples = firewall.serve(9451, TUPLES) # in front of two tuples: PQ first, then classical
print("--- pqcheck through the firewall")
main(["--timeout", "3", "127.0.0.1:9450", "127.0.0.1:9451"])
print("--- a client that sends only an X25519 key share: -groups ?X25519MLKEM768:DEFAULT")
for label, port in (("one tuple", 9450), ("two tuples", 9451)):
result = probe("127.0.0.1", port, groups="?X25519MLKEM768:DEFAULT", timeout=5)
print(f"{label:11} group={result['group']:15} hello_retry={result['hello_retry']!s:5} "
f"first ClientHello={result['client_hello']} bytes")
front_single.shutdown()
front_tuples.shutdown()
python fw_demo.py
a default ClientHello is 1526 bytes (the firewall's limit is 1460 for the whole record)
--- pqcheck through the firewall
127.0.0.1:9450 default-fails timeout hello=- the default handshake fails while a smaller one works: look for a ClientHello size problem
127.0.0.1:9451 default-fails timeout hello=- the default handshake fails while a smaller one works: look for a ClientHello size problem
--- a client that sends only an X25519 key share: -groups ?X25519MLKEM768:DEFAULT
one tuple group=X25519 hello_retry=False first ClientHello=306 bytes
two tuples group=X25519MLKEM768 hello_retry=True first ClientHello=306 bytes
Through the firewall, the checker reports default-fails for both servers: the default ClientHello (1526 bytes plus the record header) is over the limit, the probe times out, and only the smaller classical probe gets through. That label is your cue to look for a ClientHello size problem on the path. The gentler client then connects through the same firewall with a 306-byte first hello. What it ends up with depends on the server, which is the lesson from Step 7 again. Behind one tuple (the hybrid_first policy) it settles for X25519, because the share it sent is acceptable. Behind two tuples (the tuples policy) it gets X25519MLKEM768 after a Hello Retry Request; the large share travels in the second hello, which this simulated firewall lets through because it only inspects the first record of a connection. The documentation makes the same point: with the share left out, “the group will then only be selected by servers that specifically expect it, after a Hello Retry Request (HRR).”
Use that client-side recipe only where you control the clients. The better fix is to repair or update the device that mishandles large hellos, since leaving the share out turns off the default behavior for everyone behind it.
Step 11: Test the checker, then break it on purpose
A checker that reports security status has to be right, so it deserves tests. The file below has three kinds. The first group parses real transcripts that make_samples.py saved from the lab (a hybrid handshake, a classical one, a P-256 one, a TLS 1.2 one, a refusal, a Hello Retry Request and a connection to a closed port), so the parser is checked against what OpenSSL really prints. The second group is a truth table for the labels and the exit-status rule, including a fake old OpenSSL that has no ML-KEM group. The third group runs the checker against the live lab servers and against the simulated firewall.
# test_pqcheck.py
"""Tests for pqcheck.py: parsing and labels need no network, the live tests use the nginx lab on 127.0.0.1."""
import json
import pathlib
import subprocess
import pytest
import firewall
import pqcheck
import servers
from pqcheck import check, classify, is_pq, meets, parse_output, parse_target, probe
SAMPLES = pathlib.Path(__file__).resolve().parent / "samples"
def sample(name):
return (SAMPLES / f"{name}.txt").read_text(encoding="utf-8")
def fake(ok, group=None):
return {"ok": ok, "group": group if ok else None}
# ---------------------------------------------------------------- no network
@pytest.mark.parametrize("group,expected", [
("X25519MLKEM768", True), ("SecP256r1MLKEM768", True), ("SecP384r1MLKEM1024", True), ("MLKEM768", True),
("X25519", False), ("secp256r1", False), ("prime256v1", False), (None, False), ("", False)])
def test_is_pq(group, expected):
assert is_pq(group) is expected
@pytest.mark.parametrize("text,expected", [
("example.com", ("example.com", 443)), ("example.com:8443", ("example.com", 8443)),
("[::1]:8443", ("::1", 8443)), ("[::1]", ("::1", 443))])
def test_parse_target(text, expected):
assert parse_target(text) == expected
def test_parse_hybrid_transcript():
r = parse_output(sample("hybrid"))
assert r["ok"] and r["protocol"] == "TLSv1.3" and r["group"] == "X25519MLKEM768"
assert r["client_hello"] > 1400 and r["server_hello"] > 1100
assert r["hello_retry"] is False and r["error"] is None
def test_parse_classical_transcript():
r = parse_output(sample("classical"))
assert r["group"] == "X25519" and r["client_hello"] < 400
def test_parse_curve_and_tls12_transcripts():
assert parse_output(sample("p256"))["group"] == "prime256v1"
r = parse_output(sample("tls12"))
assert r["protocol"] == "TLSv1.2" and r["group"] == "X25519"
def test_parse_hello_retry_transcript():
r = parse_output(sample("hrr"))
assert r["hello_retry"] is True and r["group"] == "X25519MLKEM768"
assert r["client_hello"] < 400 and r["server_hello"] > 1100
def test_parse_alert_and_connect_failure():
alert = parse_output(sample("alert"))
assert alert["ok"] is False and alert["group"] is None and alert["error"] == "handshake_failure"
gone = parse_output(sample("refused"))
assert gone["ok"] is False and gone["error"] == "connect failed"
@pytest.mark.parametrize("default,pq,classical,label", [
(fake(True, "X25519MLKEM768"), fake(True, "X25519MLKEM768"), fake(True, "X25519"), "pq-preferred"),
(fake(True, "X25519MLKEM768"), fake(True, "X25519MLKEM768"), fake(False), "pq-only"),
(fake(True, "X25519"), fake(True, "X25519MLKEM768"), fake(True, "X25519"), "pq-available"),
(fake(True, "X25519"), fake(False), fake(True, "X25519"), "classical-only"),
(fake(False), fake(False), fake(True, "X25519"), "default-fails"),
(fake(False), fake(True, "X25519MLKEM768"), fake(False), "default-fails"),
(fake(False), fake(False), fake(False), "unreachable")])
def test_classify(default, pq, classical, label):
assert classify(default, pq, classical) == label
def test_meets():
assert meets("pq-preferred", "pq-preferred")
assert not meets("pq-only", "pq-preferred") and not meets("pq-available", "pq-preferred")
for label in ("pq-preferred", "pq-only", "pq-available"):
assert meets(label, "pq-available")
for label in ("classical-only", "default-fails", "unreachable"):
assert not meets(label, "pq-available")
def test_tool_problem_is_none_with_this_openssl():
assert pqcheck.tool_problem() is None
def test_tool_problem_for_an_old_openssl(monkeypatch):
old = subprocess.CompletedProcess([], 0, stdout="secp256r1:secp384r1:x25519:x448:ffdhe2048", stderr="")
monkeypatch.setattr(pqcheck.subprocess, "run", lambda *args, **kwargs: old)
assert "needs OpenSSL 3.5" in pqcheck.tool_problem()
def test_missing_openssl_exits_with_2(monkeypatch):
monkeypatch.setattr(pqcheck, "OPENSSL", "C:/no/such/openssl.exe")
assert "cannot run openssl" in pqcheck.tool_problem()
assert pqcheck.main(["127.0.0.1:9441"]) == 2
def test_sni_is_sent_for_names_but_not_for_addresses(monkeypatch):
seen = []
def fake_run(cmd, **kwargs):
seen.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
monkeypatch.setattr(pqcheck.subprocess, "run", fake_run)
pqcheck.run_s_client("example.com", 443)
pqcheck.run_s_client("192.0.2.1", 443)
assert "-servername" in seen[0] and "example.com" in seen[0]
assert "-servername" not in seen[1]
# ---------------------------------------------------------------- live, against the nginx lab
@pytest.fixture(scope="module")
def lab():
started = servers.start()
yield {name: port for name, (port, _) in servers.SERVERS.items()}
if started:
servers.stop()
def test_live_handshakes(lab):
assert probe("127.0.0.1", lab["auto"])["group"] == "X25519MLKEM768"
assert probe("127.0.0.1", lab["classical"], groups="X25519MLKEM768")["ok"] is False
assert probe("127.0.0.1", lab["pq_only"], groups="X25519")["error"] == "handshake_failure"
assert probe("127.0.0.1", lab["server_pref"])["group"] == "X25519"
assert probe("127.0.0.1", lab["auto"], tls12=True)["protocol"] == "TLSv1.2"
retry = probe("127.0.0.1", lab["tuples"], groups="X25519MLKEM768:*X25519")
assert retry["group"] == "X25519MLKEM768" and retry["hello_retry"] is True
single = probe("127.0.0.1", lab["hybrid_first"], groups="X25519MLKEM768:*X25519")
assert single["group"] == "X25519" and single["hello_retry"] is False
@pytest.mark.parametrize("server,label", [
("auto", "pq-preferred"), ("hybrid_first", "pq-preferred"), ("tuples", "pq-preferred"),
("classical_first", "pq-preferred"), ("pq_only", "pq-only"), ("server_pref", "pq-available"),
("classical", "classical-only"), ("x25519_only", "classical-only"), ("optional_hybrid", "pq-preferred")])
def test_live_labels(lab, server, label):
assert check("127.0.0.1", lab[server], timeout=10)["label"] == label
def test_live_unreachable():
assert check("127.0.0.1", 9499, timeout=5)["label"] == "unreachable"
def test_cli_exit_codes_and_json(lab, capsys):
host = "127.0.0.1:"
assert pqcheck.main([host + str(lab["auto"])]) == 0
assert pqcheck.main([host + str(lab["classical"])]) == 1
assert pqcheck.main([host + str(lab["server_pref"])]) == 1
assert pqcheck.main(["--require", "pq-available", host + str(lab["server_pref"])]) == 0
assert pqcheck.main([host + str(lab["auto"]), host + str(lab["classical"])]) == 1
capsys.readouterr()
assert pqcheck.main(["--json", host + str(lab["auto"])]) == 0
assert json.loads(capsys.readouterr().out)[0]["label"] == "pq-preferred"
def test_firewall_that_drops_big_hellos_shows_as_default_fails(lab):
front = firewall.serve(9450, lab["hybrid_first"])
try:
result = check("127.0.0.1", 9450, timeout=3)
finally:
front.shutdown()
assert result["label"] == "default-fails" and result["default"]["error"] == "timeout"
assert result["classical"]["group"] == "X25519"
The sample transcripts come from this small script. Run it once while the lab is up, then install pytest and run the suite:
# make_samples.py
"""make_samples.py: save real `openssl s_client` transcripts from the lab servers into samples/ for the unit tests."""
import pathlib
import servers
from pqcheck import run_s_client
HERE = pathlib.Path(__file__).resolve().parent
SAMPLES = HERE / "samples"
PORT = {name: port for name, (port, _) in servers.SERVERS.items()}
CASES = {
"hybrid": dict(server="auto", groups=None),
"classical": dict(server="auto", groups="X25519"),
"p256": dict(server="auto", groups="secp256r1"),
"tls12": dict(server="auto", tls12=True),
"alert": dict(server="pq_only", groups="X25519"),
"hrr": dict(server="tuples", groups="X25519MLKEM768:*X25519"),
}
def main():
SAMPLES.mkdir(exist_ok=True)
started = servers.start()
try:
for name, case in CASES.items():
text = run_s_client("127.0.0.1", PORT[case["server"]], case.get("groups"), case.get("tls12", False))
(SAMPLES / f"{name}.txt").write_text(text, encoding="utf-8", newline="\n")
print(f"{name:10} {len(text):6} characters")
text = run_s_client("127.0.0.1", 9499) # nothing listens here
(SAMPLES / "refused.txt").write_text(text, encoding="utf-8", newline="\n")
print(f"{'refused':10} {len(text):6} characters")
finally:
if started:
servers.stop()
if __name__ == "__main__":
main()
python make_samples.py
python -m pip install pytest
python -m pytest test_pqcheck.py -q -p no:cacheprovider
........................................... [100%]
43 passed in 63.83s (0:01:03)
Passing tests only matter if they can fail. The last script plants one bug at a time in pqcheck.py (a deliberate bug is called a mutation) and runs the suite to see whether it notices. The bugs are the kind a tired person writes: a group check that only accepts one exact name, a default port off by a digit, a probe that forgets its -groups option, an exit status that is always 0, and a tool check that lets an old OpenSSL through.
# mutants.py
"""mutants.py: plant one bug at a time in pqcheck.py and check that the test suite notices.
Run it with the same Python that runs the tests: python mutants.py
"""
import os
import pathlib
import re
import subprocess
import sys
HERE = pathlib.Path(__file__).resolve().parent
TARGET = HERE / "pqcheck.py"
MUTANTS = [
("is_pq accepts one exact group name",
'return bool(group) and "MLKEM" in group.upper()',
'return bool(group) and group.upper() == "X25519MLKEM768"'),
("default port 8443 instead of 443", "DEFAULT_PORT = 443", "DEFAULT_PORT = 8443"),
("pq-only servers called pq-preferred",
'return "pq-preferred" if classical["ok"] else "pq-only"', 'return "pq-preferred"'),
("pq-available never reported",
'return "pq-available" if pq["ok"] else "classical-only"', 'return "classical-only"'),
("--require pq-available accepts only that label",
'return label in ("pq-preferred", "pq-only", "pq-available")', 'return label == "pq-available"'),
("a second ClientHello is not a retry", '"hello_retry": len(hellos) > 1,', '"hello_retry": len(hellos) > 2,'),
("TLS 1.3 group line never matches", r'r"Negotiated TLS1\.3 group:\s*(\S+)"', r'r"Negotiated TLS1\.2 group:\s*(\S+)"'),
("alert 40 renamed", '40: "handshake_failure"', '40: "internal_error"'),
("-groups option dropped", ' if groups:\n cmd += ["-groups", groups]', ' if False:\n cmd += ["-groups", groups]'),
("-tls1_2 option dropped", ' if tls12:\n cmd += ["-tls1_2"]', ' if False:\n cmd += ["-tls1_2"]'),
("SNI sent for addresses, not names", " if not is_ip(host):", " if is_ip(host):"),
("exit status always 0", "return 1 if failed else 0", "return 0"),
("old OpenSSL passes the tool check",
"if PQ_GROUP.lower() not in run.stdout.lower():", 'if "x25519" not in run.stdout.lower():'),
("default-fails needs the PQ probe",
'return "default-fails" if (pq["ok"] or classical["ok"]) else "unreachable"',
'return "default-fails" if pq["ok"] else "unreachable"'),
]
def run_tests():
run = subprocess.run([sys.executable, "-m", "pytest", "test_pqcheck.py", "-x", "-q", "-p", "no:cacheprovider"],
cwd=HERE, capture_output=True, text=True, env={**os.environ, "COLUMNS": "170"})
failed = re.search(r"FAILED (\S+)", run.stdout)
return run.returncode, failed.group(1).split("::")[-1] if failed else ""
def main():
original = TARGET.read_text(encoding="utf-8")
code, _ = run_tests()
print(f"control (no bug planted): {'tests pass' if code == 0 else 'TESTS FAIL'}")
if code != 0:
return 1
caught = 0
try:
for number, (name, old, new) in enumerate(MUTANTS, 1):
assert original.count(old) == 1, f"mutant {number}: text to replace found {original.count(old)} times"
TARGET.write_text(original.replace(old, new), encoding="utf-8", newline="\n")
code, test = run_tests()
caught += code != 0
print(f"{number:2}. {name:48} {'caught by ' + test if code else 'SURVIVED'}")
finally:
TARGET.write_text(original, encoding="utf-8", newline="\n")
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
return 0 if caught == len(MUTANTS) else 1
if __name__ == "__main__":
sys.exit(main())
python mutants.py
control (no bug planted): tests pass
1. is_pq accepts one exact group name caught by test_is_pq[SecP256r1MLKEM768-True]
2. default port 8443 instead of 443 caught by test_parse_target[example.com-expected0]
3. pq-only servers called pq-preferred caught by test_classify[default1-pq1-classical1-pq-only]
4. pq-available never reported caught by test_classify[default2-pq2-classical2-pq-available]
5. --require pq-available accepts only that label caught by test_meets
6. a second ClientHello is not a retry caught by test_parse_hello_retry_transcript
7. TLS 1.3 group line never matches caught by test_parse_hello_retry_transcript
8. alert 40 renamed caught by test_parse_alert_and_connect_failure
9. -groups option dropped caught by test_live_handshakes
10. -tls1_2 option dropped caught by test_live_handshakes
11. SNI sent for addresses, not names caught by test_sni_is_sent_for_names_but_not_for_addresses
12. exit status always 0 caught by test_cli_exit_codes_and_json
13. old OpenSSL passes the tool check caught by test_tool_problem_for_an_old_openssl
14. default-fails needs the PQ probe caught by test_classify[default4-pq4-classical4-default-fails]
14 of 14 planted bugs caught
All 14 planted bugs were caught, and the table names the first test that failed for each. Two details are worth noticing. Mutant 1, which accepts only the exact name X25519MLKEM768, is caught by the SecP256r1MLKEM768 case in the first test, which is why that case is in the list. Mutants 9 and 10, a probe that forgets its -groups or -tls1_2 option, are caught only by the live handshakes against the lab, because no parser test can know that a command line was built wrongly. A suite made only of parser tests would have passed both.
Step 12: Check real hosts
Now point the checker at the real internet. These are ordinary TLS handshakes to the public HTTPS port, the same thing any browser does, and the script sends nothing else.
python pqcheck.py www.cloudflare.com www.google.com github.com www.microsoft.com aws.amazon.com www.apple.com kernel.org www.nist.gov www.cisa.gov en.wikipedia.org www.netflix.com www.python.org nginx.org sxz.io
echo "exit status: $?"
www.cloudflare.com:443 pq-preferred X25519MLKEM768 hello=1553 a default client gets post-quantum key exchange, a classical-only client still connects
www.google.com:443 pq-preferred X25519MLKEM768 hello=1549 a default client gets post-quantum key exchange, a classical-only client still connects
github.com:443 classical-only X25519 hello=1545 no post-quantum group accepted
www.microsoft.com:443 pq-preferred X25519MLKEM768 hello=1552 a default client gets post-quantum key exchange, a classical-only client still connects
aws.amazon.com:443 pq-preferred X25519MLKEM768 hello=1549 a default client gets post-quantum key exchange, a classical-only client still connects
www.apple.com:443 pq-preferred X25519MLKEM768 hello=1548 a default client gets post-quantum key exchange, a classical-only client still connects
kernel.org:443 classical-only X25519 hello=1545 no post-quantum group accepted
www.nist.gov:443 pq-preferred X25519MLKEM768 hello=1547 a default client gets post-quantum key exchange, a classical-only client still connects
www.cisa.gov:443 pq-preferred X25519MLKEM768 hello=1547 a default client gets post-quantum key exchange, a classical-only client still connects
en.wikipedia.org:443 classical-only X25519 hello=1551 no post-quantum group accepted
www.netflix.com:443 classical-only X25519 hello=1550 no post-quantum group accepted
www.python.org:443 pq-preferred X25519MLKEM768 hello=1549 a default client gets post-quantum key exchange, a classical-only client still connects
nginx.org:443 classical-only X25519 hello=1544 no post-quantum group accepted
sxz.io:443 pq-preferred X25519MLKEM768 hello=1541 a default client gets post-quantum key exchange, a classical-only client still connects
exit status: 1
I ran this on December 1, 2026, between 11:46 and 11:47 UTC, from one machine on one network, so treat it as a snapshot and not a ranking. Nine of the 14 hosts came back pq-preferred: Cloudflare, Google, Microsoft, Amazon Web Services, Apple, NIST, CISA, python.org and sxz.io. The other five, github.com, kernel.org, en.wikipedia.org, www.netflix.com and nginx.org, gave a default client plain X25519 and did not accept the post-quantum-only client, which makes them classical-only. Every row shows a ClientHello of 1541 to 1553 bytes; the spread comes from the length of the server name sent in SNI. The exit status is 1 because five hosts did not meet the default requirement, which is exactly the job of the status. The value of the script is not the ranking. It is that a one-minute run answers a question that is otherwise answered by assumption.
A mistake the survey caught
The first version of pqcheck.py used a classical probe that offered only X25519. In my first run of the survey it printed pq-only for www.nist.gov: the default client got X25519MLKEM768, but the X25519-only client was refused with a handshake failure. That looked like a federal site locking out classical clients. It was my probe’s fault. When I tried other client lists by hand a few minutes later, a client offering X25519:secp256r1 connected, and so did a client offering only secp256r1. The server accepts classical clients that speak P-256; it simply does not accept X25519 on its own. I do not know why NIST configured it that way and I did not look into it. The fix was to make the classical probe resemble a real client, so it now offers X25519, secp256r1 and secp384r1 (the constant CLASSICAL_GROUPS in the code above). Here is what the corrected checker says about the same site, reduced to three words by a one-line filter over the --json output:
python pqcheck.py --json www.nist.gov | python -c "import json, sys; r = json.load(sys.stdin)[0]; print(r['label'], r['classical']['group'], r['classical']['hello_retry'])"
pq-preferred prime256v1 True
The three words are the label, the group the classical probe negotiated, and whether that probe needed a Hello Retry Request: pq-preferred, prime256v1 and True. So www.nist.gov asked the classical client to retry with P-256 instead of X25519, which is a Hello Retry Request in the wild, the same mechanism you watched in Step 7. The lesson is that a probe is only as good as the client it imitates, and a wrong label in a security tool is worse than no tool, because people believe it.
Common mistakes
Testing with a client that cannot speak post-quantum
This is the one to remember. Python’s ssl module on this machine, or any older OpenSSL, will report “classical” for every server, and the result looks plausible. Check your tool first, as in Step 1, and make the tool refuse to run when it cannot do the job, as pqcheck.py does with exit status 2. One of the planted bugs in Step 11 let an old OpenSSL through, and the test with the fake old OpenSSL caught it.
Believing that a connection proves protection
Rows classical and auto of the matrix differ only in what the server chose, yet the default client connected to both. Always read the negotiated group, either with a probe or from $ssl_curve in your logs.
Testing the wrong hop
If a CDN, load balancer or ingress terminates TLS in front of your nginx, your visitors’ key exchange happens with that device, and your nginx only sees whatever that device negotiates with it. Probe the public name and the origin separately; our earlier post on Cloudflare’s post-quantum visibility treats readiness the same way.
Making the server post-quantum only
The pq_only row refuses clients that lack the hybrid group. Prefer a list that ends in classical groups unless you control every client.
A classical-first list with server preference
The server_pref row: X25519 listed first and ssl_prefer_server_ciphers on hands X25519 to a client that asked for the hybrid. List the hybrid group first.
Forgetting that TLS 1.2 and certificates stay classical
The tls12 column never shows a post-quantum group, and the certificate in this lab is ECDSA. Both are real and both are outside this tutorial. A TLS 1.2 client gets classical key exchange from any server, and the certificate signature is a separate migration.
A configuration that loads on one machine only
A bare X25519MLKEM768 in ssl_ecdh_curve stops nginx from starting when the OpenSSL underneath does not know the group. Write ?X25519MLKEM768:X25519:prime256v1 and run nginx -t on every machine before you roll out.
A probe that is narrower than the clients it imitates
See the survey section above: the first version of my classical probe offered only X25519 and wrongly called a federal site post-quantum-only. A probe is only as realistic as the client it stands in for.
Check that everything works end to end
Stop the lab, then confirm you can reproduce the story from scratch. python servers.py stop shuts nginx down. Then, on a machine you care about, do the real thing in four moves:
- Run
openssl versionandnginx -Vand confirm both say 3.5 or newer. - Put
ssl_ecdh_curve ?X25519MLKEM768:X25519:prime256v1;in yourhttporserverblock (or leave it onautoif your OpenSSL is 3.5 or newer), runnginx -t, and reload. - Run
python pqcheck.py --require pq-preferred your.host.nameand expectpq-preferredand exit status 0. - Add the
log_formatline from Step 3 and theawkpipeline from Step 9, and watch the share ofX25519MLKEM768in real traffic. Schedule the check from item 3 so that a regression, such as someone addingssl_prefer_server_ciphers onto a classical-first list, fails a job instead of going unnoticed.
Where to go next
- Signatures and certificates. Everything here left authentication classical. Our reports on NIST’s transition timetable and on Cloudflare’s post-quantum credential plan cover what comes after key exchange, and our private CA tutorial shows the certificate side in Python.
- Other servers. Apache, HAProxy, Caddy and Envoy each have their own setting for the key-exchange groups. I tested only nginx, so check each project’s documentation for the equivalent of
ssl_ecdh_curve. - HTTP/3. I did not test QUIC. The handshake there carries the same ClientHello, so the size lesson of Step 10 applies, but check your stack.
- Measure it in production. The
$ssl_curvepipeline from Step 9 is the start of a dashboard.
What I tested, and what I did not
I tested on Windows 11 with the OpenSSL 3.5.7 client that ships in Git Bash, nginx 1.30.8 for Windows (built with OpenSSL 3.5.9) on localhost, and Python 3.13.14. The public-host check is a snapshot taken on the date stated in Step 12 from one network. I did not test nginx on Linux, any other web server, browsers, QUIC, or a real firewall; the firewall in Step 10 is a simulation. I measured bytes, not latency. I could not run an nginx linked against an OpenSSL without ML-KEM, so the claim that it treats the group like an unknown name is an inference from the unknown-name test in Step 3.
Sources
- RFC 10024: Post-Quantum Traditional (PQ/T) Hybrid Key Agreement Mechanisms for TLS 1.3 (client and server share sizes, shared secret, group order).
- IANA TLS Supported Groups registry (values 4587 to 4589, the Recommended column).
- OpenSSL 3.5 documentation for SSL_CTX_set1_groups_list (group tuples, the
*and?prefixes,DEFAULT, Hello Retry Request, server preference, the TCP segment warning). - OpenSSL 3.5 s_client documentation (
-groups,-msg,-brief). - OpenSSL 3.5 release announcement (post-quantum algorithm support).
- nginx documentation for ngx_http_ssl_module (
ssl_ecdh_curve,ssl_prefer_server_ciphers,$ssl_curve). - nginx source, ngx_event_openssl.c at release-1.30.8 (how
autoand other values are handled).








No Comment! Be the first one.