Перейти к основному содержимому
Padding Oracles, Length Extension & Side-Channel Timing
Урок 14 из 19

Padding Oracles, Length Extension & Side-Channel Timing

Exploit CBC padding oracles, Merkle-Damgard length extension, and non-constant-time timing leaks, and defend systems with AEAD, HMAC, and constant-time comparisons.

Эксперт 36 мин Криптография
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Demonstrate how a CBC padding oracle recovers intermediate decryption states and plaintext byte-by-byte without knowing the key
  • Explain why Merkle-Damgard hashes such as SHA-256 leak internal chaining state and allow MAC forgery on H(secret || message)
  • Identify timing side channels in byte-by-byte equality checks and secret-dependent branches
  • Mitigate all three classes using AEAD (AES-GCM or ChaCha20-Poly1305), HMAC or SHA-3, and constant-time verification

Рекомендуется заранее: Симметричное шифрование: AES, режимы блоков и AEADКриптографическое хеширование, KDF для паролей и HMACКоды аутентификации сообщений (HMAC) и целостностьМодели криптографических атак и ошибки реализации

#Why this matters

Strong primitives such as AES-256 and SHA-256 rarely break through brute force. Instead, systems fail when implementations leak decryption metadata per request, expose hash chaining state in naive MACs, or exit early when comparing secrets.

These three flaws define modern implementation cryptanalysis: CBC padding oracles break confidentiality without the AES key, length-extension attacks forge tags on H(secret || message), and timing side channels extract secrets byte by byte.

#CBC padding oracle attacks

In 16-byte AES-CBC mode, plaintext is padded with PKCS#7 before encryption: if k padding bytes are needed (1 <= k <= 16), each appended byte holds value k (0x01, 0x02 0x02, and so on, up to a full block of sixteen 0x10 bytes). During decryption of block C_i, the cipher computes the raw intermediate block I_i = D_K(C_i) and XORs it with the previous ciphertext block C_{i-1} (or IV when i = 1):

P_i[j] = I_i[j] XOR C_{i-1}[j]

A padding oracle exists whenever a server decrypts an attacker-controlled ciphertext and reveals whether PKCS#7 unpadding succeeded - through distinct HTTP status codes (500 vs 400), error strings ("Invalid padding" vs "Invalid JSON"), or response time.

Probing the final byte of block P_i through a padding oracleProbing the final byte of block P_i through a padding oracleAttackerServerSend C'_{i-1} || C_i (byte 15 = g)P'_i = D_K(C_i) XOR C'_{i-1}; check PKCS#7500 Invalid Padding (when P'_i[15] != 0x01)Send C'_{i-1} || C_i (byte 15 = g')200 or 400 Invalid Token (padding valid!)Now I_i[15] = g' XOR 0x01, so P_i[15] = I_i[15] XOR C_{i-1}[15]

To recover P_i byte by byte from index 15 down to 0:

  1. Send a crafted two-block payload C'_{i-1} || C_i and vary C'_{i-1}[15] across 0..255 until the oracle accepts the padding.
  2. Verify it is 0x01 (not an accidental 0x02 0x02 tail) by flipping C'_{i-1}[14]; if padding stays valid, P'_i[15] is truly 0x01.
  3. Compute the intermediate byte I_i[15] = C'_{i-1}[15] XOR 0x01, then recover the real plaintext byte P_i[15] = I_i[15] XOR C_{i-1}[15].
  4. To solve byte 14, set C'_{i-1}[15] = I_i[15] XOR 0x02 so the tail byte becomes 0x02, then brute-force C'_{i-1}[14] until the oracle signals valid 0x02 0x02 padding. Repeat across all 16 bytes.

Each 16-byte block requires at most 16 * 256 = 4096 oracle queries (around 2048 on average). The exact same intermediate-state recovery works in reverse (CBC-R): an attacker who can query the oracle can forge an arbitrary multi-block plaintext by solving I_i from right to left and setting C_{i-1} = I_i XOR desired_plaintext_i.

Recovering a single CBC block once an oracle function exists
def decrypt_block(prev_block: bytes, target_block: bytes, oracle) -> bytes:
    intermediate = bytearray(16)
    plaintext = bytearray(16)
    for pos in range(15, -1, -1):
        pad_val = 16 - pos
        prefix = bytearray(16)
        for k in range(pos + 1, 16):
            prefix[k] = intermediate[k] ^ pad_val
        for guess in range(256):
            prefix[pos] = guess
            if oracle(bytes(prefix) + target_block):
                # Guard against false 0x02 0x02 match when solving pos == 15
                if pos == 15:
                    probe = bytearray(prefix)
                    probe[14] ^= 1
                    if not oracle(bytes(probe) + target_block):
                        continue
                intermediate[pos] = guess ^ pad_val
                plaintext[pos] = intermediate[pos] ^ prev_block[pos]
                break
    return bytes(plaintext)

#Hash length-extension attacks

Merkle-Damgard hash functions (MD5, SHA-1, SHA-256, SHA-512) process input in fixed-size blocks (64 bytes for SHA-256; 128 bytes for SHA-512). The compression function updates an internal chaining state one block at a time, and pads the final block with 0x80, zero bytes, and a 64-bit big-endian bit length (128-bit for SHA-512).

When an application authenticates messages with tag = SHA256(secret || message), the output digest is the full 256-bit internal chaining state right after processing secret || message || md_pad. An attacker who knows message, the original tag, and len(secret) (or guesses len(secret) over a small range) does not need secret:

  1. Load tag into the SHA-256 chaining registers as the initial state and set the processed byte counter to the padded block boundary len(secret || message || md_pad).
  2. Feed an arbitrary suffix extension (for example, &role=admin) through SHA-256 compression.
  3. Submit message || md_pad || extension together with the newly computed digest. The server hashes secret || message || md_pad || extension and produces the exact same digest.
Forging SHA-256(secret || message) with hashpumpy in a lab
import hashpumpy

orig_msg = b"role=guest"
orig_sig = "9b2a4f..."  # SHA256(secret || b"role=guest") from lab endpoint
for key_len in range(8, 33):
    forged_sig, forged_msg = hashpumpy.hashpump(
        orig_sig, orig_msg, b"&role=admin", key_len
    )
    # Submit (forged_msg, forged_sig) to the lab verifier until accepted

Length extension fails completely against HMAC (H((K XOR opad) || H((K XOR ipad) || message)), RFC 2104) because the outer hash wraps the inner state with the secret key. SHA-3 (Keccak) and KMAC are also immune because the sponge construction hides its internal capacity bits from the output.

#Side-channel timing attacks

Even when math and message formats are sound, non-constant-time execution leaks secrets through timing.

  • Early-exit string or MAC comparisons: Standard equality (== in Python or memcmp in C) returns False at the first mismatched byte. Over a local link or averaged across hundreds of samples per byte over a network to smooth out jitter, an attacker tests 256 values at index 0 until one takes slightly longer (meaning byte 0 matched and execution reached index 1), reducing a 256^32 tag space to at most 32 * 256 = 8192 probes.
  • Secret-dependent branches and cache lookups: Classic square-and-multiply modular exponentiation branches on each bit of private exponent d, while naive software AES T-table lookups index memory using secret key bytes, allowing local co-tenants to infer key bits via CPU cache timing.
Vulnerability Root cause Attacker requirement Mitigation
CBC padding oracle Unpadded check before auth Chosen-ciphertext queries AEAD or Encrypt-then-MAC
Length extension Raw H(secret || msg) state leak Known msg, tag, len(secret) HMAC (RFC 2104) or SHA-3/KMAC
Timing leak Early-exit == or secret branch Repeated latency samples hmac.compare_digest / constant-time

#Defending and common mistakes

  • Use AEAD by default: Choose AES-GCM or ChaCha20-Poly1305 (as mandated in TLS 1.3, RFC 8446). When legacy CBC is unavoidable, use Encrypt-then-MAC: verify an HMAC over IV || C in constant time before decrypting or checking padding. Never use MAC-then-Encrypt (which enabled Lucky13 and POODLE).
  • Use HMAC or KMAC: Never build H(secret || message). Use hmac.new(..., hashlib.sha256) or SHA-3/KMAC.
  • Compare secrets in constant time: Use hmac.compare_digest() in Python, crypto.timingSafeEqual() in Node.js, or subtle.ConstantTimeCompare() in Go.
  • Common mistakes: Returning 400 Bad Request on both padding and JSON errors while taking longer to parse JSON when padding succeeds (a timing padding oracle); checking hmac.new(...).hexdigest() == tag with == instead of compare_digest.

#Summary

  • CBC padding oracles convert any observable PKCS#7 validation difference into block-by-block plaintext recovery (<= 4096 queries per block) and arbitrary forgery (CBC-R).
  • Merkle-Damgard hashes such as SHA-256 expose their internal state in the digest, enabling length extension on H(secret || message).
  • Early-exit comparisons and secret-dependent branches leak secret bytes via latency differences.
  • Prevent all three with AEAD (or Encrypt-then-MAC), HMAC or SHA-3/KMAC, and constant-time comparisons.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания