Skip to content

Commit a106def

Browse files
bprosnitzgopherbot
authored andcommitted
hex: fix panic in Decode when len(src) > 2*len(dst)
hex.Decode never checks the length of dst and triggers a panic if there are insufficient bytes in the slice. There isn't document on what the behavior *should* be in this case. Two possibilities: 1. Error dst has insufficient space (as done in this change) 2. Reduce the length of the decode to min(dst, src) Option 1 was chosen because it seems the least surprising or subtle. Change-Id: I3bf029e3d928202de716830434285e3c165f26dd Reviewed-on: https://go-review.googlesource.com/c/go/+/461958 Reviewed-by: Ian Lance Taylor <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> Reviewed-by: Bryan Mills <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Benjamin Prosnitz <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent 6b8b782 commit a106def

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/encoding/hex/hex.go

+3
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ func DecodedLen(x int) int { return x / 2 }
7575
// If the input is malformed, Decode returns the number
7676
// of bytes decoded before the error.
7777
func Decode(dst, src []byte) (int, error) {
78+
if len(dst) < DecodedLen(len(src)) {
79+
return 0, errors.New("encoding/hex: output buffer too small")
80+
}
7881
i, j := 0, 1
7982
for ; j < len(src); j += 2 {
8083
p := src[j-1]

src/encoding/hex/hex_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,15 @@ func TestDecode(t *testing.T) {
5555
}
5656
}
5757

58+
func TestDecode_tooFewDstBytes(t *testing.T) {
59+
dst := make([]byte, 1)
60+
src := []byte{'0', '1', '2', '3'}
61+
_, err := Decode(dst, src)
62+
if err == nil {
63+
t.Errorf("expected Decode to return an error, but it returned none")
64+
}
65+
}
66+
5867
func TestEncodeToString(t *testing.T) {
5968
for i, test := range encDecTests {
6069
s := EncodeToString(test.dec)

0 commit comments

Comments
 (0)