Algorithm Search⌘K

Algorithmadvanced

Threshold random walk scan detection

Also called sequential hypothesis testing for port scans.

Detects a scanner by a sequential probability ratio test on whether its connection attempts succeed or fail.

Time
O(n log n) worstO(n) average
Space
O(d) extra
Where
d = the number of distinct (source, destination) pairs of sources that are still pending; n = the number of connection events
Properties
deterministicexact error boundsonlineiterative
Origin
Jaeyeon Jung, Vern Paxson, Arthur W. Berger, Hari Balakrishnan, 2004

Threshold random walk (TRW) decides whether a remote source is a scanner from the outcomes of its first connection attempts to distinct local hosts. A scanner does not know which addresses and services are in use, so many of its attempts fail. A benign source mostly contacts hosts that exist, so most of its attempts succeed. TRW runs Wald's sequential probability ratio test on these outcomes, one source at a time, and stops as soon as the evidence is strong enough. Jung, Paxson, Berger and Balakrishnan (2004) gave it, with false alarm and miss rates bounded by two chosen numbers α\alpha and β\beta, and it needed only 4 or 5 contacts per scanner on their traces. The page is about detection: the input is a list of outcomes that a monitor has already labeled, and the algorithm sends nothing.

In plain words

Watch one outside address. Each time it tries a new inside address for the first time, write down "worked" or "failed". A failure is a small piece of evidence that the outsider is probing blindly. A success is a small piece of evidence that it knows where it is going.

Keep a running score. Each failure pushes the score up, and each success pushes it down. When the score passes an upper line, call the outsider a scanner. When it passes a lower line, call it benign and stop watching it. Between the lines, wait for more evidence.

The two lines come from two error rates that you choose: how often a benign outsider may be called a scanner, and how often a scanner may be missed. The score walks up and down, and the walk stops at a line. Hence the name.

The problem

Each event is a triple (r,d,y)(r, d, y): a remote source rr, a local destination dd, and the outcome yy of the first connection attempt from rr to dd, with y=0y = 0 for a success and y=1y = 1 for a failure. A failure is an attempt to an address with no host, or to a host that does not offer the service. Repeat contacts with the same dd do not count. For each source the task is to decide between two hypotheses, H0H_0 (the source is benign) and H1H_1 (the source is a scanner), and to decide after as few first contacts as possible.

The model of Jung et al. is that, given the hypothesis, the outcomes Y1,Y2,…Y_1, Y_2, \ldots of the first contacts of one source are independent, with

P(Yi=0∣H0)=θ0,P(Yi=0∣H1)=θ1,θ0>θ1.P(Y_i = 0 \mid H_0) = \theta_0, \qquad P(Y_i = 0 \mid H_1) = \theta_1, \qquad \theta_0 > \theta_1.

The goals are a false alarm rate PF≤αP_F \le \alpha and a detection rate PD≥βP_D \ge \beta. Jung et al. used θ0=0.8\theta_0 = 0.8, θ1=0.2\theta_1 = 0.2, α=0.01\alpha = 0.01 and β=0.99\beta = 0.99. These four numbers are heuristic choices: the two θ\theta values are guesses of the success rates of benign sources and scanners, and α\alpha and β\beta are chosen rates. They are not facts about any network.

The algorithm

For a source with outcomes Y1,…,YkY_1, \ldots, Y_k, the likelihood ratio is

Λk=∏i=1kP(Yi∣H1)P(Yi∣H0),\Lambda_k = \prod_{i=1}^{k} \frac{P(Y_i \mid H_1)}{P(Y_i \mid H_0)},

