Skip to content

Commit

Permalink
panic if rc4 xor'ed buffer doesn't fit into output buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
qmuntal committed Oct 13, 2023
1 parent 78dacc3 commit 5f92ea4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions rc4.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ func (c *RC4Cipher) XORKeyStream(dst, src []byte) {
if inexactOverlap(dst[:len(src)], src) {
panic("crypto/rc4: invalid buffer overlap")
}
// panic if len(dst) < len(src) with a runtime out of bound error,
// which is what crypto/rc4 does.
_ = dst[len(src)-1]
var outLen C.int
if C.go_openssl_EVP_EncryptUpdate(c.ctx, base(dst), &outLen, base(src), C.int(len(src))) != 1 {
panic("crypto/cipher: EncryptUpdate failed")
Expand Down
23 changes: 23 additions & 0 deletions rc4_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,29 @@ func TestRC4Block(t *testing.T) {
}
}

func TestRC4OutOfBoundsWrite(t *testing.T) {
// This cipherText is encrypted "0123456789"
cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63}
cipher, err := openssl.NewRC4Cipher([]byte{0})
if err != nil {
panic(err)
}
want := "abcdefghij"
plainText := []byte(want)
shorterLen := len(cipherText) / 2
defer func() {
err := recover()
if err == nil {
t.Error("XORKeyStream expected to panic on len(dst) < len(src), but didn't")
}
const plain = "0123456789"
if plainText[shorterLen] == plain[shorterLen] {
t.Errorf("XORKeyStream did out of bounds write, want %v, got %v", want, string(plainText))
}
}()
cipher.XORKeyStream(plainText[:shorterLen], cipherText)
}

func benchmarkRC4(b *testing.B, size int64) {
if !openssl.SupportsRC4() {
b.Skip("RC4 is not supported")
Expand Down

0 comments on commit 5f92ea4

Please sign in to comment.