# GO-CRYPTO-004: Use of RC4 Stream Cipher

> **Severity:** HIGH | **CWE:** CWE-327 | **OWASP:** A02:2021

- **Language:** Go
- **Category:** Security
- **URL:** https://codepathfinder.dev/registry/golang/security/GO-CRYPTO-004
- **Detection:** `pathfinder scan --ruleset golang/GO-CRYPTO-004 --project .`

## Description

RC4 is a stream cipher designed in 1987. It was widely used in SSL/TLS, WEP (802.11
Wi-Fi), and WPA-TKIP. It has been comprehensively broken and is prohibited in all new
uses by RFC 7465 (February 2015).

**Fluhrer-Mantin-Shamir (FMS) attack (2001)**: RC4's key scheduling algorithm (KSA)
produces statistical biases in early keystream bytes when certain "weak IVs" are used.
In WEP, IVs were transmitted in the clear and incorporated directly into the per-packet
RC4 key. Tools like aircrack-ng automated FMS to recover 128-bit WEP keys from ~100,000
captured packets, completely breaking WEP in practice within months of the FMS publication.

**AlFardan et al. (2013)**: Statistical analysis demonstrated that RC4's keystream biases
allow plaintext recovery in TLS with enough ciphertext samples. The most likely plaintext
byte value at certain positions can be recovered from ~2^24 TLS sessions — demonstrated
against HTTP session cookies in real HTTPS traffic.

**RFC 7465 (February 2015)**: Explicitly prohibits RC4 cipher suites in TLS:
- TLS clients MUST NOT include RC4 cipher suites in ClientHello.
- TLS servers MUST NOT select RC4 when a client offers it.
- If a client offers ONLY RC4, the server MUST terminate the handshake.

RC4 is available in Go's standard library as `crypto/rc4`, which the package documentation
explicitly labels as "cryptographically broken and should not be used for secure applications."
Any use of rc4.NewCipher for security purposes must be replaced with AES-GCM.


## Vulnerable Code

```python
# --- file: vulnerable.go ---
// GO-CRYPTO-004 positive test cases — all SHOULD be detected
package main

import "crypto/rc4"

func brokenRC4Cipher() {
	key := []byte("secretkey")
	_, _ = rc4.NewCipher(key) // SINK: RC4 banned in TLS
}

# --- file: go.mod ---
module example.com/go-crypto-004/positive

go 1.21

# --- file: go.sum ---

```

## Secure Code

```python
// SECURE: AES-GCM stream encryption (authenticated, 128-bit block, no bias)
import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "io"
)

func encryptAESGCM(key, plaintext []byte) ([]byte, error) {
    block, err := aes.NewCipher(key) // 32 bytes = AES-256
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }
    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }
    return gcm.Seal(nonce, nonce, plaintext, nil), nil
}

// SECURE: ChaCha20-Poly1305 (AEAD, no hardware AES requirement, widely used in TLS 1.3)
import "golang.org/x/crypto/chacha20poly1305"

func encryptChaCha20(key, plaintext []byte) ([]byte, error) {
    aead, err := chacha20poly1305.New(key) // 32-byte key
    if err != nil {
        return nil, err
    }
    nonce := make([]byte, aead.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }
    return aead.Seal(nonce, nonce, plaintext, nil), nil
}

```

## Detection Rule (Python SDK)

```python
"""GO-CRYPTO-004: Use of RC4 cipher (broken algorithm)."""

from codepathfinder.go_rule import QueryType
from codepathfinder import flows
from codepathfinder.go_decorators import go_rule


class GoCryptoRC4(QueryType):
    fqns = ["crypto/rc4"]
    patterns = ["rc4.*"]
    match_subclasses = False


@go_rule(
    id="GO-CRYPTO-004",
    severity="HIGH",
    cwe="CWE-327",
    owasp="A02:2021",
    tags="go,security,crypto,rc4,broken-cipher,CWE-327,OWASP-A02",
    message=(
        "Detected use of the RC4 stream cipher (crypto/rc4). "
        "RC4 has multiple statistical biases that allow plaintext recovery. "
        "It is prohibited in TLS (RFC 7465) and should not be used for any purpose. "
        "Use AES-GCM (crypto/aes + crypto/cipher) instead."
    ),
)
def detect_rc4_cipher():
    """Detect use of RC4 cipher (crypto/rc4)."""
    return GoCryptoRC4.method("NewCipher")
```

## How to Fix

- Replace all rc4.NewCipher usage with AES-GCM (crypto/aes + crypto/cipher.NewGCM).
- For environments without hardware AES, consider ChaCha20-Poly1305 (golang.org/x/crypto/chacha20poly1305) — used in TLS 1.3 and WireGuard.
- Never use RC4 in any new protocol, application, or configuration.
- For TLS: Go's crypto/tls defaults are safe — do not override to add RC4 cipher suites.
- Remove any RC4 cipher suites from existing TLS server configurations.

## Security Implications

- **WEP/Wi-Fi Session Decryption:** RC4 with predictable IV construction (as used in WEP) leaks keystream bytes.
aircrack-ng recovers the 128-bit WEP key in minutes using 100,000 captured packets
via the FMS attack. Any RC4 implementation with low-entropy or predictable IVs
is similarly vulnerable.

- **TLS Session Cookie Theft:** AlFardan et al. (2013) demonstrated recovery of HTTP session cookies from TLS
sessions using RC4 by exploiting byte-position biases in RC4's keystream.
After 2^24 TLS connections, individual plaintext bytes at predictable positions
can be recovered with statistically significant probability.

- **Keystream Reuse:** If the same RC4 key is used to encrypt two messages (keystream reuse), XORing
the two ciphertexts gives the XOR of the plaintexts. Given known plaintext
patterns (HTTP headers, protocol markers), full message recovery is possible.


## References

- [RFC 7465 — Prohibiting RC4 Cipher Suites (IETF, February 2015)](https://datatracker.ietf.org/doc/html/rfc7465)
- [On the Security of RC4 in TLS and WPA — AlFardan et al. (USENIX Security 2013)](https://www.isg.rhul.ac.uk/tls/)
- [Fluhrer, Mantin and Shamir (FMS) WEP attack — Wikipedia](https://en.wikipedia.org/wiki/Fluhrer,_Mantin_and_Shamir_attack)
- [FMS attack paper applied to WEP (Stubblefield et al. 2001)](https://www.cs.miami.edu/home/burt/learning/Csc524.052/docs/stubbl.pdf)
- [Go crypto/rc4 package — standard library (labeled cryptographically broken)](https://pkg.go.dev/crypto/rc4)
- [Go golang.org/x/crypto/chacha20poly1305 package](https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305)
- [Go crypto/cipher package — AES-GCM](https://pkg.go.dev/crypto/cipher)
- [CWE-327: Use of a Broken or Risky Cryptographic Algorithm](https://cwe.mitre.org/data/definitions/327.html)

---

Source: https://codepathfinder.dev/registry/golang/security/GO-CRYPTO-004
Code Pathfinder — Open source, type-aware SAST with cross-file dataflow analysis
