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

test: cover Runde 3 re-review findings A, B, E

- tls_handshake_certverify_binding_test (new): drives the real
  handshake_after_connect() state machine into CLI_TLS13_WAIT_CERT_VERIFY
  with a hand-crafted in-memory CertificateVerify message -- no socket,
  no real handshake -- proving the state machine actually calls
  sigAlgMatchesLeafKey() rather than just the function being correct in
  isolation (Befund A; mutation N2 removing the call now turns it red
  with a different exception message than the one this test checks for).
- cert_verify_chain_test: three new scenarios --
  (j)/(k) an intermediate's keyUsage extnValue that's either unparseable
      (a single byte) or parses as the wrong ASN.1 type (INTEGER instead
      of BIT STRING) -- both "present but unreadable", must be rejected
      (Befund B; Probe P1, Mutation N5),
  (l) a foreign root sharing the trusted root's exact Subject DN but a
      different keypair signs the leaf -- the DN-based candidate lookup
      finds the real root, but the actual cryptographic signature check
      against it must still reject (Befund E; Mutation M5).

Co-Authored-By: default avatarClaude Sonnet 5 <noreply@anthropic.com>
parent 1eeb6b25
Loading
Loading
Loading
Loading
+7 −0
Changes for test/CMakeLists.txt: 7 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -70,6 +70,13 @@ add_executable(tls_sigalg_binding_test tls_sigalg_binding_test.cpp)
target_link_libraries(tls_sigalg_binding_test netplus-static)
add_test(NAME tls_sigalg_binding_test COMMAND tls_sigalg_binding_test)

# tls_handshake_certverify_binding_test: drives the real CLI_TLS13_WAIT_CERT_VERIFY state
# (handshake_after_connect()) with a hand-crafted in-memory message -- no socket needed --
# to prove the handshake actually calls sigAlgMatchesLeafKey() (Runde 3 review, Befund A).
add_executable(tls_handshake_certverify_binding_test tls_handshake_certverify_binding_test.cpp)
target_link_libraries(tls_handshake_certverify_binding_test netplus-static)
add_test(NAME tls_handshake_certverify_binding_test COMMAND tls_handshake_certverify_binding_test)

