Commit 0c82ebf3 authored by jan.koester's avatar jan.koester
Browse files

deb

parent acea3c3c
Loading
Loading
Loading
Loading
+38 −0
Changes for debian/changelog: 38 added lines, 0 removed lines.
Original line number Diff line number Diff line
libnetplus (20260722+27) unstable; urgency=high

  * quic: fix Initial keys being derived from the wrong DCID after a
    Retry, both server- and client-side — the actual cause of every real
    QUIC client (curl/ngtcp2, confirmed against a live capture) hanging
    to ERR_HANDSHAKE_TIMEOUT against this server's always-on-Retry mode,
    despite our own client/server pair passing every existing test
    (self-consistently sharing the same wrong assumption end to end).
    RFC 9001 §5.2 derives the Initial secret from whatever DCID is
    *currently* on the wire, which changes to the server's Retry SCID
    after a Retry — not, as previously assumed here, from the
    connection's original self-chosen DCID (which never changes across
    a Retry). accept() now calls deriveInitialKeys(dcid, ...) — this
    packet's own DCID — instead of the ODCID recovered from the retry
    token; processRetryPacket() now re-derives keys from the new
    _remote_cid before resending the Initial, instead of deliberately
    keeping the pre-Retry keys. The recovered original DCID
    (true_original_dcid / _original_dcid) is still tracked and still
    used for exactly what RFC 9000 §7.3 actually needs it for: the
    original_destination_connection_id transport parameter, which lets
    the client detect an off-path attacker's forged Retry — it was never
    part of key derivation, just misdocumented as such at both call
    sites.
  * quic: de-dupe Retry sends per client DCID (5s window). A client's
    first-flight CRYPTO data can span more than one UDP datagram (e.g. a
    large post-quantum-hybrid ClientHello); each such datagram shares
    the same token-less DCID with no registry entry yet to recognize it
    as already-answered, so each independently minted its own Retry with
    its own random SCID/token for what the client considers one attempt.
    Not the root cause above, but a real bug in its own right and
    cleaned up alongside it.
  * quic: restore QUIC_DBG tracing (a previous debugging session left it
    disabled via a bare `do {} while(0)`); gated behind the QUIC_TRACE
    env var as before. This is what made the root cause above provable:
    without it, decrypt failures on real traffic were entirely silent.

 -- Jan Koester <jan.koester@tuxist.de>  Wed, 22 Jul 2026 08:25:00 +0200

libnetplus (20260722+26) unstable; urgency=medium

  * quic: implement RFC 9000 §6 / §17.2.1 Version Negotiation. accept()
