Skip to content

PKCS#7: fix SignedData verify state across cert reload and reuse - #12286

Open
Frauschi wants to merge 10 commits into
wolfSSL:masterfrom
Frauschi:pkcs7-nostream-multipart-content
Open

Frauschi wants to merge 10 commits into
wolfSSL:masterfrom
Frauschi:pkcs7-nostream-multipart-content

Conversation

@Frauschi

@Frauschi Frauschi commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Description

Fixes SignedData verify bugs around the stage 5 signer cert reload and reusing a wc_PKCS7 across messages, several of them use-after-free reads reachable from crafted input or a nested verify.

Fixes F-19104, F-18631, F-18632, F-16374 and F-18637.

Changes

  • Point the verify content at the contentDynamic copy kept across the stage 5 reload.
  • Step over a constructed eContent by its encoded length, and read a single-part one from after its tag.
  • Use the streamed digest only for streamed content, and stream nothing out during a detached verify.
  • Keep the wc_PKCS7_SetStreamMode() callbacks across the reload.
  • Fail the verify with BUFFER_E on a negative stream-out callback return.
  • Clear certificate pointers into stream->tmpCert before freeing it.
  • Clear verifyCert when a verify starts.
  • Free the DER copy of a previous BER message when a verify starts, instead of parsing it again.
  • Copy the caller hash when a verify starts, so the reload cannot free it under the verify.
  • Reject an input inside a buffer the object owns with BAD_FUNC_ARG, and drop a content pointer left inside one. Adds wc_PKCS7.contentDynamicSz at the end of the structure.

Testing

  • New pkcs7_sd tests (test_wc_PKCS7_VerifySignedData_*): ConstructedContent, StreamOutDetached, StreamOutWithCerts, StreamOutCallbackReturn, ReuseAfterBadCertSet, DegenerateClearsVerifyCert, ReuseAfterBer, HashFromOwnedBuf, NestedSameObject.

Copilot AI balanced review requested due to automatic review settings November 26, 2026 14:56
@Frauschi Frauschi self-assigned this Nov 26, 2026
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

gcc-arm-cortex-m4-pkcs7

  • FLASH: .rodata.CSWTCH.1903 +91 B, .text +320 B (+0.1%, 226,449 B / 262,144 B, total: 86% used)

