Sub topic 14
Hash Flooding and Randomized Hashing
This chapter assumes you know how a chained hash table works, what the load factor is, and why lookups are O(1) on average and O(n) at worst. It also assumes you can read short Python programs. Here you will see how an attacker can force the O(n) worst case on purpose, and how real systems prevent it.
The average case depends on a promise
The O(1) average cost rests on one assumption: keys spread roughly evenly across buckets. With a load factor under 1, a typical chain holds one or two entries, so a lookup compares a handful of keys.
That assumption is about the keys your program usually sees. It is not a guarantee about every key someone might send. If a hash function is fixed and public, anyone can compute its outputs ahead of time and choose keys that all land in one bucket. This attack is called hash flooding. It is one kind of algorithmic complexity attack, where input is crafted to trigger a program's worst-case behavior.
If a table holds n colliding keys in one chain, each insert scans the whole chain first. Inserting n keys then costs 1 + 2 + ... + (n - 1) comparisons, which is n(n - 1) / 2, or O(n²). The memory use stays small. The attacker is spending your CPU time.
How colliding keys are built
Take the polynomial hash from earlier in this tutorial, h = h * 31 + ord(ch). The strings "Aa" and "BB" have the same hash, because 65 × 31 + 97 = 66 × 31 + 66 = 2112.
The collision carries over when you concatenate. After hashing any prefix, both blocks update h to h * 961 + 2112, so they produce the same value. Any string made of k blocks, each chosen freely from "Aa" or "BB", therefore has the same hash as every other such string. That gives 2^k distinct keys with one hash value. With k = 10 you get 1,024 keys, and with k = 17 you get over 130,000.
This was practical against real software. Crosby and Wallach described the idea for hash tables in 2003. In 2011 Klink and Wälde showed that web frameworks in several languages could be stalled by one HTTP request. Frameworks load form fields and query parameters into a hash table before application code runs. An attacker only had to send a body full of colliding parameter names.
Reproducing the effect
The program below builds colliding keys, counts key comparisons in a chained table, and compares a fixed hash with a seeded one. It is complete as shown.
import hashlib
import os
from itertools import product
def poly_hash(s):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) & 0xFFFFFFFF
return h
SECRET = os.urandom(16)
def seeded_hash(s):
digest = hashlib.blake2b(s.encode(), key=SECRET, digest_size=8).digest()
return int.from_bytes(digest, "big")
def colliding_keys(blocks):
return ["".join(p) for p in product(["Aa", "BB"], repeat=blocks)]
def comparisons(keys, hash_fn, capacity=1024):
buckets = [[] for _ in range(capacity)]
count = 0
for key in keys:
bucket = buckets[hash_fn(key) % capacity]
for k in bucket:
count += 1
if k == key:
break
else:
bucket.append(key)
return count
attack = colliding_keys(10)
normal = [f"key{i}" for i in range(1024)]
print(len(attack), len({poly_hash(k) for k in attack}))
print(comparisons(attack, poly_hash))
print(comparisons(normal, poly_hash))
print(len({seeded_hash(k) for k in attack}))
print(comparisons(attack, seeded_hash))The first line prints 1024 1: 1,024 keys, one distinct hash value. The second prints 523776, which is 1024 × 1023 / 2. The third count, for ordinary keys, is orders of magnitude smaller. The fourth prints 1024, because the seeded hash separates the keys. The last count varies from run to run, since the secret changes. It is close to what random keys would cost, nowhere near 523,776.
The blake2b call here only illustrates the idea of a hash keyed by a secret. For a real table you would use the hash your language provides.
Randomized hashing
The fix is to make the hash function depend on a secret seed chosen at random when the process or table starts. The seed is mixed into every hash computation. An attacker who cannot see the seed cannot predict which keys collide, so a list of colliding keys prepared offline is useless.
The hash function must be strong enough that outputs do not reveal the seed. Adding a random number to a weak hash does not help. If the weakness is structural, as with the "Aa"/"BB" trick, the collisions survive every seed, because the colliding strings produce the same intermediate state no matter where h started. A keyed hash function such as SipHash is designed so that without the key, collisions cannot be found faster than by guessing.
Real implementations:
- CPython hashes
strandbyteswith SipHash since Python 3.4. A random key is chosen at startup, andPYTHONHASHSEEDsets it for reproducible runs. - Rust's standard
HashMapuses SipHash 1-3 with a random key per map by default, throughRandomState. - Go gives each map its own random seed.
- Java's
HashMaptakes a different approach, described below.
Other defenses
Seeding is the main defense, but several others are used, often together.
| Defense | How it limits the damage | Trade-off |
|---|---|---|
| Keyed hash with random seed | Attacker cannot predict collisions | Slower than simple hashes for short keys; order varies between runs |
| Tree buckets (Java 8+ `HashMap`) | A chain over 8 entries becomes a balanced tree, so the worst case is O(log n) per operation | Keys must be comparable for the best result; more code and memory per bucket |
| Cap input size or count | Limits n, so n² stays small | Rejects some legitimate input; must be enforced before parsing |
| Ordered map (balanced tree) | O(log n) always, no hash involved | Slower on average than a hash table; needs ordering on keys |
Gotchas
- Integers are often not randomized. In CPython,
hash(i)for a small int isiitself. Attackers can choose integer keys that collide in a table of known size. Open addressing with perturbation, as CPython uses, softens this, but do not assume integer keys are safe from adversaries. - A seed that leaks defeats the defense. Timing differences or the iteration order of a set of strings can reveal information about the seed. Treat the seed like any other secret and do not print or log it.
- Randomized hashes are not stable. The same string hashes differently in two processes. Never store hash values on disk or send them between machines. For sharding or consistent hashing across servers, use a stable hash you control, such as one with an explicit key that you manage.
- Do not depend on iteration order. Iteration order of a hash-based set of strings changes between runs. Tests that pass by accident on one run can fail on the next. Python's
dictkeeps insertion order, butsetdoes not. - Fast non-cryptographic hashes with a fixed seed are attackable. Hashes such as FNV or MurmurHash are fine for trusted internal data. Public ones with a published constant seed can be attacked. Pick a keyed hash for tables that hold input from untrusted users.
- Table-level fixes do not repair a bad hash. Resizing does not help against full collisions, because identical hash values still map to one bucket at any capacity.
Choosing a defense
Start from the data source. If the keys come from your own code, use the standard hash table and stop. If they come from the network, use the language's default hash table, which in modern CPython, Rust, and Go is already randomized. Add an input limit anyway, since it also protects memory and parsing time. If you implement the table yourself, use a keyed hash and consider tree buckets, so that even a lucky attacker faces O(log n) instead of O(n).
Exercise
A server stores request header names in a chained hash table with the hash h = h * 31 + ord(ch). An attacker sends 50,000 colliding header names. Roughly how many key comparisons does the table perform while inserting them, and why does adding a random constant to the starting value of h (instead of 0) not fix the problem?
Show answer
All 50,000 keys land in one chain, so inserting them costs about n(n - 1) / 2 = 50,000 × 49,999 / 2, roughly 1.25 billion comparisons. Changing the starting value does not help, because the weakness is in the update rule. Two blocks such as "Aa" and "BB" produce the same intermediate value from any starting value, so every concatenation of them still collides. A keyed hash such as SipHash is needed, because it resists collision-finding without the key.
Exercise
Your service computes hash(user_id_string) in Python and stores the number in a database to decide which of four shards owns each user. After a restart, users are looked up on the wrong shard. What went wrong and what should you use instead?
Show answer
Python randomizes string hashes with a different secret in each process, so the same string gets a different hash after a restart. A value used for placement that must survive restarts or be shared between machines needs a stable hash, for example a digest from hashlib of the encoded string, taken modulo the shard count.