+27 −72
Changes for src/quic.cpp: 27 added lines, 72 removed lines.
Original line number Diff line number Diff line
@@ -1312,17 +1312,6 @@ bool quic::unprotectPacket(const uint8_t* data, size_t len,
        }
    }
    
    if (level == EncryptionLevel::Initial && getenv("QUIC_TRACE")) {
        auto hex = [](const uint8_t* p, size_t n) {
            std::string s;
            for (size_t i = 0; i < n; ++i) { char t[3]; snprintf(t, 3, "%02x", p[i]); s += t; }
            return s;
        };
        QUIC_DBG("unprotectPacket: HP_TRACE pn_offset=%zu sample_offset=%zu hp_key=%s sample=%s mask=%s",
                 pn_offset, sample_offset, hex(mat.hp, 16).c_str(),
                 hex(data + sample_offset, 16).c_str(), hex(mask, 16).c_str());
    }
    
    // Unmask first byte to get PN length
    uint8_t first_byte = data[0];
    if (is_long) {
@@ -1391,32 +1380,6 @@ bool quic::unprotectPacket(const uint8_t* data, size_t len,
    const uint8_t* ct = data + header_len;
    const uint8_t* tag = data + len - 16;

    if (level == EncryptionLevel::Initial && getenv("QUIC_TRACE") && getenv("QUIC_TRACE_DUMP")) {
        static std::atomic<int> dump_n{0};
        int n = dump_n.fetch_add(1);
        if (n == 0) {
            auto hex = [](const uint8_t* p, size_t n2) {
                std::string s;
                for (size_t i = 0; i < n2; ++i) { char t[3]; snprintf(t, 3, "%02x", p[i]); s += t; }
                return s;
            };
            FILE* f = fopen(getenv("QUIC_TRACE_DUMP"), "w");
            if (f) {
                fprintf(f, "key=%s\n", hex(mat.key, 16).c_str());
                fprintf(f, "nonce=%s\n", hex(nonce, 12).c_str());
                fprintf(f, "aad=%s\n", hex(header.data(), header.size()).c_str());
                fprintf(f, "ct=%s\n", hex(ct, ciphertext_len).c_str());
                fprintf(f, "tag=%s\n", hex(tag, 16).c_str());
                fprintf(f, "raw_len=%zu\n", len);
                fprintf(f, "raw=%s\n", hex(data, len).c_str());
                fprintf(f, "our_pn_offset=%zu\n", pn_offset);
                fprintf(f, "our_header_len=%zu\n", header_len);
                fprintf(f, "our_pn_len=%zu\n", pn_len);
                fclose(f);
            }
        }
    }

    // Cached AES instance is already role/level-resolved via `mat`.
    aes* cached_aes = mat.aes_gcm.get();

@@ -2020,15 +1983,6 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
             token.size(), (int)parsed_token.valid, (int)parsed_token.is_retry,
             dcid.size(), scid.size());
    if (!parsed_token.valid) {
        if (getenv("QUIC_TRACE")) {
            auto hex = [](const std::vector<uint8_t>& v) {
                std::string s;
                for (uint8_t b : v) { char t[3]; snprintf(t, 3, "%02x", b); s += t; }
                return s;
            };
            QUIC_DBG("accept: NOTOKEN_TRACE dcid=%s scid=%s", hex(dcid).c_str(), hex(scid).c_str());
        }

        // A client's first-flight CRYPTO data can span more than one UDP
        // datagram (e.g. a large post-quantum-hybrid ClientHello), all
        // sharing this same token-less DCID with no registry entry yet to
@@ -2064,25 +2018,16 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {

    // The client's TRUE original DCID: for a Retry-validated connection,
    // extracted from the token (this packet's own `dcid` is the server's
    // Retry SCID instead — RFC 9001 §5.2 derives Initial keys from the
    // client's *first* Initial packet's DCID, which must stay fixed across
    // the Retry round trip); for a NEW_TOKEN-validated connection (no
    // Retry occurred), `dcid` already *is* the client's first Initial's
    // DCID.
    // Retry SCID instead). NOT used for key derivation (see
    // deriveInitialKeys' call site below) — this is purely so the server
    // can echo it back via the original_destination_connection_id
    // transport parameter, letting the client detect an off-path
    // attacker's forged Retry (RFC 9000 §7.3). For a NEW_TOKEN-validated
    // connection (no Retry occurred), `dcid` already *is* the client's
    // first Initial's DCID.
    const std::vector<uint8_t>& true_original_dcid =
        parsed_token.is_retry ? parsed_token.original_dcid : dcid;

    if (getenv("QUIC_TRACE")) {
        auto hex = [](const std::vector<uint8_t>& v) {
            std::string s;
            for (uint8_t b : v) { char t[3]; snprintf(t, 3, "%02x", b); s += t; }
            return s;
        };
        QUIC_DBG("accept: DCID_TRACE this_pkt_dcid=%s this_pkt_scid=%s token_odcid=%s true_original_dcid=%s",
                 hex(dcid).c_str(), hex(scid).c_str(),
                 hex(parsed_token.original_dcid).c_str(), hex(true_original_dcid).c_str());
    }

    // Create new QUIC connection socket for this client. Lock its own
    // mutex immediately, before it's configured or registered — nothing
    // else can be contending for this specific (brand new) mutex yet, and
@@ -2098,7 +2043,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    child_ptr->_version = version;
    // RFC 9000: Server sends packets TO the client using the client's SCID as DCID
    child_ptr->_remote_cid = scid;           // Client's SCID becomes our DCID for responses
    child_ptr->_original_dcid = true_original_dcid;  // True original DCID, for key derivation
    child_ptr->_original_dcid = true_original_dcid;  // For the anti-spoofing transport parameter only — NOT key derivation
    if (parsed_token.is_retry) {
        // For the retry_source_connection_id transport parameter — see
        // _retry_scid's comment in socket.h for why `dcid` (this packet's
@@ -2201,10 +2146,16 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
        child_ptr->setNonBlock();
    }

    // Derive initial keys from the client's TRUE original DCID (RFC 9001
    // §5.2 — not this packet's own `dcid` field once a Retry occurred, see
    // true_original_dcid's comment above).
    child_ptr->deriveInitialKeys(true_original_dcid, true);
    // Derive Initial keys from THIS packet's own DCID field (RFC 9001
    // §5.2) — confirmed against a real ngtcp2 client: after a Retry, the
    // client re-derives its Initial secret from the *new* DCID (our
    // Retry's SCID), not the connection's original self-chosen one.
    // true_original_dcid (the ODCID recovered from the token) is a
    // different thing entirely: RFC 9000 §7.3 has the client compare it,
    // via the original_destination_connection_id transport parameter,
    // against what it remembers sending, solely to detect an off-path
    // attacker's forged Retry — it plays no part in key derivation.
    child_ptr->deriveInitialKeys(dcid, true);

    // Store the received Initial packet for processing
    child_ptr->_recv_buffer = dgram;
@@ -2466,10 +2417,14 @@ void quic::processRetryPacket(const uint8_t* data, size_t len) {
    _retry_scid = scid; // for the Phase 3 transport-parameter cross-check
    _remote_cid = scid; // new DCID for the resent Initial

    // Deliberately NOT re-deriving Initial keys here — RFC 9001 §5.2 keys
    // them off the client's *first* Initial's DCID, which never changes
    // across a Retry; only the wire-level _remote_cid (and the token)
    // change for the resend.
    // Re-derive Initial keys from the new DCID (RFC 9001 §5.2 keys them off
    // whatever DCID is currently in use, not the connection's original
    // self-chosen one — confirmed against a real server: reusing the
    // pre-Retry keys here fails the resent Initial's AEAD tag every time).
    // _original_dcid stays as the pre-Retry value: RFC 9000 §7.3 still
    // needs it later, to detect a forged Retry via the
    // original_destination_connection_id transport parameter.
    deriveInitialKeys(_remote_cid, false);
    std::vector<uint8_t> packet = buildInitialPacket(_initial_crypto_frame);
    applyHeaderProtection(packet, EncryptionLevel::Initial, _initial_keys.send);
    buffer send_buf(reinterpret_cast<const char*>(packet.data()), packet.size());
@@ -2987,7 +2942,7 @@ void quic::connect(const std::string& addr, int port, bool nonblock) {

    // Generate random DCID for the server (we don't know their CID yet)
    generateConnectionId(_remote_cid, 8);
    _original_dcid = _remote_cid;  // Save for key derivation
    _original_dcid = _remote_cid;  // Pre-Retry value, kept for the anti-spoofing transport-parameter check
    
    // Derive initial keys from the server's (destination) CID
    deriveInitialKeys(_remote_cid, false);