bencode: Enforce dict key ordering

Fix bencode dict key ordering in HTTP tracker test
This commit is contained in:
Matt Joiner 2021-12-10 14:05:00 +11:00
parent 78e48f71dd
commit 8764456d23
4 changed files with 13 additions and 5 deletions

View File

@ -652,7 +652,9 @@ func (d *Decoder) parseStringInterface() string {
func (d *Decoder) parseDictInterface() interface{} {
dict := make(map[string]interface{})
lastKey := ""
for {
start := d.Offset
keyi, ok := d.parseValueInterface()
if !ok {
break
@ -665,12 +667,16 @@ func (d *Decoder) parseDictInterface() interface{} {
What: errors.New("non-string key in a dict"),
})
}
if key <= lastKey {
d.throwSyntaxError(start, fmt.Errorf("dict keys unsorted: %q <= %q", key, lastKey))
}
start = d.Offset
valuei, ok := d.parseValueInterface()
if !ok {
break
d.throwSyntaxError(start, fmt.Errorf("dict elem missing value [key=%v]", key))
}
lastKey = key
dict[key] = valuei
}
return dict

View File

@ -33,8 +33,8 @@ var random_decode_tests = []random_decode_test{
ret, _ := big.NewInt(-1).SetString("604919719469385652980544193299329427705624352086", 10)
return ret
}()},
{"d1:rd6:\xd4/\xe2F\x00\x01e1:t3:\x9a\x87\x011:v4:TR%=1:y1:re", map[string]interface{}{
"r": map[string]interface{}{},
{"d1:rd6:\xd4/\xe2F\x00\x01i42ee1:t3:\x9a\x87\x011:v4:TR%=1:y1:re", map[string]interface{}{
"r": map[string]interface{}{"\xd4/\xe2F\x00\x01": int64(42)},
"t": "\x9a\x87\x01",
"v": "TR%=",
"y": "r",

View File

@ -0,0 +1,2 @@
go test fuzz v1
[]byte("d3:A005:000003:000i0ee")

View File

@ -16,7 +16,7 @@ func TestUnmarshalHTTPResponsePeerDicts(t *testing.T) {
require.NoError(t, bencode.Unmarshal(
[]byte("d5:peersl"+
"d2:ip7:1.2.3.47:peer id20:thisisthe20bytepeeri4:porti9999ee"+
"d7:peer id20:thisisthe20bytepeeri2:ip39:2001:0db8:85a3:0000:0000:8a2e:0370:73344:porti9998ee"+
"d2:ip39:2001:0db8:85a3:0000:0000:8a2e:0370:73347:peer id20:thisisthe20bytepeeri4:porti9998ee"+
"e"+
"6:peers618:123412341234123456"+
"e"),