From 692a9620cd9cd5a9810c1a78a6932eb0d610f57d Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 20:10:00 -0700 Subject: [PATCH 1/4] fix: Parse Matroska SimpleTags 64 levels deep and keep deeper ones as stored bytes --- src/TagLibSharp2/Matroska/MatroskaFile.cs | 22 ++++++++++++++++++---- src/TagLibSharp2/Matroska/MatroskaTag.cs | 8 ++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/TagLibSharp2/Matroska/MatroskaFile.cs b/src/TagLibSharp2/Matroska/MatroskaFile.cs index 03450ff9..4716d7e2 100644 --- a/src/TagLibSharp2/Matroska/MatroskaFile.cs +++ b/src/TagLibSharp2/Matroska/MatroskaFile.cs @@ -875,7 +875,7 @@ static TagBlock ReadTag (ReadOnlySpan body) if (element.Id == MatroskaIds.Targets) ReadTargets (payload, block); else if (element.Id == MatroskaIds.SimpleTag) - block.Tags.Add (ReadSimpleTag (payload)); + block.Tags.Add (ReadSimpleTag (payload, 1)); offset = element.End; } @@ -937,7 +937,14 @@ static void NoteTargetUid (ReadOnlySpan payload, ref bool all, ref bool sp specific = true; } - static SimpleTag ReadSimpleTag (ReadOnlySpan body) + /// + /// The deepest SimpleTag nesting parsed into . RFC 9559 §5.1.8.1.2 + /// lets a SimpleTag nest without a limit, so the reader stops descending here and keeps each deeper + /// SimpleTag as its stored bytes, which a save writes back unchanged. No tag mapping reads that deep. + /// + internal const int MaxSimpleTagDepth = 64; + + static SimpleTag ReadSimpleTag (ReadOnlySpan body, int depth) { var name = string.Empty; string? text = null; @@ -946,6 +953,7 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan body) byte[]? binary = null; var isDefault = true; var children = new List (); + List? kept = null; var offset = 0; while (offset < body.Length) { if (!EbmlReader.TryRead (body, offset, body.Length, out var element) || element.UnknownSize) @@ -963,8 +971,12 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan body) binary = payload.ToArray (); else if (element.Id == MatroskaIds.TagDefault || element.Id == MatroskaIds.TagDefaultBogus) isDefault = IsFlagSet (payload); - else if (element.Id == MatroskaIds.SimpleTag) - children.Add (ReadSimpleTag (payload)); + else if (element.Id == MatroskaIds.SimpleTag) { + if (depth < MaxSimpleTagDepth) + children.Add (ReadSimpleTag (payload, depth + 1)); + else + (kept ??= new List ()).Add (body.Slice (element.Position, element.End - element.Position).ToArray ()); + } offset = element.End; } @@ -975,6 +987,8 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan body) }; foreach (var child in children) tag.Children.Add (child); + if (kept is not null) + tag.KeptChildren.AddRange (kept); return tag; } diff --git a/src/TagLibSharp2/Matroska/MatroskaTag.cs b/src/TagLibSharp2/Matroska/MatroskaTag.cs index d8cc2c06..8772fcef 100644 --- a/src/TagLibSharp2/Matroska/MatroskaTag.cs +++ b/src/TagLibSharp2/Matroska/MatroskaTag.cs @@ -1354,6 +1354,12 @@ public SimpleTag (string name, string? text, bool isDefault = true) public List Children { get; } = new (); + /// + /// Nested SimpleTags below , as their stored bytes. + /// They are written back after , so the nesting is kept without being parsed. + /// + public List KeptChildren { get; } = new (); + public BinaryData Render () { using var body = new BinaryDataBuilder (); @@ -1370,6 +1376,8 @@ public BinaryData Render () body.Add (EbmlWriter.Master (MatroskaIds.TagBinary, Binary)); foreach (var child in Children) body.Add (child.Render ()); + foreach (var child in KeptChildren) + body.Add (child); return EbmlWriter.Master (MatroskaIds.SimpleTag, body.ToBinaryData ().Span); } } From 5b403feef0fb6de5dc0133c8da25e7406af4e11c Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 20:10:00 -0700 Subject: [PATCH 2/4] test: Pin that deeply nested Matroska Cues and SimpleTags read and save --- .../Matroska/MatroskaDeepNestingTests.cs | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs new file mode 100644 index 00000000..8876a239 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs @@ -0,0 +1,185 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Matroska; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Matroska; + +// A file controls how deep its elements nest. Reading or saving must not recurse once per level, +// or a small crafted file ends the process with a stack overflow that no caller can catch. +public partial class MatroskaFileTests +{ + const int HostileDepth = 100_000; + + [TestMethod] + public void Save_CuePointsNestedDeep_DoesNotOverflowTheStack () + { + var marker = new byte[] { 0xC1, 0xC2, 0xC3, 0xC4 }; + var info = Master (0x1549A966, Element (0x7BA9, "Live"u8)); + var inner = Master (MatroskaIds.CueTrackPositions, + Element (0xF7, new byte[] { 1 }), + Element (MatroskaIds.CueClusterPosition, new byte[] { 0x10 })); + var cues = Wide (MatroskaIds.Cues, Nested (MatroskaIds.CuePoint, HostileDepth, [], inner)); + var cluster = Unknown (0x1F43B675, Element (0xEC, marker)); + var original = DeepWideFile (info, cues, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = new string ('N', 400); + + var fs = new MockFileSystem (); + fs.AddFile ("/deep-cues.mkv", original); + var saved = parsed.SaveToFile ("/deep-cues.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/deep-cues.mkv"); + Assert.AreEqual (1, CountOf (bytes, marker)); + Assert.AreEqual (new string ('N', 400), MatroskaFile.Read (bytes).File!.Tag.Title); + } + + [TestMethod] + public void Save_CueClusterPositionOffTheSpecPath_IsLeftAsStored () + { + // RFC 9559 §5.1.5 places CueClusterPosition only in Cues\CuePoint\CueTrackPositions. + var marker = new byte[] { 0xC1, 0xC2, 0xC3, 0xC4 }; + var info = Master (0x1549A966, Element (0x7BA9, "Live"u8)); + var stray = Element (MatroskaIds.CueClusterPosition, new byte[] { 0x00, 0x7E }); + var cues = Master (MatroskaIds.Cues, Master (MatroskaIds.CuePoint, Element (0xB3, new byte[] { 0 }), stray)); + var cluster = Unknown (0x1F43B675, Element (0xEC, marker)); + var original = FileWith (info, cues, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = new string ('N', 400); + + var fs = new MockFileSystem (); + fs.AddFile ("/stray.mkv", original); + var saved = parsed.SaveToFile ("/stray.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual (1, CountOf (fs.ReadAllBytes ("/stray.mkv"), stray)); + } + + [TestMethod] + public void Read_SimpleTagsNestedDeep_DoesNotOverflowAndSaveKeepsTheNesting () + { + var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "deepest"u8)); + var chain = Nested (0x67C8, HostileDepth, Element (0x45A3, "N"u8), leaf); + var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain)); + var tags = Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title))); + var original = DeepWideFile (Master (0x1549A966, Element (0x7BA9, "Deep"u8)), tags); + + var read = MatroskaFile.Read (original); + + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.AreEqual ("Outer", read.File!.Tag.Title); + + read.File.Tag.Artist = "Someone"; + var rendered = read.File.Render (original).ToArray (); + Assert.AreNotEqual (0, rendered.Length); + Assert.IsTrue (rendered.AsSpan ().IndexOf (leaf) >= 0, "the deepest SimpleTag is written back"); + Assert.AreEqual (HostileDepth, NestingBelowTitle (rendered)); + + var reread = MatroskaFile.Read (rendered).File!; + Assert.AreEqual ("Outer", reread.Tag.Title); + Assert.AreEqual ("Someone", reread.Tag.Artist); + } + + [TestMethod] + [DataRow (MatroskaFile.MaxSimpleTagDepth - 1)] + [DataRow (MatroskaFile.MaxSimpleTagDepth)] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 1)] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 5)] + public void Save_SimpleTagsNestedPastTheParseDepth_AreByteIdenticalAfterAnEdit (int depth) + { + var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8)); + var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf); + var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain)); + var original = DeepWideFile ( + Master (0x1549A966, Element (0x7BA9, "Deep"u8)), + Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title)))); + var file = MatroskaFile.Read (original).File!; + + file.Tag.Artist = "Someone"; + var rendered = MatroskaFile.Read (file.Render (original).ToArray ()).File!; + rendered.Tag.Artist = null; + var restored = rendered.Render (file.Render (original).ToArray ()).ToArray (); + + Assert.AreEqual (depth, NestingBelowTitle (restored)); + Assert.IsTrue (restored.AsSpan ().IndexOf (leaf) >= 0); + } + + [TestMethod] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 1)] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 5)] + public void Save_NewValueOnATagNestedPastTheParseDepth_KeepsItsNesting (int depth) + { + var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8)); + var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf); + var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain)); + var original = DeepWideFile ( + Master (0x1549A966, Element (0x7BA9, "Deep"u8)), + Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title)))); + var file = MatroskaFile.Read (original).File!; + + file.Tag.Title = "Renamed"; + var rendered = file.Render (original).ToArray (); + + Assert.AreEqual ("Renamed", MatroskaFile.Read (rendered).File!.Tag.Title); + Assert.AreEqual (depth, NestingBelowTitle (rendered)); + Assert.IsTrue (rendered.AsSpan ().IndexOf (leaf) >= 0); + } + + // Counts the SimpleTags nested under the first TITLE SimpleTag by walking the bytes. + static int NestingBelowTitle (byte[] file) + { + var title = file.AsSpan ().IndexOf ("TITLE"u8); + Assert.IsTrue (title >= 0); + var count = 0; + var span = file.AsSpan (title); + var name = new byte[] { 0x45, 0xA3, 0x81, (byte)'N' }; + var at = span.IndexOf (name); + while (at >= 0) { + count++; + span = span.Slice (at + name.Length); + at = span.IndexOf (name); + } + + return count; + } + + // Each level is the element ID, an 8-octet size (RFC 8794 §4.4), the prefix, then the next level. + static byte[] Nested (ulong id, int depth, byte[] prefix, byte[] innermost) + { + var idBytes = Id (id); + var level = idBytes.Length + 8 + prefix.Length; + var result = new byte[(level * depth) + innermost.Length]; + for (var i = 0; i < depth; i++) { + var at = i * level; + idBytes.CopyTo (result, at); + WriteWideSize (result, at + idBytes.Length, (ulong)(result.Length - at - level + prefix.Length)); + prefix.CopyTo (result, at + idBytes.Length + 8); + } + + innermost.CopyTo (result, level * depth); + return result; + } + + static byte[] Wide (ulong id, byte[] payload) + { + var idBytes = Id (id); + var result = new byte[idBytes.Length + 8 + payload.Length]; + idBytes.CopyTo (result, 0); + WriteWideSize (result, idBytes.Length, (ulong)payload.Length); + payload.CopyTo (result, idBytes.Length + 8); + return result; + } + + static byte[] DeepWideFile (params byte[][] segmentChildren) => Matroska (Wide (0x18538067, Concat (segmentChildren))); + + static void WriteWideSize (byte[] buffer, int at, ulong size) + { + buffer[at] = 0x01; + for (var i = 7; i >= 1; i--) { + buffer[at + i] = (byte)size; + size >>= 8; + } + } +} From ac50932564157773b016bebd33dded2b9697f587 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 20:10:00 -0700 Subject: [PATCH 3/4] docs: Note the Matroska deep-nesting fix in the changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89a30d67..9e004f24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Matroska: deeply nested SimpleTags no longer crash the process with a stack overflow (#150). `MatroskaFile.Read` parses SimpleTags up to 64 levels deep and keeps any deeper SimpleTag as its stored bytes, which a save writes back unchanged; a file with SimpleTags nested 100,000 deep used to end the process on open. A save that moves Cues already walks only the RFC 9559 §5.1.5 paths. - Ogg Vorbis comment packets that run across pages without the continuation flag keep their comments, and a stream whose last audio page is cut off keeps its duration (#126). `missing_flag.ogg` from that issue now opens with its title, artist, album, genre, cover and 10.189 s duration. Its framing byte is 0x01: the comments were lost in page reassembly, not at the framing bit. - The Vorbis comment framing bit is read as the spec defines it: the low bit of the first byte after the declared comment list ([v-comment.html](https://xiph.org/vorbis/doc/v-comment.html) steps 7-8, Vorbis I spec 5.2.1, bit order per 2.1.4). 0x01, 0x03, 0x81 and 0xFF are accepted, and padding after that byte is ignored. A framing byte of 0x00, any other byte with the low bit clear, or a packet that ends at the comment list is rejected, as in libvorbis and mutagen. All 60 Ogg Vorbis files in the test corpora use 0x01. - Ogg Opus: OpusTags split across pages without the continuation flag keeps its tags (they were empty). When the last audio page is cut off, `MediaFile.Read` on a stream reports the duration instead of 0, for example `psycho4.opus` (244 s). From 623fd4d785b64021c91baa9718ce09c18d27b3fb Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 22:32:55 -0700 Subject: [PATCH 4/4] test: Check the kept Matroska SimpleTag bytes and pin the parse depth exactly --- .../Matroska/MatroskaDeepNestingTests.cs | 60 ++++++++++++++++++- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs index 8876a239..42ac4502 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs @@ -74,7 +74,7 @@ public void Read_SimpleTagsNestedDeep_DoesNotOverflowAndSaveKeepsTheNesting () read.File.Tag.Artist = "Someone"; var rendered = read.File.Render (original).ToArray (); Assert.AreNotEqual (0, rendered.Length); - Assert.IsTrue (rendered.AsSpan ().IndexOf (leaf) >= 0, "the deepest SimpleTag is written back"); + Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain)), "the SimpleTags below the parse depth are written back as stored, once"); Assert.AreEqual (HostileDepth, NestingBelowTitle (rendered)); var reread = MatroskaFile.Read (rendered).File!; @@ -82,6 +82,38 @@ public void Read_SimpleTagsNestedDeep_DoesNotOverflowAndSaveKeepsTheNesting () Assert.AreEqual ("Someone", reread.Tag.Artist); } + // TITLE is level 1 and each chain link is one level deeper, so the leaf sits at level depth + 2. + // Levels up to MaxSimpleTagDepth are parsed and re-encoded with minimal sizes; anything deeper is + // kept as stored. Every element here is written with an 8-octet size, so a parsed one changes bytes + // and a kept one does not. + [TestMethod] + [DataRow (MatroskaFile.MaxSimpleTagDepth - 2, false)] + [DataRow (MatroskaFile.MaxSimpleTagDepth - 1, true)] + [DataRow (MatroskaFile.MaxSimpleTagDepth, true)] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 1, true)] + [DataRow (MatroskaFile.MaxSimpleTagDepth + 5, true)] + public void Save_SimpleTagsAtAndPastTheParseDepth_KeepOnlyTheDeeperOnesAsStored (int depth, bool kept) + { + var leaf = Wide (0x67C8, Concat (Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8))); + var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf); + var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain)); + var original = DeepWideFile ( + Master (0x1549A966, Element (0x7BA9, "Deep"u8)), + Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title)))); + var file = MatroskaFile.Read (original).File!; + + file.Tag.Artist = "Someone"; + var rendered = file.Render (original).ToArray (); + + Assert.AreEqual (depth, NestingBelowTitle (rendered)); + Assert.AreEqual (kept ? 1 : 0, Occurrences (rendered, leaf), "the leaf's stored bytes"); + if (kept) + Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain))); + Assert.IsTrue (MatroskaFile.Read (rendered).IsSuccess); + Assert.AreEqual (1, Occurrences (rendered, Element (0x45A3, "LEAF"u8)), "the leaf is written once"); + Assert.AreEqual (1, Occurrences (rendered, Element (0x4487, "v"u8)), "with its value"); + } + [TestMethod] [DataRow (MatroskaFile.MaxSimpleTagDepth - 1)] [DataRow (MatroskaFile.MaxSimpleTagDepth)] @@ -103,7 +135,7 @@ public void Save_SimpleTagsNestedPastTheParseDepth_AreByteIdenticalAfterAnEdit ( var restored = rendered.Render (file.Render (original).ToArray ()).ToArray (); Assert.AreEqual (depth, NestingBelowTitle (restored)); - Assert.IsTrue (restored.AsSpan ().IndexOf (leaf) >= 0); + Assert.AreEqual (1, Occurrences (restored, KeptSlice (chain)), "the kept SimpleTags survive two saves byte for byte"); } [TestMethod] @@ -124,7 +156,29 @@ public void Save_NewValueOnATagNestedPastTheParseDepth_KeepsItsNesting (int dept Assert.AreEqual ("Renamed", MatroskaFile.Read (rendered).File!.Tag.Title); Assert.AreEqual (depth, NestingBelowTitle (rendered)); - Assert.IsTrue (rendered.AsSpan ().IndexOf (leaf) >= 0); + Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain))); + } + + // The stored bytes of the first SimpleTag below the parse depth: chain link MaxSimpleTagDepth - 1 + // (link i is level i + 2), through the end of the chain, which is that link's whole subtree. + static byte[] KeptSlice (byte[] chain) + { + var link = Id (0x67C8).Length + 8 + Element (0x45A3, "N"u8).Length; + return chain.AsSpan ((MatroskaFile.MaxSimpleTagDepth - 1) * link).ToArray (); + } + + static int Occurrences (byte[] data, byte[] pattern) + { + var count = 0; + var span = data.AsSpan (); + var at = span.IndexOf (pattern); + while (at >= 0) { + count++; + span = span.Slice (at + 1); + at = span.IndexOf (pattern); + } + + return count; } // Counts the SimpleTags nested under the first TITLE SimpleTag by walking the bytes.