]> Cypherpunks.ru repositories - gostls13.git/commitdiff
hex: fix panic in Decode when len(src) > 2*len(dst)
authorBenjamin Prosnitz <bprosnitz@gmail.com>
Fri, 13 Jan 2023 16:54:35 +0000 (11:54 -0500)
committerGopher Robot <gobot@golang.org>
Fri, 27 Jan 2023 15:28:30 +0000 (15:28 +0000)
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 <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Benjamin Prosnitz <bprosnitz@gmail.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>

src/encoding/hex/hex.go
src/encoding/hex/hex_test.go

index 375f5831709bb7764f73f909c541bb7830bacc0a..5a8243ae80548d9a1de901911438bc63e0326b69 100644 (file)
@@ -75,6 +75,9 @@ func DecodedLen(x int) int { return x / 2 }
 // If the input is malformed, Decode returns the number
 // of bytes decoded before the error.
 func Decode(dst, src []byte) (int, error) {
+       if len(dst) < DecodedLen(len(src)) {
+               return 0, errors.New("encoding/hex: output buffer too small")
+       }
        i, j := 0, 1
        for ; j < len(src); j += 2 {
                p := src[j-1]
index a820fe7a1514f7533e32d9d67830a23dced05361..1eb169cdee5bc6829d89f4d32a7d8b03dbe3693c 100644 (file)
@@ -55,6 +55,15 @@ func TestDecode(t *testing.T) {
        }
 }
 
+func TestDecode_tooFewDstBytes(t *testing.T) {
+       dst := make([]byte, 1)
+       src := []byte{'0', '1', '2', '3'}
+       _, err := Decode(dst, src)
+       if err == nil {
+               t.Errorf("expected Decode to return an error, but it returned none")
+       }
+}
+
 func TestEncodeToString(t *testing.T) {
        for i, test := range encDecTests {
                s := EncodeToString(test.dec)