diff --git a/src/NormalBake.IO/Fbx/FbxBinaryParser.cs b/src/NormalBake.IO/Fbx/FbxBinaryParser.cs index 1ca5e14..3ec9b33 100644 --- a/src/NormalBake.IO/Fbx/FbxBinaryParser.cs +++ b/src/NormalBake.IO/Fbx/FbxBinaryParser.cs @@ -10,10 +10,20 @@ namespace NormalBake.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/src/NormalBake.IO/GltfReader.cs b/src/NormalBake.IO/GltfReader.cs index 1a98350..eb05d35 100644 --- a/src/NormalBake.IO/GltfReader.cs +++ b/src/NormalBake.IO/GltfReader.cs @@ -142,6 +142,12 @@ private static (byte[] Json, byte[] Bin) ReadGlb(Stream stream) int len = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(pos)); uint type = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos + 4)); int start = pos + 8; + if (len < 0 || len > data.Length - start) + { + // A negative length would leave pos unchanged and loop forever; an oversized one reads past the end. + throw new InvalidDataException($"glTF chunk at {pos} has an invalid length {len}."); + } + if (type == ChunkJson) { json = data[start..(start + len)]; @@ -209,6 +215,7 @@ private static float[] ReadFloats(JsonElement root, byte[] bin, int accessor, in count = acc.GetProperty("count").GetInt32(); int accOffset = acc.TryGetProperty("byteOffset", out JsonElement ao) ? ao.GetInt32() : 0; (int viewOffset, int stride) = BufferView(root, acc, components * sizeof(float)); + RequireInBuffer(bin, count, viewOffset, accOffset, stride, components * sizeof(float)); var result = new float[count * components]; for (int i = 0; i < count; i++) @@ -238,6 +245,7 @@ private static int[] ReadIndices(JsonElement root, byte[] bin, int accessor) _ => throw new InvalidDataException($"unsupported index component type {componentType}."), }; (int viewOffset, int stride) = BufferView(root, acc, size); + RequireInBuffer(bin, count, viewOffset, accOffset, stride, size); var result = new int[count]; for (int i = 0; i < count; i++) @@ -262,6 +270,24 @@ private static (int Offset, int Stride) BufferView(JsonElement root, JsonElement return (offset, stride); } + /// + /// Checks an accessor's declared extent against the binary chunk before anything is allocated, so a + /// small file cannot make the reader allocate arrays sized by an untrusted count. + /// + private static void RequireInBuffer(byte[] bin, int count, int viewOffset, int accOffset, int stride, int elementSize) + { + if (count < 0 || viewOffset < 0 || accOffset < 0 || stride < elementSize) + { + throw new InvalidDataException("glTF accessor has a negative count/offset or a stride smaller than its element."); + } + + long end = count == 0 ? 0 : (long)viewOffset + accOffset + ((long)(count - 1) * stride) + elementSize; + if (end > bin.Length) + { + throw new InvalidDataException($"glTF accessor needs {end} bytes but the binary chunk has {bin.Length}."); + } + } + private static int[] Sequential(int count) { var result = new int[count]; diff --git a/tests/NormalBake.Tests/IoTests/FbxHostileInputTests.cs b/tests/NormalBake.Tests/IoTests/FbxHostileInputTests.cs new file mode 100644 index 0000000..2038a23 --- /dev/null +++ b/tests/NormalBake.Tests/IoTests/FbxHostileInputTests.cs @@ -0,0 +1,139 @@ +using System.Buffers.Binary; +using System.Text; +using NormalBake.IO; +using Xunit; + +namespace NormalBake.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.ReadParts(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; + } +} diff --git a/tests/NormalBake.Tests/IoTests/GltfHostileInputTests.cs b/tests/NormalBake.Tests/IoTests/GltfHostileInputTests.cs new file mode 100644 index 0000000..70f5471 --- /dev/null +++ b/tests/NormalBake.Tests/IoTests/GltfHostileInputTests.cs @@ -0,0 +1,94 @@ +using System.Buffers.Binary; +using System.Text; +using NormalBake.IO; +using Xunit; + +namespace NormalBake.Tests; + +/// +/// The glTF reader treats input as untrusted. Each hand-built hostile .glb below must be rejected +/// quickly with : no hang and no allocation sized by an untrusted count. +/// +public class GltfHostileInputTests +{ + private const uint Magic = 0x46546C67; // "glTF" + private const uint ChunkJson = 0x4E4F534A; + private const uint ChunkBin = 0x004E4942; + + [Fact(Timeout = 10_000)] + public async Task Chunk_with_negative_length_is_rejected_without_hanging() + { + // An unknown chunk type with length -8 leaves the read position where it was: an endless loop. + var glb = Header(); + glb.AddRange(Chunk(ChunkJson, Encoding.UTF8.GetBytes("{} "))); + glb.AddRange(Int32(-8)); + glb.AddRange(UInt32(0x12345678)); + await AssertRejectedAsync(glb); + } + + [Fact(Timeout = 10_000)] + public async Task Accessor_count_larger_than_the_buffer_is_rejected_before_allocating() + { + // POSITION claims 500 million VEC3 floats (6 GB) backed by a 12-byte binary chunk. + const string json = + "{\"meshes\":[{\"primitives\":[{\"attributes\":{\"POSITION\":0}}]}]," + + "\"accessors\":[{\"bufferView\":0,\"componentType\":5126,\"count\":500000000,\"type\":\"VEC3\"}]," + + "\"bufferViews\":[{\"buffer\":0,\"byteOffset\":0,\"byteLength\":12}]}"; + var glb = Header(); + glb.AddRange(Chunk(ChunkJson, Pad(Encoding.UTF8.GetBytes(json)))); + glb.AddRange(Chunk(ChunkBin, new byte[12])); + InvalidDataException ex = await AssertRejectedAsync(glb); + Assert.Contains("binary chunk has 12", ex.Message); + } + + private static async Task AssertRejectedAsync(List glb) + { + byte[] bytes = glb.ToArray(); + return await Task.Run(() => + { + using var stream = new MemoryStream(bytes); + return Assert.Throws(() => GltfReader.ReadMesh(stream)); + }); + } + + private static List Header() + { + var b = new List(); + b.AddRange(UInt32(Magic)); + b.AddRange(UInt32(2)); + b.AddRange(UInt32(0)); // total length (not relied on by the reader) + return b; + } + + private static IEnumerable Chunk(uint type, byte[] payload) + { + var b = new List(); + b.AddRange(Int32(payload.Length)); + b.AddRange(UInt32(type)); + b.AddRange(payload); + return b; + } + + private static byte[] Pad(byte[] json) + { + int padded = (json.Length + 3) & ~3; + var b = new byte[padded]; + Array.Fill(b, (byte)' '); + json.CopyTo(b, 0); + return b; + } + + 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; + } +}