# 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.
+33 −0
Changes for test/cert_verify_chain_test.cpp: 33 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -174,6 +174,39 @@ int main() {
        expect(!threw, "(i) trust-anchor root without basicConstraints/keyUsage is still accepted");
    }

    // (j) an intermediate's keyUsage extnValue doesn't parse as any TLV at all (a single
    // byte) -- "present but unreadable" must fail closed, not be treated like "absent"
    // (Runde 4, Befund B / Probe P1).
    {
        auto leaf = readFile(fixture("leaf_under_badku_unparseable"));
        auto inter = readFile(fixture("intermediate_badku_unparseable"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter}, rootPem, &msg);
        expect(threw, "(j) intermediate with an unparseable keyUsage extnValue is rejected");
    }

    // (k) an intermediate's keyUsage extnValue parses, but as the wrong ASN.1 type
    // (INTEGER instead of BIT STRING) -- also "present but unreadable", a different shape
    // than (j) (Runde 4, Befund B / Mutation N5).
    {
        auto leaf = readFile(fixture("leaf_under_badku_wrongtag"));
        auto inter = readFile(fixture("intermediate_badku_wrongtag"));
        std::string msg;
        bool threw = verifyThrows({leaf, inter}, rootPem, &msg);
        expect(threw, "(k) intermediate with a wrong-tag keyUsage extnValue is rejected");
    }

    // (l) a foreign root with the trusted root's exact Subject DN, but a different
    // keypair, signs the leaf -- the DN matches a trust-store candidate, but the actual
    // cryptographic signature check against that candidate's real key must still reject
    // it (Runde 4, Befund E / Mutation M5).
    {
        auto leaf = readFile(fixture("leaf_under_foreign_root"));
        std::string msg;
        bool threw = verifyThrows({leaf}, rootPem, &msg);
        expect(threw, "(l) leaf signed by a foreign root with the trusted root's DN is rejected");
    }

    // (e) P-384 ECDSA chain: root384 -> leaf384
    {
        auto leaf = readFile(fixture("leaf384"));
+90 −0
Changes for test/gen_cert_chain_fixtures.sh: 90 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -250,6 +250,93 @@ keyUsage=critical,digitalSignature,keyEncipherment
subjectAltName=DNS:netplus-test-leaf-under-root-no-constraints
EOF

# ----------------------------------------------------------------------------
# Scenario (j): keyUsage extnValue that doesn't parse as any TLV at all (a single byte,
# too short for even a tag+length header) -- "present but unreadable", must be
# distinguished from "extension absent" and rejected (Runde 4, Befund B / Probe P1).
# ----------------------------------------------------------------------------
openssl genrsa -out intermediate_badku_unparseable.key 2048 >/dev/null 2>&1
openssl req -new -key intermediate_badku_unparseable.key -subj "/CN=netplus-test-intermediate-badku-unparseable" \
    -out intermediate_badku_unparseable.csr 2>/dev/null
openssl x509 -req -in intermediate_badku_unparseable.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out intermediate_badku_unparseable.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,DER:FF
EOF

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

# ----------------------------------------------------------------------------
# Scenario (k): keyUsage extnValue that parses as a *wrong* ASN.1 type (an INTEGER,
# tag 0x02, instead of a BIT STRING) -- a different "unreadable" shape than (j), still
# must be rejected (Runde 4, Befund B / Mutation N5: dropping the tag check would let
# this fall through to the bit-check line and read garbage as if it were keyCertSign).
# ----------------------------------------------------------------------------
openssl genrsa -out intermediate_badku_wrongtag.key 2048 >/dev/null 2>&1
openssl req -new -key intermediate_badku_wrongtag.key -subj "/CN=netplus-test-intermediate-badku-wrongtag" \
    -out intermediate_badku_wrongtag.csr 2>/dev/null
openssl x509 -req -in intermediate_badku_wrongtag.csr -CA root.crt -CAkey root.key -CAcreateserial -sha256 -days 3650 \
    -copy_extensions none \
    -extfile /dev/stdin -extensions v3_int -out intermediate_badku_wrongtag.crt 2>/dev/null <<'EOF'
[v3_int]
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,DER:020204FF
EOF

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

# ----------------------------------------------------------------------------
# Scenario (l): a foreign root with the *same Subject DN* as the trusted root, but a
# different keypair, signs the leaf instead of the real trusted root. The DN-based
# lookup in verifyPeerChain would find the real root as a "candidate" (same DN), but its
# actual signature check (verifySignedBy, cryptographic, not just DN comparison) must
# still reject it -- Runde 4, Befund E / Mutation M5: removing that signature check
# (leaving only the DN match) would wrongly accept this (Runde 3's review noted this
# path existed but was untested).
# ----------------------------------------------------------------------------
openssl genrsa -out root_foreign_same_dn.key 2048 >/dev/null 2>&1
openssl req -x509 -new -key root_foreign_same_dn.key -sha256 -days 3650 -subj "/CN=netplus-test-root" \
    -addext "basicConstraints=critical,CA:TRUE,pathlen:1" \
    -addext "keyUsage=critical,keyCertSign,cRLSign" \
    -out root_foreign_same_dn.crt 2>/dev/null

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

# ----------------------------------------------------------------------------
# Scenario (e): P-384 ECDSA chain, root -> leaf directly
# ----------------------------------------------------------------------------
@@ -288,6 +375,9 @@ for name in root intermediate leaf notca forged_leaf expired_intermediate leaf_u
            root2 intA intB leaf_under_rootless_pathlen \
            intermediate_crlsign_only leaf_under_crlsign_only \
            root_no_constraints leaf_under_root_no_constraints \
            intermediate_badku_unparseable leaf_under_badku_unparseable \
            intermediate_badku_wrongtag leaf_under_badku_wrongtag \
            root_foreign_same_dn leaf_under_foreign_root \
            root384 leaf384; do
    openssl x509 -in "$name.crt" -outform DER -out "$name.der"
done
+103 −0
Changes for test/tls_handshake_certverify_binding_test.cpp: 103 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.
 *******************************************************************************/

// Independent-review finding A (Runde 3): tls_sigalg_binding_test exercises
// sigAlgMatchesLeafKey() directly, but nothing proved the TLS1.3 handshake state machine
// (handshake_after_connect(), case CLI_TLS13_WAIT_CERT_VERIFY, ~tls.cpp:2302) actually
// calls it. This drives that real code path -- no socket, no real handshake: just the
// state machine with hand-crafted in-memory state, the same trick RFC 8446 handshake
// messages use once reassembled (tls13_pop_hs_from_buf works purely off rx_handshake_buf).
//
// Mutation N2 (the gate call removed from the dispatch) must turn this red: without it,
// the mismatched 0x0403 would fall through to verify_ecdsa_sha256() against a default
// (point-at-infinity) peer_ec_pub, which fails with a *different* message
// ("CertificateVerify signature invalid") than the one this test checks for.

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

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

namespace {

int failures = 0;

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() {
    netplus::tls t;

    // This handshake's leaf is RSA (as if its Certificate message had just been parsed).
    t.server_cert_is_ecdsa = false;

    // A hand-crafted CertificateVerify handshake message: type(1)=0x0f,
    // length24(3)=0x000008, body = sigAlg(2)=0x0403 (ecdsa_secp256r1_sha256,
    // inconsistent with the RSA leaf above) + sigLen(2)=0x0004 + 4 dummy signature bytes.
    // The content of the signature bytes doesn't matter -- sigAlgMatchesLeafKey() must
    // reject this before any byte of it is ever looked at.
    std::vector<uint8_t> certVerifyMsg = {
        0x0f, 0x00, 0x00, 0x08,
        0x04, 0x03, 0x00, 0x04,
        0xAA, 0xAA, 0xAA, 0xAA,
    };
    t.rx_handshake_buf = certVerifyMsg;
    t.rx_handshake_off = 0;
    t.hs_state = netplus::tls::HsState::CLI_TLS13_WAIT_CERT_VERIFY;

    std::string caught;
    bool threw = false;
    try {
        t.handshake_after_connect();
    } catch (const netplus::NetException& e) {
        threw = true;
        caught = e.what();
    }

    expect(threw, "handshake_after_connect() throws on a leaf-key/sigAlg mismatch");
    expect(caught.find("does not match leaf key's type/curve") != std::string::npos,
           "the thrown message names the leaf-key/sigAlg mismatch (not some other failure)");
    if (threw) std::cout << "  (" << caught << ")" << std::endl;

    if (failures) {
        std::cout << failures << " check(s) failed" << std::endl;
        return 1;
    }
    std::cout << "all tls_handshake_certverify_binding_test checks passed" << std::endl;
    return 0;
}