Validate safetensors data offsets against file boundaries#3410
Merged
angeloskath merged 7 commits intoApr 15, 2026
Merged
Conversation
angeloskath
approved these changes
Apr 15, 2026
angeloskath
left a comment
Member
There was a problem hiding this comment.
Thanks for the PR. The original PR did not actually pass the test that it was supposed to be made for, so I would advise compiling and running the tests before PRing.
It is now fixed and the tests unified.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
Addresses #3409.
The SafeTensors loader reads
data_offsetsfrom JSON metadata without checking whether they fall within the actual file. A crafted.safetensorsfile can declare offsets that exceed the file size, causing an out-of-bounds memory read when the tensor is evaluated.This is the file-boundary counterpart to #3364 (which validates internal consistency between
data_offsetsandshape * dtype). The Rust reference implementation enforces both checks (TensorInvalidInfoandMetadataIncompleteBuffer).Changes
mlx/io/safetensors.cpp— After parsing the JSON header, compute the available data size from the actual file size and validate each tensor'sdata_offsets:data_offsetshas at least 2 elementsbegin <= endenddoes not exceed the data region of the filemlx/io/load.h—ParallelFileReader::seek()andFileWriter::seek()did not handlestd::ios_base::end, silently falling through toSEEK_CUR. AddedSEEK_ENDsupport and replaced the hardcoded0withSEEK_SET.tests/load_tests.cpp— Added tests for:data_offsetsexceeding file boundary (must throw)data_offsets(must throw)Checklist
pre-commit run --all-filesto format my code