Skip to content

Commit

Permalink
fix(dot/network): Check for size when decoding leb128. (ChainSafe#1634)
Browse files Browse the repository at this point in the history
  • Loading branch information
arijitAD authored and timwu20 committed Dec 6, 2021
1 parent 571a0be commit c20a83c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions dot/network/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ func readLEB128ToUint64(r io.Reader, buf []byte) (uint64, error) {

var out uint64
var shift uint

maxSize := 10 // Max bytes in LEB128 encoding of uint64 is 10.
for {
_, err := r.Read(buf)
if err != nil {
Expand All @@ -168,6 +170,12 @@ func readLEB128ToUint64(r io.Reader, buf []byte) (uint64, error) {
if b&0x80 == 0 {
break
}

maxSize--
if maxSize == 0 {
return 0, fmt.Errorf("invalid LEB128 encoded data")
}

shift += 7
}
return out, nil
Expand Down
17 changes: 17 additions & 0 deletions dot/network/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ func TestReadLEB128ToUint64(t *testing.T) {
input: []byte("\xB9\x64"),
output: 12857,
},
{
input: []byte{'\xFF', '\xFF', '\xFF', '\xFF', '\xFF',
'\xFF', '\xFF', '\xFF', '\xFF', '\x01'},
output: 18446744073709551615,
},
}

for _, tc := range tests {
Expand All @@ -115,3 +120,15 @@ func TestReadLEB128ToUint64(t *testing.T) {
require.Equal(t, tc.output, ret)
}
}

func TestInvalidLeb128(t *testing.T) {
input := []byte{'\xFF', '\xFF', '\xFF', '\xFF', '\xFF',
'\xFF', '\xFF', '\xFF', '\xFF', '\xFF', '\x01'}
b := make([]byte, 2)
buf := new(bytes.Buffer)
_, err := buf.Write(input)
require.NoError(t, err)

_, err = readLEB128ToUint64(buf, b[:1])
require.Error(t, err)
}

0 comments on commit c20a83c

Please sign in to comment.