Algorithm Search⌘K

Algorithmadvanced

Content prevalence worm detection

Also called EarlyBird, content sifting.

Finds worms by counting repeated payload substrings with Rabin fingerprints and flagging ones that are common and spread to many addresses.

Time
O(n s) worst · average
Space
O(s q + a) extra
Where
a = the number of distinct (key and address) pairs in the dispersion table; n = the total number of payload bytes; q = the number of counters per stage; s = the number of filter stages
Properties
deterministicno false negatives from filteronlineiterative
Origin
Sumeet Singh, Cristian Estan, George Varghese, Stefan Savage, 2004

Content prevalence worm detection, also called content sifting, finds a spreading worm from the traffic itself, with no prior signature. Its basis is three observations of Singh, Estan, Varghese and Savage (2004). A worm sends the same bytes in each copy (content invariance). So during an outbreak a substring of those bytes is unusually frequent (content prevalence). And the copies go from many sources to many destinations (address dispersion). Content sifting counts every substring of a fixed length with Rabin fingerprints and a multistage filter, and reports a substring when it is both frequent and dispersed. The reported substring is a candidate signature for a misuse detector. The method is a heuristic: the three properties are assumptions about worms, and their thresholds are chosen.

In plain words

Imagine you could see every message on a network. Most messages are unique. A worm is different. It sends the same message again and again, from each machine it reached, to many new machines.

So you count how often you have seen each short piece of each message. A piece that is seen many times is popular. But popular is not enough: a mail program that checks one server every minute also sends the same bytes many times. So, for the popular pieces only, you also note who sent them and who got them. A piece that is popular and that went between many different senders and receivers looks like a worm. You raise an alarm and give the piece as the signature to block.

The method uses compact counters that can only overcount, so it never misses a popular piece.

The problem

The input is a stream of packets (s,d,port,x)(s, d, \text{port}, x) with a source ss, a destination dd, a destination port and a payload xx, a string of bytes. A key is a pair of a port and a substring of β\beta consecutive bytes of a payload. Given thresholds TpT_p, TsT_s and TdT_d, report each key that occurs more than TpT_p times and is then seen with more than TsT_s distinct sources and more than TdT_d distinct destinations. Do it in one pass, with memory much smaller than the number of distinct keys.

Singh et al. used β=40\beta = 40, Tp=3T_p = 3 and Ts=Td=30T_s = T_d = 30, and cleared the counters every 60 seconds. These values are heuristic choices from their measurements, not constants of the method.

The algorithm

For each window ww of β\beta bytes, the fingerprint F(w)F(w) is the bits of ww read as a polynomial over GF(2), reduced modulo a fixed irreducible polynomial PP. The fingerprint of the next window comes from the previous one in constant time (Lemma 1 of the proof). The key is h=(port,F(w))h = (\text{port}, F(w)). Value sampling keeps only the keys whose fingerprint has its low bb bits equal to 0, a fraction f=2−bf = 2^{-b} of the windows.

The prevalence table is a multistage filter: ss arrays of qq counters, with an independent hash gig_i for each array. The dispersion table ADAD holds, for each key that passed the prevalence threshold, the set of its sources and the set of its destinations.

  1. CONTENT-SIFT(s, d, port, x) ▷ one packet
  2. 1for each window w of β bytes of x, left to right do
  3. 2h ← (port, F(w)) ▷ F rolled from the previous window
  4. 3if the low b bits of F(w) are not all 0 then continue ▷ value sampling
  5. 4if h ∈ AD then
  6. 5AD[h].src ← AD[h].src ∪ {s} ; AD[h].dst ← AD[h].dst ∪ {d}
  7. 6if |AD[h].src| > Ts and |AD[h].dst| > Td then report h
  8. 7else
  9. 8c ← MSF-INCREMENT(h)
  10. 9if c > Tp then AD[h] ← ({s}, {d})
  11. MSF-INCREMENT(h) ▷ conservative update
  12. 10m ← min over stages i of C_i[g_i(h)]
  13. 11for each stage i with C_i[g_i(h)] = m do C_i[g_i(h)] ← m + 1
  14. 12return m + 1

