Algorithmcore
SYN cookies
Also called SYN cookie.
Encodes the connection state in the server's initial sequence number as a keyed hash, so that the server keeps no state until the handshake ends.
- Time
- O(1) worst · average · best
- Space
- O(1) extra
- Where
- n = the number of SYN segments that have no final ACK yet
- Model
- Word RAM
- Properties
- deterministiconlinestateless
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel J. Bernstein, Eric Schenk, 1996
SYN cookies let a TCP server answer a connection request without storing anything about it. The server puts the state it needs into its own initial sequence number: a time counter, a code for the maximum segment size, and a keyed message authentication code of the connection's addresses and ports. A real client sends that number back, plus one, in the last message of the handshake, and the server checks it and only then builds the connection. This makes the server immune to SYN flooding: a flood costs it one hash per packet and no memory.
In plain words
A cloakroom runs out of hooks when many people hand in coats and never come back. So the attendant stops taking coats at the door. Instead, each visitor gets a ticket with the time, and a stamp that only the attendant can make and that depends on the visitor's name. When the visitor comes back with the ticket, the attendant checks the stamp and the time, and only then gives a hook.
The server does the same. To the first message of a connection it answers with a number that holds a stamp, the time and one small setting. It writes nothing down. A real client sends the number back in its last message. The server makes the stamp again from the message and compares. A forged ticket has the wrong stamp, and an old ticket has a time that is too old.
The problem
A server receives SYN segments from clients and must answer each with a SYN-ACK. A client is identified by the 4-tuple . The server must accept a final ACK from if and only if it sent a SYN-ACK to recently, and it must recover the maximum segment size (MSS) that it chose for . It must do this with memory that does not grow with the number of open requests.
The threat model is an off-path adversary: it can send segments with any source address, but it cannot see the SYN-ACKs that the server sends to other addresses, and it does not know the key . Under this model the server accepts a forged ACK with probability at most per attempt, plus the advantage of a distinguisher against the keyed hash. An adversary that sees the SYN-ACK, for example on the path to the client, can complete the handshake; SYN cookies do not stop it, and they are not meant to.
The algorithm
Let be a pseudorandom function with key , here HMAC-SHA256. Let be a counter that the server steps every 64 seconds, and let be a fixed table of eight MSS values. Each SYN-ACK carries the cookie as the server's initial sequence number, and the final ACK of a real client carries . The layout follows RFC 4987, Appendix A: 5 bits of time, 3 bits of MSS code, 24 bits of hash.
MAKE-COOKIE(K, c, t, m) ▷ on a SYN from c; m is the index of the MSS in T- 1
h ← F_K(c, t) mod 2^24 - 2
return (t mod 32)·2^27 + m·2^24 + h CHECK-COOKIE(K, c, a, now, A) ▷ on an ACK from c with acknowledgment number a; A < 32- 3
y ← (a - 1) mod 2^32 - 4
t5 ← ⌊y / 2^27⌋, m ← ⌊y / 2^24⌋ mod 8, h ← y mod 2^24 - 5
t ← now - ((now - t5) mod 32) - 6
if now - t > A or t < 0 then return REJECT - 7
if F_K(c, t) mod 2^24 ≠ h then return REJECT - 8
return ACCEPT with MSS T[m]
MAKE-COOKIE runs on each SYN while the backlog is full, or on each SYN if the server always uses cookies. The server picks as the largest index with at most the client's MSS, sends the SYN-ACK and forgets the request. CHECK-COOKIE runs on an ACK that matches no stored connection. Line L3 undoes the of the client, modulo . Line L4 splits the three fields. The cookie holds only , so line L5 takes the latest counter value at or before that has these 5 bits; it is the right one whenever the cookie is less than 32 steps old. Line L6 rejects cookies whose rebuilt age is more than steps. A cookie steps old with and rebuilds an age of and passes line L6; line L7 rejects it, because the hash was made with the older counter value, except with probability . Line L7 makes the hash again and compares it in constant time. If it matches, the server builds the TCB from the ACK and the MSS .
Example
Take the key $K = $ the 16 bytes 0x00, 0x01, ..., 0x0f, the client $c = $ (203.0.113.7, 49152, 192.0.2.10, 443) from the documentation ranges, the counter and a client MSS of 1460. The table is , so . Then , the truncated hash is $h = $ 0xd79c4e, and
The real client answers with $a = $ 0x45d79c4f. The server checks it with :
| case | from line L5 | age | line L7 | result | ||
|---|---|---|---|---|---|---|
| real ACK | 0x45d79c4f | 1000 | 1000 | 0 | match | accept, MSS 1460 |
| real ACK | 0x45d79c4f | 1001 | 1000 | 1 | match | accept, MSS 1460 |
| real ACK | 0x45d79c4f | 1002 | 1000 | 2 | match | accept, MSS 1460 |
| late ACK | 0x45d79c4f | 1003 | 1000 | 3 | not run | reject at line L6 |
| wrong number | 0x45d79c50 | 1000 | 1000 | 0 | 0xd79c4f ≠ 0xd79c4e | reject |
| other port 49153 | 0x45d79c4f | 1000 | 1000 | 0 | hash of another tuple | reject |
| other key | 0x45d79c4f | 1000 | 1000 | 0 | hash under another key | reject |
At , line L5 gives , so the counter is rebuilt even though the server never stored it.
Correctness
Theorem. (1) For every key , tuple , counter , index and time with , CHECK-COOKIE$(K, c, $ MAKE-COOKIE accepts and returns . (2) If is a random function, then for any fixed , and , chosen without seeing a value for the that line L5 computes, CHECK-COOKIE accepts with probability at most . An adversary that sends such ACKs succeeds with probability at most by the union bound; with a real PRF, add the PRF distinguishing advantage.
The key fact for (1) is that line L5 returns the unique with and , so it returns when . For (2), and fix one value , and acceptance needs 24 bits of a uniform value to equal a fixed . The full proof is in proofs/correctness.md.
Proof: SYN cookies accept every recent real ACK and almost no forged onefull
We use the names of the main block. A cookie is a 32-bit integer. The counter is a non-negative integer, , , and .
Lemma 1 (fields). Let $y = $ MAKE-COOKIE. Then , , and .
Proof. Line L2 returns with , and by line L1. So . Since , the quotient of by is . Since , the quotient of by is , and its residue mod 8 is . The residue of mod is .
Lemma 2 (the counter). Let and let , as in line L5. Then and . It is the only integer with both properties.
Proof. Let , so and is a multiple of 32. Then lies in , and . Two integers in an interval of 32 consecutive integers that are congruent mod 32 are equal, so is unique.
Theorem, part 1 (completeness). If , then CHECK-COOKIE with $y = $ MAKE-COOKIE returns ACCEPT with .
Proof. Line L3 computes , because by Lemma 1. Line L4 then gives , the index and , by Lemma 1. The counter satisfies and , because . By Lemma 2, line L5 gives . Line L6 does not reject, because and . Line L7 computes , so it does not reject. Line L8 returns .
Theorem, part 2 (soundness against an off-path adversary). Model as a function drawn uniformly at random from all functions from the inputs to . Fix , and , and let be the value of line L5 for these inputs. Suppose the adversary chooses without having seen . Then CHECK-COOKIE accepts with probability at most . After such attempts, with any adaptive choice of the inputs, the probability that some attempt is accepted is at most .
Proof. Lines L3 to L5 are fixed functions of and , so and are fixed before is drawn. If line L6 rejects, the claim holds. Otherwise acceptance needs . The value is uniform on 256-bit strings and independent of what the adversary has seen, so its low 24 bits are uniform on , and the probability is exactly .
For attempts, consider the run until the first accepted attempt. Up to that moment every answer is REJECT, so the adversary's choices are a fixed function of its own coins and of the SYN-ACKs it saw, which by hypothesis do not hold the points it attacks. Fix the coins and this sequence of choices. Group the attempts by the point they use, and let attempt group use attempts with guesses in a set of at most values. Some attempt in group is accepted only if , which has probability , since that value is uniform. By the union bound over the groups, some attempt is accepted with probability at most . Averaging over the coins keeps the bound.
Remark (a real PRF). If is HMAC-SHA256 with a secret uniform key, replace the random function by . Any adversary whose success probability differs from the bound above by more than gives a distinguisher between and a random function with advantage , using one oracle query per SYN-ACK it sees and per check. So the forgery probability is at most . The bound says nothing about an adversary that sees the SYN-ACK to : it knows and can complete the handshake.
Complexity
All costs are in the word RAM model, with one call of on an input of at most 45 bytes counted as (HMAC-SHA256 on that input runs a fixed number of SHA-256 blocks).
- Time per SYN. Line L1 is one hash and line L2 is a few shifts: .
- Time per ACK. Lines L3 to L6 are constant arithmetic and line L7 is one hash: .
- Space. The server keeps , the counter and the table . It keeps nothing per request, so the space is for any number of pending requests. A SYN cache keeps entries, up to its limit.
Properties
- Stateless. No memory per request until the ACK arrives. This is the only defense of RFC 4987 that removes the backlog entirely.
- Deterministic. The same , , and always give the same cookie, so a retransmitted SYN gets the same SYN-ACK within one counter step.
- Time-bound. A cookie is valid for at most counter steps. Bernstein made the cookie depend on time so that an adversary cannot collect valid cookies from one place and replay them later from another.
- Lossy. The 32 bits hold only an MSS code. Window scaling, selective acknowledgment and timestamps from the SYN are lost unless the server encodes them elsewhere (RFC 4987, Section 3.6).
Variants and improvements
- Client ISN in the cookie. Schenk added the client's initial sequence number to the cookie, so that the server's sequence numbers increase with the client's as TCP expects. Linux follows this design.
- Options in the timestamp. If the client sends the timestamp option, the server can keep the window scale and the SACK flag in the low bits of the timestamp value that the client echoes. Linux does this, so it loses fewer options.
- Hybrid with a SYN cache. Store requests in a small hash table while there is room and switch to cookies only when it is full (RFC 4987, Section 3.7). Normal traffic keeps every option, and floods hit the stateless path.
- A faster keyed hash. HMAC-SHA256 is more than the cookie needs. A short keyed hash such as SipHash is enough, because the proof needs only that the keyed function is a PRF.
- Key rotation. Change from time to time and check against the current and the previous key, so that a leaked key ends.
When to use it
Use SYN cookies on any server that can be reached by unauthenticated clients, at least as the fallback when the backlog is full. Use a SYN cache first when you need full TCP options for normal traffic, as RFC 4987 advises for defaults. SYN cookies do not help against a flood that fills the link, against an attacker that completes handshakes from real addresses (then ingress filtering and rate limits matter), or against an on-path adversary.
Pitfalls
- No key, or a guessable key. If line L1 uses a plain hash of and with no secret, anyone can compute cookies, and a forged ACK passes. Line L1 must use a keyed PRF with a secret of at least 128 bits, drawn from a cryptographic source.
- Rebuilding the counter wrong. Writing line L5 as or as gives a wrong counter when the 5-bit time wraps, and line L7 then rejects real clients just after each multiple of 32. Line L5 must take .
- Forgetting the . Line L3 must undo the client's increment modulo . Using itself, or without the modulus, rejects every client, or the one with .
- Comparing with an early exit. Line L7 should compare in constant time. A byte-by-byte comparison that stops at the first difference leaks, through time, how many leading bytes of a guess are right (see timing attack).
- No age limit. Without line L6 a cookie stays valid until the 5-bit time comes round again, 32 steps later, and captured cookies can be replayed for longer than needed.
Implementations
The code works on abstract 4-tuples with documentation addresses (RFC 5737 and RFC 3849) and takes the time counter as an argument. It opens no socket, reads no clock and sends no packet. The test compares CHECK-COOKIE with a server that stores every SYN-ACK it sends.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/syn-cookies/. The authors are listed in prov/Z3NQ59.jsonl.
"""SYN cookies in the layout of Bernstein (RFC 4987, Appendix A).
A cookie is a 32-bit initial sequence number y for the server:
bits 31..27 t mod 32, where t is a time counter that steps every 64 seconds
bits 26..24 m, an index into a table of 8 MSS values
bits 23..0 the low 24 bits of HMAC-SHA256(K, c || t), c the 4-tuple
The code works on abstract 4-tuples of strings and integers. It opens no
socket, reads no clock and sends no packet: the caller passes the counter.
"""
import hashlib
import hmac
import ipaddress
FourTuple = tuple[str, int, str, int] # (client address, client port, server address, server port)
MSS_TABLE: tuple[int, ...] = (536, 1220, 1300, 1400, 1440, 1460, 4312, 8960)
HASH_BITS = 24
MOD32 = 1 << 32
def _encode(c: FourTuple, t: int) -> bytes:
"""Encode the 4-tuple and the full counter as a fixed layout of bytes."""
src, sport, dst, dport = c
a = ipaddress.ip_address(src)
b = ipaddress.ip_address(dst)
return (
bytes([a.version]) + a.packed + sport.to_bytes(2, "big")
+ bytes([b.version]) + b.packed + dport.to_bytes(2, "big")
+ t.to_bytes(8, "big")
)
def keyed_hash(key: bytes, c: FourTuple, t: int) -> int:
"""F_K(c, t) mod 2^24: the low 24 bits of HMAC-SHA256 over c and t."""
d = hmac.new(key, _encode(c, t), hashlib.sha256).digest()
return int.from_bytes(d[-3:], "big")
def split_cookie(y: int) -> tuple[int, int, int]:
"""Split a 32-bit value into (t mod 32, m, h)."""
return y >> 27, (y >> 24) & 7, y & 0xFFFFFF
def make_cookie(key: bytes, c: FourTuple, t: int, m: int) -> int:
"""Return the server ISN y for a SYN from c at counter t with MSS index m.
Precondition: t >= 0 and 0 <= m < 8. Cost: one HMAC over 45 bytes or less,
so O(1) time and O(1) space in the word-RAM model. The server stores nothing.
"""
h = keyed_hash(key, c, t) # @line L1
return ((t % 32) << 27) | (m << 24) | h # @line L2
def check_cookie(key: bytes, c: FourTuple, a: int, now: int, max_age: int) -> int | None:
"""Check the acknowledgment number a of the final ACK from c at counter now.
Return the MSS value if a - 1 is a cookie that make_cookie gave for c at a
counter t with 0 <= now - t <= max_age; else return None.
Precondition: 0 <= max_age < 32 and now >= 0. Cost: one HMAC, O(1).
"""
y = (a - 1) % MOD32 # @line L3
t5, m, h = split_cookie(y) # @line L4
t = now - ((now - t5) % 32) # @line L5
if now - t > max_age or t < 0: # @line L6
return None
if not hmac.compare_digest(keyed_hash(key, c, t).to_bytes(3, "big"), h.to_bytes(3, "big")): # @line L7
return None
return MSS_TABLE[m] # @line L8
def mss_index(client_mss: int) -> int:
"""The largest table index whose MSS is at most the client's MSS (0 if none)."""
best = 0
for i, v in enumerate(MSS_TABLE):
if v <= client_mss:
best = i
return best
test_syn_cookies.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/syn-cookies/. The authors are listed in prov/Z3NQ59.jsonl.
import random
from syn_cookies import (
MOD32,
MSS_TABLE,
check_cookie,
keyed_hash,
make_cookie,
mss_index,
split_cookie,
)
KEY = bytes(range(16))
C = ("203.0.113.7", 49152, "192.0.2.10", 443)
def test_example() -> None:
m = mss_index(1460)
assert m == 5
y = make_cookie(KEY, C, 1000, m)
assert y == 0x45D79C4E
assert split_cookie(y) == (1000 % 32, 5, keyed_hash(KEY, C, 1000))
a = (y + 1) % MOD32
assert check_cookie(KEY, C, a, 1000, 2) == 1460
assert check_cookie(KEY, C, a, 1001, 2) == 1460
assert check_cookie(KEY, C, a, 1002, 2) == 1460
assert check_cookie(KEY, C, a, 1003, 2) is None
assert check_cookie(KEY, C, (a + 1) % MOD32, 1000, 2) is None
other = ("203.0.113.7", 49153, "192.0.2.10", 443)
assert check_cookie(KEY, other, a, 1000, 2) is None
assert check_cookie(bytes(16), C, a, 1000, 2) is None
def test_edges() -> None:
assert split_cookie(0xFFFFFFFF) == (31, 7, 0xFFFFFF)
assert split_cookie(0) == (0, 0, 0)
assert mss_index(100) == 0
assert mss_index(9000) == 7
# The counter crosses a multiple of 32 between the SYN and the ACK.
for t in (30, 31, 63, 64, 1023):
for m in range(8):
y = make_cookie(KEY, C, t, m)
for age in range(3):
assert check_cookie(KEY, C, y + 1, t + age, 2) == MSS_TABLE[m]
assert check_cookie(KEY, C, y + 1, t + 3, 2) is None
assert check_cookie(KEY, C, y + 1, t + 32, 31) is None
# A counter before 0 is never rebuilt.
y = make_cookie(KEY, C, 0, 0)
assert check_cookie(KEY, C, y + 1, 0, 0) == MSS_TABLE[0]
# An ACK of 0 means y = 2^32 - 1, which no cookie for C at t = 0 equals.
assert check_cookie(KEY, C, 0, 0, 5) is None
# IPv6 documentation addresses work the same way.
c6 = ("2001:db8::7", 50000, "2001:db8::10", 443)
y6 = make_cookie(KEY, c6, 77, 3)
assert check_cookie(KEY, c6, y6 + 1, 78, 1) == MSS_TABLE[3]
def _random_tuple(rng: random.Random) -> tuple[str, int, str, int]:
return (f"198.51.100.{rng.randrange(1, 4)}", rng.choice((49152, 49153)), "192.0.2.10", 443)
def test_against_syn_cache() -> None:
"""Compare with a server that stores every SYN-ACK it sends (a SYN cache)."""
rng = random.Random(4987)
for _ in range(600):
key = rng.randbytes(16)
max_age = rng.randrange(0, 4)
now = rng.randrange(0, 200)
issued: list[tuple[tuple[str, int, str, int], int, int, int]] = []
for _ in range(rng.randrange(1, 6)):
c = _random_tuple(rng)
t = now - rng.randrange(0, 40)
if t < 0:
continue
m = rng.randrange(8)
issued.append((c, t, m, make_cookie(key, c, t, m)))
queries = [(c, (y + 1) % MOD32) for c, _, _, y in issued]
queries += [(_random_tuple(rng), rng.randrange(MOD32)) for _ in range(3)]
queries += [(_random_tuple(rng), (y + 1) % MOD32) for _, _, _, y in issued]
for c, a in queries:
want = None
for c2, t2, m2, y2 in issued:
if c2 == c and (y2 + 1) % MOD32 == a and 0 <= now - t2 <= max_age:
want = MSS_TABLE[m2]
assert check_cookie(key, c, a, now, max_age) == want
def test_forged_acks_rejected() -> None:
"""An off-path guess passes with probability 2^-24; 20000 guesses expect 0.0012 hits."""
rng = random.Random(8)
hits = 0
for _ in range(20000):
if check_cookie(KEY, C, rng.randrange(MOD32), 500, 3) is not None:
hits += 1
assert hits == 0
History
Bernstein proposed SYN cookies on 16 September 1996, after a SYN flood had stopped the mail service of a New York internet service provider earlier that month, and he and Eric Schenk worked out the details in the following weeks. Bernstein made the cookie depend on time, and Schenk added the client's sequence number. Implementations for SunOS and for Linux followed within months. RFC 4987 (2007) describes the cookie layout used here and the trade-offs against the SYN cache.
References
- Wesley M. Eddy, TCP SYN flooding attacks and common mitigations, RFC 4987, August 2007, Section 3.6 (SYN cookies and the lost TCP options), Section 4 (analysis and advice on defaults) and Appendix A (the 32-bit layout of the cookie)
- Daniel J. Bernstein, SYN cookies, the whole page (the history from September 1996, the time counter and why the cookie depends on time)
- Wesley M. Eddy (editor), Transmission Control Protocol (TCP), RFC 9293, August 2022, Section 3.4.1 (initial sequence numbers from a keyed pseudorandom function, after RFC 6528) and Section 3.5 (the three-way handshake)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Z3NQ59 Edit this page History Report an error Markdown