Closed Bug 2029698 Opened 7 months ago Closed 5 months ago

OOB read of digests[] in sec_pkcs7_encoder_sig_and_certs leads to wild-pointer dereference in SGN_Digest

Categories

(NSS :: Libraries, defect, P3)

Tracking

(Not tracked)

RESOLVED DUPLICATE of bug 1998526

People

(Reporter: bugmon, Assigned: beurdouche)

Details

(5 keywords, Whiteboard: [prefs-checked] [nss-nofx])

Attachments

(3 files, 1 obsolete file)

In NSS's legacy PKCS#7 encoder, sec_pkcs7_encoder_sig_and_certs() (lib/pkcs7/p7encode.c) computes an index di by linearly scanning the SignedData->digestAlgorithms[] array for the entry whose OID matches signerInfo->digestAlg, then uses that same index to read SignedData->digests[di] without any bounds check. These two arrays are sized independently: when a SignedData blob is parsed by SEC_PKCS7DecodeItem(), the decoder (sec_pkcs7_decoder_start_digests / _finish_digests in lib/pkcs7/p7decode.c) silently skips unrecognised hash OIDs when building digests[], but the ASN.1 decoder keeps every wire entry in digestAlgorithms[]. An attacker who prefixes the digestAlgorithms SET with N bogus OIDs followed by SHA-256 causes NSS itself to produce len(digestAlgorithms)=N+1 but len(digests)=1.

If the same attacker sets the SignerInfo's issuerAndSerialNumber to match a certificate for which the victim holds the private key (public information obtainable from any signature the victim has previously emitted), then SEC_PKCS7VerifySignature() — which any S/MIME consumer calls after decode — looks up that certificate via CERT_FindCertByIssuerAndSN and stores it in signerinfo->cert (p7decode.c:1465) before signature verification completes. The decoded cinfo now satisfies every guard in the encoder. A subsequent SEC_PKCS7Encode() on the same cinfo (a decode→re-encode round-trip, not forbidden by the API contract) reaches sec_pkcs7_encoder_sig_and_certs(), computes di=N, reads digests[N] out of bounds, and passes the resulting wild SECItem* to SGN_Digest(), which dereferences it (digder.data = digest->data, secsign.c:650).

Because the OOB slot lands inside the arena chunk immediately following the 2-slot digests[] array — which holds the SECItem header and 32-byte SHA-256 hash of the attacker-chosen inner content — the wild pointer's value is hash-derived from attacker input. With brute-forcing of the inner content the attacker gains partial control over the dereferenced address, turning this into a constrained read primitive that is then fed into a private-key signing operation; at minimum it is a reliable memory-safety crash.

Build Info

Affected Code

File: security/nss/lib/pkcs7/p7encode.c, line 711-726, 802-803

            digestalgtag = SECOID_GetAlgorithmTag(&(signerinfo->digestAlg));
            for (di = 0; digestalgs[di] != NULL; di++) {
                /* XXX Should I be comparing more than the tag? */
                if (digestalgtag == SECOID_GetAlgorithmTag(digestalgs[di]))
                    break;
            }
            if (digestalgs[di] == NULL) {
                /* XXX oops; do what? set an error? */
                return SECFailure;
            }
            PORT_Assert(digests[di] != NULL);   /* OOB read; debug-only, no bound check */

            cert = signerinfo->cert;
            privkey = PK11_FindKeyByAnyCert(cert, pwfnarg);
            if (privkey == NULL)
                return SECFailure;
            ...
            } else {
                rv = SGN_Digest(privkey, digestalgtag, &signature,
                                digests[di]);   /* <-- OOB-derived wild pointer */
            }

File: security/nss/lib/pkcs7/p7decode.c, line 269-294, 374-376

    for (i = 0; i < digcnt; i++) {
        SECAlgorithmID *algid = digestalgs[i];
        SECOidTag oidTag = SECOID_FindOIDTag(&(algid->algorithm));
        const SECHashObject *digobj = HASH_GetHashObjectByOidTag(oidTag);
        ...
        if (digobj == NULL) {
            continue;            /* unknown OID -> skipped, digcnt not bumped */
        }
        ...
            p7dcx->worker.digcnt++;
    }
    ...
    SECItem **digests =
        (SECItem **)PORT_ArenaZAlloc(poolp, (worker->digcnt + 1) * sizeof(SECItem *));
    /* digests[] is sized by recognised hashes only, NOT by len(digestAlgorithms) */

