Algorithm Search⌘K

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
Properties
deterministiconlinestateless
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 c=(client address,client port,server address,server port)c = (\text{client address}, \text{client port}, \text{server address}, \text{server port}). The server must accept a final ACK from cc if and only if it sent a SYN-ACK to cc recently, and it must recover the maximum segment size (MSS) that it chose for cc. 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 KK. Under this model the server accepts a forged ACK with probability at most 2−242^{-24} 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 FKF_K be a pseudorandom function with key KK, here HMAC-SHA256. Let tt be a counter that the server steps every 64 seconds, and let T[0…7]T[0 \ldots 7] be a fixed table of eight MSS values. Each SYN-ACK carries the cookie yy as the server's initial sequence number, and the final ACK of a real client carries a=y+1 mod 232a = y + 1 \bmod 2^{32}. The layout follows RFC 4987, Appendix A: 5 bits of time, 3 bits of MSS code, 24 bits of hash.

  1. MAKE-COOKIE(K, c, t, m) ▷ on a SYN from c; m is the index of the MSS in T
  2. 1h ← F_K(c, t) mod 2^24
  3. 2return (t mod 32)·2^27 + m·2^24 + h
  4. CHECK-COOKIE(K, c, a, now, A) ▷ on an ACK from c with acknowledgment number a; A < 32
  5. 3y ← (a - 1) mod 2^32
  6. 4t5 ← ⌊y / 2^27⌋, m ← ⌊y / 2^24⌋ mod 8, h ← y mod 2^24
  7. 5t ← now - ((now - t5) mod 32)
  8. 6if now - t > A or t < 0 then return REJECT
  9. 7if F_K(c, t) mod 2^24 ≠ h then return REJECT
  10. 8return 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 mm as the largest index with T[m]T[m] 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 +1+1 of the client, modulo 2322^{32}. Line L4 splits the three fields. The cookie holds only t mod 32t \bmod 32, so line L5 takes the latest counter value at or before nownow 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 AA steps. A cookie 32j+a32j + a steps old with j≥1j \ge 1 and a≤Aa \le A rebuilds an age of aa and passes line L6; line L7 rejects it, because the hash was made with the older counter value, except with probability 2−242^{-24}. 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 T[m]T[m].

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 t=1000t = 1000 and a client MSS of 1460. The table is T=(536,1220,1300,1400,1440,1460,4312,8960)T = (536, 1220, 1300, 1400, 1440, 1460, 4312, 8960), so m=5m = 5. Then t mod 32=8t \bmod 32 = 8, the truncated hash is $h = $ 0xd79c4e, and

y=8⋅227+5⋅224+0xd79c4e=0x45d79c4e=1171758158.y = 8 \cdot 2^{27} + 5 \cdot 2^{24} + \text{0xd79c4e} = \text{0x45d79c4e} = 1171758158 .

The real client answers with $a = $ 0x45d79c4f. The server checks it with A=2A = 2:

case aa nownow tt 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 now=1003now = 1003, line L5 gives 1003−((1003−8) mod 32)=1003−3=10001003 - ((1003 - 8) \bmod 32) = 1003 - 3 = 1000, so the counter is rebuilt even though the server never stored it.

Correctness

Theorem. (1) For every key KK, tuple cc, counter t≥0t \ge 0, index m∈{0,…,7}m \in \{0, \ldots, 7\} and time nownow with 0≤now−t≤A<320 \le now - t \le A < 32, CHECK-COOKIE$(K, c, $ MAKE-COOKIE(K,c,t,m)+1,now,A)(K, c, t, m) + 1, now, A) accepts and returns T[m]T[m]. (2) If FKF_K is a random function, then for any fixed cc, aa and nownow, chosen without seeing a value FK(c,t′)F_K(c, t') for the t′t' that line L5 computes, CHECK-COOKIE accepts with probability at most 2−242^{-24}. An adversary that sends qq such ACKs succeeds with probability at most q⋅2−24q \cdot 2^{-24} 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 t′t' with t′≡t5(mod32)t' \equiv t_5 \pmod{32} and now−31≤t′≤nownow - 31 \le t' \le now, so it returns tt when 0≤now−t≤310 \le now - t \le 31. For (2), aa and nownow fix one value t′t', and acceptance needs 24 bits of a uniform value to equal a fixed hh. 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 tt is a non-negative integer, m∈{0,…,7}m \in \{0, \ldots, 7\}, 0≤A<320 \le A < 32, and hK(c,t)=FK(c,t) mod 224h_K(c, t) = F_K(c, t) \bmod 2^{24}.

Lemma 1 (fields). Let $y = $ MAKE-COOKIE(K,c,t,m)(K, c, t, m). Then 0≤y<2320 \le y < 2^{32}, ⌊y/227⌋=t mod 32\lfloor y / 2^{27} \rfloor = t \bmod 32, ⌊y/224⌋ mod 8=m\lfloor y / 2^{24} \rfloor \bmod 8 = m and y mod 224=hK(c,t)y \bmod 2^{24} = h_K(c, t).

Proof. Line L2 returns y=(t mod 32)⋅227+m⋅224+hy = (t \bmod 32) \cdot 2^{27} + m \cdot 2^{24} + h with 0≤t mod 32≤310 \le t \bmod 32 \le 31, 0≤m≤70 \le m \le 7 and 0≤h<2240 \le h < 2^{24} by line L1. So 0≤y≤31⋅227+7⋅224+224−1=232−10 \le y \le 31 \cdot 2^{27} + 7 \cdot 2^{24} + 2^{24} - 1 = 2^{32} - 1. Since m⋅224+h<8⋅224=227m \cdot 2^{24} + h < 8 \cdot 2^{24} = 2^{27}, the quotient of yy by 2272^{27} is t mod 32t \bmod 32. Since h<224h < 2^{24}, the quotient of yy by 2242^{24} is (t mod 32)⋅8+m(t \bmod 32) \cdot 8 + m, and its residue mod 8 is mm. The residue of yy mod 2242^{24} is hh. □\square

Lemma 2 (the counter). Let t5∈{0,…,31}t_5 \in \{0, \ldots, 31\} and let t′=now−((now−t5) mod 32)t' = now - ((now - t_5) \bmod 32), as in line L5. Then t′≡t5(mod32)t' \equiv t_5 \pmod{32} and now−31≤t′≤nownow - 31 \le t' \le now. It is the only integer with both properties.

Proof. Let r=(now−t5) mod 32r = (now - t_5) \bmod 32, so 0≤r≤310 \le r \le 31 and now−t5−rnow - t_5 - r is a multiple of 32. Then t′=now−rt' = now - r lies in [now−31,now][now - 31, now], and t′−t5=now−t5−r≡0(mod32)t' - t_5 = now - t_5 - r \equiv 0 \pmod{32}. Two integers in an interval of 32 consecutive integers that are congruent mod 32 are equal, so t′t' is unique. □\square

Theorem, part 1 (completeness). If 0≤now−t≤A0 \le now - t \le A, then CHECK-COOKIE(K,c,(y+1) mod 232,now,A)(K, c, (y + 1) \bmod 2^{32}, now, A) with $y = $ MAKE-COOKIE(K,c,t,m)(K, c, t, m) returns ACCEPT with T[m]T[m].

Proof. Line L3 computes ((y+1) mod 232−1) mod 232=y((y + 1) \bmod 2^{32} - 1) \bmod 2^{32} = y, because 0≤y<2320 \le y < 2^{32} by Lemma 1. Line L4 then gives t5=t mod 32t_5 = t \bmod 32, the index mm and h=hK(c,t)h = h_K(c, t), by Lemma 1. The counter tt satisfies t≡t5(mod32)t \equiv t_5 \pmod{32} and now−31≤now−A≤t≤nownow - 31 \le now - A \le t \le now, because A≤31A \le 31. By Lemma 2, line L5 gives t′=tt' = t. Line L6 does not reject, because now−t≤Anow - t \le A and t≥0t \ge 0. Line L7 computes hK(c,t)=hh_K(c, t) = h, so it does not reject. Line L8 returns T[m]T[m]. □\square

Theorem, part 2 (soundness against an off-path adversary). Model FKF_K as a function drawn uniformly at random from all functions from the inputs to {0,1}256\{0, 1\}^{256}. Fix cc, aa and nownow, and let t′t' be the value of line L5 for these inputs. Suppose the adversary chooses aa without having seen FK(c,t′)F_K(c, t'). Then CHECK-COOKIE accepts with probability at most 2−242^{-24}. After qq such attempts, with any adaptive choice of the inputs, the probability that some attempt is accepted is at most q⋅2−24q \cdot 2^{-24}.

