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.
- Solves
- Anomaly detection
- 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
- Model
- Word RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , each a nonempty byte string with a service label, a bin width , a smoothing factor and a threshold . For a payload , let with the number of bytes equal to in divided by . The bucket of is its service and the length bin . For each bucket with training payloads , the model is the mean and the population standard deviation of each coordinate. The distance of a payload in bucket is
and if the bucket has no model. The output for a tested payload is the flag .
Wang and Stolfo call a simplified Mahalanobis distance. The full Mahalanobis distance needs the 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
PAYL-TRAIN(training payloads, w)- 1
for each payload p with service v do - 2
x ← the relative frequency of each byte value 0..255 in p - 3
b ← (v, ⌊|p| / w⌋) - 4
update the count, the mean ȳ_b and the variance σ_b² of bucket b with x PAYL-TEST(p, v, α, θ)- 5
b ← (v, ⌊|p| / w⌋); if bucket b has no model then return ∞ - 6
x ← the relative frequency of each byte value 0..255 in p - 7
d ← Σ_i |x_i - ȳ_{b,i}| / (σ_{b,i} + α) - 8
flag p if d > θ
Line L4 uses Welford's algorithm: with the new count, , it sets and adds to a sum of squared deviations. So the model can grow one payload at a time and never stores the payloads. The factor 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, and : 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 . 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, , the distance of aaab and of abbb.
| payload | frequencies | 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 | 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 , so it adds to the distance. A byte that never occurs in normal traffic is the strongest evidence the model can see. The value of 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 payloads of bucket , the stored mean is and the stored sum is 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 and a bucket with a model, is a weighted distance between and with positive weights . So if and only if , satisfies the triangle inequality on frequency vectors, and , because both vectors have nonnegative coordinates that sum to 1.
Heuristic (the threshold). The paper chooses 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 is a nonempty byte string with a service label. Its frequency vector has , so and . 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 .
Proof. The loop adds 1 to the count of each byte value of once for each position, so count is , and the code divides each count by .
Lemma 2 (Welford's update at line L4). Fix a bucket and one coordinate , and let be the values of of the payloads that line L3 puts in the bucket, in the order they come. After updates, the stored values are and .
Proof. By induction on . At the start, and . The first update gives , and , which is correct. For the step, let . Then , which is the mean of the first values, since . For the sum, write , so for every . Then
Substitute and . The right side is . The code adds , the same value.
So the standard deviation that the code returns, , 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 are functions of the multiset of values.
Theorem 1 (the model). For each bucket , after training, the code stores the number of training payloads of , the mean and the population standard deviation 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.
Theorem 2 (the distance). Let , let be a bucket with a model, and let for . Line L7 computes . Also:
- , with equality if and only if ;
- and ;
- .
Proof. Line L7 is the formula of with the stored values of Theorem 1. Each weight is positive and finite, because and . A sum of nonnegative terms with positive weights is 0 only if each is 0, which gives 1. Symmetry and the triangle inequality hold for each term , and a positive weight keeps them, which gives 2. For 3, the weights are at most , and , because and , a mean of frequency vectors, both have nonnegative coordinates that sum to 1.
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 , and line L5 flags exactly the payloads whose bucket has no model.
Complexity
The cost is in the word-RAM model with a byte as the unit.
- Training. Line L2 counts the bytes of in time, and lines L2 and L4 do work for each payload. For payloads of total length this is .
- Space. Each bucket stores 256 means, 256 sums of squares and a count, so buckets take space. The payloads are not stored.
- Test. Lines L5 to L7 take time for a payload of length .
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 , 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 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 , line L7 divides by 0 for every byte value with . Keep , 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 , so line L7 gives large distances to normal payloads. Merge nearby lengths or use a wider 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.
# 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
- 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
- Varun Chandola, Arindam Banerjee and Vipin Kumar, Anomaly detection, a survey, ACM Computing Surveys 41(3), article 15, 2009, the section on intrusion detection
- 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.
| 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 DKYY8T Edit this page History Report an error Markdown