Skip to content

Throw InvalidDataException for malformed tar numeric header fields - #137060

Merged
rzikm merged 4 commits into
dotnet:mainfrom
earbona23:fix-tar-numeric-field-exceptions
Nov 12, 2026
Merged

rzikm merged 4 commits into
dotnet:mainfrom
earbona23:fix-tar-numeric-field-exceptions

Conversation

@earbona23

Copy link
Copy Markdown
Contributor

What this fixes

TarReader.GetNextEntry documents InvalidDataException for a malformed archive and IOException for I/O problems. Malformed numeric header fields escaped that contract in four different places, throwing OverflowException, FormatException or ArgumentOutOfRangeException instead. This makes all of them report the same way the rest of the parser already does, with InvalidDataException and SR.TarInvalidNumber.

This answers the triage on #136659:

Triage: we should make sure the exceptions we throw are consistent and update the documentation if necessary.

It is the same change uid and gid received in #134850 ("Reading a GNU base-256 or PAX uid/gid above Int32.MaxValue threw OverflowException"), applied to the numeric fields that were left behind. After #134850, uid and gid were the only numeric fields that rejected out-of-range input consistently, so the inconsistency was both between the binary and the text representations and between uid/gid and every other field.

The paths, before and after

Every row was measured from TarReader.GetNextEntry on a single-entry archive with a correct header checksum.

# Field and representation Parsed by Before After
1 mode, devmajor, devminor, GNU base-256 wider than Int32 TarHelpers.ParseNumeric<int> -> IBinaryInteger.ReadBigEndian OverflowException InvalidDataException
1 mtime, atime, ctime, GNU base-256 wider than Int64 TarHelpers.ParseNumeric<long> -> IBinaryInteger.ReadBigEndian OverflowException InvalidDataException
2 size, octal 777777777777 TarHeader.ProcessDataBlock -> Stream.Position ArgumentOutOfRangeException: Stream length must be non-negative and less than 2^31 - 1 - origin InvalidDataException
3 PAX size, mode, devmajor, devminor, uid, gid that are not a number TryGetStringAsBaseTenLong / TryGetStringAsBaseTenInteger / TryGetStringAsUidGid -> long.Parse / int.Parse FormatException InvalidDataException
3 PAX size, mode, devmajor, devminor, uid, gid out of the field's range same OverflowException InvalidDataException
4 PAX mtime out of Int64 range TryGetDateTimeOffsetFromTimestampString -> (long)(value * TicksPerSecond) OverflowException InvalidDataException
4 PAX mtime out of DateTimeOffset range (e.g. 253402300800) GetDateTimeOffsetFromSecondsSinceEpoch(decimal) ArgumentOutOfRangeException InvalidDataException
4 Header mtime within Int64 but out of DateTimeOffset range (e.g. 2^48 seconds) GetDateTimeOffsetFromSecondsSinceEpoch(long) ArgumentOutOfRangeException InvalidDataException

Rows 3 and 4 include two cases the issue did not list and that showed up while measuring: a PAX value that is not a number at all reached Parse and threw FormatException, and a PAX mtime large enough to overflow the decimal multiplication threw OverflowException from there.

The mtime case is the least obvious one of the set. decimal.TryParse succeeds because decimal holds the value; the failure happens afterwards, in the conversion to ticks. TryParse validates that the input is a number, not that it fits.

The changes

TarHelpers.ParseNumeric<T> uses T.TryReadBigEndian instead of T.ReadBigEndian and calls the existing ThrowInvalidNumber() when the field is wider than T. A value that doesn't fit the field's type can't be a valid value for that field, which is the same reasoning the octal path already applies to a digit outside 0-7.

TarHelpers.GetDateTimeOffsetFromSecondsSinceEpoch validates, in both the long and the decimal overload, that the seconds fall inside the range DateTimeOffset can represent before converting to ticks. The bounds are DateTime.MinValue and DateTime.MaxValue expressed as seconds since the Unix epoch, so 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z both still roundtrip.

TarHelpers.TryGetStringAsBaseTenInteger, TryGetStringAsBaseTenLong and TryGetStringAsUidGid parse with TryParse and NumberStyles.Integer, which is the style int.Parse(value, IFormatProvider) already used, so a valid value parses exactly as before. The stale // Parsing exceptions propagate. comments are updated.

TarHeader.GetDataStreamCore performs the stream length check for both values of copyData. The check and its resource string (SR.TarSizeFieldExceedsStreamLength) already existed for copyData: true; a copyData: false read skipped it and let the size reach the seek that advances past the data section.

Documentation. GetNextEntry and GetNextEntryAsync now name malformed numeric fields in the InvalidDataException list. No other documentation change is needed, since the thrown type is now the one those APIs already documented.

Note for review: the one behaviour change beyond the exception type

