Commit b50a81eb authored by jan.koester's avatar jan.koester
Browse files

test

parent 04873698
Loading
Loading
Loading
Loading
+188 −8
Changes for src/quic.cpp: 188 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -155,6 +155,10 @@ quic::quic(const std::string& addr, int port, int maxconnections, int sockopts)

    // Generate local connection ID for server
    generateConnectionId(_local_cid, 8);

    // Secret backing Retry/NEW_TOKEN tokens for this listener's lifetime.
    _token_secret.resize(32);
    fillRandomBytes(_token_secret.data(), _token_secret.size());
}

quic::quic(const std::map<std::string, ssl::CertificateBundle>& certs,
@@ -205,6 +209,10 @@ quic::quic(const std::map<std::string, ssl::CertificateBundle>& certs,

    // Generate local connection ID for server
    generateConnectionId(_local_cid, 8);

    // Secret backing Retry/NEW_TOKEN tokens for this listener's lifetime.
    _token_secret.resize(32);
    fillRandomBytes(_token_secret.data(), _token_secret.size());
}

quic::~quic() {
@@ -646,19 +654,191 @@ uint64_t quic::decodePacketNumber(uint32_t truncated_pn, size_t pn_len, uint64_t
}

// ============================================================================
// Retry Token Validation
// Retry / NEW_TOKEN address-validation tokens (RFC 9000 §8.1)
// ============================================================================

bool quic::validateRetryToken(const std::vector<uint8_t>& token) {
    // Basic validation - token should not be empty and have reasonable size
    if (token.empty() || token.size() > 256) {
namespace {

// Serializes a peer address into the fixed 1+N+2 byte form the token
// plaintext uses (addr_len byte, raw address bytes, big-endian port).
// Returns false for anything other than AF_INET/AF_INET6 (nothing else can
// reach this code — recvBatchAddr only ever hands back one of the two).
bool serializePeerAddr(const sockaddr_storage& addr, std::vector<uint8_t>& out) {
    if (addr.ss_family == AF_INET) {
        const auto* a4 = reinterpret_cast<const struct sockaddr_in*>(&addr);
        out.push_back(4);
        const uint8_t* ip = reinterpret_cast<const uint8_t*>(&a4->sin_addr);
        out.insert(out.end(), ip, ip + 4);
        uint16_t port = ntohs(a4->sin_port);
        out.push_back(static_cast<uint8_t>(port >> 8));
        out.push_back(static_cast<uint8_t>(port));
        return true;
    } else if (addr.ss_family == AF_INET6) {
        const auto* a6 = reinterpret_cast<const struct sockaddr_in6*>(&addr);
        out.push_back(16);
        const uint8_t* ip = reinterpret_cast<const uint8_t*>(&a6->sin6_addr);
        out.insert(out.end(), ip, ip + 16);
        uint16_t port = ntohs(a6->sin6_port);
        out.push_back(static_cast<uint8_t>(port >> 8));
        out.push_back(static_cast<uint8_t>(port));
        return true;
    }
    return false;
}

    // In a full implementation, this would verify the token's integrity tag
    // and check that it hasn't expired. For now, accept non-empty tokens.
    // TODO: Implement proper AEAD-based token validation
    return true;
// Constant-time byte compare — avoids a timing oracle on tag verification.
bool constantTimeEqual(const uint8_t* a, const uint8_t* b, size_t len) {
    uint8_t diff = 0;
    for (size_t i = 0; i < len; ++i) diff |= static_cast<uint8_t>(a[i] ^ b[i]);
    return diff == 0;
}

} // namespace

std::array<uint8_t, 16> quic::computeRetryIntegrityTag(
    const std::vector<uint8_t>& original_dcid,
    const uint8_t* header_and_token, size_t header_and_token_len) {
    // RFC 9001 §5.8: fixed, public (not secret) AES-128-GCM key/nonce —
    // this authenticates packet *format* against accidental corruption,
    // not origin against a malicious peer (anyone can compute this tag for
    // any content; real protection is the token itself plus the transport
    // parameter cross-check, both keyed off the server's private secret).
    static const uint8_t RETRY_KEY[16] = {
        0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a,
        0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e };
    static const uint8_t RETRY_NONCE[12] = {
        0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2,
        0x23, 0x98, 0x25, 0xbb };

    std::vector<uint8_t> aad;
    aad.reserve(1 + original_dcid.size() + header_and_token_len);
    aad.push_back(static_cast<uint8_t>(original_dcid.size()));
    aad.insert(aad.end(), original_dcid.begin(), original_dcid.end());
    aad.insert(aad.end(), header_and_token, header_and_token + header_and_token_len);

    aes128 retry_aead(std::vector<uint8_t>(RETRY_KEY, RETRY_KEY + 16));
    std::array<uint8_t, 16> tag{};
    // Empty plaintext: this degenerates to a pure GMAC over the AAD, which
    // is exactly what §5.8 specifies (confirmed safe — the CTR loop and
    // GHASH's ct-update both no-op cleanly when len==0).
    retry_aead.aes_gcm_encrypt(RETRY_NONCE, aad.data(), aad.size(),
                               nullptr, 0, nullptr, tag.data());
    return tag;
}

std::vector<uint8_t> quic::generateToken(bool is_retry, const std::vector<uint8_t>& original_dcid,
                                          const sockaddr_storage& peer_addr, socklen_t /*peer_len*/) const {
    quic* listener = _parent ? _parent : const_cast<quic*>(this);

    // Plaintext: type(1) + issued_at(8) + addr(1+4-or-16) + port(2) + [odcid(1+len) if retry]
    std::vector<uint8_t> plaintext;
    plaintext.push_back(is_retry ? 0 : 1);
    uint64_t now = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::system_clock::now().time_since_epoch()).count());
    for (int i = 7; i >= 0; --i) plaintext.push_back(static_cast<uint8_t>(now >> (8 * i)));
    if (!serializePeerAddr(peer_addr, plaintext)) {
        return {}; // unsupported address family — no token to issue
    }
    if (is_retry) {
        plaintext.push_back(static_cast<uint8_t>(original_dcid.size()));
        plaintext.insert(plaintext.end(), original_dcid.begin(), original_dcid.end());
    }

    // AEAD key derived from the listener's per-process secret — same HKDF
    // helper (and cipher-suite constant, 0x1301 = SHA-256-based) already
    // used throughout this file for QUIC key derivation.
    std::vector<uint8_t> token_key = netplus::tls::hkdf_expand_label(
        listener->_token_secret, "quic token", {}, 16, 0x1301);

    uint8_t nonce[12];
    fillRandomBytes(nonce, sizeof(nonce));

    aes128 token_aead(token_key);
    std::vector<uint8_t> out(12 + plaintext.size() + 16);
    std::memcpy(out.data(), nonce, 12);
    uint8_t* ct = out.data() + 12;
    uint8_t* tag = ct + plaintext.size();
    token_aead.aes_gcm_encrypt(nonce, nullptr, 0, plaintext.data(), plaintext.size(), ct, tag);
    return out;
}

quic::ParsedToken quic::validateToken(const std::vector<uint8_t>& token,
                                       const sockaddr_storage& peer_addr, socklen_t /*peer_len*/) const {
    ParsedToken result;

    // Minimum: 12-byte nonce + 16-byte tag + smallest possible plaintext
    // (type + issued_at + addr_len + 4-byte IPv4 + port = 16 bytes).
    if (token.size() < 12 + 16 + 16) return result;

    quic* listener = _parent ? _parent : const_cast<quic*>(this);
    std::vector<uint8_t> token_key = netplus::tls::hkdf_expand_label(
        listener->_token_secret, "quic token", {}, 16, 0x1301);

    const uint8_t* nonce = token.data();
    const uint8_t* ct = token.data() + 12;
    size_t ct_len = token.size() - 12 - 16;
    const uint8_t* tag = token.data() + token.size() - 16;

    std::vector<uint8_t> plaintext(ct_len);
    aes128 token_aead(token_key);
    if (!token_aead.aes_gcm_decrypt(nonce, nullptr, 0, ct, ct_len, tag, plaintext.data())) {
        return result; // tampered/wrong-key token
    }

    size_t off = 0;
    if (off + 1 > plaintext.size()) return result;
    uint8_t type = plaintext[off++];
    if (type > 1) return result;

    if (off + 8 > plaintext.size()) return result;
    uint64_t issued_at = 0;
    for (int i = 0; i < 8; ++i) issued_at = (issued_at << 8) | plaintext[off++];

    if (off + 1 > plaintext.size()) return result;
    uint8_t addr_len = plaintext[off++];
    if (addr_len != 4 && addr_len != 16) return result;
    if (off + addr_len + 2 > plaintext.size()) return result;
    const uint8_t* tok_addr = &plaintext[off];
    off += addr_len;
    uint16_t tok_port = static_cast<uint16_t>((plaintext[off] << 8) | plaintext[off + 1]);
    off += 2;

    std::vector<uint8_t> odcid;
    if (type == 0) {
        if (off + 1 > plaintext.size()) return result;
        uint8_t odcid_len = plaintext[off++];
        if (off + odcid_len > plaintext.size()) return result;
        odcid.assign(plaintext.begin() + off, plaintext.begin() + off + odcid_len);
        off += odcid_len;
    }

    // Bind to the requesting address — a token minted for one client must
    // never validate for a different one.
    std::vector<uint8_t> actual_addr;
    if (!serializePeerAddr(peer_addr, actual_addr)) return result;
    if (actual_addr.size() != static_cast<size_t>(1 + addr_len + 2)) return result;
    if (!constantTimeEqual(actual_addr.data() + 1, tok_addr, addr_len)) return result;
    uint16_t actual_port = static_cast<uint16_t>((actual_addr[1 + addr_len] << 8) | actual_addr[1 + addr_len + 1]);
    if (actual_port != tok_port) return result;

    // Expiry: Retry tokens must be used almost immediately (the round trip
    // should be near-instant); NEW_TOKEN-issued tokens are meant to survive
    // until a later, separate connection attempt, so get a much longer
    // window. Small forward tolerance for clock skew between processes.
    uint64_t now = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::system_clock::now().time_since_epoch()).count());
    const uint64_t kClockSkewTolerance = 5;
    const uint64_t kRetryWindow = 10;
    const uint64_t kNewTokenWindow = 24 * 60 * 60;
    if (issued_at > now + kClockSkewTolerance) return result;
    uint64_t age = now - issued_at;
    if (type == 0 && age > kRetryWindow) return result;
    if (type == 1 && age > kNewTokenWindow) return result;

    result.valid = true;
    result.is_retry = (type == 0);
    result.original_dcid = std::move(odcid);
    return result;
}

// ============================================================================