File: security/nss/lib/pkcs7/p7decode.c, line 1460-1465

    cert = CERT_FindCertByIssuerAndSN(certdb, signerinfo->issuerAndSN);
    if (cert == NULL) {
        goto done;
    }

    signerinfo->cert = cert;   /* set BEFORE signature is checked; persists on failure */

File: security/nss/lib/cryptohi/secsign.c, line 650

        digder.data = digest->data;   /* wild-pointer dereference */

The encoder trusts that digestAlgorithms[] and digests[] are parallel arrays of equal length. The decoder breaks that invariant by skipping unrecognised hash OIDs when sizing digests[], and SEC_PKCS7VerifySignature populates signerinfo->cert from attacker-chosen issuer/serial before any cryptographic check, allowing the encoder's PK11_FindKeyByAnyCert guard to pass and execution to reach the unchecked digests[di] use.

Exploit Chain

  1. Attacker obtains the issuer DN and serial number of any certificate for which the victim application holds a private key (public information from any signed message the victim has emitted).
  2. Attacker crafts a PKCS#7 SignedData DER blob whose digestAlgorithms SET contains 7 unrecognised hash OIDs followed by SHA-256, whose embedded certificate set contains the victim's cert, and whose single SignerInfo references the victim's issuer/serial with digestAlgorithm = SHA-256 and a bogus signature.
  3. Victim calls SEC_PKCS7DecodeItem() on the blob. The ASN.1 decoder fills digestAlgorithms[] with all 8 entries; sec_pkcs7_decoder_start_digests skips the 7 unknown OIDs so worker.digcnt = 1; sec_pkcs7_decoder_finish_digests arena-allocates digests[] with only 2 slots and writes the SHA-256 of the attacker's inner content immediately after it.
  4. Victim calls SEC_PKCS7VerifySignature(). CERT_ImportCerts loads the embedded cert, CERT_FindCertByIssuerAndSN resolves it, and signerinfo->cert is set (p7decode.c:1465). Verification later fails, but signerinfo->cert persists.
  5. Victim calls SEC_PKCS7Encode() on the same cinfo (decode→re-encode round-trip). sec_pkcs7_encoder_sig_and_certs scans digestAlgorithms[] for SHA-256, finds it at index 7, and reads digests[7] — 6 slots past the end of the 2-slot array, landing inside the SHA-256 hash buffer.
  6. PK11_FindKeyByAnyCert(signerinfo->cert) succeeds (victim owns the key), so the early-out is not taken; the wild SECItem* is passed to SGN_Digest(), which dereferences digest->data at secsign.c:650.
  7. Because the wild pointer's bytes are SHA-256(attacker_content), the attacker can brute-force inner content to influence the dereferenced address, yielding a constrained read primitive whose result is fed into a private-key signing operation; at minimum the process crashes.

Steps to Reproduce

  1. Apply the testcase at security/nss/gtests/smime_gtest/p7encode_unittest.cc and add 'p7encode_unittest.cc' plus the smime3 dependency to security/nss/gtests/smime_gtest/smime_gtest.gyp.
  2. Build NSS with ASan: ./build.sh --asan
  3. Run: GTESTFILTER='P7EncodeTest.DigestsArrayOOBRead' nss/tests/all.sh (the gtests harness creates the 'dummy' p256 cert+key the test uses as the victim identity).
  4. Observe ASan SEGV on a high non-canonical address in SGN_Digest, called from sec_pkcs7_encoder_sig_and_certs (p7encode.c:802).

Security Impact

  • Severity: Moderate
  • Attacker capability: An attacker who can deliver a crafted PKCS#7 SignedData blob to an NSS-based application that (a) decodes it with SEC_PKCS7DecodeItem, (b) calls SEC_PKCS7VerifySignature, and (c) subsequently re-encodes the same SEC_PKCS7ContentInfo with SEC_PKCS7Encode/SEC_PKCS7PrepareForEncode, can trigger an out-of-bounds pointer load whose value is derived from SHA-256 of attacker-chosen content. The wild pointer is dereferenced inside SGN_Digest with the victim's private signing key, giving a hash-brute-forceable read primitive that feeds into a signature computation (potential limited information disclosure / oracle) and a reliable memory-safety crash.
  • Preconditions: Victim application must round-trip an attacker-supplied PKCS#7 object through SEC_PKCS7DecodeItem → SEC_PKCS7VerifySignature → SEC_PKCS7Encode on the same cinfo (an uncommon but not API-forbidden pattern, e.g. an S/MIME relay/gateway). Attacker must know the issuer DN and serial number of a certificate for which the victim's NSS DB holds the matching private key (public information). No user interaction beyond message delivery is required; the signature in the blob does not need to verify.