Moving the stream length check out of the copyData branch does more than change an exception type for a seekable archive whose entry declares a size past the end of the stream:

  • With a MemoryStream, the read threw the undocumented ArgumentOutOfRangeException above.
  • With a FileStream, seeking past the end succeeds, so the read used to continue and fail later, typically with EndOfStreamException when looking for the next header.

Both now throw InvalidDataException at GetNextEntry, which is what copyData: true has always done for the same archive. That seemed like the consistent outcome, but it is the one part of this change that is a decision rather than a straight exception type fix, so flagging it explicitly. Happy to restrict it to a pure exception type change if the area prefers that.

Tests

In TarReader.Tests.cs, next to the uid/gid tests from #134850:

  • GnuBase256Field_OutOfRange_Throws and _Async: 9 cases over mode, devmajor, devminor, mtime, atime and ctime, covering both a base-256 value wider than the field's type and a timestamp that fits Int64 but is not a date DateTimeOffset can represent. devmajor and devminor are patched on a character device entry, since those are the only entry types that read them.
  • PaxNumericExtendedAttribute_OutOfRange_Throws and _Async: 19 cases over size, mode, devmajor, devminor, uid, gid and mtime, with values that are not numbers and values out of range.
  • PaxNumericExtendedAttribute_InRange_DoesNotThrow: 6 cases that must keep working, including mtime at both ends of the DateTimeOffset range and a fractional mtime.

In TarReader.GetNextEntry.Tests.cs:

  • MalformedArchive_SizeFieldExceedsStreamLength_NoCopyData: the copyData: false counterpart of the existing MalformedArchive_SizeFieldExceedsStreamLength_CopyData, sync and async.

The existing private helper CreateEntryWithRawUidGid is generalized into CreateEntryWithRawFields(params (int Offset, byte[] Value)[]) so the new tests reuse its checksum fixup instead of duplicating it.

Every new case fails on main with the exception named in the table above and passes with this change. The in-range cases pass both before and after.

Repro

The archives in the issue, plus the PAX records from the comment, all reach InvalidDataException after this change. GNU tar rejects the same archives with an explicit range diagnostic (tar: Extended header size=... is out of range 0..9223372036854775807), so the field name and the limit survive into its error message too.

Fixes #136659

TarReader documents InvalidDataException for a malformed archive, but
numeric header fields had three ways to escape that contract:

- A GNU base-256 field wider than the type it is parsed as reached
  IBinaryInteger.ReadBigEndian, which threw OverflowException. Use
  TryReadBigEndian and report the value as an invalid number, which is
  what the octal representation of the same field already does.
- A timestamp outside the range DateTimeOffset can represent overflowed
  the conversion to ticks, surfacing OverflowException or
  ArgumentOutOfRangeException. Validate the range first.
- A PAX extended attribute value that is not a number, or that doesn't
  fit the field's type, reached int.Parse/long.Parse and threw
  FormatException or OverflowException. Parse with TryParse instead.

A size field that points past the end of a seekable archive reached the
seek that skips the data section, where MemoryStream rejected it with
ArgumentOutOfRangeException. The stream length check that copyData
already performed now runs for both values of copyData.

This extends to the remaining numeric fields the handling that uid and
gid got in dotnet#134850.
Cover every numeric field that reached a parse without a range check:
the GNU base-256 header fields, the timestamps that fall outside the
range DateTimeOffset can represent, the PAX extended attribute values
for size, mode, devmajor, devminor, uid and gid, and a size field that
points past the end of the archive read with copyData set to false.
GetNextEntry and GetNextEntryAsync list what makes an archive malformed.
Name the numeric fields among them, since they are the fields an
application reading untrusted archives is most likely to hit.
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-formats-tar
See info in area-owners.md if you want to be subscribed.

@rzikm
rzikm requested a review from a team November 6, 2026 08:09
Three tests pinned the behaviour this change replaces:

- TarReader_File_Tests.Throw_ArchiveIsShort and PaxSizeLargerThanMaxAllowedByStream
  asserted ArgumentOutOfRangeException, which came from Stream.Position rejecting a
  size field past the end of the stream.
- PaxTarEntry_ExtendedAttributes_Tests.BadArchive_MalformedNumericEA_Throws asserted
  FormatException from long.Parse on a PAX uid of "notanumber".

All three now assert InvalidDataException, and the two stale comments describing the
old exception messages are updated. No other test in the suite asserts those types on
a read path; the remaining ArgumentOutOfRangeException assertions are argument
validation on setters and enum values and are unaffected.

@rzikm rzikm left a comment

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.

LGTM, thanks.

@rzikm
rzikm merged commit 5f570f8 into dotnet:main Nov 12, 2026
87 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Formats.Tar community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[System.Formats.Tar] TarReader throws undocumented OverflowException and ArgumentOutOfRangeException for malformed numeric header fields

2 participants