Sub topic 10
Hash flooding attacks and seeded hashes
This chapter assumes you know how a hash table maps keys to buckets with hash(key) % bucket_count. It also assumes you can read Python and know what chaining is: each bucket holds a list of the keys that landed in it. Earlier chapters covered collisions as an accident of probability. Here a collision is something an attacker causes on purpose.
Why a good average is not enough
A hash table promises O(1) lookups on average. That promise rests on an assumption: keys spread roughly evenly across buckets. If every key lands in one bucket, the table degrades into a linked list. Inserting n keys then costs about n²/2 comparisons instead of about n.
A hash flooding attack (also called algorithmic complexity attack or hash DoS) exploits this. The attacker sends many keys that all collide. Each key is cheap to send, but the server's work grows quadratically. A few hundred kilobytes of request parameters can keep a CPU core busy for seconds.
The attack was presented widely at the 28C3 conference in 2011 (Klink and Wälde). It hit PHP, Java, Python, Ruby, ASP.NET and others, because web frameworks put attacker-controlled strings, such as form fields, JSON keys and HTTP headers, straight into hash tables.
The attack needs two things:
- The attacker knows the hash function.
- The hash function is easy to invert or to collide on purpose.
Seeded hashing removes the first requirement. Choosing a stronger function removes the second.
A working attack on a weak hash
Polynomial hashes with base 31, such as Java's String.hashCode, are linear in the characters. That makes collisions easy to build. The two-character strings "Aa" and "BB" hash identically, because 65·31 + 97 = 66·31 + 66 = 2112. A hash that processes the string block by block gives equal results for any concatenation of equal-hash blocks. Choosing "Aa" or "BB" at each of 10 positions yields 2¹⁰ = 1024 distinct strings with one shared hash value.
The program below builds those keys and counts comparisons in a chained table. It then repeats the test with a keyed BLAKE2b hash, which the attacker cannot predict without the key.
import hashlib
import os
from itertools import product
def java_hash(s):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) & 0xFFFFFFFF
return h
KEY = os.urandom(16) # secret seed, chosen per process
def seeded_hash(s):
digest = hashlib.blake2b(s.encode(), key=KEY, digest_size=8).digest()
return int.from_bytes(digest, "big")
class ChainedTable:
def __init__(self, hash_fn, buckets=2048):
self.hash_fn = hash_fn
self.buckets = [[] for _ in range(buckets)]
self.comparisons = 0
def insert(self, key):
bucket = self.buckets[self.hash_fn(key) % len(self.buckets)]
for existing in bucket:
self.comparisons += 1
if existing == key:
return
bucket.append(key)
def longest_chain(self):
return max(len(b) for b in self.buckets)
attack_keys = ["".join(p) for p in product(["Aa", "BB"], repeat=10)]
normal_keys = [f"user{i}" for i in range(len(attack_keys))]
print("distinct java_hash values in attack set:",
len({java_hash(k) for k in attack_keys}))
for label, fn in [("java_hash", java_hash), ("seeded_hash", seeded_hash)]:
for name, keys in [("normal", normal_keys), ("attack", attack_keys)]:
table = ChainedTable(fn)
for k in keys:
table.insert(k)
print(f"{label:12} {name:7} comparisons={table.comparisons:7} "
f"longest chain={table.longest_chain()}")The attack set has exactly one distinct java_hash value. With java_hash, the attack keys cost 1024·1023/2 = 523,776 comparisons and a longest chain of 1024. Normal keys cost far fewer. With seeded_hash, the attack keys behave like ordinary keys, because the attacker's collisions were computed for a function that is not the one in use.
Seeded hashing
A seeded hash takes a secret value, the seed, along with the input. Each process picks a random seed at startup. Two processes hash the same string to different values, and an attacker who sees only responses cannot work out which keys collide.
import hashlib
import os
key = os.urandom(16) # secret seed, chosen per process
def seeded_bucket(data: bytes, buckets: int) -> int:
digest = hashlib.blake2b(data, key=key, digest_size=8).digest()
return int.from_bytes(digest, "big") % buckets
print(seeded_bucket(b"user-supplied-key", 1024))Run this twice and the printed bucket differs between runs. That is the intended behavior.
Real runtimes do this internally:
- Python randomizes
strandbyteshashing per process by default (since 3.3). The environment variablePYTHONHASHSEEDcan fix the seed, andPYTHONHASHSEED=0disables randomization. - Rust's standard
HashMapusesRandomState, which draws random keys for each map and hashes with SipHash. - Go seeds each map's hash randomly.
A seed is not enough on its own
The seed only helps if the function is a keyed function that stays unpredictable even to someone who can see many outputs. A fast non-cryptographic hash with a seed argument is not automatically safe.
Aumasson and Bernstein showed in 2012 that for MurmurHash2, MurmurHash3 and CityHash, an attacker can build colliding inputs that collide for every seed. These are called seed-independent or multi-collisions. The seed only changes the starting state, and the attacker's collisions cancel out the same way no matter what that state was.
For this reason SipHash was designed. It is a pseudorandom function (PRF): without the key, its outputs look random, and the attacker cannot predict collisions. It is fast on short inputs, though slower than FNV-1a or Murmur-style hashes in raw throughput.
| Choice | Speed on short keys | Safe against flooding | Notes |
|---|---|---|---|
| Unseeded FNV-1a or polynomial | Very fast | No | Fine only for trusted keys |
| Seeded FNV-1a or Murmur | Fast | Not reliably | Seed-independent collisions exist for some functions |
| SipHash, keyed BLAKE2 | Moderate | Yes | Defaults in many standard libraries |
| Unkeyed SHA-256 | Slower | No | Collisions are infeasible, but nothing is secret, so it is wasteful here |
Failure modes and gotchas
- Seed leakage. If the server reveals hash values or iteration order, an attacker may recover information about the seed. Do not expose raw hash values, bucket indexes or unordered iteration order to untrusted parties.
- Short or constant seeds. A seed hardcoded in source code is a published seed. Take it from the operating system's random source (
os.urandom,secrets). - Seed reuse across a fleet. Different processes giving different hashes is correct for in-memory tables. For sharding or consistent hashing across machines, all participants must share one seed. Then the seed is a secret you must protect and rotate.
- Persisted hashes. Do not store a per-process seeded hash in a file or database and expect it to match after restart. Use a stable function with a stored key for that purpose.
- Iteration order changes. Seeding makes the order of a set or unordered map differ between runs. Code that depends on that order, including tests, was already buggy and will now show it. Python dicts keep insertion order independently of hashing, but sets do not.
- Small tables still degrade. A seed protects against forced collisions, not against bad luck. Resizing on load factor still matters.
Other defenses
Seeding is the main defense, but it layers with others:
- Treeified buckets. Java 8's
HashMapconverts a long chain into a balanced tree, giving O(log n) worst case when keys are comparable. Rather than preventing collisions, this limits the damage. - Input limits. Cap the number of form fields, JSON keys or headers a request may carry. The 2011 fixes in several languages did this first, as a stopgap.
- Rate limiting and request timeouts. These bound how long an attacker can occupy a worker.
- Balanced-tree or sorted maps for untrusted keys. The cost is O(log n) on every operation, even for honest input.
Choosing in practice
If keys come from users, whether through a network, uploaded files or parsed input, use your language's default hash table, which is already seeded. Do not replace it with a custom FNV table for speed. If you write your own table that accepts untrusted keys, use SipHash or a keyed BLAKE2 hash.
If all keys are generated by your own code, for example integer IDs from a counter, an unseeded fast hash is fine. Only the possibility of an adversary choosing keys changes the answer.
Exercise
A service stores uploaded filenames in its own chained hash table that uses unseeded FNV-1a. A security reviewer says an attacker can slow it down. Your teammate proposes adding a random 32-bit value XORed into the initial FNV offset basis as a "seed". Is this enough, and what would you use instead?
Show answer
No. FNV-1a is not designed as a keyed function, and an XORed start value only changes the starting state. Collisions that depend on the structure of the mixing steps can survive across seeds, in the same way that seed-independent collisions were found for Murmur and City hashes. A 32-bit seed is also small enough to guess or probe by timing. Use a function designed as a keyed PRF, such as SipHash or keyed BLAKE2b, with a seed of at least 128 bits taken from os.urandom, or use the language's built-in hash table, which already does this.
Exercise
Why do the 1024 attack keys in the program collide under java_hash, and what would you change in the program to produce 4096 colliding keys?
Show answer
Each block "Aa" and "BB" has the same hash (2112), and a polynomial hash processes a string block by block, so replacing one block with another of equal hash leaves the final value unchanged. Changing repeat=10 to repeat=12 gives 2**12 = 4096 keys with a single hash value.