Hash Flooding & Anti-Hash Tests
Inputs that make hash tables quadratic, and the defenses against them.
In December 2011 a single web request whose form fields all collided in one hash bucket could keep a server's processor at 100% for a long time, on Java, PHP, Python, Ruby and more. The same trick still hacks contest solutions that trust std::unordered_map. This lesson shows how attackers manufacture collisions, what each defense actually guarantees, and how to write hash tables that a hostile test cannot break.
What you’ll learn
- Model an algorithmic complexity attack and show that colliding insertions cost with chaining or linear probing.
- Manufacture collisions for fixed hash functions: equal-hash blocks for polynomial string hashes, multiples of the bucket count for identity integer hashes, and birthday search for small moduli.
- Compare the defenses (input limits, keyed hashing with SipHash, randomized seeds, tree-shaped buckets) by what each guarantees and what it assumes.
- Write a contest-safe hash for
std::unordered_map, and choose safe parameters for polynomial string hashing.
From O(1) to Θ(n²): algorithmic complexity attacks
Average-case bounds assume the keys do not depend on the hash function. An algorithmic complexity attack breaks exactly that assumption: the attacker knows the code, including the hash function , and chooses the keys. If the universe has more than keys, the pigeonhole principle guarantees keys with the same slot; the attacker's only job is to find them. This is hash flooding.
Chaining. Every insertion scans the whole chain for a duplicate before appending, and the -th key finds keys there:
Linear probing. The -th key with the same home slot probes the slots its predecessors took, plus one: probes. Worse, every other key whose home falls inside that run of slots pays for it too.
Amplification. The attacker sends keys, the server does work: each byte sent buys units of work. That ratio is what makes a modest request dangerous.
Think first A server inserts attacker-chosen keys, all with the same hash, into a chained table that scans each chain for duplicates. How many key comparisons does it make?
: about 2.15 billion string comparisons, seconds of processor time, triggered by one request. Spread by a good hash function, the same keys would cost about 65,536 comparisons.
Manufacturing collisions
Pigeonhole guarantees that colliding keys exist; structure makes them cheap to find. Three recipes cover most real attacks.
Equal-hash blocks. A polynomial hash satisfies . So if two blocks of the same length have the same hash, they can be swapped anywhere without changing the total. Java's String.hashCode uses , and "Aa" and "BB" both hash to . Bernstein's times-33 hash, used by PHP for its arrays, has the pair "Ez" and "FY" (). Concatenating blocks gives colliding strings of length .
from itertools import product
def java_hash(s): # Java's String.hashCode: 31-polynomial modulo 2**32
h = 0
for ch in s:
h = (31 * h + ord(ch)) % 2**32
return h - 2**32 if h >= 2**31 else h
assert java_hash('Aa') == java_hash('BB') == 2112 # 65*31 + 97 == 66*31 + 66
def colliding(k): # 2**k strings of length 2k with one hash
return [''.join(blocks) for blocks in product(['Aa', 'BB'], repeat=k)]
keys = colliding(16)
print(len(keys), len({java_hash(s) for s in keys})) # 65536 165,536 field names of 32 characters, one hash value: about 2 MB of parameters that force the 2.15 billion comparisons of the question above.
Identity hashes on integers. GCC's libstdc++ and LLVM's libc++ hash an integer to itself, and std::unordered_map takes the remainder by a prime bucket count that the library chooses deterministically as the table grows. Run the same compiler, read bucket_count() after insertions, and insert multiples of that prime: they all land in bucket 0. Python randomizes the hashes of str and bytes, but not of int: a non-negative integer hashes to its value modulo , so every multiple of hashes to 0, and set(i * (2**61 - 1) for i in range(20000)) takes seconds where random integers take about a millisecond.
Birthday search. A fixed polynomial hash modulo a prime with a known base can be attacked by brute force: by the birthday paradox, random strings collide after about tries. With base 131, modulus and characters taken as their ASCII codes, the strings aumfgtqczm and wpoozwisuz both hash to 463,473,016. And arithmetic modulo fails for every odd base on the Thue–Morse strings, as the Optimal lesson Polynomial Hashing in Depth proves.
Defenses, and what each one guarantees
| Defense | What it guarantees | What it assumes or costs |
|---|---|---|
| Cap the input (number of form fields, of keys per request) | Bounds , hence the | Treats the symptom; every entry point needs its own cap |
| Draw at random from a universal family at startup | Expected per operation for every input fixed in advance | The keys must not depend on : timing or iteration order can leak it to an adaptive attacker |
| Keyed hash with a secret random key, such as SipHash | Finding collisions is as hard as breaking a pseudorandom function | A cryptographic assumption, not a theorem; slower than unkeyed hashes on short keys |
Tree-shaped buckets (Java's HashMap since Java 8) | per operation in the worst case, if colliding keys are Comparable or have distinct hashes | Needs an order on the keys; does nothing for open addressing |
| An ordered structure (balanced search tree) | worst case, no hashing at all | A logarithmic factor on every operation |
PYTHONHASHSEED fixes the key for reproducible runs, and 0 disables randomization), Rust's HashMap hashes every key type with SipHash-1-3 under a random per-map key, and Java keeps a deterministic String.hashCode but turns long chains into trees. PEP 456 lists Ruby, Perl, Redis and FreeBSD among other adopters of SipHash.Model the keyed hash as a random function the attacker cannot see. Then every fresh key lands in a given slot with probability , whatever the attacker does:
To pile keys into one slot the attacker must therefore send about keys, and those cost the server only expected work each:
The server's work is proportional to the attacker's, as for any honest traffic: the amplification of a fixed hash function is gone. The argument breaks only if the attacker learns about , which is why a weak seeded hash, or one that leaks its secret, is not enough.
A Python 3.12 web service stores user-supplied numeric IDs, converted with int(), as keys of a dict. Is it protected from hash flooding by Python's hash randomization?
- Yes: every
dictis seeded with a random key at startup - Yes:
dictuses open addressing, which cannot be flooded - No: randomization covers
strandbytes, and aninthashes to its value modulo , so multiples of all collide - No: Python never randomizes any hash
Show the answer
C. No: randomization covers str and bytes, and an int hashes to its value modulo , so multiples of all collide
Python's random key is applied to str and bytes. Integers hash deterministically, so an attacker can send IDs that all hash to 0. Keep such IDs as strings, combine them with a secret salt before using them as keys, or cap how many a request may create.
Anti-hash tests in competitive programming
On judges with a hacking phase, rivals read your accepted code and submit tests designed against it, and std::unordered_map<long long, …> with the default hash is a favorite target: the hash is the identity and the bucket counts are predictable, so a test of about multiples of the right prime turns your solution into . On one laptop with LLVM's libc++, inserting 200,000 multiples of the final bucket count took about 26 seconds, against about 0.01 seconds for random keys. Calling reserve does not help: it just makes the bucket count, and therefore the right prime, easier to predict.
The fix is to hash with a function the hacker cannot predict, seeded when your program runs, after the test was written:
#include <chrono>
#include <cstdint>
#include <unordered_map>
struct custom_hash {
static uint64_t splitmix64(uint64_t x) { // the finalizer of the splitmix64 generator
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t SEED = // fixed when the program starts
std::chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + SEED);
}
};
std::unordered_map<long long, int, custom_hash> safe_map; // drop-in replacementThe mixing function is the output stage of Vigna's splitmix64 generator (a fixed-increment version of Java's SplittableRandom); its first constant is , the multiply-shift constant of the Optimized lesson Hash Tables. On the 200,000-key attack above it brought the time back to about 0.01 seconds. It is fast and mixes all 64 bits, but it is not cryptographic: it defeats tests fixed in advance, not an attacker who can watch your table.
Strings deserve the same care. For polynomial hashing, draw the base at random when the program starts, and use a large prime modulus such as (or two independent moduli near ); never rely on the free overflow modulo . Then two distinct strings of length collide with probability at most , whatever the test. In Python, integer keys read from the input can be stored as strings or combined with a random salt; on 20,000 multiples of , XOR with a random 64-bit salt cut the time of building a set from seconds to about a hundredth of a second.
Your C++ solution stores up to long long keys in std::unordered_map with the default hash, and the contest allows hacking. Which change protects it while keeping expected operations?
- Call
reserve(1 << 18)before inserting - Hash with
splitmix64(x + SEED), whereSEEDis read from the clock when the program starts - Hash with instead of the identity
- Set
max_load_factor(0.25)so the buckets stay short
Show the answer
B. Hash with splitmix64(x + SEED), where SEED is read from the clock when the program starts
The hacker must fix the test before your program runs, and cannot predict a seed drawn at run time; splitmix64 then spreads any fixed set of keys like random ones. Switching to std::map would also be safe, at per operation.
Key takeaways
- With a fixed, public hash function an attacker makes insertions cost , an amplification of over the attacker's own work (Crosby & Wallach, 2003; the 2011 web-platform advisories).
- Colliding keys come from structure: equal-hash blocks for polynomial hashes ("Aa" and "BB" in Java), multiples of the bucket count for identity integer hashes, birthday search for small moduli, and seed-independent collisions in weak seeded hashes.
- Keyed hashing with a secret random key (SipHash in Python, Rust and many others) makes flooding as expensive as random guessing, under a cryptographic assumption; tree bins (Java 8) cap the damage at per operation.
- In contests, give
unordered_mapa hash such assplitmix64(x + SEED)with a run-time seed, use a random base and a large prime modulus for string hashing, and remember that Python randomizes onlystrandbytes.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
"Aa" and "BB" have the same Java hashCode. How many distinct strings of length 20 with one common hash can you build by concatenating these blocks?
- 20
- 200
- 1,024
Show the answer
C. 1,024
A string of length 20 is 10 blocks, each chosen independently from two options: strings. Because , swapping equal-hash blocks of equal length never changes the total.
A Java 8+ HashMap<String, V> receives distinct keys that all have the same hashCode. About how much work do the insertions take in total?
- , as in any chained table
- : the bin becomes a red-black tree ordered by
compareTo - : Java rehashes with a random seed when a chain gets long
- The map throws an exception once a bin holds 8 keys
Show the answer
B. : the bin becomes a red-black tree ordered by compareTo
Once a bin holds 8 entries (in a table of at least 64 bins), Java converts it to a red-black tree. Strings are Comparable, so the tree is ordered by compareTo, and each insertion costs comparisons.
A solution hashes strings with a fixed, published base and the prime modulus . About how many random strings must a hacker hash before two of them collide?
- About 30
- About 40,000
- About
- About
Show the answer
B. About 40,000
By the birthday bound, collisions among random hash values appear after about draws, a fraction of a second of computing. A random base drawn at run time, or a modulus near , defeats this.
Further reading
- S. A. Crosby & D. S. Wallach, "Denial of service via algorithmic complexity attacks," Proceedings of the 12th USENIX Security Symposium (2003).
- oCERT, "oCERT-2011-003: multiple implementations denial-of-service via hash algorithm collision" (advisory, December 28, 2011).
- J.-P. Aumasson & D. J. Bernstein, "SipHash: a fast short-input PRF," INDOCRYPT (2012).
- C. Heimes, "PEP 456: Secure and interchangeable hash algorithm" (Python Enhancement Proposal, 2013).
- J. Pachocki & J. Radoszewski, "Where to use and how not to use polynomial string hashing," Olympiads in Informatics 7 (2013), 90–100.