so a success multiplies it by θ1/θ0<1\theta_1/\theta_0 < 1 and a failure by (1−θ1)/(1−θ0)>1(1 - \theta_1)/(1 - \theta_0) > 1. Wald's thresholds are η1=β/α\eta_1 = \beta/\alpha and η0=(1−β)/(1−α)\eta_0 = (1 - \beta)/(1 - \alpha). A new source starts with Λ=1\Lambda = 1, an empty set DD of destinations and the state PENDING.

  1. TRW(E, θ0, θ1, α, β) ▷ E: events (r, d, y) in arrival order
  2. 1η1 ← β / α ; η0 ← (1 - β) / (1 - α)
  3. 2for each event (r, d, y) in E do ▷ a new r gets Λ[r] = 1, D[r] = ∅, PENDING
  4. 3if state[r] ≠ PENDING then continue
  5. 4if d ∈ D[r] then continue ▷ only first contacts count
  6. 5D[r] ← D[r] ∪ {d}
  7. 6if y = 0 then Λ[r] ← Λ[r] · θ1 / θ0
  8. 7else Λ[r] ← Λ[r] · (1 - θ1) / (1 - θ0)
  9. 8if Λ[r] ≥ η1 then state[r] ← SCANNER
  10. 9else if Λ[r] ≤ η0 then state[r] ← BENIGN
  11. 10return state[r] and |D[r]| for each source r

Line L3 stops the work on a source once it is decided. A real monitor would block or report a scanner and drop the record of a benign source. Line L4 keeps the test on first contacts, which is the unit of the model: a benign client that opens many connections to one server gives one outcome, not many. Lines L6 and L7 are the two steps of the walk. In the log domain they add ln⁡(θ1/θ0)<0\ln(\theta_1/\theta_0) < 0 or ln⁡((1−θ1)/(1−θ0))>0\ln((1 - \theta_1)/(1 - \theta_0)) > 0, so an implementation can keep one number per source and compare it with ln⁡η0\ln \eta_0 and ln⁡η1\ln \eta_1.

The outcome yy is an input. Jung et al. assume an oracle that says whether a first attempt succeeded, and in their trace study a monitor derived it from the packets it saw, for example from the reply to a connection request. How a monitor gets the label is outside the algorithm.

Example

Take θ0=0.8\theta_0 = 0.8, θ1=0.2\theta_1 = 0.2, α=0.01\alpha = 0.01 and β=0.99\beta = 0.99. Then η1=99\eta_1 = 99 and η0=1/99\eta_0 = 1/99. A failure multiplies Λ\Lambda by 0.8/0.2=40.8/0.2 = 4 and a success by 0.2/0.8=1/40.2/0.8 = 1/4. Since 43=64<99≤256=444^3 = 64 < 99 \le 256 = 4^4, the test decides when failures outnumber successes by 4, or successes outnumber failures by 4.

The events come from two remote sources, aa = 203.0.113.7 and bb = 203.0.113.9, to local hosts in 198.51.100.0/24 (documentation addresses). The outcomes are made up. The table follows source aa; a repeat of a destination does not change Λ\Lambda.

event destination outcome first contact Λ[a]\Lambda[a] state of aa
1 .1 fail yes 4 PENDING
2 .2 fail yes 16 PENDING
3 .2 success no 16 PENDING
4 .3 success yes 4 PENDING
5 .4 fail yes 16 PENDING
6 .5 fail yes 64 PENDING
7 .6 fail yes 256 SCANNER

Source aa is flagged after 6 distinct destinations, because 256≥99256 \ge 99. Source bb has the first-contact outcomes success, success, fail, success, success, success, so its ratio goes 1/4,1/16,1/4,1/16,1/64,1/2561/4, 1/16, 1/4, 1/16, 1/64, 1/256. It is called benign after 6 destinations, because 1/256≤1/991/256 \le 1/99 and 1/64>1/991/64 > 1/99.

Correctness

Two facts are proved in the full proof below. First, for each source, the loop computes Λk\Lambda_k over exactly its first contacts, and the returned state and count are the decision and the stopping time of Wald's test on that sequence. This is an induction over the events: a skipped event is either a repeat destination or an event of a decided source, and every other event multiplies Λ\Lambda by the factor of its outcome.

Second, under the independence model and with no bound on the number of contacts, the test stops with probability 1 and

PF≤αβ,1−PD≤1−β1−α.P_F \le \frac{\alpha}{\beta}, \qquad 1 - P_D \le \frac{1 - \beta}{1 - \alpha}.

