Commit 7bc124bc authored by jan.koester's avatar jan.koester
Browse files

test

parent 740b1abf
Loading
Loading
Loading
Loading
+13 −4
Changes for src/quic.cpp: 13 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -8674,7 +8674,8 @@ void quic::sendServerHandshakeFlight() {
        std::vector<uint8_t> cert_verify;
        cert_verify.push_back(0x0f);
        
        // Signature algorithm selection based on cipher suite
        // Signature algorithm selection based on cipher suite, gated by what
        // the client actually advertised in signature_algorithms.
        const bool prefer_sha384 = (_selected_cipher == 0x1302);
        const bool use_sha384_cv = prefer_sha384 && _sigalg_rsa_pss_sha384;
        std::vector<uint8_t> cv_body;
@@ -8688,7 +8689,16 @@ void quic::sendServerHandshakeFlight() {
        }

        // Build content to sign: 64 spaces + context + 0x00 + transcript hash
        // The transcript hash MUST use the cipher suite's hash function
        // The transcript hash MUST use the negotiated cipher suite's hash
        // function (RFC 8446 §4.4.1), independent of which RSA-PSS variant
        // ends up signing it below -- gating this on use_sha384_cv (a flag
        // about client-advertised *signature* algorithm support) instead of
        // _selected_cipher was a bug: whenever the client negotiated
        // TLS_AES_256_GCM_SHA384 but only advertised rsa_pss_rsae_sha256
        // (e.g. this library's own QUIC client, see buildClientHello()),
        // this signed a SHA-256 transcript hash while a spec-compliant
        // verifier (computing Transcript-Hash from the cipher suite alone)
        // checks against the SHA-384 one, so the signature never verifies.
        std::vector<uint8_t> sign_content;
        sign_content.reserve(64 + 34 + 1 + 64);  // 64 spaces + context + 0x00 + max hash
        sign_content.resize(64, 0x20);  // 64 spaces
@@ -8696,8 +8706,7 @@ void quic::sendServerHandshakeFlight() {
        sign_content.insert(sign_content.end(), context, context + strlen(context));
        sign_content.push_back(0x00);

        // Use cipher-appropriate hash for transcript
        std::vector<uint8_t> cv_transcript_hash = use_sha384_cv ? 
        std::vector<uint8_t> cv_transcript_hash = prefer_sha384 ?
            sha384_hash(_tls_transcript) : sha256_hash(_tls_transcript);
        sign_content.insert(sign_content.end(), cv_transcript_hash.begin(), cv_transcript_hash.end());
        
+55 −0
Changes for src/utils/certgen.cpp: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -124,6 +124,14 @@ static std::vector<uint8_t> derUtf8String(const std::string &s) {
    return derTag(0x0C, data);
}

static std::vector<uint8_t> derOctetString(const std::vector<uint8_t> &data) {
    return derTag(0x04, data);
}

static std::vector<uint8_t> derBoolean(bool val) {
    return derTag(0x01, {val ? uint8_t(0xFF) : uint8_t(0x00)});
}

static std::vector<uint8_t> derPrintableString(const std::string &s) {
    std::vector<uint8_t> data(s.begin(), s.end());
    return derTag(0x13, data);
@@ -173,6 +181,12 @@ static const uint8_t OID_ORG[] = {0x55, 0x04, 0x0A};
// id-at-countryName (2.5.4.6)
static const uint8_t OID_COUNTRY[] = {0x55, 0x04, 0x06};

// id-ce-subjectAltName (2.5.29.17)
static const uint8_t OID_SAN[] = {0x55, 0x1D, 0x11};

// id-ce-basicConstraints (2.5.29.19)
static const uint8_t OID_BASIC_CONSTRAINTS[] = {0x55, 0x1D, 0x13};

// ═════════════════════════════════════════════════════════════
//  RSA key DER export helpers
// ═════════════════════════════════════════════════════════════
@@ -294,6 +308,35 @@ static std::vector<uint8_t> signatureAlgId() {
    return derSequence(body);
}

// Extension ::= SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN DEFAULT FALSE,
//                           extnValue OCTET STRING }
static std::vector<uint8_t> derExtension(const uint8_t *oid, size_t oidLen, bool critical,
                                          const std::vector<uint8_t> &value) {
    std::vector<uint8_t> body;
    derAppend(body, derOid({oid, oid + oidLen}));
    if (critical) derAppend(body, derBoolean(true));
    derAppend(body, derOctetString(value));
    return derSequence(body);
}

// subjectAltName extnValue: GeneralNames ::= SEQUENCE OF GeneralName, dNSName is the
// context-specific IMPLICIT [2] choice (a bare IA5String, no extra wrapper) -- this must
// match what x509cert::getSubjectAltNames()/matchesHostname() (x509.cpp) parse back out.
static std::vector<uint8_t> buildSanExtension(const std::vector<std::string> &dnsNames) {
    std::vector<uint8_t> generalNames;
    for (const auto &name : dnsNames) {
        derAppend(generalNames, derTag(0x82, {name.begin(), name.end()}));
    }
    return derExtension(OID_SAN, sizeof(OID_SAN), /*critical=*/false, derSequence(generalNames));
}

// basicConstraints extnValue: BasicConstraints ::= SEQUENCE { cA BOOLEAN DEFAULT FALSE, ... }
// -- an empty SEQUENCE encodes cA=FALSE (the default), marking this leaf as not a CA.
static std::vector<uint8_t> buildBasicConstraintsExtension() {
    return derExtension(OID_BASIC_CONSTRAINTS, sizeof(OID_BASIC_CONSTRAINTS), /*critical=*/true,
                         derSequence({}));
}

// ═════════════════════════════════════════════════════════════
//  PEM encoding
// ═════════════════════════════════════════════════════════════
@@ -367,6 +410,17 @@ bool generateSelfSignedCert(const CertGenConfig &cfg, CertKeyPair &out) {
    derAppend(validityBody, derUtcTime(expire));
    auto validity = derSequence(validityBody);

    // Extensions ([3] EXPLICIT, v3-only): SAN (falls back to commonName alone) + a
    // non-CA basicConstraints, so this leaf is usable by TLS clients that require SAN
    // (matched via x509cert::matchesHostname()) and doesn't look like it can sign other
    // certs.
    auto sanNames = cfg.subjectAltNames;
    if (sanNames.empty() && !cfg.commonName.empty()) sanNames.push_back(cfg.commonName);
    std::vector<uint8_t> extensionsBody;
    if (!sanNames.empty()) derAppend(extensionsBody, buildSanExtension(sanNames));
    derAppend(extensionsBody, buildBasicConstraintsExtension());
    auto extensions = derExplicit(3, derSequence(extensionsBody));

    // TBSCertificate SEQUENCE
    std::vector<uint8_t> tbsBody;
    derAppend(tbsBody, derExplicit(0, derIntegerSmall(2)));  // version v3 (explicit [0])
@@ -376,6 +430,7 @@ bool generateSelfSignedCert(const CertGenConfig &cfg, CertKeyPair &out) {
    derAppend(tbsBody, validity);                            // validity
    derAppend(tbsBody, dn);                                  // subject
    derAppend(tbsBody, spki);                                // subjectPublicKeyInfo
    derAppend(tbsBody, extensions);                          // extensions [3]

    auto tbsCert = derSequence(tbsBody);

+6 −0
Changes for src/utils/certgen.h: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -39,6 +39,12 @@ namespace netplus {
        std::string country;
        size_t      rsaBits     = 2048;
        int         validDays   = 365;

        // DNS names for the subjectAltName extension (RFC 5280 §4.2.1.6). Modern TLS
        // clients (Chrome since 58, Go's crypto/x509) ignore the subject CN entirely and
        // reject a certificate that has no SAN, so every generated leaf needs one. Left
        // empty, generateSelfSignedCert() falls back to a single-entry SAN of commonName.
        std::vector<std::string> subjectAltNames;
    };

    struct CertKeyPair {
+8 −0
Changes for test/CMakeLists.txt: 8 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -236,3 +236,11 @@ else()
    target_link_libraries(rwlock_writer_starvation_test netplus-static)
endif()
add_test(NAME rwlock_writer_starvation_test COMMAND rwlock_writer_starvation_test)

add_executable(certgen_test certgen_test.cpp)
if(WIN32)
    target_link_libraries(certgen_test netplus-static ws2_32)
else()
    target_link_libraries(certgen_test netplus-static)
endif()
add_test(NAME certgen_test COMMAND certgen_test)

test/certgen_test.cpp

0 → 100644
+79 −0
Changes for test/certgen_test.cpp: 79 added lines, 0 removed lines.
Original line number Diff line number Diff line
// certgen_test.cpp
//
// Round-trips netplus::generateSelfSignedCert() through the exact consumers a TLS server
// frontend relies on: netplus::x509cert (SAN/CN/validity/self-signature) and
// netplus::tls::CertificateBundle::loadFromFile() (the same PEM-parsing path
// libhttppp::HttpD uses to load a cert+key pair for a listening socket).

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

#include "crypto/tls.h"
#include "crypto/x509.h"
#include "utils/certgen.h"

static int g_passed = 0, g_failed = 0;

static void check(bool ok, const std::string &name) {
    if (ok) { std::cout << "  PASS: " << name << std::endl; g_passed++; }
    else    { std::cout << "  FAIL: " << name << std::endl; g_failed++; }
}

int main() {
    netplus::CertGenConfig cfg;
    cfg.commonName = "proxy.internal.test";
    cfg.subjectAltNames = {"proxy.internal.test", "alt.proxy.internal.test"};
    cfg.organization = "ProxyPlus Test";
    cfg.country = "DE";
    cfg.rsaBits = 2048;
    cfg.validDays = 30;

    netplus::CertKeyPair kp;
    check(netplus::generateSelfSignedCert(cfg, kp), "generateSelfSignedCert succeeds");
    check(!kp.certDer.empty(), "cert DER is non-empty");
    check(!kp.keyDer.empty(), "key DER is non-empty");
    check(kp.certPem.rfind("-----BEGIN CERTIFICATE-----", 0) == 0, "cert PEM has correct header");
    check(kp.keyPem.rfind("-----BEGIN RSA PRIVATE KEY-----", 0) == 0, "key PEM has correct header");

    // --- Parse back with x509cert, the same class HttpD/CertificateManager use ---
    netplus::x509cert cert;
    check(cert.loadFromBuffer(kp.certDer), "x509cert parses generated DER");
    check(cert.checkValidity(), "generated cert passes checkValidity()");
    check(cert.getSubjectCN() == cfg.commonName, "subject CN matches");

    auto sans = cert.getSubjectAltNames();
    check(sans.size() == 2, "SAN extension carries both names");
    check(std::find(sans.begin(), sans.end(), "proxy.internal.test") != sans.end(),
          "SAN contains primary hostname");
    check(std::find(sans.begin(), sans.end(), "alt.proxy.internal.test") != sans.end(),
          "SAN contains alternate hostname");

    check(cert.matchesHostname("proxy.internal.test"), "matchesHostname() accepts primary SAN");
    check(cert.matchesHostname("alt.proxy.internal.test"), "matchesHostname() accepts alternate SAN");
    check(!cert.matchesHostname("not-this-host.test"), "matchesHostname() rejects unrelated host");

    // Self-signed: the cert must verify against its own public key.
    netplus::x509cert issuer;
    check(issuer.loadFromBuffer(kp.certDer), "second x509cert instance parses same DER");
    check(cert.verifySignedBy(issuer), "self-signed cert verifies against its own public key");

    // --- Load through the actual TLS server bundle path (inline PEM), like HttpD does ---
    netplus::tls::CertificateBundle bundle;
    check(bundle.loadFromFile(kp.certPem, kp.keyPem, ""),
          "CertificateBundle::loadFromFile loads generated cert+key (inline PEM)");
    check(bundle.cert.checkValidity(), "bundle's cert passes checkValidity()");
    check(static_cast<bool>(bundle.rsa_key), "bundle's RSA private key parsed");

    netplus::rsa pubFromCert;
    check(bundle.cert.extractPublicKey(pubFromCert), "public key extracted from bundle's cert");
    check(netplus::rsa::compare(pubFromCert.getN(), bundle.rsa_key.getN()) == 0,
          "bundle's private key modulus matches its cert's public key");

    std::cout << "\n==============================" << std::endl;
    std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl;
    std::cout << "==============================" << std::endl;

    return g_failed > 0 ? 1 : 0;
}