]> Sergey Matveev's repositories - btrtrc.git/commitdiff
bencode: Avoid allocating interface string up front
authorMatt Joiner <anacrolix@gmail.com>
Fri, 10 Dec 2021 04:10:26 +0000 (15:10 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Sun, 12 Dec 2021 05:56:01 +0000 (16:56 +1100)
This should fix crashes during fuzzing. It's not a complete fix, we really want to limit the amount a given Decode can allocate. Maybe Go isn't the right language for this.

bencode/decode.go
bencode/testdata/fuzz/FuzzInterfaceRoundTrip/c73f26cbd996104c4e39ce4998a08e90a5c437df90e68caeea0650ee3c7e7b42 [new file with mode: 0644]
bencode/testdata/fuzz/FuzzInterfaceRoundTrip/eef53fca91deb00d4e30f4f59e17e92d2936cda9f4b260994a830ec27cfb88c3 [new file with mode: 0644]

index 4552da1c340b4dacc28788ac4bc7c7971427b338..53ce6efd9035f9bb1034f3652b7c59e45bfd54be 100644 (file)
@@ -642,14 +642,24 @@ func (d *Decoder) parseIntInterface() (ret interface{}) {
        return
 }
 
+func (d *Decoder) readBytes(length int) []byte {
+       b, err := io.ReadAll(io.LimitReader(d.r, int64(length)))
+       if err != nil {
+               panic(err)
+       }
+       if len(b) != length {
+               panic(fmt.Errorf("read %v bytes expected %v", len(b), length))
+       }
+       return b
+}
+
 func (d *Decoder) parseStringInterface() string {
        length, err := d.parseStringLength()
        if err != nil {
                panic(err)
        }
-       b := make([]byte, length)
-       n, err := io.ReadFull(d.r, b)
-       d.Offset += int64(n)
+       b := d.readBytes(int(length))
+       d.Offset += int64(len(b))
        if err != nil {
                panic(&SyntaxError{Offset: d.Offset, What: err})
        }
diff --git a/bencode/testdata/fuzz/FuzzInterfaceRoundTrip/c73f26cbd996104c4e39ce4998a08e90a5c437df90e68caeea0650ee3c7e7b42 b/bencode/testdata/fuzz/FuzzInterfaceRoundTrip/c73f26cbd996104c4e39ce4998a08e90a5c437df90e68caeea0650ee3c7e7b42
new file mode 100644 (file)
index 0000000..7dcf27e
--- /dev/null
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("1:")
diff --git a/bencode/testdata/fuzz/FuzzInterfaceRoundTrip/eef53fca91deb00d4e30f4f59e17e92d2936cda9f4b260994a830ec27cfb88c3 b/bencode/testdata/fuzz/FuzzInterfaceRoundTrip/eef53fca91deb00d4e30f4f59e17e92d2936cda9f4b260994a830ec27cfb88c3
new file mode 100644 (file)
index 0000000..384fff7
--- /dev/null
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("d10000000000")