Skip to content

Commit

Permalink
crypto/types: fix negative index accesses in CompactUnmarshal,GetInde…
Browse files Browse the repository at this point in the history
…x,SetIndex (#9196)

Fixes unchecked negative index access that'd cause panics, in CompactBitArray's:
* CompactUnmarshal, which blindly used the result of binary.Uvarint
* GetIndex
* SetIndex

Fixes #9164
Fixes #9165
  • Loading branch information
odeke-em authored Apr 26, 2021
1 parent 9f835e7 commit 49bf077
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
7 changes: 5 additions & 2 deletions crypto/types/compact_bit_array.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (bA *CompactBitArray) GetIndex(i int) bool {
if bA == nil {
return false
}
if i >= bA.Count() {
if i < 0 || i >= bA.Count() {
return false
}

Expand All @@ -68,7 +68,7 @@ func (bA *CompactBitArray) SetIndex(i int, v bool) bool {
return false
}

if i >= bA.Count() {
if i < 0 || i >= bA.Count() {
return false
}

Expand Down Expand Up @@ -262,6 +262,9 @@ func CompactUnmarshal(bz []byte) (*CompactBitArray, error) {
}

size, n := binary.Uvarint(bz)
if n < 0 || n >= len(bz) {
return nil, fmt.Errorf("compact bit array: n=%d is out of range of len(bz)=%d", n, len(bz))
}
bz = bz[n:]

if len(bz) != int(size+7)/8 {
Expand Down
20 changes: 20 additions & 0 deletions crypto/types/compact_bit_array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,17 @@ func TestCompactMarshalUnmarshal(t *testing.T) {
}
}

// Ensure that CompactUnmarshal does not blindly try to slice using
// a negative/out of bounds index of size returned from binary.Uvarint.
// See issue https://github.com/cosmos/cosmos-sdk/issues/9165
func TestCompactMarshalUnmarshalReturnsErrorOnInvalidSize(t *testing.T) {
malicious := []byte{0xd7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x24, 0x28}
cba, err := CompactUnmarshal(malicious)
require.Error(t, err)
require.Nil(t, cba)
require.Contains(t, err.Error(), "n=-11 is out of range of len(bz)=13")
}

func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) {
testCases := []struct {
marshalledBA string
Expand Down Expand Up @@ -227,6 +238,15 @@ func TestCompactBitArrayGetSetIndex(t *testing.T) {
val := (r.Int63() % 2) == 0
bA.SetIndex(index, val)
require.Equal(t, val, bA.GetIndex(index), "bA.SetIndex(%d, %v) failed on bit array: %s", index, val, copy)

// Ensure that passing in negative indices to .SetIndex and .GetIndex do not
// panic. See issue https://github.com/cosmos/cosmos-sdk/issues/9164.
// To intentionally use negative indices, We want only values that aren't 0.
if index == 0 {
continue
}
require.False(t, bA.SetIndex(-index, val))
require.False(t, bA.GetIndex(-index))
}
}
}
Expand Down

0 comments on commit 49bf077

Please sign in to comment.