zephyr-frdm_rw612

  • FLASH: datas +16 B, log_const_area -8 B, rodata +108 B, text +14,152 B (+5.1%, 296,732 B / 67,108,864 B, total: 0% used)
  • RAM: bss +49 B, datas +16 B (+0.1%, 58,423 B / 983,040 B, total: 6% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical use-after-free remains because startup cleanup can free an owned hashBuf before verification reads it, and constructed-content fixtures lack streaming chunk-boundary coverage.

2 open issues
What changed in this PR

This PR hardens wolfCrypt’s PKCS#7 SignedData verification when reloading signer certificates and reusing a verification object across messages.

Changes:

  • Corrects constructed-content parsing and preserves content and streaming callbacks across certificate reloads.
  • Clears stale references and rejects message inputs backed by buffers the verification object owns.
  • Adds six regression tests and documents content lifetime and nested-verification restrictions.
File Description
wolfssl/​wolfcrypt/​pkcs7.h Tracks the allocated size of dynamic content.
wolfcrypt/​src/​pkcs7.c Updates parsing, buffer ownership checks, state cleanup, and streaming verification.
tests/​api/​test_pkcs7.h Declares and registers six regression tests.
tests/​api/​test_pkcs7.c Adds coverage for constructed content, callbacks, certificate state, reuse, and nested verification.
doc/​dox_comments/​header_files/​pkcs7.h Documents owned-buffer rejection and content lifetime rules.

Review effort: Balanced

Comment thread wolfcrypt/src/pkcs7.c Resolved
Comment thread tests/api/test_pkcs7.c Resolved
@Frauschi
Frauschi force-pushed the pkcs7-nostream-multipart-content branch from 8bc6b48 to e71de54 Compare November 26, 2026 15:14
@Frauschi
Frauschi requested a balanced review from Copilot November 26, 2026 15:20
@Frauschi

Copy link
Copy Markdown
Member Author

@claude review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical use-after-free remains: reusing a saved digest pointer in a subsequent verification bypasses the ownership guard, allowing the digest to be freed before signature verification reads it.

1 open issue
2 resolved since last review

Review effort: Balanced

Comment thread wolfcrypt/src/pkcs7.c Resolved
Comment thread wolfcrypt/src/pkcs7.c Resolved
Comment thread wolfcrypt/src/pkcs7.c Resolved
@Frauschi
Frauschi force-pushed the pkcs7-nostream-multipart-content branch from e71de54 to f421449 Compare November 26, 2026 16:17
@Frauschi

Copy link
Copy Markdown
Member Author

@claude review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The overlap guard misses owned signature, attribute, and certificate buffers, allowing aliased verification inputs to be freed before use and causing a critical use-after-free.

2 open issues
1 resolved since last review

Review effort: Balanced

Comment thread wolfcrypt/src/pkcs7.c Resolved
Comment thread doc/dox_comments/header_files/pkcs7.h Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review completed

Nothing new to post: everything this review found is already covered by existing comments on this pull request or didn't merit a separate one.

@Frauschi
Frauschi force-pushed the pkcs7-nostream-multipart-content branch 2 times, most recently from fae1a77 to 8e646c3 Compare November 27, 2026 09:01
When the eContent is a constructed OCTET STRING and streaming is
disabled, PKCS7_VerifySignedData() joins the parts into
pkcs7->contentDynamic and points its local content at that buffer.
Stage 5 then frees the structure with wc_PKCS7_Free() and reinitializes
it with the signer certificate, restoring a copy of contentDynamic, but
content still pointed at the freed original. The content digest and
pkcs7->content were then taken from freed memory.

Point content at the restored copy when it pointed at contentDynamic.
An offset bug, fixed separately, keeps a well-formed message from
reaching stage 5, but a crafted one gets there by placing the
certificate set inside the last part. The constructed eContent test
added with that fix reaches this path in builds without streaming, and
ASan reports the use after free there when this change is left out.

Fixes F-19104.
Without streaming, PKCS7_VerifySignedData() advanced past a constructed
eContent OCTET STRING by the number of content bytes it collected, not
by the encoded length of the string. The inner OCTET STRING headers were
left in front of the parse position, so the certificate set and the
signerInfos were read from the wrong offset and a valid message with a
definite-length constructed eContent failed with ASN_PARSE_E. A string
whose parts are all empty was not stepped over at all.

Advance by the encoded length once the parts are collected, and by the
content length only for a primitive OCTET STRING. Indefinite-length
messages were not affected because wc_BerToDer() flattens the string
first, and streaming builds parse the parts separately.

A constructed string holding a single part failed in both builds: the
part was then read as a primitive OCTET STRING, but from the position of
its tag, so the tag byte was taken as the length. Start that read after
the tag.

The new test signs a message, wraps its eContent in a constructed OCTET
STRING of one part and of two parts, and verifies both in both builds.
In stream-out mode, stage 7 of PKCS7_VerifySignedData() replaced the
digest with the one hashed while the content was streamed whenever a
stream-out callback was set. Only embedded eContent goes through the
callback, so a detached verify checked the messageDigest attribute
against the digest of no content and failed with SIG_VERIFY_E.

Use the streamed digest only when the content was streamed, and refuse
to stream content out during a detached verify, where the signature
covers the caller's content.
When a SignedData carries certificates, PKCS7_VerifySignedData() frees
and reinitializes the structure in stage 5 to load the signer
certificate. It restores the stream, the DER copy, the content and the
degenerate policy, but not the callbacks set with
wc_PKCS7_SetStreamMode(). In stream-out mode stage 3 has already handed
the content to streamOutCb and hashed it without keeping a copy, so
stage 7 found no callback, skipped the streamed digest and checked the
messageDigest attribute against missing content. The verify failed
with SIG_VERIFY_E, and the caller's stream mode was gone afterwards.

Save getContentCb, streamOutCb, streamCtx and the encodeStream flag
before the reload and put them back with the other restored fields.

Fixes F-18631.
PKCS7_VerifySignedData() ignored the return value of the stream-out
callback, so content the callback could not take was dropped and the
verify still succeeded. Fail the verify with BUFFER_E when the callback
returns a negative value. Zero or a positive byte count continues, the
values wc_PKCS7_WriteOut() accepts. The wc_PKCS7_SetStreamMode()
documentation now says how a verify and a decode treat the return.
In streaming builds, stage 5 of PKCS7_VerifySignedData() copies the
certificate set into stream->tmpCert, and the reload with the first
certificate points singleCert, cert[], issuer, the certificate list
and later verifyCert into that copy. The copy outlives the call, so the
pointers stay valid for the application.

When the same object verifies another message with a certificate set,
stage 5 frees the old copy before it has accepted the new set, and only
the reload replaces the pointers. An error in between, such as a
certificate length past the end of the set, returned with every pointer
still aimed at the freed copy. A following message without certificates
then parsed the freed memory as its signer certificate.

Clear those references before freeing the copy when one of them points
into it, and keep its allocated size in a new stream field for that
check. A set rejected before any reload leaves a copy behind with the
certificate the caller loaded still in place, so dropping the references
on any non-NULL tmpCert would lose that certificate at the next rejected
set.

Fixes F-18632.
pkcs7->verifyCert names the certificate whose signature a verify
checked, and callers such as wolfSSL_PKCS7_verify() treat a NULL value
as "nothing was signed". It was only reset when the stage 5 reload
reinitialized the structure, so a certificates-only bundle without a
certificate set, which skips that reload, verified with the previous
message's signer still in place.

Clear verifyCert and verifyCertSz with the other per-message state at
WC_PKCS7_START. The new test checks a verify that fails after the reset
in every build, and the certificates-only bundle without streaming,
where a bundle that short completes a verify.

Fixes F-16374.
Without streaming, PKCS7_VerifySignedData() converts an
indefinite-length message into pkcs7->der and parses that copy. The
copy outlived the call, and every later call replaced its input with
pkcs7->der whenever derSz was set. After a BER message without a
certificate set, the next verify on the same object therefore parsed
the old message instead of its own input, returned 0 and handed back
the old content. Each further BER message also leaked the previous
copy. Messages with certificates escaped only because the stage 5
reload restored der but not derSz.

At WC_PKCS7_START, free the previous copy instead of parsing it. Content
and certificate references that a verify pointed into the copy are
dropped with it, and derSz now survives the reload so those references
can be recognized. Content and certificates the caller set are kept. An
input or footer inside the copy, such as the content a BER message
returned, is rejected with BAD_FUNC_ARG rather than freed under the
call. A header/footer verify keeps the contentSz the caller set. A
message without certificates can no longer verify against the
certificates of a previous BER message, as they went with its copy;
streaming builds keep the previous set in stream->tmpCert as before.

The BER conversion now writes into a local buffer and stores it only
once wc_BerToDer() succeeds, and the MEMORY_E exit of the stage 5
reload puts the copy back in pkcs7->der instead of leaking it. The new
test runs without streaming, the only build that makes the copy.

Fixes F-18637.
wc_PKCS7_VerifySignedData_ex() checks the messageDigest attribute
against a content hash the caller passes in. A hash taken from memory
the object owns, such as the messageDigest attribute, plainDigest,
pkcs7Digest or signature left by a verify that returned
PKCS7_SIGNEEDS_CHECK, was freed by the stage 5 signer cert reload and
read again in stage 7.

Copy the caller hash when a verify starts, so no buffer the verify frees
can lie under it, and refuse a hash longer than WC_MAX_DIGEST_SIZE.
Streaming builds keep the copy in the stream state and use it on the
later calls of the same verify, because a chunked verify can run the
reload and stage 7 in different calls, with the caller's pointer
already freed by the time of the second.
After a verify, pkcs7->content can point into a buffer the wc_PKCS7
owns: stream->content in streaming builds, contentDynamic for an
eContent joined from several parts, or the DER copy of a BER message.
Verifying that content on the same object, as an application might for
a nested SignedData, freed the buffer during the call while the input
still pointed into it. Both builds free contentDynamic when the next
verify starts, and streaming builds also release stream->content in
stage 2 and then parse freed memory in wc_PKCS7_HandleOctetStrings().
The DER copy is already refused.

Refuse an input or footer inside any of these buffers with BAD_FUNC_ARG
on every call.

When a verify starts, content left by the previous verify was dropped
only while pkcs7->content still equalled the pointer that verify left.
A pointer the caller had advanced into contentDynamic or stream->content
survived the free and was taken as content the caller set: the next
verify of a valid message failed with SIG_VERIFY_E and handed the
dangling pointer back. Drop any pointer inside those buffers. The
checks use the allocated sizes, kept in a new stream field and a new
wc_PKCS7 member contentDynamicSz at the end of the structure, so a
pointer into the middle of a buffer is caught however the caller changed
pkcs7->content. The documentation says the content has to be copied or
verified with another structure. Content that points into the caller's
own buffer is not affected, so a nested verify without streaming of a
message the caller holds still works.
@Frauschi
Frauschi force-pushed the pkcs7-nostream-multipart-content branch from 8e646c3 to ba23254 Compare November 27, 2026 10:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants