From 46e57f75dbfc248ba2057644cd66d9a9c0398f9c Mon Sep 17 00:00:00 2001 From: David Howden Date: Sat, 29 Aug 2020 07:40:05 +1000 Subject: [PATCH] limit up-front allocation when reading bytes Fixes #73 --- sum_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ util.go | 12 ++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 sum_test.go diff --git a/sum_test.go b/sum_test.go new file mode 100644 index 0000000..0c77bcf --- /dev/null +++ b/sum_test.go @@ -0,0 +1,40 @@ +package tag + +import ( + "bytes" + "testing" +) + +func TestFuzz(t *testing.T) { + fuzzIssue73(dataIssue73) +} + +var dataIssue73 = []byte{0x49, 0x44, 0x33, 0x03, 0x00, 0x40, 0x00, 0x00, 0x00, 0x0E, 0xDB, 0xDB, 0xDB, 0xDB, 0xDB, 0xDB, + 0xDB, 0x06, 0xFF, 0x54, 0x58, 0x58, 0x00} + +func fuzzIssue73(in []byte) { + r := bytes.NewReader(in) + + Identify(r) + + m, err := ReadFrom(r) + if err != nil { + return + } + + m.Format() + m.FileType() + m.Title() + m.Album() + m.Artist() + m.AlbumArtist() + m.Composer() + m.Year() + m.Genre() + m.Track() + m.Disc() + m.Picture() + m.Lyrics() + + Sum(r) +} diff --git a/util.go b/util.go index 73078ab..c738d2f 100644 --- a/util.go +++ b/util.go @@ -5,6 +5,7 @@ package tag import ( + "bytes" "encoding/binary" "io" ) @@ -40,7 +41,18 @@ func readUint64LittleEndian(r io.Reader) (uint64, error) { return binary.LittleEndian.Uint64(b), nil } +// readBytesMaxUpfront is the max up-front allocation allowed +const readBytesMaxUpfront = 10 << 20 // 10MB + func readBytes(r io.Reader, n uint) ([]byte, error) { + if n > readBytesMaxUpfront { + b := &bytes.Buffer{} + if _, err := io.CopyN(b, r, int64(n)); err != nil { + return nil, err + } + return b.Bytes(), nil + } + b := make([]byte, n) _, err := io.ReadFull(r, b) if err != nil {