This is Wald's bound, and it is a theorem. The proof is a change of measure: on a stopped run with decision H1H_1, the probability under H1H_1 is ΛN≥η1\Lambda_N \ge \eta_1 times the probability under H0H_0. With α=0.01\alpha = 0.01 and β=0.99\beta = 0.99, both bounds are 0.01010.0101. Jung et al. state them as their Equations (10) and (11).

The bound holds only in the model. Real outcomes are not independent, the two success rates are guesses, and the attacker chooses its behavior. So the measured rates on a trace can differ from α\alpha and β\beta in both directions.

Proof: TRW runs Wald's test on the first contacts of each source and keeps Wald's error boundsfull

Fix the parameters 0<θ1<θ0<10 < \theta_1 < \theta_0 < 1 and 0<α<β<10 < \alpha < \beta < 1, and let η0=(1−β)/(1−α)\eta_0 = (1 - \beta)/(1 - \alpha) and η1=β/α\eta_1 = \beta/\alpha. Since α<β\alpha < \beta, we have η0<1<η1\eta_0 < 1 < \eta_1. For a source rr, let Y1,Y2,…Y_1, Y_2, \ldots be the outcomes of its first contacts with distinct destinations, in the order of the events, with Yi=0Y_i = 0 for a success and Yi=1Y_i = 1 for a failure. Let

Λk=∏i=1kP(Yi∣H1)P(Yi∣H0),P(0∣H1)P(0∣H0)=θ1θ0,P(1∣H1)P(1∣H0)=1−θ11−θ0.\Lambda_k = \prod_{i=1}^{k} \frac{P(Y_i \mid H_1)}{P(Y_i \mid H_0)}, \qquad \frac{P(0 \mid H_1)}{P(0 \mid H_0)} = \frac{\theta_1}{\theta_0}, \quad \frac{P(1 \mid H_1)}{P(1 \mid H_0)} = \frac{1 - \theta_1}{1 - \theta_0}.

Wald's test on YY stops at the first NN with ΛN≥η1\Lambda_N \ge \eta_1 (decide H1H_1, scanner) or ΛN≤η0\Lambda_N \le \eta_0 (decide H0H_0, benign).

Lemma 1 (what the loop computes). After each event, for each source rr seen so far: D[r]D[r] is the set of destinations of the first contacts of rr that were read while rr was pending, Λ[r]=Λ∣D[r]∣\Lambda[r] = \Lambda_{|D[r]|}, and state[r]\mathrm{state}[r] is PENDING exactly when no k≤∣D[r]∣k \le |D[r]| has Λk≥η1\Lambda_k \ge \eta_1 or Λk≤η0\Lambda_k \le \eta_0.

Proof. By induction on the number of events. Before the first event of rr, the line that creates rr sets D[r]=∅D[r] = \emptyset, Λ[r]=1=Λ0\Lambda[r] = 1 = \Lambda_0 and the state to PENDING, and the claim holds for k=0k = 0. Take an event (r,d,y)(r, d, y). If rr is not pending, line L3 skips it, and nothing changes. If d∈D[r]d \in D[r], the event is not a first contact, and line L4 skips it. Otherwise it is the first contact of rr with dd, so it gives the outcome Yk+1Y_{k+1} with k=∣D[r]∣k = |D[r]|. Line L5 makes ∣D[r]∣=k+1|D[r]| = k + 1, and line L6 or L7 multiplies Λ[r]=Λk\Lambda[r] = \Lambda_k by the factor of Yk+1Y_{k+1}, so Λ[r]=Λk+1\Lambda[r] = \Lambda_{k+1}. By the induction hypothesis no j≤kj \le k crossed a threshold, and lines L8 and L9 change the state exactly when Λk+1\Lambda_{k+1} crosses one. Events of other sources do not change the variables of rr. □\square

Theorem 1 (correctness). For each source rr, TRW returns SCANNER with count kk if and only if Wald's test on Y1,Y2,…Y_1, Y_2, \ldots stops at N=kN = k with decision H1H_1, BENIGN with count kk if and only if it stops at N=kN = k with decision H0H_0, and PENDING with count kk if and only if the events give only kk first contacts and the test has not stopped after them.

