Repository navigation
Throw InvalidDataException for malformed tar numeric header fields - #137060
Merged
Merged
Conversation
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: 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. |
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-formats-tar |
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.
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.
What this fixes
TarReader.GetNextEntrydocumentsInvalidDataExceptionfor a malformed archive andIOExceptionfor I/O problems. Malformed numeric header fields escaped that contract in four different places, throwingOverflowException,FormatExceptionorArgumentOutOfRangeExceptioninstead. This makes all of them report the same way the rest of the parser already does, withInvalidDataExceptionandSR.TarInvalidNumber.This answers the triage on #136659:
It is the same change uid and gid received in #134850 ("Reading a GNU base-256 or PAX uid/gid above
Int32.MaxValuethrewOverflowException"), 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.GetNextEntryon a single-entry archive with a correct header checksum.mode,devmajor,devminor, GNU base-256 wider thanInt32TarHelpers.ParseNumeric<int>->IBinaryInteger.ReadBigEndianOverflowExceptionInvalidDataExceptionmtime,atime,ctime, GNU base-256 wider thanInt64TarHelpers.ParseNumeric<long>->IBinaryInteger.ReadBigEndianOverflowExceptionInvalidDataExceptionsize, octal777777777777TarHeader.ProcessDataBlock->Stream.PositionArgumentOutOfRangeException: Stream length must be non-negative and less than 2^31 - 1 - originInvalidDataExceptionsize,mode,devmajor,devminor,uid,gidthat are not a numberTryGetStringAsBaseTenLong/TryGetStringAsBaseTenInteger/TryGetStringAsUidGid->long.Parse/int.ParseFormatExceptionInvalidDataExceptionsize,mode,devmajor,devminor,uid,gidout of the field's rangeOverflowExceptionInvalidDataExceptionmtimeout ofInt64rangeTryGetDateTimeOffsetFromTimestampString->(long)(value * TicksPerSecond)OverflowExceptionInvalidDataExceptionmtimeout ofDateTimeOffsetrange (e.g.253402300800)GetDateTimeOffsetFromSecondsSinceEpoch(decimal)ArgumentOutOfRangeExceptionInvalidDataExceptionmtimewithinInt64but out ofDateTimeOffsetrange (e.g. 2^48 seconds)GetDateTimeOffsetFromSecondsSinceEpoch(long)ArgumentOutOfRangeExceptionInvalidDataExceptionRows 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
Parseand threwFormatException, and a PAXmtimelarge enough to overflow thedecimalmultiplication threwOverflowExceptionfrom there.The
mtimecase is the least obvious one of the set.decimal.TryParsesucceeds becausedecimalholds the value; the failure happens afterwards, in the conversion to ticks.TryParsevalidates that the input is a number, not that it fits.The changes
TarHelpers.ParseNumeric<T>usesT.TryReadBigEndianinstead ofT.ReadBigEndianand calls the existingThrowInvalidNumber()when the field is wider thanT. 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 outside0-7.TarHelpers.GetDateTimeOffsetFromSecondsSinceEpochvalidates, in both thelongand thedecimaloverload, that the seconds fall inside the rangeDateTimeOffsetcan represent before converting to ticks. The bounds areDateTime.MinValueandDateTime.MaxValueexpressed as seconds since the Unix epoch, so0001-01-01T00:00:00Zand9999-12-31T23:59:59Zboth still roundtrip.TarHelpers.TryGetStringAsBaseTenInteger,TryGetStringAsBaseTenLongandTryGetStringAsUidGidparse withTryParseandNumberStyles.Integer, which is the styleint.Parse(value, IFormatProvider)already used, so a valid value parses exactly as before. The stale// Parsing exceptions propagate.comments are updated.TarHeader.GetDataStreamCoreperforms the stream length check for both values ofcopyData. The check and its resource string (SR.TarSizeFieldExceedsStreamLength) already existed forcopyData: true; acopyData: falseread skipped it and let the size reach the seek that advances past the data section.Documentation.
GetNextEntryandGetNextEntryAsyncnow name malformed numeric fields in theInvalidDataExceptionlist. 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
copyDatabranch does more than change an exception type for a seekable archive whose entry declares a size past the end of the stream:MemoryStream, the read threw the undocumentedArgumentOutOfRangeExceptionabove.FileStream, seeking past the end succeeds, so the read used to continue and fail later, typically withEndOfStreamExceptionwhen looking for the next header.Both now throw
InvalidDataExceptionatGetNextEntry, which is whatcopyData: truehas 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_Throwsand_Async: 9 cases overmode,devmajor,devminor,mtime,atimeandctime, covering both a base-256 value wider than the field's type and a timestamp that fitsInt64but is not a dateDateTimeOffsetcan represent.devmajoranddevminorare patched on a character device entry, since those are the only entry types that read them.PaxNumericExtendedAttribute_OutOfRange_Throwsand_Async: 19 cases oversize,mode,devmajor,devminor,uid,gidandmtime, with values that are not numbers and values out of range.PaxNumericExtendedAttribute_InRange_DoesNotThrow: 6 cases that must keep working, includingmtimeat both ends of theDateTimeOffsetrange and a fractionalmtime.In
TarReader.GetNextEntry.Tests.cs:MalformedArchive_SizeFieldExceedsStreamLength_NoCopyData: thecopyData: falsecounterpart of the existingMalformedArchive_SizeFieldExceedsStreamLength_CopyData, sync and async.The existing private helper
CreateEntryWithRawUidGidis generalized intoCreateEntryWithRawFields(params (int Offset, byte[] Value)[])so the new tests reuse its checksum fixup instead of duplicating it.Every new case fails on
mainwith 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
InvalidDataExceptionafter this change. GNUtarrejects 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