Line L3 is the main saving of CPU. Because the choice depends on the value of the fingerprint and not on chance, every copy of a content makes the same choice: a sampled window is sampled in every packet that holds it. Lines L4 to L6 count dispersion only for keys that are already frequent, which keeps the dispersion table small. Lines L8 and L9 are the filter: a key enters the dispersion table when the smallest of its counters passes TpT_p. The conservative update of lines L10 to L11 raises only the counters that hold the minimum. This keeps the estimate at or above the true count and makes it closer to the true count than a plain increment of all counters, as in a count-min sketch.

Singh et al. count dispersion with scaled bitmaps, which estimate the number of distinct addresses in a few bytes. The implementation of this page keeps exact sets, which is simpler and gives the same reports on small inputs.

Example

Take β=4\beta = 4, no sampling (b=0b = 0), exact counters, Tp=2T_p = 2 and Ts=Td=2T_s = T_d = 2. The packets go to port 80, between documentation addresses, and each payload holds the made-up string XYZW. The table follows the key of XYZW.

packet source destination count AD sources AD destinations report
1 192.0.2.1 198.51.100.1 1 none none no
2 192.0.2.1 198.51.100.1 2 none none no
3 192.0.2.2 198.51.100.2 3 .2 .2 no
4 192.0.2.2 198.51.100.3 3 .2 .2, .3 no
5 192.0.2.3 198.51.100.4 3 .2, .3 .2, .3, .4 no
6 192.0.2.4 198.51.100.1 3 .2, .3, .4 .1, .2, .3, .4 yes

Packet 3 makes the count pass Tp=2T_p = 2, so line L9 creates the entry with that packet's addresses. From then on the counter is not touched. The source of packets 1 and 2 is not in the entry, because dispersion is counted only after the key became frequent. Packet 6 gives 3 sources and 4 destinations, both more than 2, so the key is reported.

Correctness

The proof below shows four facts.

  1. The rolled fingerprint equals the direct one, by the linearity of reduction modulo PP over GF(2).
  2. With conservative update, the estimate of each key is at least its true count. A counter is never lowered, and each call raises every counter of the key that holds the minimum.
  3. With exact counters, a key is reported at the first occurrence after the (Tp+1)(T_p + 1)-th one at which the occurrences from the (Tp+1)(T_p + 1)-th on have more than TsT_s sources and more than TdT_d destinations.
  4. With the filter, every key that the exact run reports is reported, at the same packet or earlier. The filter can only make a key enter the dispersion table early, and a larger dispersion set can only satisfy line L6 earlier.

So the filter causes no false negatives with respect to the thresholds. It can cause extra entries in the dispersion table, but a report still needs the dispersion test.

The probability that value sampling misses a content of length xx is a statement in a model. If the x−β+1x - \beta + 1 windows are distinct and their low bits behave like independent fair coins, the probability is (1−f)x−β+1≈e−f(x−β+1)(1 - f)^{x - \beta + 1} \approx e^{-f(x - \beta + 1)}. With f=1/64f = 1/64 and β=40\beta = 40, the approximation gives a probability of tracking of 0.61 for a content of 100 bytes, 0.92 for 200 bytes and 0.9964 for 400 bytes. Singh et al. give 92% and 99.64% for the last two, and 55% for the first, which does not match their formula.

Proof: Content sifting reports every content that passes the prevalence and dispersion thresholds, and the filter never delays a reportfull

We fix the substring length β≥1\beta \ge 1, the sampling mask of bb low bits, the prevalence threshold TpT_p and the dispersion thresholds TsT_s and TdT_d. A key is a pair (port,F(w))(\text{port}, F(w)), where ww is a window of β\beta bytes and FF is the Rabin fingerprint: the bits of ww read as a polynomial over GF(2), reduced modulo a fixed polynomial PP of degree kk. An occurrence of a key is a sampled window of a packet with that key. The occurrences are ordered by packet, and inside a packet by the position of the window.

Lemma 1 (rolling fingerprint). Let w=c0c1⋯cβ−1w = c_0 c_1 \cdots c_{\beta-1} and w′=c1⋯cβ−1cβw' = c_1 \cdots c_{\beta-1} c_\beta be two consecutive windows. Then F(w′)=((F(w)⋅x8+cβ) mod P)+((c0⋅x8β) mod P)F(w') = \big((F(w) \cdot x^8 + c_\beta) \bmod P\big) + \big((c_0 \cdot x^{8\beta}) \bmod P\big), where ++ is addition over GF(2) (exclusive or).

Proof. As polynomials, w=c0x8(β−1)+Rw = c_0 x^{8(\beta-1)} + R with R=∑i=1β−1cix8(β−1−i)R = \sum_{i=1}^{\beta-1} c_i x^{8(\beta-1-i)}, and w′=Rx8+cβw' = R x^8 + c_\beta. So wx8+cβ=c0x8β+w′w x^8 + c_\beta = c_0 x^{8\beta} + w', and over GF(2), w′=wx8+cβ+c0x8βw' = w x^8 + c_\beta + c_0 x^{8\beta}. Reduction modulo PP is linear and F(w)≡wF(w) \equiv w, so the claim follows. The table of the implementation stores (c⋅x8β) mod P(c \cdot x^{8\beta}) \bmod P for each byte cc. □\square

So line L1 visits the windows of the packet in order and line L2 forms the key of each one.

Lemma 2 (conservative update). For a key hh, let c(h)c(h) be the number of calls MSF-INCREMENT(h)(h) so far, and let e(h)=min⁡iCi[gi(h)]e(h) = \min_i C_i[g_i(h)] be the estimate. Then e(h)≥c(h)e(h) \ge c(h) at all times, and each call returns the new value of e(h)e(h).

Proof. At the start all counters are 0. Counters never decrease. Take a call on hh, and let mm be the minimum of its counters (line L10). Line L11 raises each counter of hh that equals mm to m+1m + 1, and the others are already greater than mm. So afterwards each counter of hh is at least m+1m + 1, and one of them is exactly m+1m + 1: the new estimate is m+1m + 1, which line L12 returns. If e(h)≥c(h)e(h) \ge c(h) before the call, then m≥c(h)m \ge c(h), and after it e(h)=m+1≥c(h)+1e(h) = m + 1 \ge c(h) + 1. Calls on other keys do not lower any counter of hh. □\square

With exact counters instead of the filter, MSF-INCREMENT returns c(h)c(h) exactly.

Theorem 1 (exact mode). With exact counters, key hh is reported at the first occurrence oo of hh such that: oo is at least the (Tp+2)(T_p + 2)-th occurrence of hh, and among the occurrences from the (Tp+1)(T_p + 1)-th up to oo, there are more than TsT_s distinct sources and more than TdT_d distinct destinations. If no such occurrence exists, hh is never reported.

Proof. Lines L3 to L9 see exactly the occurrences of hh. While hh is not in the dispersion table, each occurrence goes to line L8, which counts it. The first TpT_p occurrences give counts 1,…,Tp1, \ldots, T_p, which do not pass line L9. The (Tp+1)(T_p + 1)-th occurrence gives the count Tp+1>TpT_p + 1 > T_p, and line L9 creates the entry with its source and destination. From then on, each occurrence goes to lines L5 and L6. Line L5 adds its source and destination, so after occurrence oo the two sets are the sources and destinations of the occurrences from the (Tp+1)(T_p + 1)-th to oo. Line L6 reports when both sizes pass their thresholds, and the first such oo is the one in the statement. The implementation reports a key only once. □\square

Theorem 2 (no false negatives from the filter). Run the sifter with the filter and with exact counters on the same packets. If the exact run reports hh at packet tt, the filter run reports hh at a packet t′≤tt' \le t.

Proof. By Lemma 2, in the filter run the estimate of hh is at least its true count, so the filter run creates the entry of hh at the (Tp+1)(T_p + 1)-th occurrence of hh or earlier, say at occurrence j≤Tp+1j \le T_p + 1. From then on the two runs differ only in the start of the dispersion sets: the filter run holds the sources and destinations of occurrences jj to oo, and the exact run those of occurrences Tp+1T_p + 1 to oo, a subset. So whenever the condition of line L6 holds in the exact run at an occurrence oo, it holds in the filter run at oo, unless the filter run has reported hh before. ■\blacksquare

The converse fails, by design: a key that shares counters with frequent keys can get a high estimate and enter the dispersion table early. This costs memory in the table but cannot cause a report alone, because a report also needs the dispersion thresholds, which are counted exactly.

Value sampling. Line L3 keeps the windows whose fingerprint has bb low zero bits. Theorems 1 and 2 hold for the sampled occurrences. The probability that a content of length xx has at least one sampled window is a statement about a model, not a theorem about FF: if the x−β+1x - \beta + 1 windows are distinct and their low bits behave like independent fair coins (the assumption of Singh et al.), the probability is 1−(1−f)x−β+11 - (1 - f)^{x - \beta + 1} with f=2−bf = 2^{-b}. Once one window of a content is sampled, every copy of the content gives an occurrence of the same key, so sampling does not delay the detection of that key.

Complexity

The model is the word RAM, with a fingerprint of degree at most the word size. Let nn be the total number of payload bytes. Each byte gives one window, one rolling step of O(1)O(1) word operations (a shift, a reduction and a table lookup), and, if sampled, O(s)O(s) work in the filter for ss stages, or O(1)O(1) expected work in the dispersion table. So the time is O(ns)O(n s), and value sampling divides the filter work by 1/f1/f on average. A payload of 1000 bytes has 961 windows of 40 bytes, and with f=1/64f = 1/64 about 15 of them reach the filter.

The memory is O(sq)O(s q) counters for the filter, where qq is the number of counters per stage, plus the dispersion table. The dispersion table has one entry per key that passed the filter, and each entry is a pair of sets (exact) or a pair of scaled bitmaps of a few bytes (EarlyBird). The filter needs no memory per key, which is why it fits on a fast link.

Properties

  • One pass and online. Each packet is processed once, in arrival order.
  • No false negatives from the filter. The filter only overestimates counts (Theorem 2 of the proof). Misses come from value sampling and from contents that vary between copies, not from the filter.
  • Deterministic given the hash functions. The outcome depends on the stage hashes and on PP. Singh et al. keep the fingerprint parameters secret, so that a worm author cannot pick content that is never sampled.
  • Signature as output. The output is a byte string with a port, which a misuse detector can match with Aho-Corasick or a similar multi-pattern matcher.

Variants and improvements

  • Autograph. Kim and Karp (2004) first select flows from sources that a scan detector flagged, then split their payloads into content blocks at content-defined boundaries and pick the most frequent blocks. A scan detector can play that role.
  • Exact counting. With a hash map instead of the filter, the method is exact and needs memory per distinct key. This is the reference behavior in the tests.
  • Other heavy-hitter structures. Sample and hold and Space-Saving also find frequent keys in small memory, with different error guarantees.
  • Periodic reset and garbage collection. EarlyBird clears the filter every 60 seconds and removes old dispersion entries after a time-out, so that slow background repetition does not build up.
  • Signatures for varying content. Content that changes between copies defeats a single invariant substring. Later work generates signatures from several shorter invariant parts or from the vulnerability itself; see vulnerability signature generation.

When to use it

Use content sifting at a point that sees traffic from many hosts, when the threat is a fast spreading program with a stable part in its payload. It needs no knowledge of the protocol above the transport layer and no prior signature. It is not useful for targeted attacks, which do not repeat, or for encrypted traffic, where the payload bytes of each copy differ.

Pitfalls

  • Benign prevalent and dispersed content. Singh et al. report false positives from common protocol headers (mail and web headers), from bulk mail sent by distributed mailers, and from popular files in peer-to-peer systems with a many-to-many download pattern. They remove the first group with a white-list built from a protocol parser. Each deployment needs such a white-list.
  • Variant content. A worm whose payload has no invariant substring of length β\beta is not found. Short invariant parts are found only if a window inside them is sampled.
  • Evasion at the network level. Splitting, reordering or padding packets changes the windows a sensor sees, unless it reassembles the streams.
  • Thresholds. The values of TpT_p, TsT_s and TdT_d trade speed of detection against false alarms. They are chosen, and a slow worm can stay below the dispersion thresholds within the time-out.
  • Poisoning. An attacker who knows the method can send prevalent and dispersed benign-looking content to cause a harmful automatic signature. The defense is human review or a white-list before a signature is deployed.

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.

content_prevalence_worm_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/content-prevalence-worm-detection/. The authors are listed in prov/1PFR3M.jsonl.

"""Content sifting (Singh, Estan, Varghese and Savage 2004) on synthetic packets.

A packet is an abstract tuple (source, destination, port, payload). The
sifter reports a substring key when the substring is frequent (content
prevalence) and has been sent by many sources to many destinations (address
dispersion). Nothing here reads or sends network traffic.
"""

import random
from typing import Hashable

# x^31 + x^3 + 1, an irreducible polynomial over GF(2) (the test checks it).
DEFAULT_POLY = (1 << 31) | (1 << 3) | 1
_MERSENNE61 = (1 << 61) - 1


def gf2_mod(a: int, poly: int) -> int:
    """Return a mod poly, both read as polynomials over GF(2). Cost: O(deg a)."""
    k = poly.bit_length() - 1
    while a.bit_length() > k:
        a ^= poly << (a.bit_length() - 1 - k)
    return a


def rabin(window: bytes, poly: int = DEFAULT_POLY) -> int:
    """Rabin fingerprint of a byte string: its bits as a GF(2) polynomial mod poly.

    Cost: O(len(window)) shifts and reductions.
    """
    fp = 0
    for c in window:
        fp = gf2_mod((fp << 8) ^ c, poly)
    return fp


def out_table(beta: int, poly: int = DEFAULT_POLY) -> list[int]:
    """Table of c * x^(8 beta) mod poly for each byte c: the byte that leaves."""
    shift = gf2_mod(1 << (8 * beta), poly)
    table = [0] * 256
    for c in range(256):
        prod = 0
        for bit in range(8):
            if c >> bit & 1:
                prod ^= shift << bit
        table[c] = gf2_mod(prod, poly)
    return table


def rolling_rabin(
    data: bytes, beta: int, poly: int = DEFAULT_POLY, table: list[int] | None = None
) -> list[int]:
    """Fingerprints of all len(data) - beta + 1 windows of beta bytes, rolled.

    Precondition: beta >= 1, and table is out_table(beta, poly) if given.
    Cost: O(len(data)) reductions, plus O(256) for the table if not given.
    """
    if beta < 1:
        raise ValueError("beta must be at least 1")
    if len(data) < beta:
        return []
    if table is None:
        table = out_table(beta, poly)
    fp = rabin(data[:beta], poly)
    fps = [fp]
    for i in range(beta, len(data)):
        fp = gf2_mod((fp << 8) ^ data[i], poly) ^ table[data[i - beta]]
        fps.append(fp)
    return fps


class ContentSifter:
    """Streaming content sifter with a multistage filter and dispersion sets.

    beta: substring length in bytes. sample_bits: keep a fingerprint only if
    its low sample_bits bits are 0 (value sampling, f = 2^-sample_bits).
    prevalence_th, src_th, dst_th: report a key when its count passed
    prevalence_th and its distinct sources and destinations passed src_th and
    dst_th. stages, buckets, seed: the multistage filter with conservative
    update. exact=True replaces the filter by exact counters.

    Precondition: beta >= 1, sample_bits >= 0, stages >= 1, buckets >= 1,
    ports are integers in 0..65535, and poly has degree at most 32.
    Cost per packet with payload length L: O(L) fingerprint steps and
    O(stages) work per sampled window; space O(stages * buckets) for the
    filter plus O(1) per (key, address) pair in the dispersion table.
    """

    def __init__(
        self,
        beta: int,
        sample_bits: int,
        prevalence_th: int,
        src_th: int,
        dst_th: int,
        stages: int = 4,
        buckets: int = 64,
        seed: int = 0,
        poly: int = DEFAULT_POLY,
        exact: bool = False,
    ) -> None:
        if beta < 1 or sample_bits < 0 or stages < 1 or buckets < 1:
            raise ValueError("bad parameters")
        self.beta = beta
        self.mask = (1 << sample_bits) - 1
        self.prevalence_th = prevalence_th
        self.src_th = src_th
        self.dst_th = dst_th
        self.poly = poly
        self.table = out_table(beta, poly)
        self.exact = exact
        rng = random.Random(seed)
        self.hashes = [
            (rng.randrange(1, _MERSENNE61), rng.randrange(_MERSENNE61)) for _ in range(stages)
        ]
        self.buckets = buckets
        self.counters = [[0] * buckets for _ in range(stages)]
        self.exact_counts: dict[tuple[int, int], int] = {}
        self.dispersion: dict[tuple[int, int], tuple[set, set]] = {}
        self.reported: set[tuple[int, int]] = set()

    def _slots(self, key: tuple[int, int]) -> list[int]:
        v = ((key[0] & 0xFFFF) << 32) | key[1]
        return [((a * v + b) % _MERSENNE61) % self.buckets for a, b in self.hashes]

    def msf_increment(self, key: tuple[int, int]) -> int:
        """Conservative update; return the new estimate of the count of key."""
        if self.exact:
            c = self.exact_counts.get(key, 0) + 1
            self.exact_counts[key] = c
            return c
        slots = self._slots(key)
        m = min(self.counters[i][j] for i, j in enumerate(slots))  # @line L10
        for i, j in enumerate(slots):  # @line L11
            if self.counters[i][j] == m:
                self.counters[i][j] = m + 1
        return m + 1  # @line L12

    def estimate(self, key: tuple[int, int]) -> int:
        """Current count estimate of key (no update)."""
        if self.exact:
            return self.exact_counts.get(key, 0)
        return min(self.counters[i][j] for i, j in enumerate(self._slots(key)))

    def process(self, src: Hashable, dst: Hashable, port: int, payload: bytes) -> list[tuple[int, int]]:
        """Sift one packet. Return the keys (port, fingerprint) first reported now."""
        new_reports: list[tuple[int, int]] = []
        for fp in rolling_rabin(payload, self.beta, self.poly, self.table):  # @line L1
            key = (port, fp)  # @line L2
            if fp & self.mask:  # @line L3
                continue
            if key in self.dispersion:  # @line L4
                srcs, dsts = self.dispersion[key]  # @line L5
                srcs.add(src)
                dsts.add(dst)
                if len(srcs) > self.src_th and len(dsts) > self.dst_th:  # @line L6
                    if key not in self.reported:
                        self.reported.add(key)
                        new_reports.append(key)
            else:  # @line L7
                c = self.msf_increment(key)  # @line L8
                if c > self.prevalence_th:  # @line L9
                    self.dispersion[key] = ({src}, {dst})
        return new_reports
test_content_prevalence_worm_detection.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/content-prevalence-worm-detection/. The authors are listed in prov/1PFR3M.jsonl.

import random

from content_prevalence_worm_detection import (
    DEFAULT_POLY,
    ContentSifter,
    gf2_mod,
    rabin,
    rolling_rabin,
)


def gf2_mulmod(a: int, b: int, poly: int) -> int:
    prod = 0
    while b:
        if b & 1:
            prod ^= a
        a <<= 1
        b >>= 1
    return gf2_mod(prod, poly)


def gf2_gcd(a: int, b: int) -> int:
    while b:
        a, b = b, gf2_mod(a, b)
    return a


def test_default_poly_irreducible() -> None:
    # Rabin's test for degree 31 (a prime): x^(2^31) = x mod P, and P has no
    # factor of degree 1, that is gcd(x^2 - x, P) = 1.
    x = 0b10
    r = x
    for _ in range(31):
        r = gf2_mulmod(r, r, DEFAULT_POLY)
    assert r == x
    assert gf2_gcd(DEFAULT_POLY, 0b110) == 1


def test_rabin_is_polynomial_residue() -> None:
    rng = random.Random(1)
    for _ in range(200):
        w = bytes(rng.randrange(256) for _ in range(rng.randint(1, 12)))
        assert rabin(w) == gf2_mod(int.from_bytes(w, "big"), DEFAULT_POLY)


def test_rolling_equals_direct() -> None:
    rng = random.Random(2)
    for _ in range(300):
        beta = rng.randint(1, 9)
        data = bytes(rng.randrange(256) for _ in range(rng.randint(0, 40)))
        direct = [rabin(data[i : i + beta]) for i in range(len(data) - beta + 1)]
        assert rolling_rabin(data, beta) == direct


def oracle(packets, beta, sample_bits, tp, ts, td):
    """Brute force: list each sampled window occurrence, then replay per key."""
    mask = (1 << sample_bits) - 1
    occ: dict = {}
    for t, (s, d, port, x) in enumerate(packets):
        for i in range(len(x) - beta + 1):
            fp = rabin(x[i : i + beta])
            if fp & mask:
                continue
            occ.setdefault((port, fp), []).append((t, s, d))
    first = {}
    for key, lst in occ.items():
        if len(lst) <= tp:
            continue
        srcs = {lst[tp][1]}
        dsts = {lst[tp][2]}
        for t, s, d in lst[tp + 1 :]:
            srcs.add(s)
            dsts.add(d)
            if len(srcs) > ts and len(dsts) > td:
                first[key] = t
                break
    return first


def run(sifter, packets):
    first = {}
    for t, (s, d, port, x) in enumerate(packets):
        for key in sifter.process(s, d, port, x):
            first[key] = t
    return first


def random_stream(rng: random.Random):
    alphabet = bytes(rng.sample(range(256), rng.randint(2, 4)))
    n = rng.randint(1, 14)
    packets = []
    for _ in range(n):
        length = rng.randint(0, 10)
        x = bytes(rng.choice(alphabet) for _ in range(length))
        packets.append((rng.randrange(5), rng.randrange(5), rng.choice((7, 9)), x))
    return packets


def test_exact_mode_against_oracle() -> None:
    rng = random.Random(2004)
    for _ in range(600):
        packets = random_stream(rng)
        beta = rng.randint(1, 4)
        sb = rng.randint(0, 2)
        tp, ts, td = rng.randint(0, 3), rng.randint(0, 2), rng.randint(0, 2)
        sifter = ContentSifter(beta, sb, tp, ts, td, exact=True)
        assert run(sifter, packets) == oracle(packets, beta, sb, tp, ts, td)


def test_filter_never_reports_later_than_exact() -> None:
    rng = random.Random(45)
    for case in range(500):
        packets = random_stream(rng)
        beta = rng.randint(1, 3)
        tp, ts, td = rng.randint(0, 3), rng.randint(0, 2), rng.randint(0, 2)
        exact = run(ContentSifter(beta, 0, tp, ts, td, exact=True), packets)
        msf = run(ContentSifter(beta, 0, tp, ts, td, stages=2, buckets=4, seed=case), packets)
        for key, t in exact.items():
            assert key in msf and msf[key] <= t


def test_conservative_update_overestimates() -> None:
    rng = random.Random(9)
    for case in range(50):
        sifter = ContentSifter(1, 0, 10**9, 0, 0, stages=3, buckets=5, seed=case)
        truth: dict = {}
        for step in range(200):
            key = (rng.randrange(3), rng.randrange(40))
            assert sifter.msf_increment(key) >= truth.get(key, 0) + 1
            truth[key] = truth.get(key, 0) + 1
            if step % 25 == 24:
                for k, c in truth.items():
                    assert sifter.estimate(k) >= c


def test_planted_pattern_is_reported() -> None:
    # Synthetic traffic between documentation addresses (RFC 5737). The
    # planted pattern is random bytes from a fixed seed, not real content.
    rng = random.Random(77)
    pattern = bytes(rng.randrange(256) for _ in range(24))
    popular = bytes(rng.randrange(256) for _ in range(24))
    packets = []
    for i in range(40):
        src = "192.0.2.%d" % (i + 1)
        dst = "198.51.100.%d" % (i + 1)
        noise = bytes(rng.randrange(256) for _ in range(32))
        packets.append((src, dst, 80, noise))
        packets.append((src, dst, 80, noise[:10] + pattern + noise[10:]))
        # Frequent content between one pair of hosts: prevalent, not dispersed.
        packets.append(("203.0.113.1", "203.0.113.2", 80, popular))
    rng.shuffle(packets)
    beta = 8
    sifter = ContentSifter(beta, 2, 3, 10, 10, stages=4, buckets=256, seed=1)
    reported = set()
    for s, d, port, x in packets:
        reported.update(sifter.process(s, d, port, x))
    pattern_keys = {(80, fp) for fp in rolling_rabin(pattern, beta) if fp & 3 == 0}
    assert pattern_keys
    assert pattern_keys <= reported
    popular_keys = {(80, fp) for fp in rolling_rabin(popular, beta)}
    assert not (popular_keys & reported)
    # Every reported key comes from a window that overlaps the pattern.
    allowed = set(pattern_keys)
    for s, d, port, x in packets:
        j = x.find(pattern)
        if j >= 0:
            for i in range(max(0, j - beta + 1), min(len(x) - beta, j + len(pattern) - 1) + 1):
                allowed.add((80, rabin(x[i : i + beta])))
    assert reported <= allowed

History

Singh, Estan, Varghese and Savage described content sifting and its EarlyBird prototype at OSDI 2004. They ran it on the network of UCSD for about eight months. They report that it found the worms known to be active there and some that were not yet known, with few false positives, most of which a white-list removed, and that the software kept up with about 200 Mbps of traffic with f=1/64f = 1/64. These are measurements on that network, reported in 2004. Kim and Karp presented Autograph at USENIX Security 2004, and the multistage filter with conservative update is from the traffic measurement work of Estan and Varghese.

References

  1. Sumeet Singh, Cristian Estan, George Varghese and Stefan Savage, Automated worm fingerprinting, 6th Symposium on Operating Systems Design and Implementation (OSDI) 2004, pages 45 to 60, Section 3 (content invariance, content prevalence and address dispersion), Section 5 (multistage filters with conservative update, scaled bitmaps, value sampling of Rabin fingerprints, and the main loop), Section 6 (the parameters and the experience at UCSD), Section 7 (limitations)
  2. Hyang-Ah Kim and Brad Karp, Autograph, toward automated, distributed worm signature detection, 13th USENIX Security Symposium 2004, pages 271 to 286, the selection of frequent content blocks from the flows of suspected scanners
  3. Andrei Z. Broder, Some applications of Rabin's fingerprinting method, in Sequences II, Methods in Communication, Security, and Computer Science, Springer, 1993, pages 143 to 152, the fingerprint modulo an irreducible polynomial over GF(2), its collision probability and its table-driven rolling computation
  4. Cristian Estan and George Varghese, New directions in traffic measurement and accounting, focusing on the elephants, ignoring the mice, ACM Transactions on Computer Systems 21(3), 2003, pages 270 to 313, multistage filters and the conservative update

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