PQ Python

Audit each worker image, grep for 256-bit curves, and record what every hop negotiates

Two runtime scripts, two code searches, the handshake checks and an inventory record format. Run the scripts inside the image that serves traffic: the interpreter, the cryptography wheel and the shell can each carry a different OpenSSL.

State as of 3 Dec 2026

In short

  • Run a read-only audit inside each worker image, not a developer shell; ssl, the cryptography wheel and openssl version can report three different builds (details).
  • Grep code and configs for 256-bit curves, JWT algorithm lists and classical-only curve settings; combine the searches, because each misses terms the others catch (details).
  • Prove the negotiated group with SSLSocket.group() on Python 3.15, or the Cloudflare trace endpoint and curl --curves elsewhere (details).
  • Record one inventory row per hop or trust decision, with metadata only: never private keys, bearer tokens or session secrets (details).
  • OPENSSL_CONF and server-hook recipes live on the TLS page.

Run the runtime audit inside the image that serves traffic#

Hybrid key exchange depends on the OpenSSL linked to the interpreter’s _ssl module, not on the Python version. Official cryptography wheels statically link their own OpenSSL, and the openssl binary in a shell can be a third build. In one isolated CPython 3.13.5 process, ssl reported OpenSSL 3.6.3 while cryptography 51.0.0 and pyOpenSSL 26.5.1 both reported 4.1.1 ASTRA.

Two scripts follow. The AGY script probes live hosts and lists package versions. The ASTRA script makes no network connections and only reports what is installed. Run either in web servers, workers, cron jobs, CI images, Lambda and container bases, and developer machines (action plan).

The AGY script checks OpenSSL, probes two hosts and lists crypto packages#

Run it in every container, CI job and production host. It reports the linked OpenSSL, whether it is 3.5 or later, the PQ groups the build implements on Python 3.15, a TLS 1.3 probe of pypi.org and cloudflare.com, whether cryptography’s backend supports ML-KEM and ML-DSA, and the installed versions of 17 relevant distributions.

#!/usr/bin/env python3
"""Audit a Python environment's readiness for NSA Advisory PP-26-4956."""
import importlib.metadata, socket, ssl, sys

print(f"Python:          {sys.version.split()[0]}")
print(f"ssl.OPENSSL:     {ssl.OPENSSL_VERSION} (0x{ssl.OPENSSL_VERSION_NUMBER:08x})")
has_35 = ssl.OPENSSL_VERSION_NUMBER >= 0x30500000
print(f"OpenSSL >= 3.5:  {has_35} ({'PQ KEX ready' if has_35 else 'CLASSICAL ONLY — UPGRADE RUNTIME!'})")

ctx = ssl.create_default_context()
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
if hasattr(ctx, "get_groups"):
    print(f"PQ groups (3.15): {[g for g in ctx.get_groups() if 'MLKEM' in g]}")
else:
    print("PQ groups API:   Requires Python 3.15+ (using OpenSSL defaults / OPENSSL_CONF)")

for host in ("pypi.org", "cloudflare.com"):
    try:
        with socket.create_connection((host, 443), timeout=5) as raw:
            with ctx.wrap_socket(raw, server_hostname=host) as ss:
                grp = ss.group() if hasattr(ss, "group") else "(inspect via Python 3.15 or openssl s_client)"
                print(f"Probe {host:15s}: {ss.version()} | {ss.cipher()[0]} | group={grp}")
    except Exception as exc:
        print(f"Probe {host:15s}: FAILED ({exc})")

try:
    from cryptography.hazmat.backends.openssl import backend
    print(f"cryptography PQ: mlkem={backend.mlkem_supported()}, mldsa={backend.mldsa_supported()}")
except Exception as exc:
    print(f"cryptography PQ: unavailable ({exc})")

for pkg in ("cryptography", "pycryptodome", "pycryptodomex", "PyNaCl", "python-jose",
            "PyJWT", "jwcrypto", "joserfc", "fastapi", "uvicorn", "granian",
            "paramiko", "asyncssh", "certbot", "sigstore", "grpcio", "psycopg-binary"):
    try:
        print(f"  {pkg:18s} {importlib.metadata.version(pkg)}")
    except importlib.metadata.PackageNotFoundError:
        pass