Proof. When the state of rr changes from PENDING, it changes at the first kk with Λk≥η1\Lambda_k \ge \eta_1 or Λk≤η0\Lambda_k \le \eta_0, by Lemma 1, and the two cases cannot hold together because η0<η1\eta_0 < \eta_1. This is the stopping time and the decision of Wald's test. After that, line L3 skips all events of rr, so the state and ∣D[r]∣|D[r]| do not change. If the state never changes, Lemma 1 says that no prefix crossed a threshold, and ∣D[r]∣|D[r]| is the number of first contacts. Line L10 returns the state and ∣D[r]∣|D[r]|. □\square

Theorem 2 (error bounds). Assume that, given the hypothesis, the outcomes are independent with P(Yi=0∣H0)=θ0P(Y_i = 0 \mid H_0) = \theta_0 and P(Yi=0∣H1)=θ1P(Y_i = 0 \mid H_1) = \theta_1, and that the number of first contacts is not bounded. Then the test stops with probability 1 under both hypotheses, and

PF=P0(decide H1)≤αβ,1−PD=P1(decide H0)≤1−β1−α.P_F = P_0(\text{decide } H_1) \le \frac{\alpha}{\beta}, \qquad 1 - P_D = P_1(\text{decide } H_0) \le \frac{1 - \beta}{1 - \alpha}.

Proof. Let Zi=ln⁡Z_i = \ln of the factor of YiY_i. The ZiZ_i are independent and take two values, ln⁡(θ1/θ0)<0\ln(\theta_1/\theta_0) < 0 and ln⁡((1−θ1)/(1−θ0))>0\ln((1 - \theta_1)/(1 - \theta_0)) > 0, each with positive probability under both hypotheses. So ln⁡Λk=Z1+⋯+Zk\ln \Lambda_k = Z_1 + \cdots + Z_k is a random walk whose steps have positive variance. Let c=ln⁡η1−ln⁡η0c = \ln \eta_1 - \ln \eta_0, and let q>0q > 0 be the probability that one step is positive, so that j=⌈c/ln⁡((1−θ1)/(1−θ0))⌉j = \lceil c / \ln((1 - \theta_1)/(1 - \theta_0)) \rceil positive steps in a row leave the interval (ln⁡η0,ln⁡η1)(\ln \eta_0, \ln \eta_1) from any point in it. The walk survives tt disjoint blocks of jj steps with probability at most (1−qj)t→0(1 - q^j)^t \to 0. So N<∞N < \infty with probability 1.

For a finite sequence y1,…,yny_1, \ldots, y_n on which the test stops at nn, P1(y1,…,yn)=Λn P0(y1,…,yn)P_1(y_1, \ldots, y_n) = \Lambda_n \, P_0(y_1, \ldots, y_n). Let A1A_1 be the set of such sequences with decision H1H_1. On A1A_1, Λn≥η1\Lambda_n \ge \eta_1, so

PD=P1(A1)=∑y∈A1ΛnP0(y)≥η1P0(A1)=η1PF.P_D = P_1(A_1) = \sum_{y \in A_1} \Lambda_n P_0(y) \ge \eta_1 P_0(A_1) = \eta_1 P_F.

So PF≤PD/η1≤1/η1=α/βP_F \le P_D / \eta_1 \le 1/\eta_1 = \alpha/\beta. In the same way, on the set A0A_0 of sequences with decision H0H_0, Λn≤η0\Lambda_n \le \eta_0, so 1−PD=P1(A0)≤η0P0(A0)=η0(1−PF)≤η01 - P_D = P_1(A_0) \le \eta_0 P_0(A_0) = \eta_0 (1 - P_F) \le \eta_0. The sets A0A_0 and A1A_1 cover all stopped runs because N<∞N < \infty with probability 1. ■\blacksquare

The bounds use only the independence model and do not depend on how far ΛN\Lambda_N jumps past a threshold. The overshoot makes the true error rates smaller than the bounds, and the true expected number of contacts larger than Wald's approximation. In the case θ0=4/5\theta_0 = 4/5, θ1=1/5\theta_1 = 1/5, α=1/100\alpha = 1/100, β=99/100\beta = 99/100, the walk in units of ln⁡4\ln 4 is absorbed at +4+4 or −4-4, the exact false alarm rate is 1/2571/257, and E[N∣H1]=6.61E[N \mid H_1] = 6.61, against Wald's approximation 5.415.41.

