A reset link anyone can guess
A site emails a password-reset link with a 32-character token. It looks impossible to guess.
But the token comes from Python's random module. An attacker who asks for enough resets on their own account can predict the next one, sent to somebody else.
The one rule
Warning
You predict tokens only from the toy service in your own lab. Requesting resets on a real site to predict other people's is illegal without written permission. In the UK 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 why the random module is predictable and make secrets with the secrets module.
Key words
| Word | What it means | Example |
|---|---|---|
| PRNG | a program that makes numbers that look random | |
| Seed | the starting value that fixes every later number | |
| Mersenne Twister | the PRNG behind Python's random module | |
| CSPRNG | a PRNG safe for secrets, fed by the operating system | |
| Linter | a program that reads code and flags risky patterns | Bandit |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsThe random module is predictable by design
random uses the Mersenne Twister. It is fast and fine for games and sampling, and it is predictable. The same seed gives the same numbers, and a seed taken from the clock can be guessed.
Worse, 624 outputs of 32 bits reveal its whole state. After that, every later number is known.
Try it: one seed, the same numbers
import random
import secrets
one = random.Random(1763800000)
two = random.Random(1763800000)
print(one.getrandbits(32), two.getrandbits(32))
print(len(secrets.token_urlsafe(32)), "characters from secrets")
# The seed is a time in seconds. Change it by 1: are the numbers still equal?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsPredict the admin's reset token
resets.py makes tokens with random.getrandbits(128). predict.py asks for 156 tokens for its own account, which is 624 numbers of 32 bits. It undoes the generator's final mixing step and copies its state.
Then it predicts the next token, the one the service sends to the admin.
Write the reset service
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import random' '' '' 'def reset_token():' ' return format(random.getrandbits(128), \"032x\")' > steps/resets.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the prediction, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import random' 'from resets import reset_token' '' 'MASK = 0xFFFFFFFF' '' '' 'def undo_right(y, s):' ' x = y' ' for n in range(6):' ' x = y ^ (x >> s)' ' return x' '' '' 'def undo_left(y, s, mask):' ' x = y' ' for n in range(6):' ' x = y ^ ((x << s) & mask)' ' return x & MASK' '' '' 'def untemper(y):' ' y = undo_right(y, 18)' ' y = undo_left(y, 15, 0xEFC60000)' ' y = undo_left(y, 7, 0x9D2C5680)' ' return undo_right(y, 11)' '' '' 'words = []' 'for n in range(156):' ' value = int(reset_token(), 16)' ' words.extend((value >> (32 * i)) & MASK for i in range(4))' 'print(\"tokens collected from my own account:\", len(words) // 4)' '' 'copy = random.Random()' 'copy.setstate((3, tuple(untemper(w) for w in words) + (624,), None))' 'predicted = format(copy.getrandbits(128), \"032x\")' 'admin = reset_token()' 'print(\"predicted next token:\", predicted[:8] + \"...\")' > steps/predict.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the prediction, part 2
docker exec jupyter sh -c "printf '%s\n' 'print(\"matches the token sent to the admin:\", predicted == admin)' >> steps/predict.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Predict the next token
docker exec jupyter python3 steps/predict.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsThe fix: the secrets module
secrets reads the operating system's CSPRNG, which cannot be predicted from its outputs. secrets.token_urlsafe(32) gives 32 random bytes, 256 bits, as 43 URL-safe characters.
Use it for reset links, session ids, API keys and nonces. Keep random for simulations and games.
Write the strong tokens
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import secrets' '' 'tokens = set(secrets.token_urlsafe(32) for n in range(10000))' 'one = secrets.token_urlsafe(32)' 'print(\"token length:\", len(one), \"characters\")' 'print(\"random bits in it:\", 32 * 8)' 'print(\"different tokens in 10000:\", len(tokens))' > steps/safe.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Make strong tokens
docker exec jupyter python3 steps/safe.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a long token is a safe token. Length only counts if every bit is unpredictable. A 128-bit token from random fell to 156 requests; use secrets for anything an attacker must not guess.
One review rule for the whole module
Each misuse in this module leaves a pattern a program can spot. Think of random for secrets, MD5 or SHA-1 tags, == on a tag, a fixed nonce and ECB. A linter checks every change for them.
Bandit flags several (B311 for random, B324 for weak hashes). cryptolint.py is a small checker of your own, run on a file with all of them.
Write the code to review
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import hashlib' 'import random' 'from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes' '' 'NONCE = bytes(12)' '' '' 'def new_reset_token():' ' return str(random.random())' '' '' 'def sign(key, message):' ' return hashlib.md5(key + message).hexdigest()' '' '' 'def check(key, message, tag):' ' return sign(key, message) == tag' '' '' 'def box(key):' ' return Cipher(algorithms.AES(key), modes.ECB())' > steps/review.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the fixed code
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import hashlib' 'import hmac' 'import os' 'import secrets' 'from cryptography.hazmat.primitives.ciphers.aead import AESGCM' '' '' 'def new_reset_token():' ' return secrets.token_urlsafe(32)' '' '' 'def sign(key, message):' ' return hmac.new(key, message, hashlib.sha256).hexdigest()' '' '' 'def check(key, message, tag):' ' return hmac.compare_digest(sign(key, message), tag)' '' '' 'def seal(key, message):' ' nonce = os.urandom(12)' ' return nonce + AESGCM(key).encrypt(nonce, message, None)' > steps/fixed.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the crypto linter, part 1
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import ast' 'import sys' '' 'RULES = {' ' \"random\": \"random module: use secrets for anything secret\",' ' \"md5\": \"MD5: use HMAC-SHA256 for a tag\",' ' \"sha1\": \"SHA-1: use HMAC-SHA256 for a tag\",' ' \"ECB\": \"ECB mode: use AES-GCM or ChaCha20-Poly1305\",' '}' 'WORDS = (\"tag\", \"token\", \"mac\", \"sig\", \"digest\")' '' 'path = sys.argv[1]' 'tree = ast.parse(open(path).read())' 'found = set()' 'for node in ast.walk(tree):' ' if isinstance(node, ast.Attribute):' ' name = node.value.id if isinstance(node.value, ast.Name) else node.attr' ' if name in RULES:' ' found.add((node.lineno, RULES[name]))' ' elif node.attr in RULES:' ' found.add((node.lineno, RULES[node.attr]))' ' if isinstance(node, ast.Assign):' ' target = getattr(node.targets[0], \"id\", \"\")' ' value = node.value' > steps/cryptolint.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the crypto linter, part 2
docker exec jupyter sh -c "printf '%s\n' ' fixed = isinstance(value, ast.Constant) or getattr(getattr(value, \"func\", None), \"id\", \"\") == \"bytes\"' ' if target.upper() == \"NONCE\" and fixed:' ' found.add((node.lineno, \"fixed nonce: make a new one for every message\"))' ' if isinstance(node, ast.Compare) and isinstance(node.ops[0], ast.Eq):' ' text = ast.unparse(node).lower()' ' if any(word in text for word in WORDS):' ' found.add((node.lineno, \"== on a secret: use hmac.compare_digest\"))' 'for line, words in sorted(found):' ' print(path + \":\" + str(line), words)' 'print(\"findings:\", len(found))' 'sys.exit(1 if found else 0)' >> steps/cryptolint.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Review the weak code
docker exec jupyter python3 steps/cryptolint.py steps/review.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Review the fixed code
docker exec jupyter python3 steps/cryptolint.py steps/fixed.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: find the seed, then fix it
A weak service seeds random with the time in seconds. Find the seed, then replace the generator.
token_from(seed) returns random.Random(seed).getrandbits(64) as 16 hex characters (format(n, "016x")). seed_of(token, first, last) returns the seed from first to last, both included, that makes the token, or None. strong_token() returns secrets.token_urlsafe(32).
import random
import secrets
def token_from(seed):
# The token a weak service makes: 64 random bits from random.Random(seed), as 16 hex characters.
return ""
def seed_of(token, first, last):
# The seed from first to last (both included) that makes this token, or None.
return None
def strong_token():
# A token from the secrets module with 32 random bytes, URL-safe.
return ""
Make a free account to save your work and track your progress.
Exit quiz
Have a go