Closed Bug 2030103 Opened 7 months ago Closed 7 months ago

OOB array index in sec_pkcs7_verify_signature via desynced digests[]/digestalgs[] arrays

Categories

(NSS :: Libraries, defect)

defect

Tracking

(Not tracked)

RESOLVED DUPLICATE of bug 1998526

People

(Reporter: bugmon, Unassigned)

Details

(5 keywords)

Attachments

(4 files)

NSS's legacy PKCS#7 signature-verification path contains a parallel-array desynchronization that leads to out-of-bounds reads, type confusion, and wild pointer dereference. During decode, sec_pkcs7_decoder_start_digests silently skips unrecognized hash OIDs in the SignedData digestAlgorithms SET, packing only recognized digest contexts into a dense array and tracking their count in worker->digcnt. sec_pkcs7_decoder_finish_digests then sizes the digests[] result array using this reduced count. However, sec_pkcs7_verify_signature later searches the original, uncompacted digestalgs[] array for the SignerInfo's hash OID and uses the resulting position to index directly into digests[] — assuming the two arrays are parallel when they are not.

An attacker who can present a PKCS#7 SignedData blob containing N unrecognized algorithm OIDs followed by one recognized OID (e.g. SHA-256) causes digests[] to be allocated with only 2 slots while the verification loop sets i=N. The expression digest = digests[N] reads arena memory beyond the array. With N=7, the read lands on the first 8 bytes of the SHA-256 hash buffer (allocated immediately after digests[], a threadmark, and a SECItem header in the same arena pool). Those bytes are interpreted as a SECItem* and dereferenced at line 1610 (digest->len) and line 1614 (PORT_Memcmp on digest->data). When authenticated attributes are absent, the wild pointer flows further into VFY_VerifyDigestDirect at line 1693.

The attacker controls both the OOB index (via the count of bogus OIDs) and the bytes landed on (via the inner content, which determines the hash). The vulnerability is reachable through the exported public API SEC_PKCS7VerifySignature, used by the p7content command-line tool and the PKCS#12 import path (security/nss/lib/pkcs12/p12d.c:1525). The precondition is that CERT_VerifyCert succeeds for the signer — which is the normal operating mode for any consumer that has chosen to trust an S/MIME or code-signing identity, and is independent of the malformed digestAlgorithms field.

Build Info

Affected Code

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

    for (i = 0; i < digcnt; i++) {
        SECAlgorithmID *algid = digestalgs[i];
        SECOidTag oidTag = SECOID_FindOIDTag(&(algid->algorithm));
        const SECHashObject *digobj = HASH_GetHashObjectByOidTag(oidTag);
        void *digcx;

        /*
         * Skip any algorithm we do not even recognize; obviously,
         * this could be a problem, but if it is critical then the
         * result will just be that the signature does not verify.
         * We do not necessarily want to error out here, because
         * the particular algorithm may not actually be important,
         * but we cannot know that until later.
         */
        if (digobj == NULL) {
            continue;             /* <-- silently skips, does NOT advance digcnt */
        }

        digcx = (*digobj->create)();
        if (digcx != NULL) {
            (*digobj->begin)(digcx);
            p7dcx->worker.digobjs[p7dcx->worker.digcnt] = digobj;
            p7dcx->worker.digcxs[p7dcx->worker.digcnt] = digcx;
            p7dcx->worker.digcnt++;   /* <-- counts ONLY recognized algs */
        }
    }

File: security/nss/lib/pkcs7/p7decode.c, line 375-376

    SECItem **digests =
        (SECItem **)PORT_ArenaZAlloc(poolp, (worker->digcnt + 1) * sizeof(SECItem *));
    /* digests[] sized for COMPACTED count, not original digestalgs[] count */

File: security/nss/lib/pkcs7/p7decode.c, line 1554-1563

        /*
         * pick digest matching signerinfo->digestAlg from digests
         */
        for (i = 0; digestalgs[i] != NULL; i++) {
            if (SECOID_FindOIDTag(&(digestalgs[i]->algorithm)) == digestTag)
                break;
        }
        if (digestalgs[i] == NULL) {
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
            goto done;
        }

        digest = digests[i];   /* <-- OOB: i is position in UNCOMPACTED digestalgs[] */

