A password checker with a stopwatch
An API checks a secret token with ==. Python's == stops at the first character that differs, so a better guess takes slightly longer to refuse.
With enough tries, an attacker can time the refusals and read the token one character at a time. You will do it to your own toy.
The one rule
Warning
You time only the toy checker in your own lab. Timing a real service's login to guess a secret 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 questionsBy the end of this lesson
Note
I can show how a timing leak reveals a secret and compare secrets in constant time.
Key words
| Word | What it means | Example |
|---|---|---|
| Timing attack | learning a secret from how long an answer takes | |
| Early exit | stopping a loop as soon as the answer is known | |
| Constant time | taking the same time whatever the input matches | |
| Median | the middle value, which ignores rare slow tries | |
| compare_digest | Python's constant-time comparison | hmac.compare_digest(a, b) |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsAn early exit leaks how much matched
A normal compare checks one character, then the next, and stops at the first difference. A guess with three right characters does three steps; one with none does one.
Each step is tiny, nanoseconds. An attacker repeats each guess many times and keeps the middle time, the median, which ignores the rare slow try.
Try it: count the steps of a compare
def leaky_steps(given, real):
steps = 0
for a, b in zip(given, real):
steps = steps + 1
if a != b:
break
return steps
real = "7f3a9c"
for guess in ["000000", "700000", "7f0000", "7f3000"]:
print(guess, "takes", leaky_steps(guess, real), "steps")
# Try "7f3a90". Each right character costs one more step.
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsRead a token with a stopwatch
timing.py holds a random 6-character token. Its leaky compare waits 10 milliseconds for each matching character, so the leak shows in a busy lab. A real one leaks far less, and an attacker makes up for it with more tries.
The attack tries all 16 characters at each place and keeps the slowest. It takes a little while.
Write the timing toy, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import hmac' 'import secrets' 'import statistics' 'import sys' 'import time' '' 'TOKEN = secrets.token_hex(3)' '' '' 'def leaky_equal(given, real):' ' if not len(given) == len(real):' ' return False' ' for a, b in zip(given, real):' ' if not a == b:' ' return False' ' time.sleep(0.01)' ' return True' '' '' 'def fair_equal(given, real):' ' return hmac.compare_digest(given, real)' '' '' 'check = fair_equal if \"fixed\" in sys.argv else leaky_equal' '' '' 'def how_long(guess):' ' times = []' ' for n in range(5):' ' start = time.perf_counter()' ' check(guess, TOKEN)' ' times.append(time.perf_counter() - start)' ' return statistics.median(times)' '' '' 'known = \"\"' 'for place in range(len(TOKEN)):' ' best = max(\"0123456789abcdef\", key=lambda c: how_long(known + c + \"0\" * (5 - place)))' ' known = known + best' > steps/timing.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the timing toy, part 2
docker exec jupyter sh -c "printf '%s\n' 'print(\"compare:\", check.__name__)' 'print(\"guessed:\", known)' 'print(\"right:\", known == TOKEN)' >> steps/timing.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Time the leaky compare
docker exec jupyter python3 steps/timing.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsThe fix: compare in constant time
hmac.compare_digest(a, b) looks at every byte whatever matches, so its time says nothing about the guess. Use it for tokens, tags, API keys and reset codes.
Better still, compare a hash or HMAC of the secret, and never write your own loop for it. Run the same attack on the fixed compare.
Time the constant-time compare
docker exec jupyter python3 steps/timing.py fixedShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a network hides tiny timing differences, so == is fine on a server. Averaging thousands of tries pulls a small difference out of noise. Compare secrets with hmac.compare_digest wherever they are checked.
Check
Have a go
Check
3 questionsHow a team catches it
A review rule flags == on anything named token, tag, mac, signature or key. Lesson 6 writes that rule as a small linter.
A test can check that a function calls compare_digest. Rate limits and lockouts also make thousands of timed tries hard to collect.
Find the early exit
docker exec jupyter grep -n "return False" steps/timing.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: steps and a fair compare
Measure the leak, then write a compare without one.
steps_taken(given, real) returns how many characters an early-exit compare looks at: up to and including the first difference, the whole length for a match, and 0 when the lengths differ. fair_equal(given, real) returns True only when the strings are equal, looking at every character whatever matches (combine differences with XOR and OR, then test once).
def steps_taken(given, real):
# How many characters an early-exit compare looks at. 0 if the lengths differ.
return 0
def fair_equal(given, real):
# True when equal. Look at every character, whatever matches.
return False
Make a free account to save your work and track your progress.
Exit quiz
Have a go