Complexity

The model is the word RAM. Each event does one lookup of the source, one lookup and one insert in the set D[r]D[r], one multiplication and two comparisons. With hash tables this is O(1)O(1) expected time per event, so O(n)O(n) expected time for nn events. With balanced search trees it is O(log⁡n)O(\log n) worst case per event. The space is O(d)O(d) for the destination sets of the pending sources, plus O(1)O(1) per source for its state.

The number of contacts the test needs is the interesting cost. By Wald's equation, when the overshoot past the thresholds is ignored,

E[N∣H1]≈βln⁡βα+(1−β)ln⁡1−β1−αθ1ln⁡θ1θ0+(1−θ1)ln⁡1−θ11−θ0,E[N \mid H_1] \approx \frac{\beta \ln\frac{\beta}{\alpha} + (1 - \beta) \ln\frac{1 - \beta}{1 - \alpha}}{\theta_1 \ln\frac{\theta_1}{\theta_0} + (1 - \theta_1) \ln\frac{1 - \theta_1}{1 - \theta_0}},

and the analog with H0H_0, 1−α1 - \alpha, α\alpha and θ0\theta_0 for benign sources. With the parameters of the example, both are 5.415.41. This is Equation (14) of Jung et al., who give 5.4. In the example the walk moves in whole units of ln⁡4\ln 4 and stops at ±4\pm 4, not at ±3.31\pm 3.31, so the exact values differ: the false alarm rate and the miss rate are both 1/257=0.003891/257 = 0.00389, and the exact expected stopping time is 6.616.61 under each hypothesis. The approximation underestimates the stopping time because it ignores the overshoot.

Properties

  • Online and per source. It reads each event once and keeps a constant amount of state per source, plus the set of destinations of the pending sources.
  • Error rates set by design. The thresholds depend only on α\alpha and β\beta, and the bounds above hold for all θ0>θ1\theta_0 > \theta_1 in the model. The parameters θ0\theta_0 and θ1\theta_1 change only the speed.
  • Optimal in its model. Among all tests with the same error rates, Wald and Wolfowitz (1948) proved that the SPRT has the smallest expected sample size under both hypotheses. See the SPRT page.
  • No time window. Unlike detectors that count destinations in a window of ZZ seconds, TRW does not depend on the rate of the scan, so a slow scan is detected after the same number of first contacts.

Variants and improvements

  • Reverse test on local hosts. Schechter, Jung and Berger (2004) ran a sequential test on the outgoing first contacts of local hosts to detect an infected host early, together with a limit on the rate of its new connections.
  • Friendly hosts. Jung et al. drop the failures of a remote host to which a local host has already connected. This removes false alarms caused by replies to the site's own traffic, without a change to the test.
  • Log-domain integer walk. When ln⁡((1−θ1)/(1−θ0))\ln((1 - \theta_1)/(1 - \theta_0)) and ln⁡(θ1/θ0)\ln(\theta_1/\theta_0) are in a rational ratio, as in the example, the walk can run on small integers, which suits a hardware or high-rate implementation.
  • Rate-based detectors. The classic alternative counts distinct destinations of one source in a fixed window. Jung et al. compare TRW with the detector of Bro, which flags a source after NN distinct destinations of failed attempts on some services, and with the portscan detector of Snort, which by default flags a source that contacts 5 addresses in 60 seconds. These counts and windows are heuristics.

When to use it

Use TRW when the observable signal is a success or a failure per new destination and a fast decision matters: scan detection at the edge of a network with many unused addresses, or detection of a spreading host by its failed first contacts. It needs a monitor that can label each first attempt. It is a poor fit for a scan of many services on one host (a vertical scan), because the unit of the test is a distinct host.

