Skip to content

Commit

Permalink
Prevent infinite loop when calling ReadBoxStructure
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
aler9 committed Sep 30, 2023
1 parent 1261cd9 commit 4a9be83
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion box_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mp4
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
)
Expand Down Expand Up @@ -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()
Expand All @@ -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
}

Expand Down
10 changes: 10 additions & 0 deletions read_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 4a9be83

Please sign in to comment.