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

verify certs

parent bff978e8
Loading
Loading
Loading
Loading
+2 −0
Changes for src/CMakeLists.txt: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@ list(APPEND netplussrc
    crypto/rc4.cpp
    crypto/rsa.cpp
    crypto/x509.cpp
    crypto/cert_verify.cpp
    crypto/ecc_u256.cpp
    crypto/ecc_p256.cpp
    crypto/hkdf.cpp
@@ -66,6 +67,7 @@ set(headers
    crypto/rc4.h
    crypto/rsa.h
    crypto/x509.h
    crypto/cert_verify.h
    crypto/ecc_u256.h
    crypto/ecc_p256.h
    crypto/hkdf.h
+121 −0
Changes for src/crypto/cert_verify.cpp: 121 added lines, 0 removed lines.
Original line number Diff line number Diff line
#include "cert_verify.h"

#include <fstream>
#include <mutex>
#include <unordered_map>

#include "x509.h"
#include "../exception.h"

namespace netplus {

namespace {

// Process-wide cache of parsed root stores, keyed by bundle path -- avoids re-parsing a
// ~150-certificate system bundle on every single connection.
std::vector<x509cert>& systemRootStore(const std::string& path) {
    static std::mutex mtx;
    static std::unordered_map<std::string, std::vector<x509cert>> cache;

    std::lock_guard<std::mutex> lk(mtx);
    auto it = cache.find(path);
    if (it != cache.end()) return it->second;

    std::vector<x509cert> store;
    std::ifstream file(path, std::ios::binary);
    if (file) {
        std::string pem((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
        static const std::string beginMarker = "-----BEGIN CERTIFICATE-----";
        static const std::string endMarker = "-----END CERTIFICATE-----";
        size_t pos = 0;
        while (pos < pem.size()) {
            auto b = pem.find(beginMarker, pos);
            if (b == std::string::npos) break;
            auto e = pem.find(endMarker, b);
            if (e == std::string::npos) break;
            e += endMarker.size();

            std::string block = pem.substr(b, e - b);
            x509cert cert;
            std::vector<uint8_t> der = cert.pemCertToDer(block);
            if (!der.empty() && cert.loadFromBuffer(std::move(der))) {
                store.push_back(std::move(cert));
            }
            pos = e;
        }
    }

    auto inserted = cache.emplace(path, std::move(store));
    return inserted.first->second;
}

} // namespace

void verifyPeerChain(const std::vector<std::vector<uint8_t>>& presentedDerCerts,
                      const TlsTrustPolicy& policy) {
    if (!policy.verifyPeer) return;

    auto fail = [](const std::string& msg) {
        NetException e;
        e[NetException::Error] << "TLS peer verification failed: " << msg;
        throw e;
    };

    if (presentedDerCerts.empty()) fail("no certificate presented");

    x509cert leaf;
    if (!leaf.loadFromBuffer(presentedDerCerts[0])) fail("could not parse leaf certificate");
    if (!leaf.checkValidity()) fail("leaf certificate is expired or not yet valid");
    if (!policy.expectedHostname.empty() && !leaf.matchesHostname(policy.expectedHostname))
        fail("hostname mismatch (expected " + policy.expectedHostname + ")");

    // A pinned fingerprint trusts the leaf outright -- this is what makes a self-signed (or
    // otherwise not-CA-issued) upstream cert usable at all, without needing a chain.
    if (!policy.pinnedSha256Fingerprints.empty()) {
        auto fp = leaf.sha256Fingerprint();
        for (const auto& pinned : policy.pinnedSha256Fingerprints) {
            if (fp == pinned) return;
        }
    }

    auto& roots = systemRootStore(policy.caBundlePath);

    // Peer-sent intermediates (presentation order: leaf, then intermediate(s), then
    // optionally the root itself) are candidate issuers too, consulted alongside the trust
    // store while walking up from the leaf.
    std::vector<x509cert> intermediates;
    for (size_t i = 1; i < presentedDerCerts.size(); ++i) {
        x509cert c;
        if (c.loadFromBuffer(presentedDerCerts[i])) intermediates.push_back(std::move(c));
    }

    x509cert current = leaf;
    for (int depth = 0; depth < 10; ++depth) {
        auto issuerContent = current.getIssuerNameContent();
        if (issuerContent.empty()) fail("certificate has no issuer");

        // The root store confers trust: if the current cert's issuer matches a trusted root
        // and the signature checks out, the whole chain is trusted right here.
        for (auto& root : roots) {
            if (root.getSubjectNameContent() == issuerContent && current.verifySignedBy(root)) {
                return;
            }
        }

        // Otherwise keep walking up through whatever intermediates the peer offered.
        bool advanced = false;
        for (size_t i = 0; i < intermediates.size(); ++i) {
            if (intermediates[i].getSubjectNameContent() == issuerContent &&
                current.verifySignedBy(intermediates[i])) {
                current = intermediates[i];
                intermediates.erase(intermediates.begin() + i); // no revisiting -- avoids loops
                advanced = true;
                break;
            }
        }
        if (!advanced) fail("no trusted issuer found for the presented certificate chain");
    }
    fail("certificate chain exceeded maximum depth");
}

} // namespace netplus
+37 −0
Changes for src/crypto/cert_verify.h: 37 added lines, 0 removed lines.
Original line number Diff line number Diff line
#pragma once

#include <cstdint>
#include <string>
#include <vector>

namespace netplus {

// Trust configuration for a single TLS client connection (netplus::tls::trust_policy).
// Default-constructed means "verify nothing" -- the pre-existing behavior of every consumer
// that doesn't opt in, so adding this never changes behavior for callers that don't set it.
struct TlsTrustPolicy {
    bool verifyPeer = false;

    // System CA bundle used when the peer's leaf certificate isn't pinned (see below).
    std::string caBundlePath = "/etc/ssl/certs/ca-certificates.crt";

    // SHA-256 digests (raw 32-byte, not hex) of specific leaf certificates to trust outright,
    // regardless of chain-of-trust -- this is what makes a self-signed upstream usable: pin
    // its known fingerprint instead of requiring a CA-issued chain.
    std::vector<std::vector<uint8_t>> pinnedSha256Fingerprints;

    // Hostname the connection was made to, checked against the leaf's SAN/CN. Empty skips
    // the hostname check (not recommended, but some callers may not have a hostname, e.g. a
    // raw IP connection with only a pinned fingerprint to go on).
    std::string expectedHostname;
};

// Verifies `presentedDerCerts` (leaf first, then any intermediates, in the order the peer's
// Certificate message listed them) against `policy`. No-op if policy.verifyPeer is false.
// Throws netplus::NetException describing the failure otherwise -- callers that want the
// connection to fail closed should let it propagate (matches this codebase's convention of
// throwing on handshake-fatal conditions rather than returning bool, see tls.cpp's throwSSL).
void verifyPeerChain(const std::vector<std::vector<uint8_t>>& presentedDerCerts,
                      const TlsTrustPolicy& policy);

} // namespace netplus
+55 −0
Changes for src/crypto/rsa_pss_sha256.cpp: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -118,5 +118,60 @@ std::vector<uint8_t> rsa_pss_sha256::sign(netplus::rsa& key,
    return out;
}

// VERIFY: RSASSA-PSS with SHA-256
bool rsa_pss_sha256::verify(const netplus::rsa& key,
                           const std::vector<uint8_t>& signature,
                           const std::vector<uint8_t>& message)
{
    // hash message with SHA-256
    std::vector<uint8_t> mHash = sha256(message);
    if (mHash.size() != 32)
        return false;

    // Decrypt signature to get EM
    size_t modBits = key.n.bitLength();
    size_t emLen = (modBits + 7) / 8;

    // Convert signature to bigInt and do raw RSA verify: m = s^e mod n
    netplus::rsa::bigInt s = rsa::bytesToBigIntBE(signature);
    netplus::rsa::bigInt m = netplus::rsa::modPow(s, key.e, key.n);

    std::vector<uint8_t> EM = rsa::bigIntToBytesBE(m, emLen);

    if (EM.empty() || EM.back() != 0xBC)
        return false;

    // Extract H and verify
    const size_t hLen = 32;
    const size_t sLen = 32;
    if (emLen < sLen + hLen + 2)
        return false;
    size_t psLen = emLen - sLen - hLen - 2;

    // Extract maskedDB and H
    std::vector<uint8_t> maskedDB(EM.begin(), EM.begin() + psLen + 1 + sLen);
    std::vector<uint8_t> H(EM.begin() + psLen + 1 + sLen, EM.end() - 1);

    // Recover salt
    std::vector<uint8_t> dbMask = mgf1_sha256(H, maskedDB.size());
    std::vector<uint8_t> DB(maskedDB.size());
    for (size_t i = 0; i < maskedDB.size(); i++)
        DB[i] = maskedDB[i] ^ dbMask[i];

    // Verify DB format
    if (DB[psLen] != 0x01)
        return false;

    std::vector<uint8_t> salt(DB.begin() + psLen + 1, DB.end());

    // Verify H
    std::vector<uint8_t> Mprime(8, 0x00);
    Mprime.insert(Mprime.end(), mHash.begin(), mHash.end());
    Mprime.insert(Mprime.end(), salt.begin(), salt.end());
    std::vector<uint8_t> H_expected = sha256(Mprime);

    return H == H_expected;
}

} // namespace netplus
+4 −0
Changes for src/crypto/rsa_pss_sha256.h: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -11,6 +11,10 @@ public:
    static std::vector<uint8_t> sign(netplus::rsa& key,
                                    const std::vector<uint8_t>& message);

    // Verify signature using RSA-PSS with SHA-256 (mirrors rsa_pss_sha384::verify())
    static bool verify(const netplus::rsa& key, const std::vector<uint8_t>& signature,
                      const std::vector<uint8_t>& message);

private:
    static std::vector<uint8_t> sha256(const std::vector<uint8_t>& in);
    static std::vector<uint8_t> mgf1_sha256(const std::vector<uint8_t>& seed, size_t outLen);
Loading