Pitfalls

  • The independence assumption. Jung et al. note that a scanner that alternates attempts to inactive and active hosts keeps the walk near its start, so it is never flagged. A scanner that first collects a list of active hosts by other means has a success rate close to that of a benign source. These are limits of the model, not bugs of the code.
  • Labels. A wrong success or failure label moves the walk the wrong way. Packet loss and filtering devices can make a benign attempt look like a failure.
  • Wrong θ\theta values. A scanner with a success rate above about 0.3 needs many more contacts at the parameters of the example (Figure 4 of Jung et al.). The bounds on the error rates still hold for sources that follow the model, but real benign sources with many failures, such as some peer-to-peer clients, raise false alarms.
  • Spoofed sources. The test is per source address. An attacker who can use many source addresses, or forge them, spreads its evidence thin.
  • Base rates. A false alarm rate of α\alpha per benign source still gives many false alarms when benign sources outnumber scanners by a large factor. See the base-rate fallacy.

Implementations

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.

threshold_random_walk_scan_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/threshold-random-walk-scan-detection/. The authors are listed in prov/V1VA3S.jsonl.

"""Threshold random walk (TRW) scan detection of Jung, Paxson, Berger and
Balakrishnan (2004), on abstract connection outcomes.

The input is a list of events (source, destination, success) that a monitor
has already labeled. This module does not open, send or read any network
connection. It only runs the sequential test on the labels it is given.
"""

from fractions import Fraction
from typing import Hashable, Iterable

PENDING = "pending"
BENIGN = "benign"
SCANNER = "scanner"


def trw_thresholds(alpha: Fraction, beta: Fraction) -> tuple[Fraction, Fraction]:
    """Return Wald's thresholds (eta0, eta1) = ((1 - beta)/(1 - alpha), beta/alpha).

    Precondition: 0 < alpha < beta < 1. Cost: O(1).
    """
    if not (0 < alpha < beta < 1):
        raise ValueError("need 0 < alpha < beta < 1")
    return (1 - beta) / (1 - alpha), beta / alpha


def trw(
    events: Iterable[tuple[Hashable, Hashable, bool]],
    theta0: Fraction,
    theta1: Fraction,
    alpha: Fraction,
    beta: Fraction,
) -> dict[Hashable, tuple[str, int]]:
    """Run one sequential probability ratio test per remote source.

    events: (source, destination, success) in arrival order. success is True
    when the first connection attempt from the source to the destination
    succeeded. theta0 = P(success | benign), theta1 = P(success | scanner).
    Only the first contact of a source with each distinct destination counts.

    Returns, for each source, its state (PENDING, BENIGN or SCANNER) and the
    number of distinct destinations counted when the state was fixed (or so
    far, if it is still PENDING).

    Precondition: 0 < theta1 < theta0 < 1 and 0 < alpha < beta < 1.
    Cost: O(1) Fraction operations and O(1) expected hash operations per event,
    and O(d) space, where d is the number of distinct (source, destination)
    pairs of the sources that are still pending.
    """
    if not (0 < theta1 < theta0 < 1):
        raise ValueError("need 0 < theta1 < theta0 < 1")
    eta0, eta1 = trw_thresholds(alpha, beta)  # @line L1
    up_success = theta1 / theta0
    up_failure = (1 - theta1) / (1 - theta0)
    state: dict[Hashable, str] = {}
    seen: dict[Hashable, set[Hashable]] = {}
    ratio: dict[Hashable, Fraction] = {}
    for src, dst, success in events:  # @line L2
        if src not in state:
            state[src], seen[src], ratio[src] = PENDING, set(), Fraction(1)
        if state[src] != PENDING:  # @line L3
            continue
        if dst in seen[src]:  # @line L4
            continue
        seen[src].add(dst)  # @line L5
        if success:  # @line L6
            ratio[src] *= up_success
        else:  # @line L7
            ratio[src] *= up_failure
        if ratio[src] >= eta1:  # @line L8
            state[src] = SCANNER
        elif ratio[src] <= eta0:  # @line L9
            state[src] = BENIGN
    return {s: (state[s], len(seen[s])) for s in state}  # @line L10
test_threshold_random_walk_scan_detection.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/threshold-random-walk-scan-detection/. The authors are listed in prov/V1VA3S.jsonl.

import math
import random
from fractions import Fraction

from threshold_random_walk_scan_detection import (
    BENIGN,
    PENDING,
    SCANNER,
    trw,
    trw_thresholds,
)

T0 = Fraction(4, 5)
T1 = Fraction(1, 5)
ALPHA = Fraction(1, 100)
BETA = Fraction(99, 100)


def test_thresholds() -> None:
    eta0, eta1 = trw_thresholds(ALPHA, BETA)
    assert eta1 == 99
    assert eta0 == Fraction(1, 99)


def test_page_example() -> None:
    # Documentation addresses only (RFC 5737). The outcomes are made up.
    a = "203.0.113.7"
    b = "203.0.113.9"
    events = [
        (a, "198.51.100.1", False),
        (b, "198.51.100.2", True),
        (a, "198.51.100.2", False),
        (a, "198.51.100.2", True),  # repeat destination, ignored
        (b, "198.51.100.2", True),  # repeat destination, ignored
        (a, "198.51.100.3", True),
        (b, "198.51.100.3", True),
        (a, "198.51.100.4", False),
        (b, "198.51.100.5", False),
        (a, "198.51.100.5", False),
        (b, "198.51.100.6", True),
        (a, "198.51.100.6", False),
        (b, "198.51.100.7", True),
        (b, "198.51.100.8", True),
        (a, "198.51.100.9", False),  # a is already decided, ignored
    ]
    out = trw(events, T0, T1, ALPHA, BETA)
    assert out[a] == (SCANNER, 6)
    assert out[b] == (BENIGN, 6)


def oracle(events, theta0, theta1, alpha, beta):
    """Collect each source's first-contact outcomes, then scan prefixes."""
    eta0, eta1 = (1 - beta) / (1 - alpha), beta / alpha
    outcomes: dict = {}
    for src, dst, ok in events:
        lst = outcomes.setdefault(src, [])
        if dst not in [d for d, _ in lst]:
            lst.append((dst, ok))
    result = {}
    for src, lst in outcomes.items():
        decided = None
        for k in range(1, len(lst) + 1):
            prod = Fraction(1)
            for _, ok in lst[:k]:
                prod *= theta1 / theta0 if ok else (1 - theta1) / (1 - theta0)
            if prod >= eta1:
                decided = (SCANNER, k)
                break
            if prod <= eta0:
                decided = (BENIGN, k)
                break
        result[src] = decided if decided else (PENDING, len(lst))
    return result


def test_random_against_oracle() -> None:
    rng = random.Random(2004)
    params = [
        (T0, T1, ALPHA, BETA),
        (Fraction(3, 4), Fraction(1, 3), Fraction(1, 20), Fraction(9, 10)),
        (Fraction(9, 10), Fraction(1, 2), Fraction(1, 10), Fraction(4, 5)),
    ]
    for case in range(600):
        theta0, theta1, alpha, beta = params[case % len(params)]
        n_src = rng.randint(1, 4)
        n_dst = rng.randint(1, 8)
        events = []
        for _ in range(rng.randint(0, 30)):
            events.append((rng.randrange(n_src), rng.randrange(n_dst), rng.random() < 0.5))
        assert trw(events, theta0, theta1, alpha, beta) == oracle(
            events, theta0, theta1, alpha, beta
        )


def walk_exact(p_up: float, top: int, bottom: int, steps: int = 400):
    """Distribution of the integer walk from 0, absorbed at top or bottom."""
    dist = {0: 1.0}
    hit_top = 0.0
    mean_n = 0.0
    for t in range(1, steps + 1):
        nxt: dict = {}
        for pos, pr in dist.items():
            for move, q in ((1, p_up), (-1, 1 - p_up)):
                np_ = pos + move
                if np_ >= top:
                    hit_top += pr * q
                    mean_n += t * pr * q
                elif np_ <= bottom:
                    mean_n += t * pr * q
                else:
                    nxt[np_] = nxt.get(np_, 0.0) + pr * q
        dist = nxt
    return hit_top, mean_n