File: security/nss/lib/pkcs7/p7decode.c, line 1610-1614

        if (value == NULL || value->len != digest->len) {   /* <-- wild ptr deref, line 1610 */
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
            goto done;
        }
        if (PORT_Memcmp(value->data, digest->data, value->len) != 0) {  /* <-- controlled-addr read */

File: security/nss/lib/pkcs7/p7decode.c, line 1693-1694

        goodsig = (PRBool)(VFY_VerifyDigestDirect(digest, publickey, sig,
                                                  encTag, digestTag, cinfo->pwfn_arg) == SECSuccess);
        /* <-- alternative path: when authAttr is absent, wild digest flows into VFY layer */

The decoder compacts the digests[] result array by skipping unrecognized algorithm OIDs, but the verifier indexes that compacted array using positions from the original, uncompacted digestalgs[] array. The two arrays are assumed parallel but are not. The OOB-read pointer is then dereferenced as a SECItem* — first at ->len (offset 16) for a length comparison, then at ->data (offset 8) as a memcmp source, or alternatively passed wholesale into VFY_VerifyDigestDirect when no authenticated attributes are present.

Exploit Chain

  1. Attacker crafts a PKCS#7 SignedData DER blob whose digestAlgorithms SET contains N unrecognized OIDs (e.g. 1.2.3) followed by a recognized hash OID (SHA-256), and whose SignerInfo.digestAlgorithm references the recognized OID.
  2. Attacker chooses inner content such that SHA-256(content) bytes form a useful pointer-shaped value at the offset where digests[N] will land in the arena (or chooses N to land on a real heap pointer such as the SECItem.data field of the hash result).
  3. The blob is delivered to a victim that calls SEC_PKCS7DecodeItem followed by SEC_PKCS7VerifySignature — e.g. the p7content tool processing a .p7m file, or the PKCS#12 import path processing a .p12 file with public-key integrity mode (no MAC).
  4. During decode, sec_pkcs7_decoder_start_digests skips the N bogus OIDs (digcnt stays at 0 for each) and only creates a digest context for SHA-256 (digcnt becomes 1).
  5. sec_pkcs7_decoder_finish_digests allocates digests[] with (1+1)=2 pointer slots and stores the SHA-256 result in digests[0]. The hash buffer is allocated immediately after in the same arena.
  6. During verification, CERT_VerifyCert succeeds for the trusted signer (the normal operating condition).
  7. The loop at p7decode.c:1554 walks digestalgs[] (which still has all N+1 entries) and finds SHA-256 at index i=N. Line 1563 reads digest = digests[N] — 8*(N-1) bytes past the end of the 16-byte array, into adjacent arena allocations.
  8. If authAttr is present: line 1610 dereferences digest->len (read at wild_ptr+16); if that compare passes, line 1614 calls PORT_Memcmp reading value->len bytes from digest->data — an attacker-influenced address read.
  9. If authAttr is absent: the wild digest pointer flows directly into VFY_VerifyDigestDirect at line 1693, which dereferences digest->data and digest->len inside the signature-verification machinery.
  10. In the demonstrated PoC (N=7, content='A'), digests[7] reads the first 8 bytes of SHA-256('A') = 559aead08264d579, which little-endian forms the non-canonical address 0x79d56482d0ea9a55, causing a guaranteed general-protection fault on x86-64. With different N or content, the read lands on real heap pointers and the dereference proceeds.

Steps to Reproduce

  1. Build NSS with ASAN: cd /firefox/security/nss && ./build.sh --asan
  2. Apply test additions to /firefox/security/nss/gtests/smime_gtest/smime_unittest.cc (test SMimeTest.PKCS7VerifySignedDataDigestIndexOOB) and change /firefox/security/nss/gtests/smime_gtest/smime_gtest.gyp to depend on smime3 instead of smime.
  3. Rebuild smime_gtest target.
  4. rm -rf /firefox/security/tests_results (to ensure fresh trust DB).
  5. Run: GTESTFILTER='SMimeTest.PKCS7VerifySignedDataDigestIndexOOB' /firefox/security/nss/tests/all.sh
  6. Observe ASan SEGV at p7decode.c:1610 with 'dereference of a high value address'.

Security Impact

  • Severity: Moderate
  • Attacker capability: Out-of-bounds heap read followed by type confusion: arena bytes adjacent to the digests[] array are interpreted as a SECItem* and dereferenced. The attacker controls the OOB index (via the count of bogus algorithm OIDs, freely chosen up to ASN.1 limits) and influences the bytes landed on (via the inner content, which determines the hash result stored adjacently in the arena). Demonstrated outcome is process crash via non-canonical pointer dereference. With careful index/content selection, the OOB read can land on a real heap pointer (e.g. the SECItem.data field at digests[]+40), turning digest->data and digest->len into hash-derived attacker-controlled values that feed PORT_Memcmp (line 1614) or VFY_VerifyDigestDirect (line 1693) — a controlled-address read primitive. No write primitive demonstrated.
  • Preconditions: CERT_VerifyCert must succeed for the SignerInfo's certificate (p7decode.c:1493) — i.e., the signer must chain to a trusted root or be marked as a trusted peer for emailSigner usage. This is the NORMAL operating condition for SEC_PKCS7VerifySignature; consumers call it precisely because they trust the signer. The malformed digestAlgorithms SET is fully independent of any cryptographic signature, so a compromised-but-trusted signer, a stolen signing key, or a mis-issued certificate from a trusted CA all suffice. Reachable callers: p7content command-line tool (direct file input) and the PKCS#12 import path (p12d.c:1525) when a .p12/.pfx file uses public-key integrity mode rather than password-MAC.

ASAN Report

[*] digestAlgorithms=8 digests=1 (mismatch confirmed)
[*] calling SEC_PKCS7VerifySignature - expect crash...
AddressSanitizer:DEADLYSIGNAL
=================================================================
==9902==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x7e0ca804d6c5 bp 0x7fffba48aa50 sp 0x7fffba48a820 T0)
==9902==The signal is caused by a READ memory access.
==9902==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 0x7e0ca804d6c5 in sec_pkcs7_verify_signature ../../lib/pkcs7/p7decode.c:1610
    #1 0x7e0ca804e129 in SEC_PKCS7VerifySignature ../../lib/pkcs7/p7decode.c:1798
    #2 0x58f54aee3ce2 in nss_test::SMimeTest_PKCS7VerifySignedDataDigestIndexOOB_Test::TestBody() (/firefox/security/dist/Debug/bin/smime_gtest+0x24ce2) (BuildId: ada7fc0cb2820c96640bb11d3b24e1e0b6211ce9)
    #3 0x58f54af88822 in void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2607
    #4 0x58f54af740cd in void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) ../../gtests/google_test/gtest/src/gtest.cc:2643
    #5 0x58f54af1b7dd in testing::Test::Run() ../../gtests/google_test/gtest/src/gtest.cc:2682
    #6 0x58f54af1ce05 in testing::TestInfo::Run() ../../gtests/google_test/gtest/src/gtest.cc:2861
    #7 0x58f54af1e290 in testing::TestSuite::Run() ../../gtests/google_test/gtest/src/gtest.cc:3015
    #8 0x58f54af45310 in testing::internal::UnitTestImpl::RunAllTests() ../../gtests/google_test/gtest/src/gtest.cc:5855
    #9 0x58f54af8bf34 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
    #10 0x58f54af76e9e 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
    #11 0x58f54af417a5 in testing::UnitTest::Run() ../../gtests/google_test/gtest/src/gtest.cc:5438
    #12 0x58f54aefad69 in RUN_ALL_TESTS() ../../gtests/google_test/gtest/include/gtest/gtest.h:2490
    #13 0x58f54aefb133 in main ../../gtests/common/gtests.cc:45
    #14 0x7e0ca77f91c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 8e9fd827446c24067541ac5390e6f527fb5947bb)
    #15 0x7e0ca77f928a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 8e9fd827446c24067541ac5390e6f527fb5947bb)
    #16 0x58f54aeda0b4 in _start (/firefox/security/dist/Debug/bin/smime_gtest+0x1b0b4) (BuildId: ada7fc0cb2820c96640bb11d3b24e1e0b6211ce9)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV ../../lib/pkcs7/p7decode.c:1610 in sec_pkcs7_verify_signature
==9902==ABORTING
Attached file smime_unittest.cc —
Attached file smime_gtest.gyp —
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Group: core-security → crypto-core-security
Status: UNCONFIRMED → RESOLVED
Closed: 7 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: