Skip to content

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

Description

@earbona23

Description

TarReader.GetNextEntry documents InvalidDataException for malformed archives and IOException for I/O problems. Two malformed numeric header fields escape that contract instead, each from a different place:

  1. OverflowException from TarHelpers.ParseNumeric<T>. For the GNU base-256 representation (lead byte 0x80/0xff) the value goes straight to T.ReadBigEndian, which throws OverflowException when the field is wider than T. The octal path right next to it already funnels bad input into InvalidDataException via ThrowInvalidNumber(), so the two representations disagree about what a bad number is.

  2. ArgumentOutOfRangeException from TarHeader.ProcessDataBlock. A size field that overflows reaches Stream.Position unvalidated, and MemoryStream rejects it with "Stream length must be non-negative and less than 2^31 - 1 - origin."

Both are reachable from a 1536-byte archive with a correct header checksum, so an application that reads untrusted tar data and catches the documented exceptions still gets an unexpected throw. GNU tar rejects both archives.

Reproduction Steps

using System.Formats.Tar;
using System.Text;

// Builds a single-entry tar archive with a valid checksum and one patched numeric field.
static byte[] Archive(int offset, byte[] value)
{
    byte[] tar = new byte[1536];               // header + two zero blocks (end of archive)
    void Write(int off, string s) => Encoding.ASCII.GetBytes(s).CopyTo(tar, off);

    Write(0, "f.txt");                          // name
    Write(100, "0000644\0");                    // mode
    Write(108, "0000000\0");                    // uid
    Write(116, "0000000\0");                    // gid
    Write(124, "00000000000\0");                // size
    Write(136, "15270727363\0");                // mtime
    tar[156] = (byte)'0';                       // typeflag: regular file
    Write(257, "ustar\0" + "00");               // magic + version

    value.CopyTo(tar, offset);                  // the field under test

    for (int i = 148; i < 156; i++) tar[i] = (byte)' ';   // checksum field counts as spaces
    int sum = 0;
    for (int i = 0; i < 512; i++) sum += tar[i];
    Write(148, Convert.ToString(sum, 8).PadLeft(6, '0') + "\0 ");
    return tar;
}

static void Read(string label, byte[] tar)
{
    try
    {
        using var stream = new MemoryStream(tar);
        using var reader = new TarReader(stream);
        while (reader.GetNextEntry() is TarEntry entry) { _ = entry.Name; _ = entry.ModificationTime; }
        Console.WriteLine($"{label}: no exception");
    }
    catch (Exception ex)
    {
        bool documented = ex is InvalidDataException or IOException;
        Console.WriteLine($"{label}: {ex.GetType().Name}{(documented ? "" : "   <-- not documented")}");
        Console.WriteLine($"    {ex.Message}");
        Console.WriteLine($"    {ex.StackTrace.Split('\n')[0].Trim()}");
    }
}

Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
Console.WriteLine();

// 1. mtime (offset 136), GNU base-256 with the 0x80 lead byte: 11 payload bytes of 0xff.
Read("mtime, GNU base-256", Archive(136, new byte[] { 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }));

// 2. size (offset 124), octal digits that exceed the field's range.
Read("size, octal overflow", Archive(124, Encoding.ASCII.GetBytes("777777777777")));

// 3. control: both fields well-formed.
Read("control", Archive(136, Encoding.ASCII.GetBytes("15270727363\0")));

Expected behavior

InvalidDataException, which is what TarReader.GetNextEntry documents for a malformed archive and what the octal path already throws for a digit outside 0-7.

Actual behavior

.NET 10.0.14

mtime, GNU base-256: OverflowException   <-- not documented
    Arithmetic operation resulted in an overflow.
    at System.Numerics.IBinaryInteger`1.ReadBigEndian(ReadOnlySpan`1 source, Boolean isUnsigned)
size, octal overflow: ArgumentOutOfRangeException   <-- not documented
    Stream length must be non-negative and less than 2^31 - 1 - origin. (Parameter 'value')
    at System.IO.MemoryStream.set_Position(Int64 value)
control: no exception

Full stacks:

System.OverflowException: Arithmetic operation resulted in an overflow.
   at System.Numerics.IBinaryInteger`1.ReadBigEndian(ReadOnlySpan`1 source, Boolean isUnsigned)
   at System.Formats.Tar.TarHelpers.ParseNumeric[T](ReadOnlySpan`1 buffer)
   at System.Formats.Tar.TarHeader.ParseAsTimestamp(ReadOnlySpan`1 buffer)
   at System.Formats.Tar.TarHeader.TryReadCommonAttributes(ReadOnlySpan`1 buffer, TarEntryFormat initialFormat)

System.ArgumentOutOfRangeException: Stream length must be non-negative and less than 2^31 - 1 - origin. (Parameter 'value')
   at System.IO.MemoryStream.set_Position(Int64 value)
   at System.Formats.Tar.TarHeader.ProcessDataBlock(Stream archiveStream, Boolean copyData)
   at System.Formats.Tar.TarReader.TryGetNextEntryHeader(Boolean copyData)

Regression?

No. The parsing code is unchanged on main, and I reproduced the same behavior on the current 10.0 servicing build.

Known Workarounds

Catching Exception rather than the documented InvalidDataException/IOException around GetNextEntry.

Configuration

.NET 10.0.14, Linux x64. Not specific to this configuration: the code paths are platform independent. ParseNumeric is reached from mtime, size, mode, uid, gid, devmajor, devminor, atime and ctime.

Other information

ParseUidGid was given an unchecked conversion in #134850, which covered uid/gid only; ParseNumeric itself still propagates the overflow for the other fields.

Both cases were found by the TarReader fuzzer I am contributing for #136371, within seconds. For calibration, 7000 mutated inputs (random bytes, bit flips over a valid archive, and truncations) produced only InvalidDataException and EndOfStreamException, so these two are the only escapes.

Worth noting for anyone reproducing: TarReader does not verify the header checksum, so 487 of 500 single-bit flips over a valid archive still parse successfully. The archives above keep a correct checksum anyway so the repro does not depend on that.

Activity

  1. added
    untriaged
    on Oct 29, 2026
  2. added a commit that references this issue on Oct 29, 2026
  3. dotnet-policy-service commented on Oct 29, 2026

    @dotnet-policy-service
    Contributor

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

  4. removed
    untriaged
    on Nov 5, 2026
  5. added theissue type on Nov 5, 2026
  6. added this to the Future milestone on Nov 5, 2026
  7. rzikm commented on Nov 5, 2026

    @rzikm
    Member

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

  8. earbona23 commented on Nov 5, 2026

    @earbona23
    ContributorAuthor

    Thanks for the triage. On "make sure the exceptions we throw are consistent": there is a second, independent path that throws the same undocumented OverflowException, and a fix confined to TarHelpers.ParseNumeric<T> would not cover it. Posting it here so the consistency pass covers both.

    The second path: PAX extended attribute values, parsed by TarHeader.ReplaceNormalAttributesWithExtended. The original report covers the binary header field (GNU base-256); this one is the text of the len key=value\n records in the data block of an x-typeflag header.

    Measured on .NET 10.0.14 (System.Formats.Tar.dll, FileVer 10.0.1426.52326), from both TarReader.GetNextEntry and TarFile.ExtractToDirectory:

    PAX record helper throws
    size=777777777777777777773 TryGetStringAsBaseTenLong -> long.Parse OverflowException (Int64)
    mtime=17930586772622498093 TryGetDateTimeOffsetFromTimestampString -> (long)(value * TicksPerSecond) OverflowException (Int64)
    mode / devmajor / devminor =4294967296 TryGetStringAsBaseTenInteger -> int.Parse OverflowException (Int32)
    uid / gid =4294967296 TryGetStringAsBaseTenInteger -> int.Parse OverflowException (Int32)

    Two notes that matter for the fix:

    • The mtime case is the least obvious one. decimal.TryParse succeeds — decimal holds the value — and the overflow happens afterwards, in the (long) conversion inside GetDateTimeOffsetFromSecondsSinceEpoch(decimal). The TryParse validates that the input is a number, not that it fits.
    • uid / gid already behave differently in main, where they go through the newer TryGetStringAsUidGid and out-of-range values are clamped rather than thrown. The other five fields still call long.Parse / int.Parse directly in main, so the inconsistency is currently inside the PAX path as well as between the two paths.

    For reference on the expected behaviour, GNU tar rejects these archives with an explicit range diagnostic — tar: Extended header size=... is out of range 0..9223372036854775807 — so both the field name and the limit survive into the error message.

    Minimal repro is a 2560-byte archive: one x header plus a single PAX record. Happy to attach the generator or a .tar for any of the rows above if that is useful for the fix or for a test case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions