gh-137396: tarfile: Guard against negative offset/length in GNU sparse headers #138726
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.
Summary
This change fixes a bug in
tarfile.py
where negativeoffset
andnumbytes
values were not properly handled when parsing GNU sparse file headers. The existing validation only checked for non-zero values, allowing negative integers to pass, which could lead to errors or a potential security vulnerability when processing a corrupted or malicious tar archive.The problem with the original code was twofold:
offset
andnumbytes
according to the tar specification. (ref)The fix introduces a direct check to ensure these values are non-negative (
>= 0
) before they are used, making the parsing logic more robust.Additional Context
During the discussion in the issue, a more comprehensive refactoring of the module's integer handling and error reporting was suggested. While that is a valid long-term improvement, this pull request provides a focused, immediate, and safe fix for the specific vulnerability identified. The broader refactoring can be considered separately.