Algorithm Search⌘K

Algorithmcore

Probabilistic packet marking

Also called PPM traceback, Savage packet marking.

Each router overwrites a mark in a packet with a small probability, and the next router completes it into an edge with a distance. The victim rebuilds the attack path from many packets.

Time
O(1) worst · average · best
Space
O(e) extra
Where
d = the number of routers on the attack path; e = the number of distinct edges received; m = the number of packets received; p = the marking probability
Properties
randomizedonlinestateless routers
Origin
Stefan Savage, David Wetherall, Anna Karlin, Tom Anderson, 2000

Probabilistic packet marking (PPM) is a solution to the IP traceback problem in which routers write parts of the path into the packets they forward. In edge sampling, the version of Savage, Wetherall, Karlin and Anderson, each router overwrites a mark field with its own address with a small probability pp, the next router writes its address as the other end of the edge, and every router adds one to a distance field. A victim of a flood collects the marks and rebuilds the attack path, router by router, from the edges and their distances. Routers keep no state, and the part of the path between the victim and the attacker cannot be faked.

In plain words

Think of a long line of people who pass a bucket of notes from a stranger to you. Each person, with a small chance, throws out the note in the bucket and writes a new one: "I am Ann". The next person in line adds "and after me came Bob", and every person after that adds a tally mark. When the bucket arrives, the note says who wrote it, who came next, and how many people passed it after that.

One bucket tells you about one pair of neighbors in the line. After many buckets you have a note for every pair, and the tally marks tell you how to put the pairs in order. A fake note from the stranger may be thrown out by anyone, and if it survives, its tally shows that it started beyond the whole line.

The problem

The setting is the approximate traceback problem of the IP traceback problem page. An attacker sends many packets to a victim vv along a stable path of routers R1,…,RdR_1, \ldots, R_d, where R1R_1 is the first router after the attacker and RdR_d is next to vv. Each packet has a mark with three fields: start, end and distance. The attacker can write any value into these fields. Routers have no memory per flow. From the marks it receives, vv must output a path that ends with (R1,…,Rd,v)(R_1, \ldots, R_d, v). The threat model is that of Savage et al., Section 3.2: no router on the path is compromised.

The algorithm

Each router runs MARK on each packet it forwards, with a fresh uniform draw uu. The victim runs RECONSTRUCT on the marks of the packets it received. The distance field saturates at its largest value, 31 for the 5-bit field of the IP encoding.

  1. MARK(w, R, p) ▷ router R forwards a packet with mark w
  2. 1u ← a uniform draw from [0, 1)
  3. 2if u < p then
  4. 3return (R, nil, 0) ▷ start, end, distance
  5. 4if w.distance = 0 then
  6. 5w.end ← R
  7. 6return (w.start, w.end, min(w.distance + 1, 31))
  8. RECONSTRUCT(W, v) ▷ W: the marks the victim received
  9. 7E ← the empty set of edges (x, y, k)
  10. 8for each mark w in W with w.start ≠ nil do
  11. 9if w.distance = 0 then add (w.start, v, 0) to E
  12. 10else add (w.start, w.end, w.distance) to E
  13. 11keep (x, y, k) only if y = v and k = 0, or (y, z, k - 1) is kept, for k = 0, 1, 2, ...
  14. 12return the kept edges and the paths they form toward v

The time column of the front matter is the cost of MARK for one router and one packet. A router that marks (line L3) starts a new edge and sets the distance to 0. The next router sees distance 0 and writes itself as the end of the edge (line L5); every router that does not mark adds one to the distance (line L6). So when the router jj hops from vv marks a packet and no later router marks it, the victim gets the edge from that router to the next one, with distance j−1j - 1. The router next to vv produces (Rd,nil,0)(R_d, \text{nil}, 0), which line L9 turns into the edge (Rd,v,0)(R_d, v, 0). Line L11 removes edges that do not chain to vv: it keeps the edges at distance 0 that end at vv, then the edges at distance 1 that end at the start of a kept edge, and so on.

Example

Take the path R1,R2,R3,R4R_1, R_2, R_3, R_4 to vv and p=1/4p = 1/4. A router marks when its draw is below 0.25. The table shows the first eight packets of a seeded run; when several routers mark one packet, only the last one counts.

