Skip to content

Commit 5f92ea4

Browse files
committed
panic if rc4 xor'ed buffer doesn't fit into output buffer
1 parent 78dacc3 commit 5f92ea4

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

rc4.go

+3
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ func (c *RC4Cipher) XORKeyStream(dst, src []byte) {
5252
if inexactOverlap(dst[:len(src)], src) {
5353
panic("crypto/rc4: invalid buffer overlap")
5454
}
55+
// panic if len(dst) < len(src) with a runtime out of bound error,
56+
// which is what crypto/rc4 does.
57+
_ = dst[len(src)-1]
5558
var outLen C.int
5659
if C.go_openssl_EVP_EncryptUpdate(c.ctx, base(dst), &outLen, base(src), C.int(len(src))) != 1 {
5760
panic("crypto/cipher: EncryptUpdate failed")

rc4_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,29 @@ func TestRC4Block(t *testing.T) {
138138
}
139139
}
140140

141+
func TestRC4OutOfBoundsWrite(t *testing.T) {
142+
// This cipherText is encrypted "0123456789"
143+
cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63}
144+
cipher, err := openssl.NewRC4Cipher([]byte{0})
145+
if err != nil {
146+
panic(err)
147+
}
148+
want := "abcdefghij"
149+
plainText := []byte(want)
150+
shorterLen := len(cipherText) / 2
151+
defer func() {
152+
err := recover()
153+
if err == nil {
154+
t.Error("XORKeyStream expected to panic on len(dst) < len(src), but didn't")
155+
}
156+
const plain = "0123456789"
157+
if plainText[shorterLen] == plain[shorterLen] {
158+
t.Errorf("XORKeyStream did out of bounds write, want %v, got %v", want, string(plainText))
159+
}
160+
}()
161+
cipher.XORKeyStream(plainText[:shorterLen], cipherText)
162+
}
163+
141164
func benchmarkRC4(b *testing.B, size int64) {
142165
if !openssl.SupportsRC4() {
143166
b.Skip("RC4 is not supported")

0 commit comments

Comments
 (0)