A signed payment that grows
A payments app signs each request with sha256(secret + message). Nobody outside knows the secret, so the tag looks safe.
Yet an attacker who sees one signed request can add text to it and make a valid tag, without the secret. You will do that to your own toy, then fix it.
The one rule
Warning
You forge requests only to the toy server in your own lab. Sending forged requests to a real service without written permission is illegal. In the UK it can break the Computer Misuse Act 1990, and forging a payment is fraud too.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can explain a length extension attack and sign messages with HMAC instead.
Key words
| Word | What it means |
|---|---|
| MAC | a tag that proves a message came from a key holder |
| Hash state | the numbers a hash keeps while it reads data |
| Length extension | adding data to a hashed message without the secret |
| HMAC | a MAC built from a hash in a way that resists extension |
| Forgery | a valid tag made by someone without the key |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsThe tag is the hash's state
SHA-256 reads data in 64-byte blocks and updates eight numbers, its state. At the end it adds padding and prints the state as the hash.
So a tag of sha256(secret + message) is the state after the padding. An attacker can load that state and keep hashing more data. The secret is never needed.
Try it: a naive tag and an HMAC
import hashlib
import hmac
key = b"lab key, never a real one"
message = b"to=amy&amount=10"
naive = hashlib.sha256(key + message).hexdigest()
proper = hmac.new(key, message, hashlib.sha256).hexdigest()
print("naive :", naive[:16])
print("HMAC :", proper[:16])
print("same? ", naive == proper)
# Change amount=10 to amount=11. Both tags change completely.
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsForge a bigger payment
sha.py is SHA-256 in plain Python with a state you can set, so you can watch the trick. It checks itself against Python's own hashlib.
extend.py is a server that signs to=amy&amount=10. Then, knowing only that message, its tag and the secret's length, it adds &to=eve&amount=900.
Write SHA-256 in plain Python, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import math' '' 'MASK = 0xFFFFFFFF' '' '' 'def primes(count):' ' found, n = [], 2' ' while len(found) < count:' ' if all(n % p for p in found):' ' found.append(n)' ' n = n + 1' ' return found' '' '' 'def cube_root(n):' ' x = 1 << ((n.bit_length() + 2) // 3)' ' while True:' ' y = (2 * x + n // (x * x)) // 3' ' if y >= x:' ' return x' ' x = y' '' '' 'K = [cube_root(p << 96) & MASK for p in primes(64)]' 'START = [math.isqrt(p << 64) & MASK for p in primes(8)]' '' '' 'def turn(x, n):' ' return ((x >> n) | (x << (32 - n))) & MASK' '' '' 'def squeeze(state, block):' ' w = [int.from_bytes(block[i:i + 4], \"big\") for i in range(0, 64, 4)]' ' for i in range(16, 64):' ' s0 = turn(w[i - 15], 7) ^ turn(w[i - 15], 18) ^ (w[i - 15] >> 3)' ' s1 = turn(w[i - 2], 17) ^ turn(w[i - 2], 19) ^ (w[i - 2] >> 10)' > steps/sha.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write SHA-256 in plain Python, part 2
docker exec jupyter sh -c "printf '%s\n' ' w.append((w[i - 16] + s0 + w[i - 7] + s1) & MASK)' ' a, b, c, d, e, f, g, h = state' ' for i in range(64):' ' t1 = h + (turn(e, 6) ^ turn(e, 11) ^ turn(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]' ' t2 = (turn(a, 2) ^ turn(a, 13) ^ turn(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))' ' a, b, c, d, e, f, g, h = (t1 + t2) & MASK, a, b, c, (d + t1) & MASK, e, f, g' ' return [(x + y) & MASK for x, y in zip(state, [a, b, c, d, e, f, g, h])]' '' '' 'def glue(length):' ' zeros = (55 - length) % 64' ' return bytes([128]) + bytes(zeros) + (length * 8).to_bytes(8, \"big\")' '' '' 'def sha256(data, state=None, done=0):' ' state = list(START) if state is None else list(state)' ' data = data + glue(done + len(data))' ' for at in range(0, len(data), 64):' ' state = squeeze(state, data[at:at + 64])' ' return b\"\".join(x.to_bytes(4, \"big\") for x in state)' >> steps/sha.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the length extension, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import hashlib' 'import os' 'from sha import sha256, glue' '' 'print(\"my SHA-256 matches hashlib:\", sha256(b\"abc\") == hashlib.sha256(b\"abc\").digest())' '' 'SECRET = os.urandom(16)' '' '' 'def sign(message):' ' return hashlib.sha256(SECRET + message).hexdigest()' '' '' 'def accept(message, tag):' ' if not sign(message) == tag:' ' return \"refused\"' ' fields = dict(part.split(b\"=\") for part in message.split(b\"&\"))' ' return \"pay \" + fields[b\"amount\"].decode() + \" to \" + fields[b\"to\"].decode()' '' '' 'message = b\"to=amy&amount=10\"' 'tag = sign(message)' 'print(\"server:\", accept(message, tag))' '' 'extra = b\"&to=eve&amount=900\"' 'padding = glue(16 + len(message))' 'state = [int.from_bytes(bytes.fromhex(tag)[i:i + 4], \"big\") for i in range(0, 32, 4)]' 'done = 16 + len(message) + len(padding)' 'forged_tag = sha256(extra, state, done).hex()' > steps/extend.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the length extension, part 2
docker exec jupyter sh -c "printf '%s\n' 'forged = message + padding + extra' 'print(\"forged message bytes:\", len(forged))' 'print(\"server:\", accept(forged, forged_tag))' >> steps/extend.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Forge the payment
docker exec jupyter python3 steps/extend.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsThe fix: HMAC and a fair compare
HMAC hashes twice with the key mixed in at both ends, so the final state never meets the outside. Python's hmac module does it in one line.
Check a tag with hmac.compare_digest, never == (lesson 5 shows why). SHA-3 and BLAKE2 also resist extension, but HMAC is the rule to remember.
Write the HMAC server, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import hashlib' 'import hmac' 'import os' 'from sha import sha256, glue' '' 'KEY = os.urandom(32)' '' '' 'def sign(message):' ' return hmac.new(KEY, message, hashlib.sha256).hexdigest()' '' '' 'def accept(message, tag):' ' if not hmac.compare_digest(sign(message), tag):' ' return \"refused\"' ' fields = dict(part.split(b\"=\") for part in message.split(b\"&\"))' ' return \"pay \" + fields[b\"amount\"].decode() + \" to \" + fields[b\"to\"].decode()' '' '' 'message = b\"to=amy&amount=10\"' 'tag = sign(message)' 'print(\"server:\", accept(message, tag))' 'extra = b\"&to=eve&amount=900\"' 'state = [int.from_bytes(bytes.fromhex(tag)[i:i + 4], \"big\") for i in range(0, 32, 4)]' 'for guess in range(1, 65):' ' padding = glue(guess + len(message))' ' forged_tag = sha256(extra, state, guess + len(message) + len(padding)).hex()' > steps/hmacfix.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the HMAC server, part 2
docker exec jupyter sh -c "printf '%s\n' ' if not accept(message + padding + extra, forged_tag) == \"refused\":' ' print(\"forgery accepted with key length\", guess)' ' break' 'else:' ' print(\"server: refused every forgery, key lengths 1 to 64\")' >> steps/hmacfix.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Try the same forgery on HMAC
docker exec jupyter python3 steps/hmacfix.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think putting the secret first makes a hash a MAC, because nobody can hash without it. That is exactly the shape length extension breaks. Use HMAC, or the MAC an AEAD already gives you.
Check
Have a go
Check
3 questionsHow a team catches it
A review rule flags any hash of a secret joined to a message: sha256(key + ...) or md5(secret + ...). A unit test asserts the tag equals hmac.new for a known key and message.
Bandit flags MD5 and SHA-1 calls, and a team adds its own rule for the joined secret.
Find the naive tag
docker exec jupyter grep -n "sha256(SECRET" steps/extend.py steps/hmacfix.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: tag with HMAC
Replace a naive sha256(key + message) tag with HMAC.
make_tag(key, message) returns the HMAC-SHA256 of message under key, as hex. check_tag(key, message, tag) returns True only for the right tag, compared with hmac.compare_digest.
import hashlib
import hmac
def make_tag(key, message):
# The HMAC-SHA256 of message under key, as hex.
return ""
def check_tag(key, message, tag):
# True only when tag is the right HMAC. Compare in constant time.
return False
Make a free account to save your work and track your progress.
Exit quiz
Have a go