Skip to content

Fix XNNPACK FlatBuffer verification and header bounds checking#18784

Merged
lucylq merged 1 commit intomainfrom
security33-34
Apr 14, 2026
Merged

Fix XNNPACK FlatBuffer verification and header bounds checking#18784
lucylq merged 1 commit intomainfrom
security33-34

Conversation

@lucylq
Copy link
Copy Markdown
Contributor

@lucylq lucylq commented Apr 8, 2026

  1. Add flatbuffer verification to xnnpack graph
  2. Check the flatbuffer and constant data region are valid (within flatbuffer size, and do not overlap with each other)

This PR was authored with the assistance of Claude.

@pytorch-bot
Copy link
Copy Markdown

pytorch-bot Bot commented Apr 8, 2026

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/18784

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 1 New Failure, 1 Cancelled Job, 3 Pending, 1 Unrelated Failure

As of commit 23e507b with merge base 21d9c64 (image):

NEW FAILURE - The following job has failed:

CANCELLED JOB - The following job was cancelled. Please retry:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Apr 8, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 8, 2026

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@lucylq lucylq marked this pull request as ready for review April 8, 2026 23:48
@lucylq lucylq requested a review from digantdesai as a code owner April 8, 2026 23:48
@lucylq lucylq requested review from GregoryComer and Copilot April 8, 2026 23:48
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens XNNPACK delegate deserialization by validating wrapper-header regions and verifying the embedded FlatBuffer before traversing it, aiming to prevent OOB reads on malformed/corrupt inputs.

Changes:

  • Add bounds/overlap checks for the flatbuffer and constant-data regions in XNNHeader::Parse.
  • Track the effective flatbuffer byte length and run FlatBuffers verifier before GetXNNGraph access in XNNCompiler::compileModel.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
backends/xnnpack/runtime/XNNHeader.cpp Adds header-based range checks for flatbuffer/constant-data offsets & sizes, including non-overlap enforcement.
backends/xnnpack/runtime/XNNCompiler.cpp Introduces FlatBuffer verification using the computed flatbuffer size before parsing the graph.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +1849 to +1856
// Verify the FlatBuffer data integrity before accessing it. Without this,
// malformed data could cause out-of-bounds reads when traversing the
// FlatBuffer's internal offset tables.
flatbuffers::Verifier verifier(flatbuffer_data, flatbuffer_size);
ET_CHECK_OR_RETURN_ERROR(
fb_xnnpack::VerifyXNNGraphBuffer(verifier),
DelegateInvalidCompatibility,
"FlatBuffer verification failed; data may be truncated or corrupt");
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

flatbuffers::Verifier is run via fb_xnnpack::VerifyXNNGraphBuffer(verifier), but the generated verifier typically enforces the schema’s file_identifier. In this repo, the runtime schema uses file_identifier "XN00" while the Python serializer produces buffers with identifier XN01 (and this function already intends to support both). As written, verification will likely reject valid XN01 payloads and break backward compatibility.

Consider verifying the buffer without enforcing the identifier (e.g., verifier.VerifyBuffer<fb_xnnpack::XNNGraph>(nullptr)), or selecting the expected identifier string ("XN00"/"XN01") based on the earlier identifier check and passing it to VerifyBuffer<...>(expected_id) instead of calling the generated VerifyXNNGraphBuffer.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you double check BC with this change? We don't have good CI coverage for this currently (I need to fix this).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ah this is updated to use verifier.VerifyBuffer.. which doesn't specify the magic number

Comment on lines 1846 to 1847
"XNNPACK Delegate Serialization Format version identifier '%.4s' != expected XN00 or XN01'",
flatbuffers::GetBufferIdentifier(flatbuffer_data));
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

flatbuffers::GetBufferIdentifier(flatbuffer_data) is used before any minimum-length/verification check. If flatbuffer_size is < 8 (e.g., truncated/corrupt input), this can read past the provided buffer. Add an explicit minimum-size check before calling it (at least sizeof(flatbuffers::uoffset_t) + flatbuffers::kFileIdentifierLength), or perform verification/bounds checking prior to identifier access.

Copilot uses AI. Check for mistakes.
Comment on lines +69 to +75
ET_CHECK_OR_RETURN_ERROR(
flatbuffer_offset <= size && flatbuffer_size <= size - flatbuffer_offset,
InvalidArgument,
"flatbuffer_offset: %u and flatbuffer_size: %u are invalid for buffer of size: %zu",
flatbuffer_offset,
flatbuffer_size,
size);
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

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

The new error messages print uint32_t fields using %u. In this codebase there are already places using PRIu32 for uint32_t formatting; using the PRIu32 macros here as well avoids type/format mismatches on platforms where uint32_t isn’t unsigned int and keeps formatting consistent.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Valid nit.

Copy link
Copy Markdown
Contributor Author

@lucylq lucylq Apr 10, 2026

Choose a reason for hiding this comment

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

thanks, updated!

Copilot AI review requested due to automatic review settings April 10, 2026 21:54
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backends/xnnpack/runtime/XNNHeader.cpp
@lucylq
Copy link
Copy Markdown
Contributor Author

lucylq commented Apr 14, 2026

@claude review

