Skip to content

Bounds-check the FlatTensor root table offset before reading it - #22118

Merged
shoumikhin merged 1 commit into
mainfrom
ft-bounds-check
Aug 25, 2026
Merged

shoumikhin merged 1 commit into
mainfrom
ft-bounds-check

Conversation

@shoumikhin

Copy link
Copy Markdown
Contributor

Summary

FlatTensorDataMap::load() reads the flatbuffer root table without first bounds-checking the root offset:

const flat_tensor_flatbuffer::FlatTensor* flat_tensor =
    flat_tensor_flatbuffer::GetFlatTensor(flat_tensor_data->data());
// then immediately:
flat_tensor->named_data();   // walks the root vtable
flat_tensor->segments();

GetFlatTensor() interprets the uoffset_t at the start of the buffer as the root-table offset and returns buf + offset. The first field access then walks that table's vtable. Nothing on this path runs full flatbuffer verification, so a corrupt or truncated PTD file with a bad root offset makes these accessors dereference memory outside the buffer (an OOB read, flagged by ASan).

The program loader already guards against exactly this in runtime/executor/program.cpp. This change mirrors that guard for PTD files.

What changed

After the existing identifier and alignment checks, before GetFlatTensor():

  • Confirm the buffer is at least a flatbuffer header long (uoffset_t + file identifier).
  • Confirm the root offset is >= kMinBufferSize and leaves room for a vtable soffset_t within the buffer.
  • Return InvalidExternalData otherwise (the same error the surrounding checks use).

FlatTensor is not size-prefixed — both writers finish the buffer plain (builder.Finish in C++, default flatc in Python) and the reader uses GetFlatTensor (not the size-prefixed variant) — so the root offset is at byte 0, exactly as in the program case.

Scope

This is a pre-existing hardening, independent of the schema-version work in #22114 (the version gate this protects is additive; the OOB path exists today via named_data()/segments()).

Test plan

New FlatTensorDataMapTest.RejectsOutOfBoundsRootOffset: copies a valid PTD into a max-aligned buffer, overwrites only the root offset with a value past the end (leaving identifier + alignment intact), and asserts load() returns InvalidExternalData. Without the check, that same input is an out-of-bounds vtable read under ASan.

Note: I was unable to build/run the C++ suite in my local environment, so I'm relying on this PR's CI (which builds the runtime and runs extension/flat_tensor tests, including under ASan) as the authoritative check. The change mirrors an existing, tested guard in program.cpp.

Copilot AI lite review requested due to automatic review settings August 25, 2026 01:37
@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 Cancelled Job

As of commit df10f77 with merge base 1afd07f (image):

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

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 Aug 25, 2026

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

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.

Copilot AI review requested due to automatic review settings August 25, 2026 01:45

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings August 25, 2026 01:57

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review the PR

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 4m 10s —— View job


PR Review: Bounds-check the FlatTensor root table offset

  • Read the changed files and diff
  • Compare against the existing guard in program.cpp
  • Analyze correctness, edge cases, and the test
  • Post review feedback

Verdict: LGTM. This is a correct, well-scoped hardening that faithfully mirrors the tested guard in runtime/executor/program.cpp (lines 155–224). The reasoning in the PR body checks out against the code.

What I verified

  • Non-size-prefixed claim holds. The C++ writer uses builder.Finish(...) (serialize/serialize.cpp:116) and the reader uses GetFlatTensor (not GetSizePrefixed...), so the root uoffset_t really is at byte 0 — the check reads the right bytes.
  • Buffer layout matches. Bytes 0–3 = root offset, bytes 4–7 = flatbuffer file identifier, and the FlatTensorHeader magic (FH01) lives at kHeaderOffset = 8, embedded inside the flatbuffer exactly like ExtendedHeader in the program case. The test corrupts only bytes 0–3, leaving the identifier and header intact, so it exercises precisely the new check.
  • No underflow. size - sizeof(soffset_t) is guarded by the preceding size() >= kMinBufferSize (= 8) check, and soffset_t is 4 bytes, so the unsigned subtraction can't wrap. root_offset >= kMinBufferSize correctly keeps the root table from overlapping the header/identifier.
  • The test reaches the new check. flat_tensor_data->size() is flatbuffer_offset + flatbuffer_size, and bad_offset = full_file_size + 0x1000 is comfortably past it, so it trips the root-offset bound rather than the size or identifier checks. Good.

Non-blocking notes

  1. Partial hardening, not full verification (matches program.cpp). This validates only that the root offset lands inside the buffer. A corrupt vtable or a field uoffset inside the table can still produce an OOB read via named_data() / segments(), since nothing on this path runs flatbuffers::Verifier. That's the same tradeoff program.cpp accepts in Minimal-verification mode, so consistency-wise this is the right call — just worth being explicit that it closes the specific root-offset OOB, not all malformed-PTD OOBs. If you ever want the complete guarantee here, VerifyFlatTensorBuffer (generated verifier) would be the equivalent of VerifyProgramBuffer.

  2. version() in the comment. The comment at flat_tensor_data_map.cpp:296 mentions named_data()/segments()/version(). If version() isn't in the current schema (the PR notes the version gate is additive, landing in Refuse a PTE or PTD file whose schema version is newer than the runtime can read #22114), consider dropping it from the comment to avoid referencing an accessor that doesn't exist yet on this branch. Minor.

  3. Missing <cstring> in the test. The test now calls std::memcpy (and already used std::getenv → <cstdlib>) but only adds <memory>. It'll almost certainly compile via transitive includes, but adding #include <cstring> would be the clean, self-documenting fix. Nit.

  4. Broadened using namespace. The test swapped explicit using X::Y; declarations for using namespace executorch::extension; / ::runtime;. Fine for a test file, though the explicit form was arguably tidier. Purely stylistic — no action needed.

None of these block merge. The core change is sound and the new RejectsOutOfBoundsRootOffset test targets the exact regression. Since CI builds extension/flat_tensor under ASan, that's the authoritative confirmation the OOB path is closed.
· branch ft-bounds-check

Copilot AI review requested due to automatic review settings August 25, 2026 02:04

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings August 25, 2026 02:09

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks @claude. Changes made:

On the two nits, keeping as-is on purpose:

  • Note 3 (#include <cstring>) — <cstring> already comes in through buffer_data_loader.h, which this test includes directly, so adding it would be a duplicate. The file already relies on the same transitive path for std::getenv/<cstdlib>. House preference here is to keep the include list minimal rather than restate transitively-available headers.
  • Note 4 (using namespace) — this matches the convention used across the codebase, so leaving it.

The partial-hardening framing (note 1) is exactly right: this closes the root-offset OOB specifically, mirroring program.cpp. Full VerifyFlatTensorBuffer would be a separate, larger change.

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 42s —— View job


Re: review follow-up

Thanks for the thorough responses — all three resolutions look right to me.

  • Note 2 (version()) — confirmed fixed on ft-bounds-check. The comment at flat_tensor_data_map.cpp:296 now reads named_data()/segments(), matching what this branch actually calls. 👍
  • Note 3 (#include <cstring>) — agreed, no change needed. <cstring> (and <cstdlib>) come in transitively via buffer_data_loader.h, which the test includes directly; restating them would just be a duplicate. Keeping the include list minimal is a reasonable house call.
  • Note 4 (using namespace) — fair, matching the codebase convention wins.

And yes — the partial-hardening framing (note 1) is the key point: this closes the specific root-offset OOB and mirrors the program.cpp guard exactly. Full VerifyFlatTensorBuffer would be a separate, larger change. Nothing here blocks merge — LGTM.
· branch ft-bounds-check

FlatTensorDataMap::load() calls GetFlatTensor() and then reads named_data(),
segments() (and, with the version gate, version()) straight away. GetFlatTensor()
takes the uoffset_t at the start of the buffer as the root-table offset and
returns buf + offset; the first field access then walks that table's vtable.
Nothing on this path runs full flatbuffer verification, so a corrupt or
truncated file with a bad root offset makes those accessors dereference memory
outside the buffer.

The program loader already guards against this (runtime/executor/program.cpp).
Mirror that here: after the identifier and alignment checks, confirm the buffer
is at least a flatbuffer header long and that the root offset stays within the
buffer with room for a vtable soffset, returning InvalidExternalData otherwise.
FlatTensor is not size-prefixed (both writers finish the buffer plain and the
reader uses GetFlatTensor, not the size-prefixed variant), so the offset is at
byte 0, exactly as in the program case.

Add a regression test that copies a valid file into a max-aligned buffer, points
the root offset past the end, and checks load() returns InvalidExternalData.
Without the check that read is an out-of-bounds vtable access under ASan.
Copilot AI review requested due to automatic review settings August 25, 2026 02:48

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review the PR

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 1m 26s —— View job


PR Review: Bounds-check the FlatTensor root table offset

  • Read the changed files and diff
  • Compare against the existing guard in program.cpp
  • Re-verify correctness, edge cases, and the test against current branch state
  • Post review feedback

Verdict: LGTM. Re-reviewed against the current ft-bounds-check HEAD. The guard is correct, faithfully mirrors the tested check in runtime/executor/program.cpp:209-224, and the new test targets exactly the regression it closes.

What I re-verified

  • Bound logic is sound and can't underflow. kMinBufferSize = sizeof(uoffset_t) + kFileIdentifierLength = 8. The size() >= kMinBufferSize check gates the subtraction, and soffset_t is 4 bytes, so size() - sizeof(soffset_t) never wraps. root_offset >= kMinBufferSize correctly keeps the root table from overlapping the 8-byte header, and <= size - 4 leaves room for the vtable soffset_t. Matches program.cpp byte-for-byte in intent (flat_tensor_data_map.cpp:302-322).
  • Reads the right bytes. FlatTensor is not size-prefixed — writer uses builder.Finish and reader uses GetFlatTensor (not the size-prefixed variant) — so the root uoffset_t sits at byte 0 and ReadScalar<uoffset_t>(data()) reads the actual root offset.
  • Test reaches the new check. bad_offset = size + 0x1000 fails the upper bound (<= size - 4) while leaving the identifier (bytes 4-7) and the embedded FlatTensorHeader magic (byte 8) intact, so it trips the root-offset bound rather than the identifier or size checks. The max-aligned scratch buffer also keeps the is_aligned check from firing first. Correctly returns InvalidExternalData.

Note on the earlier follow-up (version() in the comment)

The prior round concluded the comment should drop version(). On the current branch state that's no longer applicable, and I want to flag it so it isn't re-"fixed":

  • Line 296 still reads version()/named_data()/segments(), and flat_tensor->version() is now called at flat_tensor_data_map.cpp:335 (with kMaxSupportedSchemaVersion). So the version gate that the PR body described as landing separately in Refuse a PTE or PTD file whose schema version is newer than the runtime can read #22114 is present here, and the comment is accurate as written — version() is one of the accessors this bound protects. No change needed; leave the comment as-is.

Non-blocking (unchanged from prior review)

  • Partial hardening, by design. This closes the root-offset OOB specifically. A corrupt vtable or an in-table field uoffset can still produce an OOB via named_data()/segments()/version(), since nothing on this path runs flatbuffers::Verifier. That's the same tradeoff program.cpp accepts in Minimal mode — consistent. Full coverage would mean wiring up VerifyFlatTensorBuffer, a separate larger change.

Nothing blocks merge. Already approved by @huydhn; CI builds extension/flat_tensor under ASan, which is the authoritative confirmation the OOB path is closed.
· branch ft-bounds-check

@shoumikhin
shoumikhin merged commit e831b3e into main Aug 25, 2026
171 checks passed
@shoumikhin
shoumikhin deleted the ft-bounds-check branch August 25, 2026 03:00

This branch was previously deployed

1 inactive deployment
cadence — ff519782 Deployed Aug 25, 2026 by shoumikhin
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