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

test: cover verifyPeerChain's issuer/validity checks with an openssl-built chain

Builds an invented RSA + P-384 test PKI with the system openssl (offline,
no real CA) and exercises verifyPeerChain against it: a valid chain, a
non-CA issuer misused to sign a forged leaf, an expired intermediate, a
pathLenConstraint violation, an intermediate whose keyUsage omits
keyCertSign, and a P-384 ECDSA chain. Skipped when openssl isn't on PATH.

Co-Authored-By: default avatarClaude Sonnet 5 <noreply@anthropic.com>
parent ff3032ca
Loading
Loading
Loading
Loading
+29 −0
Changes for test/CMakeLists.txt: 29 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -64,6 +64,28 @@ add_executable(benchmark_crypto benchmark_crypto.cpp)

target_link_libraries(benchmark_crypto netplus-static)

# cert_verify_chain_test: exercises verifyPeerChain() against invented RSA/P-384 test
# chains built with the system openssl (offline, no real CA). Skipped when openssl isn't
# available to build the fixtures.
find_program(OPENSSL_EXECUTABLE openssl)
if(OPENSSL_EXECUTABLE)
    set(CERT_CHAIN_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/cert_chain_fixtures")
    add_custom_command(
        OUTPUT "${CERT_CHAIN_FIXTURE_DIR}/leaf.der"
        COMMAND sh "${CMAKE_CURRENT_SOURCE_DIR}/gen_cert_chain_fixtures.sh" "${CERT_CHAIN_FIXTURE_DIR}"
        DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/gen_cert_chain_fixtures.sh"
        COMMENT "Generating cert_verify_chain_test fixtures with openssl"
    )
    add_custom_target(cert_chain_fixtures DEPENDS "${CERT_CHAIN_FIXTURE_DIR}/leaf.der")

    add_executable(cert_verify_chain_test cert_verify_chain_test.cpp)
    target_link_libraries(cert_verify_chain_test netplus-static)
    target_compile_definitions(cert_verify_chain_test PRIVATE CERT_CHAIN_FIXTURE_DIR="${CERT_CHAIN_FIXTURE_DIR}")
    add_dependencies(cert_verify_chain_test cert_chain_fixtures)
else()
    message(STATUS "openssl not found - skipping cert_verify_chain_test (can't build its fixtures)")
endif()

# Temporarily disabled: TLS test needs refactoring
# add_executable(tls tls.cpp)
# if(WIN32)
@@ -137,6 +159,13 @@ add_test(
    COMMAND benchmark_crypto
)

if(OPENSSL_EXECUTABLE)
    add_test(
        NAME cert_verify_chain_test
        COMMAND cert_verify_chain_test
    )
endif()


add_executable(https_test https_test.cpp)

+156 −0
Changes for test/cert_verify_chain_test.cpp: 156 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

// Exercises netplus::verifyPeerChain against invented RSA/P-384 test chains generated by
// gen_cert_chain_fixtures.sh (openssl, offline, no real-world CA involved). Covers the
// chain-of-trust gaps fixed alongside this test: issuer basicConstraints CA:TRUE,
// pathLenConstraint, keyUsage keyCertSign, and intermediate certificate validity.

#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include "crypto/cert_verify.h"
#include "exception.h"

#ifndef CERT_CHAIN_FIXTURE_DIR
#error "CERT_CHAIN_FIXTURE_DIR must be defined by the build"
#endif

namespace {

int failures = 0;

std::vector<uint8_t> readFile(const std::string& path) {
    std::ifstream f(path, std::ios::binary);
    if (!f) {
        std::cerr << "FAIL: could not open fixture " << path << std::endl;
        std::exit(1);
    }
    return std::vector<uint8_t>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
}

std::string fixture(const std::string& name) {
    return std::string(CERT_CHAIN_FIXTURE_DIR) + "/" + name + ".der";
}

// Runs verifyPeerChain and reports whether it threw.
bool verifyThrows(const std::vector<std::vector<uint8_t>>& chain, const std::string& rootPem,
                   std::string* caughtMessage = nullptr) {
    netplus::TlsTrustPolicy policy;
    policy.caBundlePath = rootPem;
    try {
        netplus::verifyPeerChain(chain, policy);
        return false;
    } catch (const netplus::NetException& e) {
        if (caughtMessage) *caughtMessage = e.what();
        return true;
    }
}

void expect(bool condition, const std::string& what) {
    if (condition) {
        std::cout << "ok   " << what << std::endl;
    } else {
        std::cout << "FAIL " << what << std::endl;
        ++failures;
    }
}

} // namespace

int main() {
    const std::string dir = CERT_CHAIN_FIXTURE_DIR;
    const std::string rootPem = dir + "/root.crt";
    const std::string root384Pem = dir + "/root384.crt";

    // (a) valid chain: root -> intermediate(CA:TRUE) -> leaf
    {
        auto leaf = readFile(fixture("leaf"));
        auto inter = readFile(fixture("intermediate"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter}, rootPem, &msg);
        if (threw) std::cout << "  (unexpected: " << msg << ")" << std::endl;
        expect(!threw, "(a) valid root->intermediate->leaf chain is accepted");
    }

    // (b) issuer without CA:TRUE (a non-CA cert misused to sign a forged leaf) is rejected
    {
        auto forged = readFile(fixture("forged_leaf"));
        auto notca = readFile(fixture("notca"));
        std::string msg;
        bool threw = verifyThrows({forged, notca}, rootPem, &msg);
        expect(threw, "(b) non-CA issuer (missing basicConstraints CA:TRUE) is rejected");
    }

    // (c) expired intermediate is rejected
    {
        auto leaf = readFile(fixture("leaf_under_expired"));
        auto inter = readFile(fixture("expired_intermediate"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter}, rootPem, &msg);
        expect(threw, "(c) expired intermediate certificate is rejected");
    }

    // (d) pathLenConstraint violated: intermediate (pathlen:0) signs a second CA
    // (intermediate2) instead of an end-entity cert
    {
        auto leaf = readFile(fixture("leaf_under_pathlen"));
        auto inter2 = readFile(fixture("intermediate2"));
        auto inter1 = readFile(fixture("intermediate"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter2, inter1}, rootPem, &msg);
        expect(threw, "(d) pathLenConstraint violation (CA below a pathlen:0 issuer) is rejected");
    }

    // (f) intermediate is a CA but its keyUsage omits keyCertSign
    {
        auto leaf = readFile(fixture("leaf_under_no_keycertsign"));
        auto inter = readFile(fixture("intermediate_no_keycertsign"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter}, rootPem, &msg);
        expect(threw, "(f) intermediate keyUsage without keyCertSign is rejected");
    }

    // (e) P-384 ECDSA chain: root384 -> leaf384
    {
        auto leaf = readFile(fixture("leaf384"));
        std::string msg;
        bool threw = verifyThrows({leaf}, root384Pem, &msg);
        if (threw) std::cout << "  (unexpected: " << msg << ")" << std::endl;
        expect(!threw, "(e) P-384 ECDSA root->leaf chain is accepted");
    }

    if (failures) {
        std::cout << failures << " check(s) failed" << std::endl;
        return 1;
    }
    std::cout << "all cert_verify_chain_test checks passed" << std::endl;
    return 0;
}
+179 −0
Changes for test/gen_cert_chain_fixtures.sh: 179 added lines, 0 removed lines.
Original line number Diff line number Diff line
#!/bin/sh
# Generates the certificate-chain fixtures used by cert_verify_chain_test.cpp.
#
# Invented test-only PKI (no real-world CA involved), built once at configure/build time
# with the openssl that ships in the devel container so the test binary doesn't need to
# link or shell out to openssl itself -- it just loads the resulting DER files.
#
# Usage: gen_cert_chain_fixtures.sh <output-dir>
set -e

OUT="$1"
if [ -z "$OUT" ]; then
    echo "usage: $0 <output-dir>" >&2
    exit 1
fi
mkdir -p "$OUT"
cd "$OUT"

# ----------------------------------------------------------------------------
# RSA chain: root (CA:TRUE, pathlen:1) -> intermediate (CA:TRUE, pathlen:0) -> leaf
# ----------------------------------------------------------------------------
openssl genrsa -out root.key 2048 >/dev/null 2>&1
openssl req -x509 -new -key root.key -sha256 -days 3650 -subj "/CN=netplus-test-root" \
    -addext "basicConstraints=critical,CA:TRUE,pathlen:1" \
    -addext "keyUsage=critical,keyCertSign,cRLSign" \
    -out root.crt 2>/dev/null

openssl genrsa -out intermediate.key 2048 >/dev/null 2>&1
openssl req -new -key intermediate.key -subj "/CN=netplus-test-intermediate" -out intermediate.csr 2>/dev/null
openssl x509 -req -in intermediate.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out intermediate.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,keyCertSign,cRLSign
EOF

openssl genrsa -out leaf.key 2048 >/dev/null 2>&1
openssl req -new -key leaf.key -subj "/CN=netplus-test-leaf" -out leaf.csr 2>/dev/null
openssl x509 -req -in leaf.csr -CA intermediate.crt -CAkey intermediate.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out leaf.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-leaf
EOF

# ----------------------------------------------------------------------------
# Scenario (b): a non-CA cert (CA:FALSE) misused as an issuer -- signs a forged leaf
# ----------------------------------------------------------------------------
openssl genrsa -out notca.key 2048 >/dev/null 2>&1
openssl req -new -key notca.key -subj "/CN=netplus-test-not-a-ca" -out notca.csr 2>/dev/null
openssl x509 -req -in notca.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_notca -out notca.crt 2>/dev/null <<'EOF'
[v3_notca]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyCertSign
EOF

openssl genrsa -out forged_leaf.key 2048 >/dev/null 2>&1
openssl req -new -key forged_leaf.key -subj "/CN=netplus-test-forged-leaf" -out forged_leaf.csr 2>/dev/null
openssl x509 -req -in forged_leaf.csr -CA notca.crt -CAkey notca.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out forged_leaf.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-forged-leaf
EOF

# ----------------------------------------------------------------------------
# Scenario (c): an intermediate whose own validity period already expired
# ----------------------------------------------------------------------------
openssl genrsa -out expired_intermediate.key 2048 >/dev/null 2>&1
openssl req -new -key expired_intermediate.key -subj "/CN=netplus-test-expired-intermediate" -out expired_intermediate.csr 2>/dev/null
openssl x509 -req -in expired_intermediate.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 \
    -not_before 20200101000000Z -not_after 20200201000000Z \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out expired_intermediate.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,keyCertSign,cRLSign
EOF

openssl genrsa -out leaf_under_expired.key 2048 >/dev/null 2>&1
openssl req -new -key leaf_under_expired.key -subj "/CN=netplus-test-leaf-under-expired" -out leaf_under_expired.csr 2>/dev/null
openssl x509 -req -in leaf_under_expired.csr -CA expired_intermediate.crt -CAkey expired_intermediate.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out leaf_under_expired.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-leaf-under-expired
EOF

# ----------------------------------------------------------------------------
# Scenario (d): pathLenConstraint violated -- intermediate1 (pathlen:0) signs a second
# CA (intermediate2) instead of an end-entity cert directly.
# ----------------------------------------------------------------------------
openssl genrsa -out intermediate2.key 2048 >/dev/null 2>&1
openssl req -new -key intermediate2.key -subj "/CN=netplus-test-intermediate2" -out intermediate2.csr 2>/dev/null
openssl x509 -req -in intermediate2.csr -CA intermediate.crt -CAkey intermediate.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out intermediate2.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,keyCertSign,cRLSign
EOF

openssl genrsa -out leaf_under_pathlen.key 2048 >/dev/null 2>&1
openssl req -new -key leaf_under_pathlen.key -subj "/CN=netplus-test-leaf-under-pathlen" -out leaf_under_pathlen.csr 2>/dev/null
openssl x509 -req -in leaf_under_pathlen.csr -CA intermediate2.crt -CAkey intermediate2.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out leaf_under_pathlen.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-leaf-under-pathlen
EOF

# ----------------------------------------------------------------------------
# keyUsage without keyCertSign: a CA:TRUE intermediate whose keyUsage omits keyCertSign
# ----------------------------------------------------------------------------
openssl genrsa -out intermediate_no_keycertsign.key 2048 >/dev/null 2>&1
openssl req -new -key intermediate_no_keycertsign.key -subj "/CN=netplus-test-intermediate-no-keycertsign" \
    -out intermediate_no_keycertsign.csr 2>/dev/null
openssl x509 -req -in intermediate_no_keycertsign.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out intermediate_no_keycertsign.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,digitalSignature
EOF

openssl genrsa -out leaf_under_no_keycertsign.key 2048 >/dev/null 2>&1
openssl req -new -key leaf_under_no_keycertsign.key -subj "/CN=netplus-test-leaf-under-no-keycertsign" \
    -out leaf_under_no_keycertsign.csr 2>/dev/null
openssl x509 -req -in leaf_under_no_keycertsign.csr -CA intermediate_no_keycertsign.crt -CAkey intermediate_no_keycertsign.key \
    -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out leaf_under_no_keycertsign.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-leaf-under-no-keycertsign
EOF

# ----------------------------------------------------------------------------
# Scenario (e): P-384 ECDSA chain, root -> leaf directly
# ----------------------------------------------------------------------------
openssl ecparam -name secp384r1 -genkey -noout -out root384.key 2>/dev/null
openssl req -x509 -new -key root384.key -sha384 -days 3650 -subj "/CN=netplus-test-root-p384" \
    -addext "basicConstraints=critical,CA:TRUE" \
    -addext "keyUsage=critical,keyCertSign,cRLSign" \
    -out root384.crt 2>/dev/null

openssl ecparam -name secp384r1 -genkey -noout -out leaf384.key 2>/dev/null
openssl req -new -key leaf384.key -sha384 -subj "/CN=netplus-test-leaf-p384" -out leaf384.csr 2>/dev/null
openssl x509 -req -in leaf384.csr -CA root384.crt -CAkey root384.key -CAcreateserial -sha384 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_leaf -out leaf384.crt 2>/dev/null <<'EOF'
[v3_leaf]
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
subjectAltName=DNS:netplus-test-leaf-p384
EOF

# ----------------------------------------------------------------------------
# DER conversion -- the test loads DER directly (same as a peer's Certificate message)
# ----------------------------------------------------------------------------
for name in root intermediate leaf notca forged_leaf expired_intermediate leaf_under_expired \
            intermediate2 leaf_under_pathlen intermediate_no_keycertsign leaf_under_no_keycertsign \
            root384 leaf384; do
    openssl x509 -in "$name.crt" -outform DER -out "$name.der"
done

rm -f ./*.csr ./*.srl