From b429f612fbfe30e747514e8f3aeb83fe351e8ae2 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sun, 29 Nov 2026 12:27:23 -0700 Subject: [PATCH] fix(drm): raise ValueError when a file ends inside a box largesize in read_top_boxes --- tests/core/test_kid_windows.py | 9 ++++++++- unshackle/core/drm/verify.py | 8 ++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/tests/core/test_kid_windows.py b/tests/core/test_kid_windows.py index d3e2c2739..7febfaf46 100644 --- a/tests/core/test_kid_windows.py +++ b/tests/core/test_kid_windows.py @@ -4,7 +4,7 @@ from uuid import UUID import pytest -from unshackle.core.drm.verify import PIFF_TENC, PIFF_TFXD, KidMap, kid_windows, pick_windows +from unshackle.core.drm.verify import PIFF_TENC, PIFF_TFXD, KidMap, kid_windows, pick_windows, read_top_boxes A, B, C = UUID(int=0xA), UUID(int=0xB), UUID(int=0xC) @@ -192,6 +192,13 @@ def test_oversized_box(tmp_path: Path) -> None: assert kid_windows(path) is None +def test_box_cut_inside_its_largesize(tmp_path: Path) -> None: + path = tmp_path / "cut.mp4" + path.write_bytes(struct.pack(">I4s", 1, b"moof") + bytes(4)) + with path.open("rb") as f, pytest.raises(ValueError): + list(read_top_boxes(f)) + + def test_not_a_fragmented_mp4(tmp_path: Path) -> None: path = tmp_path / "video.ts" path.write_bytes(b"\x47" * 188 * 4) diff --git a/unshackle/core/drm/verify.py b/unshackle/core/drm/verify.py index 550d3652c..5312fe07e 100644 --- a/unshackle/core/drm/verify.py +++ b/unshackle/core/drm/verify.py @@ -273,7 +273,8 @@ def senc_protects_samples(buf: bytes, body: int, end: int) -> bool: def read_top_boxes(f: BinaryIO) -> Iterator[tuple[bytes, bytes | None]]: """Yield each top-level box type, with the body of a moov or moof. Every other body is skipped. - Raises ValueError when a moov or moof claims more bytes than the file has left. + Raises ValueError when a moov or moof claims more bytes than the file has left, or when the file + ends inside the largesize field of a box. """ file_size = os.fstat(f.fileno()).st_size while True: @@ -283,7 +284,10 @@ def read_top_boxes(f: BinaryIO) -> Iterator[tuple[bytes, bytes | None]]: size, kind = struct.unpack(">I4s", head) body_size = size - 8 if size == 1: - body_size = struct.unpack(">Q", f.read(8))[0] - 16 + large = f.read(8) + if len(large) < 8: + raise ValueError(f"{kind!r} box is larger than the rest of the file") + body_size = struct.unpack(">Q", large)[0] - 16 elif size == 0: return if body_size < 0: