Commit ff3032ca authored by MIDAS NEXT's avatar MIDAS NEXT Committed by jan.koester
Browse files

cert_verify: enforce issuer CA:TRUE, pathLen, keyUsage and intermediate validity

A peer-sent intermediate was accepted as an issuer purely on a matching
subject name and a valid signature -- never checked whether the issuer was
actually a CA, respected its own pathLenConstraint, or was itself still
valid. That let an end-entity certificate (or an expired/over-length CA)
sign a forged leaf and pass verifyPeerChain(). Retrofits basicConstraints
and keyUsage parsing onto x509cert and uses them in the chain walk.

Co-Authored-By: default avatarClaude Sonnet 5 <noreply@anthropic.com>
parent 97d177a9
Loading
Loading
Loading
Loading
+22 −0
Changes for src/crypto/cert_verify.cpp: 22 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -119,7 +119,23 @@ void verifyPeerChain(const std::vector<std::vector<uint8_t>> &presentedDerCerts,
        if (c.loadFromBuffer(presentedDerCerts[i])) intermediates.push_back(std::move(c));
    }

    // Checks every issuer in the path (RFC 5280 §6.1) must pass before it's trusted to have
    // signed the cert below it: it must actually be a CA, its keyUsage (if stated) must allow
    // certificate signing, and its pathLenConstraint (if stated) must not already be
    // exceeded by the CA certificates accumulated below it. `caCountBelow` is the number of
    // CA certificates already accepted between the leaf and the issuer under test.
    auto checkIssuerConstraints = [&](x509cert &issuer, int caCountBelow, const char *what) {
        x509cert::BasicConstraints bc = issuer.getBasicConstraints();
        if (!bc.present || !bc.isCA)
            fail(std::string(what) + " certificate is not a CA (missing basicConstraints CA:TRUE)");
        if (!issuer.keyUsageAllowsCertSign())
            fail(std::string(what) + " certificate's keyUsage does not permit certificate signing");
        if (bc.hasPathLen && caCountBelow > bc.pathLen)
            fail(std::string(what) + " certificate's pathLenConstraint exceeded");
    };

    x509cert current = leaf;
    int caCountBelow = 0;
    for (int depth = 0; depth < 10; ++depth) {
        auto issuerContent = current.getIssuerNameContent();
        if (issuerContent.empty()) fail("certificate has no issuer");
@@ -128,6 +144,7 @@ void verifyPeerChain(const std::vector<std::vector<uint8_t>> &presentedDerCerts,
        // and the signature checks out, the whole chain is trusted right here.
        for (auto &root : roots) {
            if (root.getSubjectNameContent() == issuerContent && current.verifySignedBy(root)) {
                checkIssuerConstraints(root, caCountBelow, "root");
                return;
            }
        }
@@ -137,8 +154,13 @@ void verifyPeerChain(const std::vector<std::vector<uint8_t>> &presentedDerCerts,
        for (size_t i = 0; i < intermediates.size(); ++i) {
            if (intermediates[i].getSubjectNameContent() == issuerContent &&
                current.verifySignedBy(intermediates[i])) {
                checkIssuerConstraints(intermediates[i], caCountBelow, "intermediate");
                if (!intermediates[i].checkValidity())
                    fail("intermediate certificate not currently valid");

                current = intermediates[i];
                intermediates.erase(intermediates.begin() + i); // no revisiting -- avoids loops
                ++caCountBelow;
                advanced = true;
                break;
            }
+95 −0
Changes for src/crypto/x509.cpp: 95 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -704,6 +704,101 @@ std::vector<std::string> netplus::x509cert::getSubjectAltNames() {
    return dnsNames;
}

// ------------------------------------------------------------
// findExtensionValue -- locates extension `wantOid`, parses its extnValue OCTET STRING
// content and returns the resulting node (e.g. the BasicConstraints SEQUENCE, or the
// KeyUsage BIT STRING itself for a non-constructed type). Mirrors the Extensions-wrapper
// lookup in getSubjectAltNames above.
// ------------------------------------------------------------
bool netplus::x509cert::findExtensionValue(const std::string& wantOid, ASN1Node& outValue) {
    auto& r = root();
    if (r.children.empty()) return false;

    auto& tbs = r.children[0];

    ASN1Node* extWrapper = nullptr;
    for (auto& child : tbs.children) {
        if (child.tag == 0xA3) {
            extWrapper = &child;
            break;
        }
    }
    if (!extWrapper) return false;

    const ASN1Node* extensionsSeq = nullptr;
    ASN1Node parsedWrapper;

    if (!extWrapper->children.empty()) {
        extensionsSeq = &extWrapper->children[0];
    } else {
        if (!extWrapper->data || extWrapper->len == 0) return false;
        if (parseInternal(extWrapper->data, extWrapper->len, parsedWrapper) == 0) return false;
        if (parsedWrapper.children.empty()) return false;
        extensionsSeq = &parsedWrapper.children[0];
    }
    if (!extensionsSeq) return false;

    for (const auto& ext : extensionsSeq->children) {
        if (ext.children.empty()) continue;

        const ASN1Node& oidNode = ext.children[0];
        std::string oid = decodeOID(oidNode.data, oidNode.len);
        if (oid != wantOid) continue;

        for (const auto& valNode : ext.children) {
            if (valNode.tag != 0x04) continue; // extnValue: OCTET STRING
            if (!valNode.data || valNode.len == 0) continue;
            if (parseInternal(valNode.data, valNode.len, outValue) == 0) continue;
            return true;
        }
        return false;
    }
    return false;
}

// ------------------------------------------------------------
// getBasicConstraints -- 2.5.29.19: SEQUENCE { cA BOOLEAN DEFAULT FALSE,
// pathLenConstraint INTEGER OPTIONAL }
// ------------------------------------------------------------
netplus::x509cert::BasicConstraints netplus::x509cert::getBasicConstraints() {
    BasicConstraints info;

    ASN1Node val;
    if (!findExtensionValue("2.5.29.19", val)) return info; // absent -> defaults (not a CA)
    info.present = true;

    size_t idx = 0;
    if (idx < val.children.size() && val.children[idx].tag == 0x01) { // BOOLEAN
        const ASN1Node& b = val.children[idx];
        info.isCA = b.data && b.len > 0 && b.data[0] != 0x00;
        ++idx;
    }
    if (idx < val.children.size() && val.children[idx].tag == 0x02) { // INTEGER
        const ASN1Node& n = val.children[idx];
        if (n.data && n.len > 0 && n.len <= sizeof(long)) {
            long pl = 0;
            for (size_t i = 0; i < n.len; ++i) pl = (pl << 8) | n.data[i];
            info.hasPathLen = true;
            info.pathLen = static_cast<int>(pl);
        }
    }
    return info;
}

// ------------------------------------------------------------
// keyUsageAllowsCertSign -- 2.5.29.15: BIT STRING, keyCertSign is bit 5
// ------------------------------------------------------------
bool netplus::x509cert::keyUsageAllowsCertSign() {
    ASN1Node val;
    if (!findExtensionValue("2.5.29.15", val)) return true; // no restriction stated

    // BIT STRING content: [0] = unused-bits count, [1..] = the bits, MSB-first.
    if (val.tag != 0x03 || !val.data || val.len < 1) return true; // malformed: not our call
    if (val.len < 2) return false; // zero-length bit string: no bits asserted

    return (val.data[1] & 0x04) != 0; // keyCertSign = bit 5
}

// ------------------------------------------------------------
// getTbsCertificateDer -- full DER bytes of tbsCertificate, header included
// (exactly what signatureValue is computed over)
+22 −0
Changes for src/crypto/x509.h: 22 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -106,6 +106,23 @@ namespace netplus {
        std::vector<uint8_t> getIssuerNameContent();
        std::vector<uint8_t> getSubjectNameContent();

        // basicConstraints (2.5.29.19): CA ::= BOOLEAN DEFAULT FALSE, pathLenConstraint ::=
        // INTEGER OPTIONAL. `present == false` means the extension is absent entirely, so
        // `isCA` stays at its RFC 5280 default of false -- a cert without basicConstraints is
        // not a CA and may not sign other certificates.
        struct BasicConstraints {
            bool present = false;
            bool isCA = false;
            bool hasPathLen = false;
            int pathLen = 0;
        };
        BasicConstraints getBasicConstraints();

        // keyUsage (2.5.29.15) keyCertSign bit (RFC 5280 §4.2.1.3). Returns true when the
        // extension is absent (no restriction stated) or present with keyCertSign set; false
        // only when the extension is present and keyCertSign is not asserted.
        bool keyUsageAllowsCertSign();

        // SHA-256 digest of the whole DER certificate -- what a pinned-certificate allowlist
        // matches against.
        std::vector<uint8_t> sha256Fingerprint();
@@ -123,6 +140,11 @@ namespace netplus {
    private:
        size_t parseInternal(const uint8_t* data, size_t size, ASN1Node& outNode);

        // Finds extension `oid` among the certificate's Extensions, parses its extnValue
        // (the OCTET STRING content) and returns the resulting top-level ASN1Node in
        // `outValue`. False if the extension isn't present or can't be parsed.
        bool findExtensionValue(const std::string& oid, ASN1Node& outValue);

        // Helper um bequem root zu bekommen
        ASN1Node& root() { return state->root; }
        const ASN1Node& root() const { return state->root; }