ASAN Report

==43377==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x7bd13c573ffd bp 0x7ffdcd646480 sp 0x7ffdcd646380 T0)
==43377==The signal is caused by a READ memory access.
==43377==Hint: this fault was caused by a dereference of a high value address (see register values below).  Disassemble the provided pc to learn which register was used.
    #0 0x7bd13c573ffd in SGN_Digest ../../lib/cryptohi/secsign.c:650
    #1 0x7bd13c425479 in sec_pkcs7_encoder_sig_and_certs ../../lib/pkcs7/p7encode.c:802
    #2 0x7bd13c426271 in SEC_PKCS7PrepareForEncode ../../lib/pkcs7/p7encode.c:983
    #3 0x7bd13c426361 in SEC_PKCS7Encode ../../lib/pkcs7/p7encode.c:1023
    #4 0x5ad969bc5c79 in nss_test::P7EncodeTest_DigestsArrayOOBRead_Test::TestBody() ../../gtests/smime_gtest/p7encode_unittest.cc:218
    #5 0x5ad969c689d2 in void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2607
    #6 0x5ad969c542b7 in void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2643
    #7 0x5ad969bfb919 in testing::Test::Run() ../../gtests/google_test/gtest/src/gtest.cc:2682
    #8 0x5ad969bfcf41 in testing::TestInfo::Run() ../../gtests/google_test/gtest/src/gtest.cc:2861
    #9 0x5ad969bfe3cc in testing::TestSuite::Run() ../../gtests/google_test/gtest/src/gtest.cc:3015
    #10 0x5ad969c2544c in testing::internal::UnitTestImpl::RunAllTests() ../../gtests/google_test/gtest/src/gtest.cc:5855
    #11 0x5ad969c6c0e4 in bool testing::internal::HandleSehExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2607
    #12 0x5ad969c57088 in bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2643
    #13 0x5ad969c218e1 in testing::UnitTest::Run() ../../gtests/google_test/gtest/src/gtest.cc:5438
    #14 0x5ad969bdaea5 in RUN_ALL_TESTS() ../../gtests/google_test/gtest/include/gtest/gtest.h:2490
    #15 0x5ad969bdb26f in main ../../gtests/common/gtests.cc:45
    #16 0x7bd13bbcd1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9)
    #17 0x7bd13bbcd28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a)
    #18 0x5ad969bb6184 in _start (/firefox/security/dist/Debug/bin/smime_gtest+0x24184)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV ../../lib/cryptohi/secsign.c:650 in SGN_Digest
==43377==ABORTING
Attached file smime_gtest.gyp —
Attached file p7encode_unittest.cc —
Attached file crash_stack.txt —
Group: core-security → crypto-core-security

Unable to reproduce bug 2029698 using build mozilla-central 20260406213346-97bdd50d0475. Without a baseline, bugmon is unable to analyze this bug.
Removing bugmon keyword as no further action possible. Please review the bug and re-add the keyword for further analysis.

Keywords: bugmon
Whiteboard: [prefs-checked]

Triage notes:

  • No prefs involved; the crash path is a pure NSS C API sequence (SEC_PKCS7DecodeItem → SEC_PKCS7VerifySignature → SEC_PKCS7Encode). Marking [prefs-checked].
  • sec-moderate left as-is: none of the standard downgrade conditions apply (not a guaranteed NULL/SIGBUS, no chrome-JS/patched-process precondition).
  • Not auto-patching: the testcase is an NSS smime_gtest, which I cannot reproduce with the available Firefox/grizzly automation, and bugmon also failed to reproduce. Needs manual reproduction and fix.

This is an automated analysis result. If this result is incorrect please add a needinfo and feel free to correct the error.

Severity: -- → S3
Status: UNCONFIRMED → NEW
Ever confirmed: true
Priority: -- → P3
Whiteboard: [prefs-checked] → [prefs-checked] [nss-nofx]
Assignee: nobody → bbeurdouche
Status: NEW → ASSIGNED
Attached file (secure) (obsolete) —
Attachment #9575364 - Attachment is obsolete: true
Status: ASSIGNED → RESOLVED
Closed: 5 months ago
Duplicate of bug: 1998526
Resolution: --- → DUPLICATE
Group: crypto-core-security
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: