crypto/types: fix negative index accesses in CompactUnmarshal,GetIndex,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
This commit is contained in:
Emmanuel T Odeke 2021-04-26 09:40:27 -07:00 committed by GitHub
parent 9f835e7f74
commit 49bf0774bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 2 deletions

View File

@ -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
}
@ -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
}
@ -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 {

View File

@ -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
@ -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))
}
}
}