packet draws at R1,R2,R3,R4R_1, R_2, R_3, R_4 routers that mark mark at vv edges known
1 0.32, 0.15, 0.65, 0.07 R2R_2, R4R_4 (R4,nil,0)(R_4, \text{nil}, 0) (R4,v,0)(R_4, v, 0)
2 0.54, 0.37, 0.06, 0.51 R3R_3 (R3,R4,1)(R_3, R_4, 1) + (R3,R4,1)(R_3, R_4, 1)
3 0.04, 0.43, 0.07, 0.09 R1R_1, R3R_3, R4R_4 (R4,nil,0)(R_4, \text{nil}, 0) no change
4 0.42, 0.83, 0.12, 0.22 R3R_3, R4R_4 (R4,nil,0)(R_4, \text{nil}, 0) no change
5 0.63, 0.95, 0.58, 0.40 none the empty initial mark, now (nil,R1,4)(\text{nil}, R_1, 4) no change
6 0.98, 0.05, 0.86, 0.29 R2R_2 (R2,R3,2)(R_2, R_3, 2) + (R2,R3,2)(R_2, R_3, 2)
7 0.14, 0.12, 0.31, 0.82 R1R_1, R2R_2 (R2,R3,2)(R_2, R_3, 2) no change
8 0.18, 0.58, 0.64, 0.37 R1R_1 (R1,R2,3)(R_1, R_2, 3) + (R1,R2,3)(R_1, R_2, 3)

After packet 8 the victim has all four edges, and line L11 keeps them in the order of their distances: (R1,R2,R3,R4,v)(R_1, R_2, R_3, R_4, v). A forged mark such as (X,Y,3)(X, Y, 3) that survives all four routers arrives as (X,Y,7)(X, Y, 7); line L11 drops it, because no kept edge at distance 6 starts at YY.

The mark of the router jj hops from vv arrives with probability qj=p(1−p)j−1q_j = p(1-p)^{j-1}: here 0.25, 0.1875, 0.1406 and 0.1055, and the attacker's mark survives with probability (3/4)4=0.3164(3/4)^4 = 0.3164. The exact expected number of packets until all four edges arrive is 14.17. For the case d=10d = 10 and p=1/25p = 1/25 that Savage et al. use, the exact expectation is 89.57 packets.

Correctness

Theorem. Assume that no router on the path is compromised and the path is fixed. (1) Each packet's mark at vv is the edge (Rd−j+1,Rd−j+2,j−1)(R_{d-j+1}, R_{d-j+2}, j - 1) (with Rd+1=vR_{d+1} = v) with probability qj=p(1−p)j−1q_j = p(1-p)^{j-1} for j=1,…,dj = 1, \ldots, d, independently across packets, and otherwise it is the attacker's mark with distance at least dd. (2) If WW contains every edge of the path, RECONSTRUCT keeps all of them, and every other kept edge has distance at least dd, so every path it returns ends with (R1,…,Rd,v)(R_1, \ldots, R_d, v). This solves approximate traceback robustly against an attacker who controls the initial mark. (3) The expected number of packets until every edge has arrived is

E[X]=∑∅≠S⊆{1,…,d}(−1)∣S∣+1∑j∈Sqj≤Hdp(1−p)d−1.E[X] = \sum_{\emptyset \ne S \subseteq \{1, \ldots, d\}} \frac{(-1)^{|S|+1}}{\sum_{j \in S} q_j} \le \frac{H_d}{p(1-p)^{d-1}} .

The key invariant for (1) is that after the router at position ii the distance field equals the number of routers since the last marking router, or exceeds the number of routers so far if none marked; the saturation at 31 keeps this a lower bound. Part (3) is inclusion and exclusion on the event that some edge is missing, and the bound is the coupon collector argument with each missing edge arriving with probability at least p(1−p)d−1p(1-p)^{d-1}. The full proof is in proofs/correctness.md.

About the printed bound. Savage et al. (Section 4.3) write the bound as E[X]<ln⁡(d)/(p(1−p)d−1)E[X] < \ln(d) / (p(1-p)^{d-1}), from the coupon collector estimate d(ln⁡d+O(1))d(\ln d + O(1)) with the O(1)O(1) term dropped. It is an estimate, not a bound: for d=10d = 10 and p=1/25p = 1/25 it gives 83.12, but the exact value is 89.57; for d=2d = 2 and p=1/25p = 1/25 it gives 18.05 against an exact 38.29. The bound with the harmonic number HdH_d holds for all dd and pp: it gives 105.73 for d=10d = 10 and p=1/25p = 1/25.

