diff --git a/src/UVBake.IO/Fbx/FbxBinaryParser.cs b/src/UVBake.IO/Fbx/FbxBinaryParser.cs index a08ed35..bc3990b 100644 --- a/src/UVBake.IO/Fbx/FbxBinaryParser.cs +++ b/src/UVBake.IO/Fbx/FbxBinaryParser.cs @@ -10,10 +10,20 @@ namespace UVBake.IO; /// (primitives, raw or zlib-compressed typed arrays, and strings) — into an tree. /// No Autodesk SDK and no native code; array decompression uses the framework . /// +/// +/// Input is treated as untrusted: every length and offset read from the file is checked before it is used, +/// nesting depth and array sizes are capped, and any malformed file fails with +/// rather than hanging, overflowing the stack, or exhausting memory. +/// internal sealed class FbxBinaryParser { private static readonly byte[] Magic = Encoding.ASCII.GetBytes("Kaydara FBX Binary "); + // Hardening limits for untrusted input. Real FBX files nest well under 20 levels deep. + private const int MaxDepth = 64; + private const long MaxArrayBytes = 512L * 1024 * 1024; + private const long MaxDeflateRatio = 1032; // DEFLATE's theoretical maximum expansion + private readonly byte[] _data; private int _pos; private int _offsetSize; @@ -24,12 +34,21 @@ private FbxBinaryParser(byte[] data) } /// Parses a stream into a synthetic root node whose children are the top-level records. + /// The stream is not a well-formed binary FBX file. public static FbxNode Parse(Stream stream) { ArgumentNullException.ThrowIfNull(stream); using var ms = new MemoryStream(); stream.CopyTo(ms); - return new FbxBinaryParser(ms.ToArray()).ParseDocument(); + try + { + return new FbxBinaryParser(ms.ToArray()).ParseDocument(); + } + catch (Exception ex) when (ex is ArgumentException or IndexOutOfRangeException or OverflowException) + { + // Truncated or inconsistent records surface as a single, catchable error type. + throw new InvalidDataException("malformed binary FBX file.", ex); + } } private FbxNode ParseDocument() @@ -46,7 +65,7 @@ private FbxNode ParseDocument() var root = new FbxNode("(root)"); while (_pos + (3 * _offsetSize) + 1 <= _data.Length) { - FbxNode? node = ReadNode(); + FbxNode? node = ReadNode(0); if (node is null) { break; @@ -58,17 +77,38 @@ private FbxNode ParseDocument() return root; } - private FbxNode? ReadNode() + private FbxNode? ReadNode(int depth) { + if (depth > MaxDepth) + { + throw new InvalidDataException($"FBX nesting is deeper than {MaxDepth} levels."); + } + + int nodeStart = _pos; long endOffset = ReadOffset(); long numProperties = ReadOffset(); ReadOffset(); // property-list length (unused — we read each property) + Require(1); int nameLen = _data[_pos++]; if (endOffset == 0) { return null; // null record (3*offsetSize+1 zero bytes) terminates a child list / the document } + // A record must end after it starts and inside the file. This also guarantees forward progress, + // so a hostile offset can never send the parser backwards into an endless loop. + if (endOffset <= nodeStart || endOffset > _data.Length) + { + throw new InvalidDataException($"FBX record at {nodeStart} has an invalid end offset {endOffset}."); + } + + // Every property takes at least one byte, so a larger count cannot be honest. + if (numProperties < 0 || numProperties > endOffset - _pos) + { + throw new InvalidDataException($"FBX record at {nodeStart} claims {numProperties} properties."); + } + + Require(nameLen); var node = new FbxNode(Encoding.ASCII.GetString(_data, _pos, nameLen)); _pos += nameLen; @@ -79,7 +119,7 @@ private FbxNode ParseDocument() while (_pos < endOffset) { - FbxNode? child = ReadNode(); + FbxNode? child = ReadNode(depth + 1); if (child is null) { break; @@ -88,17 +128,23 @@ private FbxNode ParseDocument() node.Children.Add(child); } + if (_pos > endOffset) + { + throw new InvalidDataException($"FBX record at {nodeStart} overruns its end offset."); + } + _pos = (int)endOffset; return node; } private object ReadProperty() { + Require(1); char type = (char)_data[_pos++]; switch (type) { case 'Y': return (long)ReadInt16(); - case 'C': return _data[_pos++] != 0; + case 'C': Require(1); return _data[_pos++] != 0; case 'I': return (long)ReadInt32(); case 'F': return (double)ReadSingle(); case 'D': return ReadDouble(); @@ -119,9 +165,41 @@ private object ReadProperty() int length = ReadInt32(); int encoding = ReadInt32(); int compressedLength = ReadInt32(); + long rawBytes = (long)length * elementSize; + if (length < 0 || rawBytes > MaxArrayBytes) + { + throw new InvalidDataException($"FBX array length {length} is out of range."); + } + + Require(compressedLength); ReadOnlySpan payload = _data.AsSpan(_pos, compressedLength); _pos += compressedLength; - byte[] raw = encoding == 1 ? Inflate(payload, length * elementSize) : payload.ToArray(); + + byte[] raw; + if (encoding == 0) + { + if (compressedLength != rawBytes) + { + throw new InvalidDataException("FBX raw array size does not match its element count."); + } + + raw = payload.ToArray(); + } + else if (encoding == 1) + { + // Refuse decompression bombs: the declared size must be reachable from the compressed bytes. + if (rawBytes > (compressedLength * MaxDeflateRatio) + 1024) + { + throw new InvalidDataException("FBX compressed array claims an impossible expanded size."); + } + + raw = Inflate(payload, (int)rawBytes); + } + else + { + throw new InvalidDataException($"unknown FBX array encoding {encoding}."); + } + return (raw, length); } @@ -202,12 +280,18 @@ private static byte[] Inflate(ReadOnlySpan compressed, int rawLength) read += n; } + if (read != rawLength) + { + throw new InvalidDataException("FBX compressed array is shorter than its declared size."); + } + return buffer; } private string ReadString() { int len = ReadInt32(); + Require(len); string s = Encoding.Latin1.GetString(_data, _pos, len); // Latin1 preserves the \0\1 name separator _pos += len; return s; @@ -216,13 +300,24 @@ private string ReadString() private byte[] ReadRaw() { int len = ReadInt32(); + Require(len); byte[] bytes = _data.AsSpan(_pos, len).ToArray(); _pos += len; return bytes; } + /// Throws unless bytes remain at the current position. + private void Require(int count) + { + if (count < 0 || count > _data.Length - _pos) + { + throw new InvalidDataException($"FBX field at {_pos} claims {count} bytes past the end of the file."); + } + } + private long ReadOffset() { + Require(_offsetSize); long value = _offsetSize == 8 ? BinaryPrimitives.ReadInt64LittleEndian(_data.AsSpan(_pos)) : BinaryPrimitives.ReadUInt32LittleEndian(_data.AsSpan(_pos)); diff --git a/tests/UVBake.Tests/FbxHostileInputTests.cs b/tests/UVBake.Tests/FbxHostileInputTests.cs new file mode 100644 index 0000000..298df60 --- /dev/null +++ b/tests/UVBake.Tests/FbxHostileInputTests.cs @@ -0,0 +1,139 @@ +using System.Buffers.Binary; +using System.Text; +using UVBake.IO; +using Xunit; + +namespace UVBake.Tests; + +/// +/// The FBX parser treats input as untrusted. Each hand-built hostile file below must be rejected quickly +/// with : no hang, no stack overflow, no runaway allocation. +/// +public class FbxHostileInputTests +{ + private const int Version = 7400; // 32-bit record offsets + + [Fact(Timeout = 10_000)] + public async Task Deeply_nested_records_are_rejected_without_stack_overflow() + { + // 100,000 records, each nested inside the previous one. Without a depth cap this recursion + // overflows the stack, which .NET cannot catch and which kills the whole process. + const int levels = 100_000; + const int recordHeader = 13 + 1; // 3 offsets + name length + 1-byte name + var file = Header(27 + (levels * recordHeader)); + for (int i = 0; i < levels; i++) + { + file.AddRange(Record(endOffset: (uint)(27 + (levels * recordHeader)), numProperties: 0, name: "A")); + } + + await AssertRejectedAsync(file); + } + + [Fact(Timeout = 10_000)] + public async Task Record_whose_end_offset_points_backwards_is_rejected_without_hanging() + { + // The end offset points into the header, before the record itself. Following it would move + // the parser backwards and loop forever. + var file = Header(0); + file.AddRange(Record(endOffset: 5, numProperties: 0, name: "A")); + file.AddRange(new byte[13]); // a null record after it, as a real file would have + await AssertRejectedAsync(file); + } + + [Fact(Timeout = 10_000)] + public async Task Compressed_array_claiming_a_huge_size_is_rejected_before_allocating() + { + // A double array declaring 10 million elements (80 MB, under the size cap) backed by 4 compressed + // bytes: more than DEFLATE could ever expand to, so it is a decompression bomb. + var property = new List { (byte)'d' }; + property.AddRange(Int32(10_000_000)); // element count + property.AddRange(Int32(1)); // encoding: zlib + property.AddRange(Int32(4)); // compressed length + property.AddRange(new byte[] { 0x78, 0x9C, 0x03, 0x00 }); + InvalidDataException ex = await AssertRejectedAsync(SingleRecordWith(property)); + Assert.Contains("impossible expanded size", ex.Message); // refused before inflating, not after + } + + [Fact(Timeout = 10_000)] + public async Task Array_length_beyond_the_size_cap_is_rejected() + { + var property = new List { (byte)'l' }; + property.AddRange(Int32(int.MaxValue)); // ~17 GB of longs + property.AddRange(Int32(0)); // encoding: raw + property.AddRange(Int32(0)); + await AssertRejectedAsync(SingleRecordWith(property)); + } + + [Fact(Timeout = 10_000)] + public async Task String_with_negative_length_is_rejected() + { + var property = new List { (byte)'S' }; + property.AddRange(Int32(-1)); + await AssertRejectedAsync(SingleRecordWith(property)); + } + + [Fact(Timeout = 10_000)] + public async Task Record_running_past_end_of_file_is_rejected_with_InvalidDataException() + { + // A record header claiming to end at byte 1000 in a 40-byte file. + var file = Header(0); + file.AddRange(Record(endOffset: 1000, numProperties: 0, name: "")); + await AssertRejectedAsync(file); + } + + private static async Task AssertRejectedAsync(List file) + { + byte[] bytes = file.ToArray(); + return await Task.Run(() => + { + using var stream = new MemoryStream(bytes); + return Assert.Throws(() => FbxReader.Read(stream)); + }); + } + + private static List SingleRecordWith(List property) + { + var file = Header(0); + uint end = (uint)(file.Count + 13 + 1 + property.Count); + file.AddRange(Record(end, numProperties: 1, name: "A")); + file.AddRange(property); + file.AddRange(new byte[13]); + return file; + } + + private static List Header(int sizeHint) + { + var header = new List(Math.Max(sizeHint, 64)); + header.AddRange(Encoding.ASCII.GetBytes("Kaydara FBX Binary ")); + header.Add(0x00); + header.Add(0x1A); + header.Add(0x00); + header.AddRange(Int32(Version)); + return header; // 27 bytes + } + + private static IEnumerable Record(uint endOffset, uint numProperties, string name) + { + var bytes = new List(); + bytes.AddRange(UInt32(endOffset)); + bytes.AddRange(UInt32(numProperties)); + bytes.AddRange(UInt32(0)); // property-list length (unused by the parser) + bytes.Add((byte)name.Length); + bytes.AddRange(Encoding.ASCII.GetBytes(name)); + return bytes; + } + + private static byte[] Int32(int v) + { + var b = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(b, v); + return b; + } + + private static byte[] UInt32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, v); + return b; + } +}