Edge casesreading the AGY script's output
  • “PQ groups (3.15)” shows capability, not configuration. SSLContext.get_groups() returns the groups the build implements, not the configured or negotiated set ASTRA. It needs Python 3.15 built against OpenSSL ≥3.5; unsupported builds can raise NotImplementedError.
  • group= is filled in only on Python 3.15. SSLSocket.group() needs Python 3.15 and OpenSSL ≥3.2. On older Pythons, use the trace endpoint or openssl s_client (verify the handshake).
  • The probe context requires TLS 1.3. A FAILED line can mean the peer is TLS 1.2-only. Hybrid groups are TLS 1.3-only anyway.
  • What to expect from the probe hosts. pypi.org negotiated X25519MLKEM768 in both the Claude and AGY reports’ live probes on 3 Dec 2026, so on Python 3.15 with OpenSSL ≥3.5 the line should show that group (supply-chain page).
  • LibreSSL. ssl.OPENSSL_VERSION_INFO reports LibreSSL’s own version number, so also read the ssl.OPENSSL_VERSION text (Claude report, not tested). macOS /usr/bin/python3 3.9.6 links LibreSSL 2.8.3 and negotiated TLS 1.2 with X25519 in the Claude report’s tests.
  • mlkem_supported() / mldsa_supported() return true only on AWS-LC, BoringSSL or OpenSSL ≥3.5 backends; OS-packaged cryptography linked to OpenSSL 3.0 to 3.4 or LibreSSL returns false (cryptography page).

The ASTRA script is read-only and makes no connections#

Use this where outbound probes are not allowed. It reports the CPython version, the stdlib TLS library, six relevant distributions and the PyCA backend’s OpenSSL, which is a diagnostic, not a TLS result. Run it inside the actual worker image, not the developer’s shell.

import ssl, sys
from importlib.metadata import PackageNotFoundError, version

print("CPython:", sys.version.split()[0], "stdlib TLS:", ssl.OPENSSL_VERSION)
for name in ("cryptography", "pyOpenSSL", "fastapi", "uvicorn", "PyJWT", "jwcrypto"):
    try:
        print(name, version(name))
    except PackageNotFoundError:
        pass
try:
    from cryptography.hazmat.backends.openssl.backend import backend
except ImportError:
    pass
else:
    print("PyCA backend:", backend.openssl_version_text())  # diagnostic, not a TLS result

Fail CI when the cryptography backend has no PQ#

The AGY report recommends asserting PQ support in CI, because a distro-packaged or source-built cryptography on OpenSSL 3.0 to 3.4 or LibreSSL imports cleanly but raises UnsupportedAlgorithm on ML-KEM and ML-DSA calls.

from cryptography.hazmat.backends.openssl import backend
assert backend.mlkem_supported() and backend.mldsa_supported()

A version-independent feature-detection pattern using UnsupportedAlgorithm is on the cryptography page.

Grep the code for 256-bit curves, JWT algorithm lists and classical-only curve settings#

Three searches cover different ground. The AGY search finds 256-bit ECC, pairing and legacy crypto use plus risky JWT and SSH libraries. The Claude report’s inventory terms (checklist item 11) add SSH key names and lowercase spellings. The kill-switch search finds explicit curve lists that silently disable X25519MLKEM768.

Treat hits as leads, not findings. Inventory each use by purpose and recipient, not just by import: what it encrypts or signs, who verifies it, and how long the result must stay safe ASTRA.

The AGY ripgrep audit#

# Find affected 256-bit ECC, pairing, legacy crypto, and vulnerable JWT/SSH libraries
rg -n "SECP256R1|SECP256K1|Ed25519|X25519|nacl\.public|nacl\.signing|pyrage\.x25519|from jose|import jose|ES256|EdDSA|algorithms=\[|coincurve|py_ecc|blst|PGPy|ecdsa|fastecdsa|secp256r1" .

The Claude report’s inventory terms and kill-switch search#

Following NSA Action 1, grep for SECP256R1, ed25519, Ed25519PrivateKey, x25519, ES256, EdDSA, ES256K, ecdsa-sha2-nistp256, ssh-ed25519 and RSA keys under 3072 bits. Record algorithms per system, and flag long-lived, internet-facing or widely depended-on systems.

Then search code, dependencies and proxy configs for explicit curve lists. Any classical-only list silently disables X25519MLKEM768:

grep -rn "set_ecdh_curve\|ssl_ecdh_curve\|curvePreferences\|ecdh_curves\|set_tmp_ecdh"
Edge caseswhat each search misses
  • Case. rg is case-sensitive by default. The AGY pattern’s X25519 and Ed25519 do not match lowercase x25519, ed25519 or ssh-ed25519, which the Claude terms include.
  • OpenSSL names. Neither list includes prime256v1, OpenSSL’s name for P-256, which the ASTRA report lists alongside SECP256R1, ec.ECDH(), ec.ECDSA(...), X25519* and Ed25519*. A set_ecdh_curve('prime256v1') call is also a kill switch.
  • RSA key sizes. “RSA keys under 3072 bits” cannot be found by a name search; inspect key-generation parameters and the keys themselves.
  • Broad matches. ecdsa matches ecdsa-sha2-nistp384 and other safe uses; algorithms=\[ matches HS256 allowlists too. Review each hit.
  • Configuration outside the repository. Proxy, load-balancer and crypto-policy settings often live in infrastructure repositories or consoles; search those too (TLS page).

Verify the negotiated group on a fresh, verified handshake#

A successful request proves nothing about the group. Neither the Python version, the cipher string, a client’s offer, a redirect, HSTS nor X-Forwarded-Proto: https is handshake evidence. Record the final group on a fresh, non-resumed, verified connection, and record the handshake signature algorithm and validated certificate path separately ASTRA.

Where How
Python 3.15 Log SSLSocket.group() in a health check; server_sigalg() shows the handshake signature
Python before 3.15 Hit https://pq.cloudflareresearch.com/cdn-cgi/trace and look for kex=X25519MLKEM768
Your own domain curl -v --curves X25519MLKEM768 https://your.domain
Terminators and managed edges The terminator’s own connection log or telemetry
Recipeprobe commands

The Caddy maintainers suggest this check for your own domain (caddy #8494):

curl -v --curves X25519MLKEM768 https://your.domain

The Claude report’s live probes ran from macOS with OpenSSL 4.1.0 s_client, offering X25519MLKEM768:X25519:secp256r1:secp384r1. An equivalent command line:

openssl s_client -connect pypi.org:443 -groups X25519MLKEM768:X25519:secp256r1:secp384r1

For a Python client before 3.15, read the server-side echo from Cloudflare’s trace endpoint: the response lines tls=TLSv1.3 and kex=X25519MLKEM768 confirm the hybrid. A ready-made Python snippet that does this is on the TLS page.

If a middlebox chokes on the larger ClientHello, prefix the group as ?X25519MLKEM768 without *, which defers the PQ key share to a HelloRetryRequest.

Recipecanaries and telemetry without session secrets
  • Staging canary (ASTRA). Record the final group at the terminator on a fresh verified connection, the handshake signing algorithm, and the validated certificate path separately. On older runtimes use trusted terminator telemetry or the final ServerHello key share on an authorized staging trace; no session secrets or payloads are needed.
  • Count outcomes. Count hybrid, classical, failed and unknown results from representative clients, and measure handshake latency, retries, fragmentation and middlebox failures (acceptance criteria).
  • AWS ALB. Inspect the actual listener and its connection-log tls_keyexchange field (FastAPI page).
  • AWS KMS. For direct calls, CloudTrail tlsDetails.keyExchange can show the exchange used on that call; service-on-behalf-of calls may omit it, and it does not identify how a stored data key was wrapped (infrastructure page).
  • Never use verify=False to make a migration test pass.

Record one inventory row per hop or trust decision#

The ASTRA report’s minimal record follows a hop or trust decision from owner to deadline. Fill it with metadata only. An SBOM or vulnerability scanner helps find packages but cannot fill in negotiated groups, external IdP policy or the trust graph.

service/hop → owner → data sensitivity & retention → actual TLS/process/backend or signer → allowed vs observed KEX → handshake signature / issuer key / trust anchor → consumers & fallback → evidence date → mitigation & deadline

Record metadata, not private keys, raw bearer tokens, plaintext or session secrets. Mark unknowns explicitly. Following NSA Action 1, also flag systems with long-lived data that are essential to the mission, internet-facing or widely depended on (what the advisory asks).

Recipethe same record as spreadsheet columns
Field Example of what goes here
Service or hop Browser to CDN; CDN to origin; app to IdP JWKS; CI to PyPI
Owner The team that can change the terminator, client or key
Data sensitivity and retention How long the traffic or ciphertext must stay confidential
Actual TLS, process, backend or signer The terminator and the OpenSSL or library build it actually runs
Allowed vs observed KEX The configured group list and the group seen on fresh handshakes
Handshake signature, issuer key, trust anchor For example rsa_pss_rsae_sha256, a P-256 intermediate, a P-384 root
Consumers and fallback Who verifies or connects, and what they fall back to
Evidence date When the observation was made
Mitigation and deadline The planned change, its owner and due date

Change TLS group settings with OPENSSL_CONF or server hooks: recipes are on the TLS page#

Process-wide OPENSSL_CONF overrides for Python before 3.15, uvicorn’s ssl_context_factory, gunicorn’s ssl_context hook, the hypercorn workaround and per-client contexts are on the TLS page.

Two cautions travel with them. The AGY report found that CPython resets MinProtocol = TLSv1.3 from OPENSSL_CONF back to TLS 1.2, so also set ctx.minimum_version in code or list only TLS 1.3 groups AGY. Whether OPENSSL_CONF reaches the OpenSSL statically linked inside cryptography and pyOpenSSL wheels was not determined (open questions).

Sources cited on this page 2
  1. caddy #8494 github.com
  2. Cloudflare’s trace endpoint pq.cloudflareresearch.com

All sources across the guide