def test_exact_walk_matches_gamblers_ruin() -> None:
    # With theta0 = 4/5 and theta1 = 1/5 a failure multiplies the ratio by 4
    # and a success by 1/4, and 4^3 < 99 <= 4^4, so the test is the walk
    # absorbed at +4 and -4.
    r = 0.25
    closed_pd = (1 - r**4) / (1 - r**8)
    hit, mean_n = walk_exact(0.8, 4, -4)
    assert abs(hit - closed_pd) < 1e-12
    closed_mean = 4 / (-0.6) - 8 / (-0.6) * closed_pd
    assert abs(mean_n - closed_mean) < 1e-9
    # Wald's bounds hold for the exact error rates.
    pf = 1 - closed_pd
    assert pf <= float(ALPHA / BETA)
    assert 1 - closed_pd <= float((1 - BETA) / (1 - ALPHA))


def simulate(rng: random.Random, p_success: float, n_sources: int, cap: int):
    events = []
    for s in range(n_sources):
        for d in range(cap):
            events.append((s, d, rng.random() < p_success))
    return trw(events, T0, T1, ALPHA, BETA)


def test_monte_carlo_error_rates() -> None:
    rng = random.Random(7)
    n = 1500
    margin = math.sqrt(math.log(2 / 1e-3) / (2 * n))
    pf_exact = 1 - (1 - 0.25**4) / (1 - 0.25**8)
    benign = simulate(rng, 0.8, n, 40)
    false_alarms = sum(1 for st, _ in benign.values() if st == SCANNER)
    assert false_alarms / n <= pf_exact + margin
    assert false_alarms / n <= float(ALPHA / BETA) + margin
    scanners = simulate(rng, 0.2, n, 40)
    hits = [k for st, k in scanners.values() if st == SCANNER]
    assert len(hits) / n >= 1 - pf_exact - margin
    _, mean_exact = walk_exact(0.8, 4, -4)
    all_n = [k for _, k in scanners.values()]
    assert abs(sum(all_n) / n - mean_exact) < 0.5


def test_bad_parameters() -> None:
    for args in ((T1, T0, ALPHA, BETA), (T0, T1, BETA, ALPHA)):
        try:
            trw([], *args)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

History

Wald (1945) gave the sequential probability ratio test and its thresholds. Earlier scan detectors in the Network Security Monitor, in Snort and in Bro counted distinct destinations, or distinct destinations of failed attempts, in a window. Jung, Paxson, Berger and Balakrishnan (2004) observed that the outcome of a first contact is the better signal and ran Wald's test on it. On traces from LBL (about 6000 hosts) and ICSI (about 200 hosts), with the parameters of the example, they measured an efficiency (the fraction of flagged sources that were scanners) of 0.998 at LBL and 1.000 at ICSI, and a detection rate of 0.983 at LBL and 0.973 at ICSI. Flagged scanners had contacted 4 or 5 distinct hosts on average and never more than 16. These are measurements on those traces in 2004, not properties of the algorithm.

References

  1. Jaeyeon Jung, Vern Paxson, Arthur W. Berger and Hari Balakrishnan, Fast portscan detection using sequential hypothesis testing, IEEE Symposium on Security and Privacy 2004, pages 211 to 225, Section 4 (the model of first-contact outcomes, the likelihood ratio, the thresholds, the error bounds and the expected number of contacts), Section 5 (the trace-driven evaluation at LBL and ICSI, and the comparison with Bro and Snort)
  2. Abraham Wald, Sequential tests of statistical hypotheses, Annals of Mathematical Statistics 16(2), 1945, the thresholds A and B and the bounds on the two error probabilities
  3. Stuart E. Schechter, Jaeyeon Jung and Arthur W. Berger, Fast detection of scanning worm infections, Recent Advances in Intrusion Detection (RAID) 2004, LNCS, pages 59 to 81, the sequential test run on the outgoing connections of local hosts
  4. Vern Paxson, Bro, a system for detecting network intruders in real-time, Computer Networks 31(23-24), 1999, pages 2435 to 2463, the scan detector that counts distinct destinations of failed attempts, used as the baseline

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.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