Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Padding oracles and honest error messages

After this lesson: I can explain how a padding oracle leaks a message and close it with one error and an AEAD.

65 min lesson7 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

An error message that says too much

A college app keeps who you are in an encrypted cookie. When a cookie is wrong, the app is helpful. It says "bad padding" or "bad cookie".

That small kindness is enough to read the whole cookie without the key. You will build the toy, watch it leak, and close it.

The one rule

Warning

You attack only the toy service you write in your own lab. Sending crafted cookies to a real site needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can explain how a padding oracle leaks a message and close it with one error and an AEAD.

Key words

WordWhat it means
Paddingbytes added so data fills its last block
PKCS#7padding of n bytes, each worth n
CBCa mode that mixes each block with the one before
Oracleanything that answers a question an attacker should not ask
Side channelinformation leaked by how a system behaves

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Padding fills the last block

AES in CBC mode needs whole 16-byte blocks. PKCS#7 padding adds n bytes, each with the value n. A 4-byte text gets twelve bytes of 12.

When the server decrypts, it checks the padding first. If it then says whether the padding was right, it is answering a question about the plaintext.

Try it: pad three texts

Code: python
def pad(data, size=16):
    n = size - len(data) % size
    return data + bytes([n]) * n

for text in [b"exam", b"room 4 at nine", b"0123456789abcdef"]:
    padded = pad(text)
    print(len(text), "bytes ->", len(padded), "bytes, last byte", padded[-1])
# Try a text of exactly 15 bytes. What is the last byte?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Two different errors are an oracle

In CBC, changing a byte of one block changes the same byte of the next block's plaintext. An attacker changes a byte and asks the server.

When the answer is "bad cookie" instead of "bad padding", the padding came out right. That reveals one plaintext byte. About 128 tries a byte read the whole cookie.

Write the toy cookie service

Command
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives import padding' 'from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes' '' 'KEY = os.urandom(16)' 'asked = [0]' '' '' 'def make_cookie():' '    text = b\"user=amy role=student exam=room 4\"' '    padder = padding.PKCS7(128).padder()' '    data = padder.update(text) + padder.finalize()' '    iv = os.urandom(16)' '    box = Cipher(algorithms.AES(KEY), modes.CBC(iv)).encryptor()' '    return iv + box.update(data) + box.finalize()' '' '' 'def check(cookie):' '    asked[0] = asked[0] + 1' '    iv, body = cookie[:16], cookie[16:]' '    box = Cipher(algorithms.AES(KEY), modes.CBC(iv)).decryptor()' '    data = box.update(body) + box.finalize()' '    try:' '        unpadder = padding.PKCS7(128).unpadder()' '        unpadder.update(data) + unpadder.finalize()' '    except ValueError:' '        return \"bad padding\"' '    return \"bad cookie\"' > steps/oracle.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the attack script, part 1

Command
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import importlib' 'import sys' '' 'service = importlib.import_module(sys.argv[1] if len(sys.argv) > 1 else \"oracle\")' 'cookie = service.make_cookie()' 'answers = set()' 'for guess in range(256):' '    probe = bytearray(cookie)' '    if guess == probe[-17]:' '        continue' '    probe[-17] = guess' '    answers.add(service.check(bytes(probe)))' 'print(\"answers to 255 changed cookies:\", sorted(answers))' 'if len(answers) < 2:' '    print(\"one answer for everything: nothing to learn\")' '    sys.exit(0)' '' 'blocks = [cookie[at:at + 16] for at in range(0, len(cookie), 16)]' 'found = b\"\"' 'for n in range(1, len(blocks)):' '    before, target = blocks[n - 1], blocks[n]' '    middle = bytearray(16)' '    for pad in range(1, 17):' '        at = 16 - pad' '        for guess in range(256):' '            fake = bytearray(16)' '            for k in range(at + 1, 16):' > steps/attack.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the attack script, part 2

Command
docker exec jupyter sh -c "printf '%s\n' '                fake[k] = middle[k] ^ pad' '            fake[at] = guess' '            if service.check(bytes(fake) + target) == \"bad padding\":' '                continue' '            if pad == 1 and at > 0:' '                fake[at - 1] = fake[at - 1] ^ 1' '                if service.check(bytes(fake) + target) == \"bad padding\":' '                    continue' '            middle[at] = guess ^ pad' '            break' '    found = found + bytes(m ^ b for m, b in zip(middle, before))' 'print(\"recovered:\", found[: -found[-1]].decode())' 'print(\"questions asked:\", service.asked[0])' >> steps/attack.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Read the cookie through the oracle

Command
docker exec jupyter python3 steps/attack.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The fix: one answer and an AEAD

First, give one answer for every failure: "refused". Second, check integrity before anything else. An AEAD such as AES-GCM checks its tag first, so a changed cookie is refused before padding exists.

If CBC must stay, use encrypt-then-MAC: check an HMAC over the IV and ciphertext before decrypting. sealed.py uses AES-GCM.

Write the sealed service

Command
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives.ciphers.aead import AESGCM' '' 'KEY = AESGCM.generate_key(bit_length=128)' 'asked = [0]' '' '' 'def make_cookie():' '    nonce = os.urandom(12)' '    return nonce + AESGCM(KEY).encrypt(nonce, b\"user=amy role=student exam=room 4\", b\"cookie\")' '' '' 'def check(cookie):' '    asked[0] = asked[0] + 1' '    try:' '        AESGCM(KEY).decrypt(cookie[:12], cookie[12:], b\"cookie\")' '    except Exception:' '        return \"refused\"' '    return \"ok\"' > steps/sealed.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Attack the sealed service

Command
docker exec jupyter python3 steps/attack.py sealed

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think hiding the words fixes it, so "error 1" and "error 2" feel safe. Any difference counts: a different code, length or time. Refuse every failure the same way, and let the AEAD check the tag first.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

How a team catches it

In review, look at every decrypt path. More than one kind of failure reaching the caller is a finding. A test sends a changed ciphertext and asserts the single answer.

In production, an attack sends thousands of failing cookies from one client. An alert on a burst of decrypt failures catches it early.

Find the two answers in the code

Command
docker exec jupyter grep -n "return \"bad" steps/oracle.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: padding and one answer

Write PKCS#7 padding with strict checking, and the one answer a service gives.

pad(data, size) adds n bytes worth n so the length is a multiple of size (a full block when it already is). unpad(data, size) returns the data without padding, or None when the length or the padding is wrong. public_answer(problem) returns "ok" when problem is None and "refused" for any problem.

Code: python
def pad(data, size):
    # PKCS#7: add n bytes, each worth n, so the length is a multiple of size.
    return data


def unpad(data, size):
    # Return data without its padding, or None when the padding is not valid.
    return data


def public_answer(problem):
    # problem is None when all went well, else a word such as "padding" or "tag".
    # Return "ok" or one answer for every problem.
    return problem

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.