From 4a9be83c541f724440c454b1cc1b420351e865ca Mon Sep 17 00:00:00 2001 From: aler9 <46489434+aler9@users.noreply.github.com> Date: Sat, 30 Sep 2023 13:24:09 +0200 Subject: [PATCH] Prevent infinite loop when calling ReadBoxStructure When ReadBoxStructure is called against a box with a size of zero, an infinite loop is generated due to the fact that the loop contained in readBoxStructure() never ends. This patch fixes the issue and provides a test case. --- box_info.go | 6 +++++- read_test.go | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/box_info.go b/box_info.go index b5c587f..402b418 100644 --- a/box_info.go +++ b/box_info.go @@ -3,6 +3,7 @@ package mp4 import ( "bytes" "encoding/binary" + "fmt" "io" "math" ) @@ -128,7 +129,6 @@ func ReadBoxInfo(r io.ReadSeeker) (*BoxInfo, error) { if _, err := bi.SeekToPayload(r); err != nil { return nil, err } - } else if bi.Size == 1 { // read more 8 bytes buf.Reset() @@ -139,6 +139,10 @@ func ReadBoxInfo(r io.ReadSeeker) (*BoxInfo, error) { bi.Size = binary.BigEndian.Uint64(buf.Bytes()) } + if bi.Size == 0 { + return nil, fmt.Errorf("invalid size") + } + return bi, nil } diff --git a/read_test.go b/read_test.go index 57f3793..698d58b 100644 --- a/read_test.go +++ b/read_test.go @@ -228,3 +228,13 @@ func TestReadBoxStructureQT(t *testing.T) { // 47 [stsc] Size=28 Version=0 Flags=0x000000 EntryCount=1 Entries=[{FirstChunk=1 SamplesPerChunk=1 SampleDescriptionIndex=1}] // 48 [stsz] Size=111852 ... (use "-full stsz" to show all) // 49 [stco] Size=111848 ... (use "-full stco" to show all) + +// this used to cause an infinite loop. +func TestReadBoxStructureZeroSize(t *testing.T) { + b := []byte("\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01") + + _, err := ReadBoxStructure(bytes.NewReader(b), func(h *ReadHandle) (interface{}, error) { + return nil, nil + }) + require.Error(t, err) +}