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.
- Solves
- Intrusion detection
- 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
- Model
- Word RAM
- Properties
- deterministicexact error boundsonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and , 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 : a remote source , a local destination , and the outcome of the first connection attempt from to , with for a success and 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 do not count. For each source the task is to decide between two hypotheses, (the source is benign) and (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 of the first contacts of one source are independent, with
The goals are a false alarm rate and a detection rate . Jung et al. used , , and . These four numbers are heuristic choices: the two values are guesses of the success rates of benign sources and scanners, and and are chosen rates. They are not facts about any network.
The algorithm
For a source with outcomes , the likelihood ratio is
so a success multiplies it by and a failure by . Wald's thresholds are and . A new source starts with , an empty set of destinations and the state PENDING.
TRW(E, θ0, θ1, α, β) ▷ E: events (r, d, y) in arrival order- 1
η1 ← β / α ; η0 ← (1 - β) / (1 - α) - 2
for each event (r, d, y) in E do ▷ a new r gets Λ[r] = 1, D[r] = ∅, PENDING - 3
if state[r] ≠ PENDING then continue - 4
if d ∈ D[r] then continue ▷ only first contacts count - 5
D[r] ← D[r] ∪ {d} - 6
if y = 0 then Λ[r] ← Λ[r] · θ1 / θ0 - 7
else Λ[r] ← Λ[r] · (1 - θ1) / (1 - θ0) - 8
if Λ[r] ≥ η1 then state[r] ← SCANNER - 9
else if Λ[r] ≤ η0 then state[r] ← BENIGN - 10
return 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 or , so an implementation can keep one number per source and compare it with and .
The outcome 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 , , and . Then and . A failure multiplies by and a success by . Since , the test decides when failures outnumber successes by 4, or successes outnumber failures by 4.
The events come from two remote sources, = 203.0.113.7 and = 203.0.113.9, to local hosts in 198.51.100.0/24 (documentation addresses). The outcomes are made up. The table follows source ; a repeat of a destination does not change .
| event | destination | outcome | first contact | state of | |
|---|---|---|---|---|---|
| 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 is flagged after 6 distinct destinations, because . Source has the first-contact outcomes success, success, fail, success, success, success, so its ratio goes . It is called benign after 6 destinations, because and .
Correctness
Two facts are proved in the full proof below. First, for each source, the loop computes 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 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
This is Wald's bound, and it is a theorem. The proof is a change of measure: on a stopped run with decision , the probability under is times the probability under . With and , both bounds are . 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 and 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 and , and let and . Since , we have . For a source , let be the outcomes of its first contacts with distinct destinations, in the order of the events, with for a success and for a failure. Let
Wald's test on stops at the first with (decide , scanner) or (decide , benign).
Lemma 1 (what the loop computes). After each event, for each source seen so far: is the set of destinations of the first contacts of that were read while was pending, , and is PENDING exactly when no has or .
Proof. By induction on the number of events. Before the first event of , the line that creates sets , and the state to PENDING, and the claim holds for . Take an event . If is not pending, line L3 skips it, and nothing changes. If , the event is not a first contact, and line L4 skips it. Otherwise it is the first contact of with , so it gives the outcome with . Line L5 makes , and line L6 or L7 multiplies by the factor of , so . By the induction hypothesis no crossed a threshold, and lines L8 and L9 change the state exactly when crosses one. Events of other sources do not change the variables of .
Theorem 1 (correctness). For each source , TRW returns SCANNER with count if and only if Wald's test on stops at with decision , BENIGN with count if and only if it stops at with decision , and PENDING with count if and only if the events give only first contacts and the test has not stopped after them.
Proof. When the state of changes from PENDING, it changes at the first with or , by Lemma 1, and the two cases cannot hold together because . This is the stopping time and the decision of Wald's test. After that, line L3 skips all events of , so the state and do not change. If the state never changes, Lemma 1 says that no prefix crossed a threshold, and is the number of first contacts. Line L10 returns the state and .
Theorem 2 (error bounds). Assume that, given the hypothesis, the outcomes are independent with and , and that the number of first contacts is not bounded. Then the test stops with probability 1 under both hypotheses, and
Proof. Let of the factor of . The are independent and take two values, and , each with positive probability under both hypotheses. So is a random walk whose steps have positive variance. Let , and let be the probability that one step is positive, so that positive steps in a row leave the interval from any point in it. The walk survives disjoint blocks of steps with probability at most . So with probability 1.
For a finite sequence on which the test stops at , . Let be the set of such sequences with decision . On , , so
So . In the same way, on the set of sequences with decision , , so . The sets and cover all stopped runs because with probability 1.
The bounds use only the independence model and do not depend on how far 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 , , , , the walk in units of is absorbed at or , the exact false alarm rate is , and , against Wald's approximation .
Complexity
The model is the word RAM. Each event does one lookup of the source, one lookup and one insert in the set , one multiplication and two comparisons. With hash tables this is expected time per event, so expected time for events. With balanced search trees it is worst case per event. The space is for the destination sets of the pending sources, plus 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,
and the analog with , , and for benign sources. With the parameters of the example, both are . This is Equation (14) of Jung et al., who give 5.4. In the example the walk moves in whole units of and stops at , not at , so the exact values differ: the false alarm rate and the miss rate are both , and the exact expected stopping time is 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 and , and the bounds above hold for all in the model. The parameters and 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 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 and 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 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 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 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.
# 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
- 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)
- 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
- 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
- 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.
| 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 V1VA3S Edit this page History Report an error Markdown