@claude
Copy link
Copy Markdown

claude Bot commented Apr 14, 2026

Claude finished @lucylq's task in 3m 50s —— View job


Review: Fix XNNPACK FlatBuffer verification and header bounds checking

  • Read changed files and gather context
  • Analyze header bounds checking logic (XNNHeader.cpp)
  • Analyze FlatBuffer verification logic (XNNCompiler.cpp)
  • Post review feedback

Overall this is a good security hardening PR. The bounds-checking math is correct, the FlatBuffer verifier is properly placed before any traversal, and passing nullptr for the identifier in VerifyBuffer is the right call since both XN00 and XN01 need to be accepted (and the identifier is already validated above). A few issues to address:

Issue 1: Missing minimum flatbuffer_size check — potential OOB read

XNNHeader.cpp — The validation accepts flatbuffer_size == 0 (or any small value). When the header is present (header.ok() path), flatbuffer_size flows into XNNCompiler.cpp where GetBufferIdentifier(flatbuffer_data) is called at line 1839 before the verifier runs. GetBufferIdentifier reads at offset sizeof(uoffset_t) (4 bytes) plus 4 identifier bytes = 8 bytes minimum. A flatbuffer_size of 0–7 would allow an OOB read here.

Copilot flagged both the zero-size issue (in XNNHeader.cpp) and the pre-verification read (in XNNCompiler.cpp). The simplest fix is to enforce a minimum flatbuffer size in XNNHeader::Parse. FlatBuffers requires at least sizeof(uoffset_t) + kFileIdentifierLength = 8 bytes for even the most trivial valid buffer:

// XNNHeader.cpp, after validating flatbuffer region bounds:
constexpr size_t kMinFlatbufferSize = sizeof(uint32_t) + 4; // root offset + identifier
ET_CHECK_OR_RETURN_ERROR(
    flatbuffer_size >= kMinFlatbufferSize,
    InvalidArgument,
    "flatbuffer_size %" PRIu32 " is too small (minimum %zu)",
    flatbuffer_size,
    kMinFlatbufferSize);

Alternatively, add this check in XNNCompiler.cpp before the identifier read at line 1838, which would also protect the NotFound path (though that path is already safe since num_bytes >= kMinSize = 30).

Fix this →

Issue 2: Overlap check is one-directional

XNNHeader.cpp:90-98 — The overlap check assumes flatbuffer always precedes constant data (constant_data_offset >= flatbuffer_offset). If the serializer ever places them in reverse order, this would reject valid data. This seems like an intentional hardening decision (matching the serializer's layout), but worth noting that it's enforcing layout order, not just non-overlap.

If the intent is strictly to prevent overlap (without enforcing order), the check would be:

// No overlap: either constant_data ends before flatbuffer starts,
// or flatbuffer ends before constant_data starts.
(constant_data_offset + constant_data_size <= flatbuffer_offset) ||
(flatbuffer_offset + flatbuffer_size <= constant_data_offset)

If enforcing order is intentional (which is reasonable), consider updating the comment from "does not overlap" to "comes after flatbuffer and does not overlap" to make the intent clear.

Minor nits

  • XNNHeader.cpp:82: constant_data_size is uint64_t but constant_data_offset is uint32_t. The format specifier PRIu32 is correct for constant_data_offset, and PRIu64 is correct for constant_data_size — these look good.

  • The size parameter is size_t, formatted with %zu — correct.

What looks good

  • The bounds-checking arithmetic in XNNHeader::Parse correctly avoids integer overflow by using subtraction instead of addition (flatbuffer_size <= size - flatbuffer_offset instead of flatbuffer_offset + flatbuffer_size <= size).
  • Using verifier.VerifyBuffer<fb_xnnpack::XNNGraph>(nullptr) rather than VerifyXNNGraphBuffer correctly handles the dual-identifier (XN00/XN01) situation.
  • Tracking flatbuffer_size through both code paths (header present vs. not found) is done correctly.

…XECUTORCH-33, TOB-EXECUTORCH-34)

TOB-EXECUTORCH-33: XNNCompiler::compileModel() processed FlatBuffer data
via fb_xnnpack::GetXNNGraph() without first running the FlatBuffer verifier.
A malformed or truncated payload could cause out-of-bounds reads when the
FlatBuffer library follows internal offset tables. This adds a
flatbuffers::Verifier pass (matching the pattern used in program.cpp) before
any FlatBuffer accessors are called, and tracks the flatbuffer_size so the
verifier knows the exact bounds of the serialized data.

TOB-EXECUTORCH-34: XNNHeader::Parse() read flatbuffer_offset,
flatbuffer_size, constant_data_offset, and constant_data_size from untrusted
header bytes but never validated that the resulting regions actually fit within
the provided buffer. Crafted offset/size values could point past the end of
the buffer, leading to out-of-bounds reads in compileModel(). This adds
overflow-safe bounds checks that ensure both the flatbuffer and constant data
regions fall within [0, size).

This PR was authored with the assistance of Claude.
@lucylq lucylq merged commit dbd5118 into main Apr 14, 2026
164 of 167 checks passed
@lucylq lucylq deleted the security33-34 branch April 14, 2026 23:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants