Algorithm Search⌘K

Algorithmadvanced

Payload anomaly detection

Also called PAYL.

Models the byte frequency distribution of normal packet payloads per port and length and flags payloads far from it by a simplified Mahalanobis distance.

Time
O(s + 256 n) worst
Space
O(256 b) extra
Where
b = the number of buckets; n = the number of training payloads; s = the total length of the training payloads
Properties
deterministicexactonlineiterative
Origin
Ke Wang, Salvatore J. Stolfo, 2004

Payload anomaly detection, as in the PAYL system of Wang and Stolfo (2004), learns what the content of normal network packets looks like for each service, and flags packets whose content looks different. The model is simple: for each service port and each payload length, it keeps the mean and the standard deviation of the relative frequency of each of the 256 byte values. A new payload is compared with the model of its port and length by a weighted distance. The method needs no examples of attacks, so it is a detector for the anomaly detection problem. A traffic source that sends content of a new kind to a service, such as binary data where the service normally gets text, gets a large distance.

In plain words

Count how often each byte value appears in a packet, and divide by the length. This gives 256 numbers that sum to 1, a profile of the packet. Text has a profile with many letters and spaces and no control bytes. Compressed or encrypted data has a flat profile.

For each service and each packet length, average the profiles of many normal packets, and note how much each of the 256 numbers usually varies. A new packet is suspicious when its profile differs from the average in many places, and most of all in the places where normal packets never vary.

The problem

The input is a training set of normal payloads pp, each a nonempty byte string with a service label, a bin width w≥1w \ge 1, a smoothing factor α>0\alpha > 0 and a threshold θ\theta. For a payload pp, let x(p)∈[0,1]256x(p) \in [0, 1]^{256} with xi(p)x_i(p) the number of bytes equal to ii in pp divided by ∣p∣|p|. The bucket of pp is its service and the length bin ⌊∣p∣/w⌋\lfloor |p| / w \rfloor. For each bucket bb with training payloads p1,…,pcp_1, \ldots, p_c, the model is the mean yˉb,i=1c∑kxi(pk)\bar y_{b,i} = \frac1c \sum_k x_i(p_k) and the population standard deviation σb,i\sigma_{b,i} of each coordinate. The distance of a payload pp in bucket bb is

d(p)=∑i=0255∣xi(p)−yˉb,i∣σb,i+α,d(p) = \sum_{i=0}^{255} \frac{\lvert x_i(p) - \bar y_{b,i} \rvert}{\sigma_{b,i} + \alpha},

and d(p)=∞d(p) = \infty if the bucket has no model. The output for a tested payload is the flag d(p)>θd(p) > \theta.

Wang and Stolfo call dd a simplified Mahalanobis distance. The full Mahalanobis distance needs the 256×256256 \times 256 covariance matrix and its inverse. The simplified one treats the bytes as independent and uses the absolute value instead of the square, which is cheaper and less sensitive to one large coordinate.

The algorithm

  1. PAYL-TRAIN(training payloads, w)
  2. 1for each payload p with service v do
  3. 2x ← the relative frequency of each byte value 0..255 in p
  4. 3b ← (v, ⌊|p| / w⌋)
  5. 4update the count, the mean ȳ_b and the variance σ_b² of bucket b with x
  6. PAYL-TEST(p, v, α, θ)
  7. 5b ← (v, ⌊|p| / w⌋); if bucket b has no model then return ∞
  8. 6x ← the relative frequency of each byte value 0..255 in p
  9. 7d ← Σ_i |x_i - ȳ_{b,i}| / (σ_{b,i} + α)
  10. 8flag p if d > θ

Line L4 uses Welford's algorithm: with cc the new count, δ=xi−yˉb,i\delta = x_i - \bar y_{b,i}, it sets yˉb,i←yˉb,i+δ/c\bar y_{b,i} \leftarrow \bar y_{b,i} + \delta / c and adds δ(xi−yˉb,i)\delta (x_i - \bar y_{b,i}) to a sum of squared deviations. So the model can grow one payload at a time and never stores the payloads. The factor α\alpha in line L7 keeps the distance finite when a byte value has standard deviation 0, for example a byte that never occurs in training. Line L5 reports a payload of a length the model has never seen; the paper instead merges the models of nearby lengths, so that each bucket has enough data.

Example

Take one service and four training payloads of length 4, w=1w = 1 and α=0.001\alpha = 0.001: aaab, aabb, abab and abbb. The frequency of a is 0.75, 0.5, 0.5 and 0.25, so its mean is 0.5 and its standard deviation is 0.03125≈0.17678\sqrt{0.03125} \approx 0.17678. The same holds for b. The 254 other byte values have mean 0 and standard deviation 0. Let the threshold be the largest distance on the training set, θ=2.8125\theta = 2.8125, the distance of aaab and of abbb.

payload frequencies dd flagged
baab a 0.5, b 0.5 0 no
aaaa a 1 5.6250 yes
abca a 0.5, b 0.25, c 0.25 251.41 yes
abcab length 5 ∞\infty yes

The payload aaaa is twice as far from the mean as aaab on the coordinates a and b. The payload abca has a byte value, c, that no training payload has. That coordinate has σ=0\sigma = 0, so it adds 0.25/0.001=2500.25 / 0.001 = 250 to the distance. A byte that never occurs in normal traffic is the strongest evidence the model can see. The value of α\alpha sets how strong.

Correctness

The model and the distance are exact computations. The flag is a heuristic.

Theorem (the model). After line L4 has processed cc payloads of bucket bb, the stored mean is 1c∑kx(pk)\frac1c \sum_k x(p_k) and the stored sum is ∑k(x(pk)−yˉb)2\sum_k (x(p_k) - \bar y_b)^2 in each coordinate, in exact arithmetic. So training on the payloads in any order, and in any number of batches, gives the same model.

Theorem (the distance). For α>0\alpha > 0 and a bucket with a model, dd is a weighted ℓ1\ell_1 distance between x(p)x(p) and yˉb\bar y_b with positive weights 1/(σb,i+α)1/(\sigma_{b,i} + \alpha). So d(p)=0d(p) = 0 if and only if x(p)=yˉbx(p) = \bar y_b, dd satisfies the triangle inequality on frequency vectors, and d(p)≤2/αd(p) \le 2 / \alpha, because both vectors have nonnegative coordinates that sum to 1.

Heuristic (the threshold). The paper chooses θ\theta from the distances of normal training traffic, so that a chosen fraction of normal payloads passes. The model does not say that payloads with a large distance are attacks. It says only that their byte content is rare for that port and length. Normal traffic of a new kind, such as a new file type, also gets a large distance, and an attack whose bytes look like normal traffic gets a small one.

Measurement. In the tests, with payloads from a stated Markov chain on 9 byte values, a threshold set on 100 normal payloads gives at most 5% false alarms on 300 fresh normal payloads, and flags all of 100 payloads of uniform random bytes and all of 100 normal payloads with a run of 4 bytes of a value not in the chain.

The proofs section below proves the two theorems.

Proof: The payload model stores the exact mean and variance of each bucket, and its distance is a bounded weighted l1 distancefull

Setting. Each training payload pp is a nonempty byte string with a service label. Its frequency vector x(p)∈[0,1]256x(p) \in [0, 1]^{256} has xi(p)=∣{j:pj=i}∣/∣p∣x_i(p) = |\{j : p_j = i\}| / |p|, so xi(p)≥0x_i(p) \ge 0 and ∑ixi(p)=1\sum_i x_i(p) = 1. The arithmetic is exact in this proof; the code uses floating point, and the tests check it against the two pass formulas.

Lemma 1 (line L2). The code computes x(p)x(p).

Proof. The loop adds 1 to the count of each byte value of pp once for each position, so count ii is ∣{j:pj=i}∣|\{j : p_j = i\}|, and the code divides each count by ∣p∣>0|p| > 0. □\square

Lemma 2 (Welford's update at line L4). Fix a bucket and one coordinate ii, and let x(1),x(2),…x^{(1)}, x^{(2)}, \ldots be the values of xix_i of the payloads that line L3 puts in the bucket, in the order they come. After c≥1c \ge 1 updates, the stored values are μc=1c∑k≤cx(k)\mu_c = \frac1c \sum_{k \le c} x^{(k)} and Mc=∑k≤c(x(k)−μc)2M_c = \sum_{k \le c} (x^{(k)} - \mu_c)^2.

Proof. By induction on cc. At the start, μ0=0\mu_0 = 0 and M0=0M_0 = 0. The first update gives δ=x(1)\delta = x^{(1)}, μ1=x(1)\mu_1 = x^{(1)} and M1=δ(x(1)−μ1)=0M_1 = \delta (x^{(1)} - \mu_1) = 0, which is correct. For the step, let δ=x(c)−μc−1\delta = x^{(c)} - \mu_{c-1}. Then μc=μc−1+δ/c\mu_c = \mu_{c-1} + \delta / c, which is the mean of the first cc values, since cμc=(c−1)μc−1+x(c)c \mu_c = (c - 1) \mu_{c-1} + x^{(c)}. For the sum, write Sc=∑k≤c(x(k))2S_c = \sum_{k \le c} (x^{(k)})^2, so Mc=Sc−cμc2M_c = S_c - c \mu_c^2 for every cc. Then

Mc−Mc−1=(x(c))2−cμc2+(c−1)μc−12.M_c - M_{c-1} = (x^{(c)})^2 - c \mu_c^2 + (c - 1) \mu_{c-1}^2 .

Substitute μc=μc−1+δ/c\mu_c = \mu_{c-1} + \delta / c and x(c)=μc−1+δx^{(c)} = \mu_{c-1} + \delta. The right side is μc−12+2μc−1δ+δ2−cμc−12−2μc−1δ−δ2/c+(c−1)μc−12=δ2(c−1)/c\mu_{c-1}^2 + 2 \mu_{c-1} \delta + \delta^2 - c \mu_{c-1}^2 - 2 \mu_{c-1} \delta - \delta^2 / c + (c - 1) \mu_{c-1}^2 = \delta^2 (c - 1) / c. The code adds δ(x(c)−μc)=δ(δ−δ/c)=δ2(c−1)/c\delta (x^{(c)} - \mu_c) = \delta (\delta - \delta / c) = \delta^2 (c - 1) / c, the same value. □\square

So the standard deviation that the code returns, Mc/c\sqrt{M_c / c}, is the population standard deviation of the bucket, and the model does not depend on the order of the payloads or on how they are split into batches: the mean and McM_c are functions of the multiset of values.

Theorem 1 (the model). For each bucket bb, after training, the code stores the number cc of training payloads of bb, the mean yˉb=1c∑kx(pk)\bar y_b = \frac1c \sum_k x(p_k) and the population standard deviation σb\sigma_b of each coordinate.

Proof. Line L3 sends each payload to the bucket of its service and length bin, and by Lemmas 1 and 2 each of the 256 coordinates of the bucket is the mean and the sum of squares of the frequencies of the payloads sent there. □\square

Theorem 2 (the distance). Let α>0\alpha > 0, let bb be a bucket with a model, and let D(u,v)=∑i∣ui−vi∣/(σb,i+α)D(u, v) = \sum_i |u_i - v_i| / (\sigma_{b,i} + \alpha) for u,v∈R256u, v \in \mathbb{R}^{256}. Line L7 computes d(p)=D(x(p),yˉb)d(p) = D(x(p), \bar y_b). Also:

  1. D(u,v)≥0D(u, v) \ge 0, with equality if and only if u=vu = v;
  2. D(u,v)=D(v,u)D(u, v) = D(v, u) and D(u,w)≤D(u,v)+D(v,w)D(u, w) \le D(u, v) + D(v, w);
  3. d(p)≤2/αd(p) \le 2 / \alpha.

Proof. Line L7 is the formula of DD with the stored values of Theorem 1. Each weight 1/(σb,i+α)1/(\sigma_{b,i} + \alpha) is positive and finite, because σb,i≥0\sigma_{b,i} \ge 0 and α>0\alpha > 0. A sum of nonnegative terms with positive weights is 0 only if each ∣ui−vi∣|u_i - v_i| is 0, which gives 1. Symmetry and the triangle inequality hold for each term ∣ui−vi∣|u_i - v_i|, and a positive weight keeps them, which gives 2. For 3, the weights are at most 1/α1/\alpha, and ∑i∣xi−yˉb,i∣≤∑ixi+∑iyˉb,i=2\sum_i |x_i - \bar y_{b,i}| \le \sum_i x_i + \sum_i \bar y_{b,i} = 2, because x(p)x(p) and yˉb\bar y_b, a mean of frequency vectors, both have nonnegative coordinates that sum to 1. □\square

Termination. Training makes one pass over a finite list of payloads, and each update does a fixed 256 steps. The test does one pass over the payload and 256 steps. No loop depends on a value it changes.

By Theorem 1 the model of each bucket is the exact mean and standard deviation of its training frequencies, and by Theorem 2 the test computes the weighted distance of the definition, which is a bounded metric on frequency vectors, so line L8 flags exactly the payloads with d(p)>θd(p) > \theta, and line L5 flags exactly the payloads whose bucket has no model. ■\blacksquare

Complexity

The cost is in the word-RAM model with a byte as the unit.

  • Training. Line L2 counts the bytes of pp in O(∣p∣)O(|p|) time, and lines L2 and L4 do O(256)O(256) work for each payload. For nn payloads of total length ss this is O(s+256n)O(s + 256 n).
  • Space. Each bucket stores 256 means, 256 sums of squares and a count, so bb buckets take O(256b)O(256 b) space. The payloads are not stored.
  • Test. Lines L5 to L7 take O(l+256)O(l + 256) time for a payload of length ll.

The test is fast enough to run on each packet of a busy service, which was a goal of the design.

Properties

  • Online. The model grows one payload at a time, and it can be updated while the detector runs.
  • Unsupervised. It needs only normal traffic, and it tolerates a small fraction of attacks in the training data, because they shift the mean little.
  • One model for each service and length. The byte content of a service depends on its protocol, and short and long payloads of the same service differ, for example short requests and long replies. So the buckets separate them.
  • Order-blind. The frequencies ignore the order of the bytes. Two payloads with the same bytes in any order have distance 0 from each other.

Variants and improvements

  • Clustering of lengths. Wang and Stolfo merge the models of neighboring lengths when their means are close, which cuts the number of models and gives more data to each.
  • Higher order n-grams. The Anagram detector of Wang, Parekh and Stolfo (2006) stores the n-grams of normal payloads, for n>1n > 1, in a Bloom filter and scores a payload by the fraction of its n-grams never seen. This sees the order of the bytes. The same idea is behind the byte n-gram classifiers of malware.
  • Ingress and egress correlation. Wang, Cretu and Stolfo (2005) compare the anomalous payloads that a host receives with those it then sends, as a sign of a self-propagating program. The page on content prevalence covers a related signal.
  • Full Mahalanobis distance. With enough data, the full covariance matrix gives a better model of bytes that occur together, at a cost of 2562256^2 entries per bucket.

When to use it

Use it as one signal in a network monitor when the services carry content with a stable byte distribution, such as text protocols, and when content of a new kind is a reason for a closer look. It is fast and needs no labels. Do not use it alone: Sommer and Paxson (2010) explain why anomaly detectors on network data give many false alarms, and the base rate fallacy explains why a small false alarm rate on each packet still gives many false alarms in total. Encrypted traffic has a flat byte distribution for all payloads, so the model sees nothing in it.

Pitfalls

  • No smoothing. With α=0\alpha = 0, line L7 divides by 0 for every byte value with σ=0\sigma = 0. Keep α>0\alpha > 0, and know that its value sets the weight of rare bytes.
  • Sparse buckets. A bucket with few payloads has a poor mean and a small σ\sigma, so line L7 gives large distances to normal payloads. Merge nearby lengths or use a wider ww at line L3.
  • Unseen lengths. Line L5 flags every payload of a length that has no model. If the service has many lengths, this alone can give many false alarms.
  • Counts instead of frequencies. If line L2 does not divide by the length, payloads of different lengths in one bin have profiles of different scales, and the distance measures the length, not the content.
  • Mimicry. An attacker who knows the model can add bytes so that the frequencies of a malicious payload match the normal ones. Fogla and coauthors (2006) showed this against byte frequency models, and it is why later detectors use higher order n-grams and randomized models. The model alone is not a defense against an adaptive adversary.
  • Polluted training data. If attacks are a large part of the training traffic, line L4 learns them as normal.

Implementations

The code reads only byte strings that the caller gives it. The tests build them from a stated Markov chain with a fixed seed; no real traffic is used.

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.

payload_anomaly_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/payload-anomaly-detection/. The authors are listed in prov/DKYY8T.jsonl.

"""A byte frequency payload model after PAYL (Wang and Stolfo, RAID 2004).

This is a detector. It reads only byte strings that the caller gives it,
such as the synthetic strings of the tests, and it never opens a socket or a file.
"""

import math
from dataclasses import dataclass, field
from typing import Hashable, Iterable

Key = tuple[Hashable, int]


def byte_frequencies(payload: bytes) -> list[float]:
    """Relative frequency of each byte value 0..255 in payload. Precondition: payload is not empty. Cost: O(len + 256)."""
    counts = [0] * 256
    for b in payload:
        counts[b] += 1
    n = len(payload)
    return [c / n for c in counts]


@dataclass
class BucketModel:
    """Running mean and sum of squared deviations (Welford) of the 256 frequencies."""

    count: int = 0
    mean: list[float] = field(default_factory=lambda: [0.0] * 256)
    m2: list[float] = field(default_factory=lambda: [0.0] * 256)

    def add(self, freq: list[float]) -> None:
        self.count += 1
        for i, x in enumerate(freq):
            delta = x - self.mean[i]
            self.mean[i] += delta / self.count
            self.m2[i] += delta * (x - self.mean[i])

    def std(self) -> list[float]:
        """Population standard deviation of each frequency."""
        return [math.sqrt(max(0.0, v) / self.count) for v in self.m2]


@dataclass
class PayloadModel:
    width: int
    buckets: dict[Key, BucketModel] = field(default_factory=dict)

    def key(self, service: Hashable, payload: bytes) -> Key:
        return (service, len(payload) // self.width)


def train(samples: Iterable[tuple[Hashable, bytes]], width: int = 1, model: PayloadModel | None = None) -> PayloadModel:
    """Build or extend a model from (service, payload) pairs of normal traffic.

    One bucket per service and length bin of the given width. Each bucket keeps
    the mean and the standard deviation of the relative frequency of each byte value.
    Precondition: width >= 1 and every payload is not empty.
    Cost: O(s + 256 n) time for n payloads of total length s, and O(256) space per bucket.
    """
    if width < 1:
        raise ValueError("width must be at least 1")
    if model is None:
        model = PayloadModel(width)
    for service, payload in samples:  # @line L1
        if not payload:
            raise ValueError("empty payload")
        freq = byte_frequencies(payload)  # @line L2
        key = model.key(service, payload)  # @line L3
        model.buckets.setdefault(key, BucketModel()).add(freq)  # @line L4
    return model


def distance(model: PayloadModel, service: Hashable, payload: bytes, alpha: float = 0.001) -> float:
    """Simplified Mahalanobis distance sum_i |x_i - mean_i| / (std_i + alpha) of payload to its bucket.

    Returns math.inf when the bucket has no model, so that an unseen length is
    always reported. Precondition: alpha > 0 and payload is not empty. Cost: O(len + 256).
    """
    if alpha <= 0.0:
        raise ValueError("alpha must be positive")
    bucket = model.buckets.get(model.key(service, payload))  # @line L5
    if bucket is None:
        return math.inf
    x = byte_frequencies(payload)  # @line L6
    sd = bucket.std()
    return sum(abs(xi - mi) / (si + alpha) for xi, mi, si in zip(x, bucket.mean, sd))  # @line L7


def is_anomalous(model: PayloadModel, service: Hashable, payload: bytes, threshold: float, alpha: float = 0.001) -> bool:
    """True when the distance exceeds the threshold, a value the operator chooses. Cost: O(len + 256)."""
    return distance(model, service, payload, alpha) > threshold  # @line L8
test_payload_anomaly_detection.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/payload-anomaly-detection/. The authors are listed in prov/DKYY8T.jsonl.

import math
import random

import pytest

from payload_anomaly_detection import byte_frequencies, distance, is_anomalous, train

ALPHABET = b"abcdefgh "


def markov_payload(rng: random.Random, length: int) -> bytes:
    """A synthetic payload from a stated Markov chain on 9 byte values.

    From symbol i the next symbol is i + 1, i + 2 or i + 3 (mod 9), with
    probabilities 1/2, 1/4 and 1/4.
    """
    i = rng.randrange(len(ALPHABET))
    out = bytearray()
    for _ in range(length):
        out.append(ALPHABET[i])
        i = (i + rng.choice((1, 1, 2, 3))) % len(ALPHABET)
    return bytes(out)


def two_pass(freqs):
    """Mean and population standard deviation of each coordinate, by the two pass formula."""
    n = len(freqs)
    mean = [0.0] * 256
    sd = [0.0] * 256
    for i in {i for f in freqs for i in range(256) if f[i]}:
        mean[i] = sum(f[i] for f in freqs) / n
        sd[i] = math.sqrt(sum((f[i] - mean[i]) ** 2 for f in freqs) / n)
    return mean, sd


def test_example() -> None:
    model = train([("p", b"aaab"), ("p", b"aabb"), ("p", b"abab"), ("p", b"abbb")])
    bucket = model.buckets[("p", 4)]
    assert bucket.mean[ord("a")] == pytest.approx(0.5) and bucket.mean[ord("b")] == pytest.approx(0.5)
    assert bucket.std()[ord("a")] == pytest.approx(math.sqrt(0.03125))
    s = math.sqrt(0.03125) + 0.001
    assert distance(model, "p", b"aaab") == pytest.approx(0.5 / s)
    assert distance(model, "p", b"baab") == pytest.approx(0.0, abs=1e-12)
    assert distance(model, "p", b"aaaa") == pytest.approx(1.0 / s)
    assert distance(model, "p", b"abca") == pytest.approx(0.25 / s + 0.25 / 0.001)
    assert distance(model, "p", b"aaabb") == math.inf
    assert distance(model, "q", b"aaab") == math.inf
    threshold = max(distance(model, "p", p) for p in (b"aaab", b"aabb", b"abab", b"abbb"))
    flags = [is_anomalous(model, "p", p, threshold) for p in (b"baab", b"aaaa", b"abca", b"abcab")]
    assert flags == [False, True, True, True]


def test_welford_and_distance_against_brute_force() -> None:
    rng = random.Random(4)
    for _ in range(500):
        width = rng.choice([1, 2, 4])
        values = rng.sample(range(256), rng.randint(1, 6))
        samples = []
        for _ in range(rng.randint(1, 8)):
            length = rng.randint(1, 9)
            samples.append((rng.choice(["x", 7]), bytes(rng.choice(values) for _ in range(length))))
        model = train(samples, width)
        groups = {}
        for service, p in samples:
            groups.setdefault((service, len(p) // width), []).append(byte_frequencies(p))
        assert set(groups) == set(model.buckets)
        stats = {key: two_pass(freqs) for key, freqs in groups.items()}
        for key, (mean, sd) in stats.items():
            bucket = model.buckets[key]
            assert bucket.count == len(groups[key])
            assert max(abs(a - b) for a, b in zip(bucket.mean, mean)) <= 1e-12
            assert max(abs(a - b) for a, b in zip(bucket.std(), sd)) <= 1e-7
        service, p = rng.choice(samples)
        q = bytes(rng.choice(values + [rng.randrange(256)]) for _ in range(len(p)))
        mean, sd = stats[(service, len(q) // width)]
        x = [q.count(i) / len(q) for i in range(256)]
        want = sum(abs(x[i] - mean[i]) / (sd[i] + 0.01) for i in range(256))
        assert distance(model, service, q, alpha=0.01) == pytest.approx(want, rel=1e-6, abs=1e-6)


def test_incremental_training_equals_batch() -> None:
    rng = random.Random(9)
    samples = [("s", markov_payload(rng, rng.randint(20, 40))) for _ in range(60)]
    batch = train(samples, 10)
    step = train(samples[:25], 10)
    step = train(samples[25:], 10, step)
    for key in batch.buckets:
        assert step.buckets[key].count == batch.buckets[key].count
        assert step.buckets[key].mean == pytest.approx(batch.buckets[key].mean, abs=1e-12)
        assert step.buckets[key].std() == pytest.approx(batch.buckets[key].std(), abs=1e-9)


def test_detection_on_synthetic_traffic() -> None:
    rng = random.Random(2024)
    length = lambda: rng.randint(40, 69)
    model = train((("s", markov_payload(rng, length())) for _ in range(300)), 10)
    calibration = [markov_payload(rng, length()) for _ in range(100)]
    threshold = max(distance(model, "s", p) for p in calibration)
    normal = [markov_payload(rng, length()) for _ in range(300)]
    false_alarms = sum(is_anomalous(model, "s", p, threshold) for p in normal) / len(normal)
    assert false_alarms <= 0.05
    uniform = [bytes(rng.randrange(256) for _ in range(length())) for _ in range(100)]
    assert all(is_anomalous(model, "s", p, threshold) for p in uniform)
    # A normal payload with a run of one byte value never seen in training is also flagged.
    spliced = []
    for _ in range(100):
        p = bytearray(markov_payload(rng, length()))
        at = rng.randrange(len(p) - 4)
        p[at : at + 4] = bytes([0x7E]) * 4
        spliced.append(bytes(p))
    assert all(is_anomalous(model, "s", p, threshold) for p in spliced)


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        train([("s", b"")])
    with pytest.raises(ValueError):
        train([("s", b"ab")], width=0)
    model = train([("s", b"ab")])
    with pytest.raises(ValueError):
        distance(model, "s", b"ab", alpha=0.0)
    assert distance(model, "s", b"ba") == 0.0

History

Byte frequency models of payloads appeared in network anomaly detection in the early 2000s. Wang and Stolfo presented PAYL at RAID 2004 with one model for each port and length, the simplified Mahalanobis distance and the incremental training, and evaluated it on the 1999 DARPA evaluation data and on traffic of their own department. Later work by the same group extended it to the correlation of incoming and outgoing payloads and to higher order n-grams in the Anagram detector. Work on mimicry and blending, from 2006, showed the limits of byte frequency models against an adversary who knows them.

References

  1. Ke Wang and Salvatore J. Stolfo, Anomalous payload-based network intrusion detection, RAID 2004, LNCS 3224, pages 203 to 222, the byte frequency model for each port and payload length, the incremental update of the mean and the standard deviation, the simplified Mahalanobis distance with a smoothing factor, and the clustering of models of nearby lengths
  2. Varun Chandola, Arindam Banerjee and Vipin Kumar, Anomaly detection, a survey, ACM Computing Surveys 41(3), article 15, 2009, the section on intrusion detection
  3. Robin Sommer and Vern Paxson, Outside the closed world, on using machine learning for network intrusion detection, IEEE Symposium on Security and Privacy 2010, pages 305 to 316, the reasons why anomaly detectors on network data give many false alarms in practice

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