Proof: Correctness of probabilistic packet marking (edge sampling)full

Setting. The path is R1,…,RdR_1, \ldots, R_d with RdR_d next to the victim vv, and we write Rd+1=vR_{d+1} = v. The path is fixed, and no router on it is compromised. The attacker chooses the initial mark w0=(s0,e0,k0)w_0 = (s_0, e_0, k_0) of every packet with 0≤k0≤310 \le k_0 \le 31, and may choose it as a function of everything except the draws of the routers on the path. Each router runs MARK of the main page with a fresh uniform draw, independent of all other draws. We assume d≤31d \le 31, so the saturated distance field never hides a path length.

Lemma 1 (the mark at the victim). Fix one packet. Let JJ be the position of the last router on the path that marks it, if any. If J=iJ = i, the mark at vv is (Ri,nil,0)(R_i, \text{nil}, 0) when i=di = d and (Ri,Ri+1,d−i)(R_i, R_{i+1}, d - i) when i<di < d. If no router marks, the mark at vv has distance min⁡(k0+d,31)≥d\min(k_0 + d, 31) \ge d.

Proof. After a router marks (line L3), the mark is (Ri,nil,0)(R_i, \text{nil}, 0). The routers Ri+1,…,RdR_{i+1}, \ldots, R_d do not mark, by the choice of ii. Each of them runs lines L4 to L6. By induction on t=0,…,d−it = 0, \ldots, d - i, after the router Ri+tR_{i+t} the distance is tt, and for t≥1t \ge 1 the end field is Ri+1R_{i+1}: at t=1t = 1 the distance before Ri+1R_{i+1} is 0, so line L5 writes Ri+1R_{i+1}; for t≥2t \ge 2 the distance before Ri+tR_{i+t} is t−1≥1t - 1 \ge 1, so line L5 does not run and the end field stays Ri+1R_{i+1}. Since t≤d≤31t \le d \le 31, the minimum in line L6 equals tt. For t=d−it = d - i this gives the claim. If no router marks, each of the dd routers runs line L6 once, and the distance is min⁡(k0+d,31)\min(k_0 + d, 31), which is at least dd because k0≥0k_0 \ge 0 and d≤31d \le 31. □\square

Lemma 2 (the probabilities). For j=1,…,dj = 1, \ldots, d, the mark at vv yields the edge fj=(Rd−j+1,Rd−j+2,j−1)f_j = (R_{d-j+1}, R_{d-j+2}, j - 1) (after line L9 turns (Rd,nil,0)(R_d, \text{nil}, 0) into (Rd,v,0)(R_d, v, 0)) with probability qj=p(1−p)j−1q_j = p(1-p)^{j-1}, and these events are independent across packets.

Proof. By Lemma 1 the edge fjf_j arrives exactly when the router Rd−j+1R_{d-j+1} marks and the j−1j - 1 routers after it do not. These are independent events of probabilities pp and 1−p1 - p, so the probability is p(1−p)j−1p(1-p)^{j-1}. Different packets use independent draws. The attacker's choice of w0w_0 does not change this event, because line L3 discards w0w_0. □\square

Lemma 3 (forged edges sit beyond the suffix). Every edge in EE (after lines L8 to L10) is either some fjf_j or has distance at least dd.

Proof. By Lemma 1, a mark at vv either comes from a router on the path, and then gives some fjf_j, or no router marked it, and then its distance is at least dd. □\square

Theorem 1 (reconstruction). If EE contains every fjf_j, then RECONSTRUCT keeps every fjf_j, every other kept edge has distance at least dd, and every maximal chain of kept edges ends with (R1,…,Rd,v)(R_1, \ldots, R_d, v) or contains it as a suffix.

Proof. Line L11 keeps the edges level by level: at level k=0k = 0 the edges (x,v,0)(x, v, 0), at level k≥1k \ge 1 the edges (x,y,k)(x, y, k) whose end yy is the start of a kept edge at level k−1k - 1. By induction on k=0,…,d−1k = 0, \ldots, d - 1, the edge fk+1f_{k+1} is kept: f1=(Rd,v,0)f_1 = (R_d, v, 0) is kept at level 0, and fk+1=(Rd−k,Rd−k+1,k)f_{k+1} = (R_{d-k}, R_{d-k+1}, k) ends at Rd−k+1R_{d-k+1}, the start of the kept fkf_k. By Lemma 3, every kept edge other than the fjf_j has distance at least dd. A chain toward vv visits kept edges with distances 0,1,2,…0, 1, 2, \ldots in order, and the edges at distances 0,…,d−10, \ldots, d - 1 that end at the start of the previous edge are the fjf_j only, by Lemma 3. So the last dd edges of every chain of length at least dd are fd,…,f1f_d, \ldots, f_1, which spell (R1,…,Rd,v)(R_1, \ldots, R_d, v). □\square

