Skip to content

Commit

Permalink
Better error handling in x.Parse (#4987)
Browse files Browse the repository at this point in the history
Robust key length checks

(cherry picked from commit d0bfee7)
  • Loading branch information
parasssh committed Mar 20, 2020
1 parent 9b483c3 commit ee2a12d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions x/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,16 +438,26 @@ func SplitKey(baseKey []byte, startUid uint64) ([]byte, error) {
func Parse(key []byte) (ParsedKey, error) {
var p ParsedKey

if len(key) == 0 {
return p, errors.Errorf("0 length key")
}

p.bytePrefix = key[0]
if p.bytePrefix == ByteUnused {
return p, nil
}

p.HasStartUid = key[0] == ByteSplit

if len(key) < 3 {
return p, errors.Errorf("Invalid format for key %v", key)
}
sz := int(binary.BigEndian.Uint16(key[1:3]))
k := key[3:]

if len(k) < sz {
return p, errors.Errorf("Invalid size %v for key %v", sz, key)
}
p.Attr = string(k[:sz])
k = k[sz:]

Expand Down
21 changes: 21 additions & 0 deletions x/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,24 @@ func TestBadStartUid(t *testing.T) {
key = CountKey("aa", 0, true)
testKey(key)
}

func TestBadKeys(t *testing.T) {
// 0-len key
key := []byte{}
_, err := Parse(key)
require.Error(t, err)

// key of len < 3
key = []byte{1}
_, err = Parse(key)
require.Error(t, err)

key = []byte{1, 2}
_, err = Parse(key)
require.Error(t, err)

// key of len < sz (key[1], key[2])
key = []byte{1, 0x00, 0x04, 1, 2}
_, err = Parse(key)
require.Error(t, err)
}

0 comments on commit ee2a12d

Please sign in to comment.