1
0
mirror of https://github.com/golang/go synced 2024-11-18 12:14:42 -07:00

base64: fix bug that decoder fails to detect corruption

Encoding.Decode() failed to detect trailing garbages if input contains "==" followed by garbage smaller than 3 bytes (for example, it failed to detect "x" in "AA==x"). This patch fixes the bug and adds a few tests.

LGTM=nigeltao
R=golang-codereviews, bradfitz, nigeltao
CC=golang-codereviews
https://golang.org/cl/75340044
This commit is contained in:
Rui Ueyama 2014-03-20 16:00:34 +11:00 committed by Nigel Tao
parent 90a66fa6af
commit a2770af447
2 changed files with 24 additions and 9 deletions

View File

@ -224,21 +224,33 @@ func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
var dbuf [4]byte var dbuf [4]byte
dlen := 4 dlen := 4
for j := 0; j < 4; { for j := range dbuf {
if len(src) == 0 { if len(src) == 0 {
return n, false, CorruptInputError(olen - len(src) - j) return n, false, CorruptInputError(olen - len(src) - j)
} }
in := src[0] in := src[0]
src = src[1:] src = src[1:]
if in == '=' && j >= 2 && len(src) < 4 { if in == '=' {
// We've reached the end and there's padding // We've reached the end and there's padding
if len(src)+j < 4-1 { switch j {
// not enough padding case 0, 1:
return n, false, CorruptInputError(olen)
}
if len(src) > 0 && src[0] != '=' {
// incorrect padding // incorrect padding
return n, false, CorruptInputError(olen - len(src) - 1) return n, false, CorruptInputError(olen - len(src) - 1)
case 2:
// "==" is expected, the first "=" is already consumed.
if len(src) == 0 {
// not enough padding
return n, false, CorruptInputError(olen)
}
if src[0] != '=' {
// incorrect padding
return n, false, CorruptInputError(olen - len(src) - 1)
}
src = src[1:]
}
if len(src) > 0 {
// trailing garbage
return n, false, CorruptInputError(olen - len(src))
} }
dlen, end = j, true dlen, end = j, true
break break
@ -247,7 +259,6 @@ func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
if dbuf[j] == 0xFF { if dbuf[j] == 0xFF {
return n, false, CorruptInputError(olen - len(src) - 1) return n, false, CorruptInputError(olen - len(src) - 1)
} }
j++
} }
// Pack 4x 6-bit source blocks into 3 byte destination // Pack 4x 6-bit source blocks into 3 byte destination

View File

@ -149,9 +149,13 @@ func TestDecodeCorrupt(t *testing.T) {
}{ }{
{"", -1}, {"", -1},
{"!!!!", 0}, {"!!!!", 0},
{"====", 0},
{"x===", 1}, {"x===", 1},
{"=AAA", 0},
{"A=AA", 1},
{"AA=A", 2}, {"AA=A", 2},
{"AAA=AAAA", 3}, {"AA==A", 4},
{"AAA=AAAA", 4},
{"AAAAA", 4}, {"AAAAA", 4},
{"AAAAAA", 4}, {"AAAAAA", 4},
{"A=", 1}, {"A=", 1},