Padding and the Padding-Oracle Idea
CBC encrypts whole 16-byte blocks, so a 5-byte message has to be padded first and the padding removed after decryption. That small step created one of the most productive attack classes in applied cryptography: if a server reveals, in any way, whether the padding of a ciphertext it received was valid, an attacker can decrypt messages without the key, one byte at a time. The attack works against unauthenticated CBC; the fix is to authenticate before you decrypt, which in practice means using an AEAD.
PKCS#7 padding
PKCS#7 (RFC 5652; for AES it is also called PKCS#5 padding) appends n bytes, each of value n, where n is between 1 and 16. A message that already fills its last block gets a whole extra block of 0x10 bytes, so the padding can always be removed unambiguously.
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
for msg in (b"HELLO", b"0123456789ABCDEF"):
p = padding.PKCS7(128).padder()
padded = p.update(msg) + p.finalize()
print(f"{msg!r:20} -> {len(padded)} bytes, last bytes {padded[-3:].hex(' ')}")
# A toy server, made by this example: decrypts CBC and answers ONLY "padding ok" or "padding bad".
KEY = bytes(range(16)); IV = bytes(16) # fixed toy values
def toy_encrypt(msg):
p = padding.PKCS7(128).padder(); data = p.update(msg) + p.finalize()
e = Cipher(algorithms.AES(KEY), modes.CBC(IV)).encryptor()
return e.update(data) + e.finalize()
def toy_oracle(iv, block): # the leak: a distinguishable padding error
d = Cipher(algorithms.AES(KEY), modes.CBC(iv)).decryptor()
data = d.update(block) + d.finalize()
n = data[-1]
return 1 <= n <= 16 and data[-n:] == bytes([n]) * n
ct = toy_encrypt(b"PIN=4821") # one block
queries = 0
for guess in range(256): # try every value for the last byte of a fake IV
fake_iv = bytearray(16); fake_iv[15] = guess
queries += 1
if toy_oracle(bytes(fake_iv), ct):
# check it is 0x01 padding and not a longer one by disturbing byte 14
fake_iv[14] ^= 1
if toy_oracle(bytes(fake_iv), ct):
last = guess ^ 0x01 ^ IV[15]
print(f"after {queries} queries: last plaintext byte = {last:#04x} ({last} = padding length 8)")
breakb'HELLO' -> 16 bytes, last bytes 0b 0b 0b
b'0123456789ABCDEF' -> 32 bytes, last bytes 10 10 10
after 10 queries: last plaintext byte = 0x08 (8 = padding length 8)
HELLO gets eleven bytes of 0x0b; the full 16-byte block gets a second block of sixteen 0x10.
The mechanism
In CBC, the last plaintext block is P = D(K, C) ⊕ C_prev, where C_prev is the previous ciphertext block (or the IV). The attacker can't compute D(K, C), but they choose C_prev: they send the server the pair (fake previous block, C). The server decrypts and checks the padding. Only one value of the last byte of the fake block makes the decrypted last byte equal to 0x01, which is valid padding. When the server says "padding ok", the attacker knows:
D(K, C)[15] XOR guess = 0x01 => D(K, C)[15] = guess XOR 0x01
real plaintext byte = D(K, C)[15] XOR real_previous_block[15]The toy above does exactly this for the last byte of a block that the example itself encrypted and a "server" function it defines: after at most 256 queries (here 10), it knows the last plaintext byte, 0x08, the padding length of PIN=4821. The second check rules out the rare false positive where the guess produced a longer valid padding such as 02 02. Repeating the trick with target padding 02 02, 03 03 03 and so on recovers the whole block, then every block, with at most 256 queries per byte: at most 4,096 queries for a 16-byte block, about half that on average. The attacker never learns the key; the server decrypts for them.
The attack was described by Serge Vaudenay in 2002 and has reappeared many times: ASP.NET's WebResource.axd (2010, MS10-070), the TLS Lucky Thirteen timing attack on CBC records (2013), and POODLE against SSL 3.0 (2014), whose padding bytes weren't checked at all (only the final length byte).
The oracle doesn't have to be an error message
Any observable difference between "bad padding" and "bad MAC" or "bad content" is an oracle:
- distinct error codes or messages (
500 padding errorversus403 invalid token); - different response times, because the MAC is only computed when the padding is valid (Lucky Thirteen measured differences of microseconds over a network);
- different log entries, redirects or retry behaviour.
How it is detected
- Code review: CBC decryption followed by a padding check, with the MAC (if any) verified afterwards or computed over the plaintext (MAC-then-encrypt); exception handlers that distinguish
ValueError: Invalid paddingfrom other failures. - Testing your own service (in scope): send a valid ciphertext with the last byte of the second-to-last block changed, and compare status codes, bodies and response times with a ciphertext whose content is corrupted. Any systematic difference is a finding.
- Monitoring: a single client producing thousands of decryption failures in a short time on one endpoint.
How it is fixed
- Use an AEAD (AES-GCM, ChaCha20-Poly1305). The tag is verified before any plaintext exists, there is no padding, and every failure is the same
InvalidTag. - If CBC must stay: encrypt-then-MAC. Compute HMAC-SHA-256 over IV and ciphertext with a separate key, verify it in constant time first, and only then decrypt. Forged ciphertexts never reach the padding check.
- Return one generic error for every decryption failure, and make failures take the same time. This is a mitigation, not a fix: timing differences are hard to remove completely, as Lucky Thirteen showed.
TLS 1.3 removed CBC cipher suites entirely; every TLS 1.3 record is AEAD-protected.
Pitfalls
- MAC-then-encrypt (MAC over the plaintext, then encrypt both): the receiver must decrypt and unpad before it can check the MAC, so the oracle is still there. TLS 1.0–1.2 CBC suites work this way, which is why they kept needing patches.
- Treating a padding error as harmless because "it reveals nothing secret". It reveals one bit per query, and that is enough.
- Writing your own unpadding code that throws a different exception from the MAC check.
Practice
1. A legacy API returns HTTP 500 for "bad padding" and HTTP 401 for "bad signature". Rewrite the error handling so it is no longer an oracle.
Verify an HMAC over IV and ciphertext first, in constant time, and return the same 401 (same body, same code path) for any failure, including padding. Better, migrate the tokens to AES-GCM.
2. Why does the toy attack need at most 256 queries per byte?
The last byte of the fake previous block has 256 possible values, and exactly one (barring the longer-padding false positive) makes the decrypted byte equal to the target padding value.
3. Does encrypt-then-MAC stop the padding oracle even if the error messages differ? Why?
Yes. A forged or modified ciphertext fails the MAC check, which happens before decryption, so the padding of attacker-made ciphertexts is never examined. Different messages for "bad MAC" and "bad padding" can't leak anything, because only genuine ciphertexts ever reach the padding step.
Test yourself
What does PKCS#7 append to a message that already fills a whole 16-byte block?
- Nothing
- One byte 0x01
- A full block of sixteen 0x10 bytes
- Sixteen zero bytes
What does a padding oracle let an attacker do?
- Recover the key directly
- Decrypt ciphertexts byte by byte by asking the server whether padding is valid
- Sign messages
- Speed up AES
Which order of operations prevents the padding oracle?
- MAC-then-encrypt
- Encrypt-then-MAC, verifying the MAC before decrypting
- Encrypt-and-MAC over the plaintext
- Decrypt first, then check the MAC
Why are TLS 1.3 records immune to padding-oracle attacks?
- They use longer keys
- TLS 1.3 only allows AEAD ciphers, with no CBC suites
- They are compressed
- They use RSA