The algorithm is therefore a robust solution of approximate traceback against this attacker: a forged mark can add edges only at distance dd or more, before R1R_1.

Theorem 2 (expected number of packets). Let XX be the number of packets until every fjf_j has arrived. Then

E[X]=∑∅≠S⊆{1,…,d}(−1)∣S∣+1∑j∈Sqj≤Hdp(1−p)d−1,E[X] = \sum_{\emptyset \ne S \subseteq \{1, \ldots, d\}} \frac{(-1)^{|S|+1}}{\sum_{j \in S} q_j} \le \frac{H_d}{p(1-p)^{d-1}} ,

where Hd=1+1/2+⋯+1/dH_d = 1 + 1/2 + \cdots + 1/d.

Proof of the equality. Let TjT_j be the index of the first packet that yields fjf_j, so X=max⁡jTjX = \max_j T_j. For n≥0n \ge 0, Pr⁡[X>n]=Pr⁡[⋃j{Tj>n}]\Pr[X > n] = \Pr[\bigcup_j \{T_j > n\}]. For a nonempty set SS, the event ⋂j∈S{Tj>n}\bigcap_{j \in S} \{T_j > n\} says that none of the first nn packets yields an edge of SS. The edges fjf_j are disjoint outcomes of one packet, so a packet yields an edge of SS with probability QS=∑j∈SqjQ_S = \sum_{j \in S} q_j, and the event has probability (1−QS)n(1 - Q_S)^n. By inclusion and exclusion,

Pr⁡[X>n]=∑∅≠S(−1)∣S∣+1(1−QS)n.\Pr[X > n] = \sum_{\emptyset \ne S} (-1)^{|S|+1} (1 - Q_S)^n .

Summing over n≥0n \ge 0 with E[X]=∑n≥0Pr⁡[X>n]E[X] = \sum_{n \ge 0} \Pr[X > n] and ∑n≥0(1−QS)n=1/QS\sum_{n \ge 0} (1 - Q_S)^n = 1 / Q_S (valid since 0<QS≤10 < Q_S \le 1; the sums are finite, so the order of summation can be changed) gives the equality.

Proof of the bound. Let q=min⁡jqj=p(1−p)d−1q = \min_j q_j = p(1-p)^{d-1}. Split the time into phases: phase ii, for i=0,…,d−1i = 0, \ldots, d - 1, starts when exactly ii distinct edges of the path have arrived and ends when one more arrives. During phase ii, d−id - i edges are missing, and each packet yields one of them with probability ∑j missingqj≥(d−i)q\sum_{j \text{ missing}} q_j \ge (d - i) q, independently of earlier packets. So the length of phase ii is a geometric random variable with success probability at least (d−i)q(d - i) q, and its mean is at most 1/((d−i)q)1 / ((d - i) q). By linearity of expectation,

E[X]≤∑i=0d−11(d−i)q=Hdq=Hdp(1−p)d−1.E[X] \le \sum_{i=0}^{d-1} \frac{1}{(d - i) q} = \frac{H_d}{q} = \frac{H_d}{p(1-p)^{d-1}} .

□\square

Remark (the printed estimate). Savage et al. state E[X]<ln⁡(d)/(p(1−p)d−1)E[X] < \ln(d)/(p(1-p)^{d-1}). Since Hd>ln⁡dH_d > \ln d, this does not follow from the argument above, and it is false in general: for d=2d = 2 and p=1/25p = 1/25 the equality of Theorem 2 gives E[X]≈38.29E[X] \approx 38.29, while ln⁡(2)/(p(1−p))≈18.05\ln(2)/(p(1-p)) \approx 18.05. For d=10d = 10 and p=1/25p = 1/25 the exact value is about 89.57 and the estimate is about 83.12. The bound with HdH_d gives about 105.73 there. ■\blacksquare

Complexity

In the word RAM model, with router addresses as words:

  • Routers. MARK does one draw, one comparison and at most two writes: O(1)O(1) time per packet per router and no memory per flow.
  • Victim. Lines L7 to L10 take O(m)O(m) expected time with a hash set for mm marks. Line L11 groups the ee distinct edges by distance and checks each against the starts of the previous level, which is O(e)O(e) expected time. The space is O(e)O(e).
  • Packets. By the theorem, the expected number of packets is at most Hd/(p(1−p)d−1)H_d / (p(1-p)^{d-1}). The function p(1−p)d−1p(1-p)^{d-1} is largest at p=1/dp = 1/d, which is why Savage et al. suggest pp near 1/d1/d; their examples use p=1/25p = 1/25.

Properties

  • Stateless routers. No table, no per-flow memory, and no extra packets.
  • Robust suffix. A forged mark can only add edges at distance dd or more, so it cannot change the part of the answer next to the victim.
  • Needs many packets. Rebuilding a path takes tens to thousands of packets, so PPM fits floods, not single packets.
  • Randomized. The marks depend on the draws of the routers, so the number of packets is a random variable; the theorem bounds its mean.

Variants and improvements

  • Node append. Every router appends its address to the packet (Section 4.1). The path arrives in one packet, but the packet grows with dd, which IP does not allow.
  • Node sampling. Each router writes only its address with probability pp (Section 4.2). The victim orders routers by how often they appear, which needs very many packets for far routers: Savage et al. report more than 42,000 packets for d=15d = 15 and p=0.51p = 0.51. It is also not robust to forged marks.
  • Compressed edge fragments. To fit in the 16-bit IP identification field, a router stores the XOR of the two addresses of an edge and splits it, with a hash for checking, into k=8k = 8 fragments of 8 bits (Sections 5.1 and 5.2: 3 bits of offset, 5 bits of distance, 8 bits of fragment). The victim must collect all kdk d fragments. Savage et al. give about kln⁡(kd)/(p(1−p)d−1)k \ln(kd)/(p(1-p)^{d-1}), slightly under 1300 packets for k=8k = 8, d=10d = 10 and p=1/25p = 1/25; the exact expectation by inclusion and exclusion over the 80 fragments is 1228.5.
  • Advanced and authenticated marking. Song and Perrig (INFOCOM 2001) use a map of upstream routers to cut the cost of reconstruction with many attackers, and add authentication of marks against compromised routers.
  • Fewer bits. Adler (STOC 2002) showed that a single bit per packet suffices for one path, at a cost in packets that grows exponentially with the length of the path's description, and studied the trade-off between bits and packets.

When to use it

Use PPM when the routers on the path cannot keep state and the attack is a flood of many packets. Use hash-based IP traceback when a single packet must be traced and the routers can store digests for a time window. Use ingress filtering to prevent forged sources in the first place; PPM exists because ingress filtering is not deployed everywhere. With many attackers on many paths, the victim gets many edges at each distance, and combining fragments becomes expensive; this is the case that Song and Perrig improved.

Pitfalls

  • Writing the end on every packet. If the test of line L4 is dropped and line L5 writes w.end←Rw.end \leftarrow R whenever the router does not mark, the end field holds the last router instead of the router after the start, and every edge with distance above 1 is wrong. Write the end only when w.distance=0w.distance = 0, as in line L4.
  • Wrapping the distance. If line L6 uses w.distance+1w.distance + 1 modulo 32 instead of saturating at 31, an attacker can set the initial distance so that it wraps to a small value at the victim, and a forged edge then lands inside the valid suffix. Use min⁡(w.distance+1,31)\min(w.distance + 1, 31).
  • Trusting edges that do not chain. If line L11 is skipped and every received edge is used, a forged mark adds routers that are not on the path. Keep only edges that chain to vv with distances decreasing by one.
  • A large marking probability. With p=1/2p = 1/2 and d=10d = 10, the far router's edge arrives with probability 2−102^{-10}, and the expected number of packets is in the thousands. Choose pp near 1/d1/d for the longest expected path.
  • Using the printed estimate as a bound. The value ln⁡(d)/(p(1−p)d−1)\ln(d)/(p(1-p)^{d-1}) is below the true expectation for small dd and for d=10d = 10, p=1/25p = 1/25. Use the exact sum or the bound with HdH_d.

Implementations

The code runs on synthetic paths and trees of abstract router names; it builds no packet and touches no network. The tests enumerate every marking decision on short paths and compare the distribution of the mark at the victim with qjq_j, rebuild random attack trees, and check the Monte Carlo mean against the exact expectation.

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.

probabilistic_packet_marking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/probabilistic-packet-marking/. The authors are listed in prov/EZNZ9R.jsonl.

"""Edge sampling of Savage, Wetherall, Karlin and Anderson (SIGCOMM 2000, Section 4.3).

Routers are abstract names on a synthetic path or tree. A mark is a tuple
(start, end, distance). No packet is built and no network is touched.
"""

from fractions import Fraction
from itertools import combinations
from math import log
from typing import Hashable, Iterable

Router = Hashable
Mark = tuple[Router | None, Router | None, int]
Edge = tuple[Router, Router, int]

DIST_MAX = 31  # the 5-bit distance field of Section 5.2 saturates here


def mark(w: Mark, r: Router, p: float, u: float) -> Mark:
    """Router r forwards a packet with mark w; u is its uniform draw in [0, 1).

    Precondition: 0 < p < 1 and 0 <= u < 1. Cost: O(1).
    """
    start, end, distance = w
    # @line L1 (the caller draws u)
    if u < p:  # @line L2
        return (r, None, 0)  # @line L3
    if distance == 0:  # @line L4
        end = r  # @line L5
    return (start, end, min(distance + 1, DIST_MAX))  # @line L6


def send(path: list[Router], w0: Mark, p: float, us: Iterable[float]) -> Mark:
    """The mark that reaches the victim after the routers of path, in order.

    path[0] is the router next to the attacker and path[-1] the router next to
    the victim; w0 is the mark the attacker wrote. Cost: O(len(path)).
    """
    w = w0
    for r, u in zip(path, us):
        w = mark(w, r, p, u)
    return w


def reconstruct(marks: Iterable[Mark], v: Router) -> set[Edge]:
    """Keep the edges that chain to the victim v with consistent distances.

    An edge (x, y, k) is kept when y = v and k = 0, or when a kept edge
    (y, z, k - 1) exists. Cost: O(m + e log e) for m marks and e distinct edges.
    """
    edges: set[Edge] = set()  # @line L7
    for start, end, distance in marks:  # @line L8
        if start is None:
            continue
        if distance == 0:  # @line L9
            edges.add((start, v, 0))
        elif end is not None:  # @line L10
            edges.add((start, end, distance))
    kept: set[Edge] = set()  # @line L11
    level = {v}
    by_dist: dict[int, list[Edge]] = {}
    for e in edges:
        by_dist.setdefault(e[2], []).append(e)
    for k in range(0, max(by_dist, default=-1) + 1):
        nxt = set()
        for x, y, dist in by_dist.get(k, []):
            if y in level:
                kept.add((x, y, dist))
                nxt.add(x)
        level = nxt
        if not level:
            break
    return kept  # @line L12


def paths(kept: set[Edge], v: Router) -> set[tuple[Router, ...]]:
    """All maximal chains in the kept edges, each listed from far end to v."""
    into: dict[Router, list[Router]] = {}
    for x, y, _ in kept:
        into.setdefault(y, []).append(x)
    out: set[tuple[Router, ...]] = set()
    stack: list[tuple[Router, ...]] = [(v,)]
    while stack:
        chain = stack.pop()
        preds = into.get(chain[0], [])
        if not preds and len(chain) > 1:
            out.add(chain)
        for x in preds:
            if x not in chain:
                stack.append((x,) + chain)
    return out


def edge_probabilities(d: int, p: Fraction) -> list[Fraction]:
    """q[j] = p (1 - p)^j: the chance that the edge of the router j + 1 hops from the victim arrives."""
    return [p * (1 - p) ** j for j in range(d)]


def expected_packets(d: int, p: Fraction) -> Fraction:
    """Exact E[packets until all d edges have arrived], by inclusion and exclusion.

    E = sum over nonempty S of (-1)^(|S|+1) / sum_{j in S} q_j. Cost: O(2^d d).
    """
    q = edge_probabilities(d, p)
    total = Fraction(0)
    for size in range(1, d + 1):
        sign = 1 if size % 2 else -1
        for s in combinations(q, size):
            total += sign / sum(s)
    return total


def harmonic_bound(d: int, p: float) -> float:
    """H_d / (p (1 - p)^(d - 1)), an upper bound on expected_packets."""
    return sum(1 / i for i in range(1, d + 1)) / (p * (1 - p) ** (d - 1))


def savage_estimate(d: int, p: float) -> float:
    """ln(d) / (p (1 - p)^(d - 1)), the estimate printed by Savage et al."""
    return log(d) / (p * (1 - p) ** (d - 1))
test_probabilistic_packet_marking.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/probabilistic-packet-marking/. The authors are listed in prov/EZNZ9R.jsonl.

import random
from fractions import Fraction
from itertools import product

from probabilistic_packet_marking import (
    expected_packets,
    harmonic_bound,
    mark,
    paths,
    reconstruct,
    savage_estimate,
    send,
)

EMPTY = (None, None, 0)


def path_edges(path: list[str], v: str) -> set[tuple[str, str, int]]:
    d = len(path)
    nxt = path[1:] + [v]
    return {(path[i], nxt[i], d - 1 - i) for i in range(d)}


def test_example() -> None:
    path = ["R1", "R2", "R3", "R4"]
    # R2 marks; R3 and R4 do not.
    w = send(path, EMPTY, 0.25, [0.9, 0.1, 0.9, 0.9])
    assert w == ("R2", "R3", 2)
    # R4, next to the victim, marks.
    assert send(path, EMPTY, 0.25, [0.9, 0.9, 0.9, 0.1]) == ("R4", None, 0)
    # Nobody marks: the attacker's mark arrives, 4 hops further away.
    assert send(path, ("X", "Y", 3), 0.25, [0.9] * 4) == ("X", "Y", 7)
    marks = [("R4", None, 0), ("R3", "R4", 1), ("R2", "R3", 2), ("R1", "R2", 3), ("X", "Y", 7), ("X", "R9", 2)]
    kept = reconstruct(marks, "V")
    assert kept == path_edges(path, "V")
    assert paths(kept, "V") == {("R1", "R2", "R3", "R4", "V")}
    assert abs(float(expected_packets(10, Fraction(1, 25))) - 89.572) < 0.001
    assert abs(savage_estimate(10, 0.04) - 83.122) < 0.001
    assert abs(harmonic_bound(10, 0.04) - 105.734) < 0.001


def test_edges() -> None:
    assert reconstruct([], "V") == set()
    assert paths(set(), "V") == set()
    assert reconstruct([EMPTY], "V") == set()
    assert expected_packets(1, Fraction(1, 2)) == 2
    # d = 2, p = 1/2: q = 1/2 and 1/4, E = 2 + 4 - 4/3.
    assert expected_packets(2, Fraction(1, 2)) == Fraction(14, 3)
    # The distance saturates at 31.
    assert mark(("X", "Y", 31), "R", 0.5, 0.9) == ("X", "Y", 31)
    # A forged mark with distance 0 is completed by the first router.
    assert send(["R1", "R2"], ("X", None, 0), 0.5, [0.9, 0.9]) == ("X", "R1", 2)


def test_mark_distribution_exact() -> None:
    """Enumerate every marking decision and compare with q_j = p (1 - p)^j."""
    rng = random.Random(2000)
    for _ in range(500):
        d = rng.randrange(1, 7)
        p = Fraction(rng.randrange(1, 10), 10)
        path = [f"R{i}" for i in range(1, d + 1)]
        w0 = ("X", "Y", rng.randrange(0, 4))
        dist: dict[tuple, Fraction] = {}
        for bits in product((0, 1), repeat=d):
            us = [0.0 if b else 0.999999 for b in bits]
            w = send(path, w0, float(p), us)
            pr = Fraction(1)
            for b in bits:
                pr *= p if b else 1 - p
            dist[w] = dist.get(w, Fraction(0)) + pr
        want = {e: p * (1 - p) ** e[2] for e in ((path[i], (path[i + 1] if i + 1 < d else None), d - 1 - i) for i in range(d))}
        forged = (w0[0], w0[1] if w0[2] > 0 else path[0], w0[2] + d)
        want[forged] = (1 - p) ** d
        assert dist == want


def random_tree(rng: random.Random, n: int) -> dict[str, str]:
    """Parent links of a random tree of routers R1..Rn rooted at the victim V."""
    parent = {}
    names = [f"R{i}" for i in range(1, n + 1)]
    for i, r in enumerate(names):
        parent[r] = "V" if i == 0 or rng.random() < 0.2 else names[rng.randrange(0, i)]
    return parent


def test_reconstruct_random_trees() -> None:
    """Collect marks from several attackers until every edge has arrived; compare with the true graph."""
    rng = random.Random(295)
    for _ in range(500):
        parent = random_tree(rng, rng.randrange(1, 9))
        leaves = [r for r in parent if r not in parent.values()]
        attackers = rng.sample(leaves, rng.randrange(1, len(leaves) + 1))
        true_edges: set = set()
        routes = []
        for a in attackers:
            route = [a]
            while parent[route[-1]] != "V":
                route.append(parent[route[-1]])
            routes.append(route)
            true_edges |= path_edges(route, "V")
        p = rng.choice((0.2, 0.3, 0.5))
        marks = []
        seen: set = set()
        while not true_edges <= seen:
            route = routes[rng.randrange(len(routes))]
            w0 = (f"F{rng.randrange(3)}", "Y", rng.randrange(0, 3))
            w = send(route, w0, p, (rng.random() for _ in route))
            marks.append(w)
            if w[0] is not None:
                seen.add((w[0], "V" if w[2] == 0 else w[1], w[2]))
        kept = reconstruct(marks, "V")
        assert true_edges <= kept
        for x, y, k in kept - true_edges:
            assert x.startswith("F")  # only attacker marks add edges
            route = next(r for r in routes if y in r)
            assert k >= len(route) - route.index(y)  # and they sit beyond the valid suffix
        for chain in paths(kept, "V"):
            assert any(list(chain[len(chain) - 1 - len(r):-1]) == r for r in routes)


def test_convergence_monte_carlo() -> None:
    """The mean number of packets matches the exact expectation within 4 standard errors."""
    rng = random.Random(306)
    d, p = 5, Fraction(1, 5)
    path = [f"R{i}" for i in range(1, d + 1)]
    want = path_edges(path, "V")
    counts = []
    for _ in range(2000):
        seen: set = set()
        n = 0
        while len(seen) < d:
            w = send(path, EMPTY, float(p), (rng.random() for _ in path))
            n += 1
            if w[0] is not None:
                seen.add((w[0], "V" if w[2] == 0 else w[1], w[2]))
        assert seen == want
        counts.append(n)
    mean = sum(counts) / len(counts)
    var = sum((c - mean) ** 2 for c in counts) / (len(counts) - 1)
    exact = float(expected_packets(d, p))
    assert abs(mean - exact) < 4 * (var / len(counts)) ** 0.5
    assert exact <= harmonic_bound(d, float(p))


def test_bounds() -> None:
    rng = random.Random(25)
    for _ in range(40):
        d = rng.randrange(1, 9)
        p = Fraction(rng.randrange(1, 20), 20)
        assert float(expected_packets(d, p)) <= harmonic_bound(d, float(p)) + 1e-9
    # The printed estimate is not an upper bound for small d.
    assert float(expected_packets(2, Fraction(1, 25))) > savage_estimate(2, 0.04)

History

Savage et al. credit Burch and Cheswick with the idea of marking packets with the addresses of routers to trace floods. Savage, Wetherall, Karlin and Anderson worked out node append, node sampling, edge sampling and the compressed encoding, with an implementation and a simulation, at SIGCOMM 2000, and in the journal version in 2001. Song and Perrig improved the reconstruction and added authentication in 2001, and Adler gave the first study of how many header bits a marking scheme needs in 2002.

References

  1. Stefan Savage, David Wetherall, Anna Karlin and Tom Anderson, Practical network support for IP traceback, ACM SIGCOMM 2000, pages 295 to 306, doi:10.1145/347059.347560, Section 3 (definitions and assumptions), Section 4.2 (node sampling), Section 4.3 and Figure 4 (edge sampling and its expected number of packets), Section 5.1 (compressed edge fragments) and Section 5.2 (the encoding in the IP identification field)
  2. Stefan Savage, David Wetherall, Anna Karlin and Tom Anderson, Network support for IP traceback, IEEE/ACM Transactions on Networking 9(3), pages 226 to 237, 2001, the journal version of the same algorithms and analysis
  3. Micah Adler, Tradeoffs in probabilistic packet marking for IP traceback, ACM STOC 2002, pages 407 to 418, the abstract and the introduction (the trade-off between header bits and packets)

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