Proof. Lines L3 to L5 are fixed functions of aa and nownow, so t′t' and hh are fixed before FK(c,t′)F_K(c, t') is drawn. If line L6 rejects, the claim holds. Otherwise acceptance needs FK(c,t′) mod 224=hF_K(c, t') \bmod 2^{24} = h. The value FK(c,t′)F_K(c, t') is uniform on 256-bit strings and independent of what the adversary has seen, so its low 24 bits are uniform on {0,…,224−1}\{0, \ldots, 2^{24} - 1\}, and the probability is exactly 2−242^{-24}.

For qq 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 (c,t′)(c, t') they use, and let attempt group PP use qPq_P attempts with guesses in a set HPH_P of at most qPq_P values. Some attempt in group PP is accepted only if FK(P) mod 224∈HPF_K(P) \bmod 2^{24} \in H_P, which has probability ∣HP∣/224≤qP/224|H_P| / 2^{24} \le q_P / 2^{24}, since that value is uniform. By the union bound over the groups, some attempt is accepted with probability at most ∑PqP/224=q⋅2−24\sum_P q_P / 2^{24} = q \cdot 2^{-24}. Averaging over the coins keeps the bound. □\square

Remark (a real PRF). If FKF_K is HMAC-SHA256 with a secret uniform key, replace the random function by FKF_K. Any adversary whose success probability differs from the bound above by more than ε\varepsilon gives a distinguisher between FKF_K and a random function with advantage ε\varepsilon, using one oracle query per SYN-ACK it sees and per check. So the forgery probability is at most q⋅2−24+AdvFprfq \cdot 2^{-24} + \mathrm{Adv}^{\mathrm{prf}}_F. The bound says nothing about an adversary that sees the SYN-ACK to cc: it knows FK(c,t)F_K(c, t) and can complete the handshake. ■\blacksquare

Complexity

All costs are in the word RAM model, with one call of FKF_K on an input of at most 45 bytes counted as O(1)O(1) (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: O(1)O(1).
  • Time per ACK. Lines L3 to L6 are constant arithmetic and line L7 is one hash: O(1)O(1).
  • Space. The server keeps KK, the counter and the table TT. It keeps nothing per request, so the space is O(1)O(1) for any number nn of pending requests. A SYN cache keeps Θ(n)\Theta(n) 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 KK, cc, tt and mm 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 A+1A + 1 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 KK 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 cc and tt with no secret, anyone can compute cookies, and a forged ACK passes. Line L1 must use a keyed PRF with a secret KK of at least 128 bits, drawn from a cryptographic source.
  • Rebuilding the counter wrong. Writing line L5 as t←t5t \leftarrow t_5 or as now−(now mod 32)+t5now - (now \bmod 32) + t_5 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 now−((now−t5) mod 32)now - ((now - t_5) \bmod 32).
  • Forgetting the +1+1. Line L3 must undo the client's increment modulo 2322^{32}. Using aa itself, or a−1a - 1 without the modulus, rejects every client, or the one with a=0a = 0.
  • 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.

syn_cookies.pyI0RawGitHub
# 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

  1. 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)
  2. Daniel J. Bernstein, SYN cookies, the whole page (the history from September 1996, the time counter and why the cookie depends on time)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example