Algorithmcore
System call sequence anomaly detection
Also called stide, sense of self.
Stores the short sequences of system calls a program makes in normal runs and flags runs with many sequences never seen.
- Solves
- Anomaly detection
- Time
- O(k s) worst
- Space
- O(k u) extra
- Where
- k = the window length; s = the total length of the training traces; u = the number of distinct windows
- Model
- Word RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephanie Forrest, Steven A. Hofmeyr, Anil Somayaji, Thomas A. Longstaff, 1996
A program that runs normally makes system calls in a few typical orders. Forrest, Hofmeyr, Somayaji and Longstaff (1996) used this as a "sense of self" for a process. Record all the short runs of consecutive calls, the windows, that the program makes in normal use. When the program runs later, slide the same window over its calls and count the windows that are not in the record. A program whose control flow was taken over, or that runs in a way never seen, makes many such windows close together. The method is a detector for the anomaly detection problem on one program at a time, and it needs no examples of attacks.
In plain words
Watch a program for a while and write down every group of a few calls in a row that it makes. The list is short, because a program repeats itself. Later, watch the program again and check each group of calls against the list. A group that is not on the list is a surprise. One surprise now and then is normal, because the training never sees everything. Many surprises close together mean that the program does something new.
The problem
The input is a set of normal traces, each a sequence of symbols (the names of the calls), a window length , a frame length and a threshold . The database is the set of all windows of the normal traces . For a test trace with windows , the mismatch flag is if and otherwise, and the locality frame count at is
the number of mismatches among the last windows. The trace is flagged if .
The algorithm
SEQ-TRAIN(normal traces, k)- 1
D ← an empty hash set of windows - 2
for each normal trace T do - 3
for i ← 1 to |T| - k + 1 do add (T_i, …, T_{i+k-1}) to D SEQ-TEST(T, D, k, f, θ)- 4
for i ← 1 to |T| - k + 1 do - 5
m_i ← 0 if (T_i, …, T_{i+k-1}) ∈ D, else 1 - 6
c_i ← c_{i-1} + m_i - m_{i-f} ▷ with m_j = 0 and c_j = 0 for j < 1 - 7
flag T if max_i c_i ≥ θ
Line L6 keeps the count of the last flags in constant time per window: it adds the new flag and drops the one that leaves the frame. The test reads the trace once, so it can run while the program runs and raise the flag at the first frame with mismatches.
Example
Let , and . Train on two normal traces:
- open, read, read, write, close
- open, read, write, close
The database has four windows: (open, read, read), (read, read, write), (read, write, close) and (open, read, write). Test two traces:
| trace | windows not in | flagged | ||
|---|---|---|---|---|
| open, read, read, read, write, close | (read, read, read) | 0, 1, 0, 0 | 0, 1, 1, 1 | no |
| open, write, read, close | (open, write, read), (write, read, close) | 1, 1 | 1, 2 | yes |
The first trace has one more read than any training trace. One window is new, but one mismatch in a frame is below the threshold. This is how the frame count tolerates the gaps of the training data. The second trace writes before it reads, an order never seen, and every window it has is new.
Correctness
Theorem (the flags). if and only if the window occurs at no position of any training trace. So every training trace has no mismatch, a trace made only of windows seen in training has no mismatch, and adding training traces can only change flags from 1 to 0.
Theorem (the count). Line L6 gives , and line L7 flags exactly the traces with some frame of consecutive windows that holds at least mismatches.
Heuristic (the parameters). The window length , the frame and the threshold are choices. A short window gives a small database with few false alarms but misses changes that only show over a longer span; a long window gives the reverse. Forrest et al. reported that windows of a few calls already separated normal runs from intrusions on the programs they studied, and Warrender et al. (1999) used a frame of 20 windows. These are results on their data, not guarantees.
Measurement. In the tests, traces come from a stated automaton on six call names. With , , and 300 training traces, at most 2% of 300 fresh normal traces are flagged, and at least 95% of 300 traces with two calls inserted in an order the automaton never makes are flagged.
What the method cannot see follows from the first theorem: an anomaly whose windows all occur in normal runs gives no mismatch. The proofs section below proves the two theorems.
Proof: The sequence database flags exactly the windows never seen in training, and the frame count is the number of mismatches in the last f windowsfull
Setting. The training traces are finite sequences over a set of symbols, and . For a sequence and , the window at is . A sequence shorter than has no window.
Lemma 1 (the database). After lines L1 to L3, .
Proof. Line L1 starts with the empty set. Line L3 adds each window of each training trace once, for every valid , and adds nothing else. A set keeps one copy of each window, and the order of the additions does not change the final set.
Theorem 1 (the flags). For a test trace , if and only if occurs at no position of any training trace. As a consequence:
- every training trace, and every trace whose windows all occur in training traces, has for all ;
- if the training set grows, no flag changes from 0 to 1.
Proof. Line L5 sets exactly when , and by Lemma 1 this holds exactly when is a window of some training trace. Point 1 is the case where every window is in . For point 2, a larger training set gives a superset of by Lemma 1, and membership in a set is kept by a superset.
Theorem 2 (the frame count). For , line L6 gives .
Proof. By induction on , with and for . Assume , where the terms with are 0. Then
since the new sum gains the term and loses the term . The terms with are 0, so this is the sum from to . The code subtracts the flag at index only when that index is at least the first index, which is the same rule.
Corollary (the flag of a trace). Let . Then is the largest number of mismatches in a set of consecutive positions cut to , over all integers . So line L7 flags if and only if some frame of consecutive windows holds at least mismatches. A trace with no window has by the convention of the code, and it is not flagged, because .
Proof. By Theorem 2, is the count on the frame with , cut to . A frame with ends at a position , so its count is some . A frame with and , cut to , is the set , which is a subset of the frame that ends at , so its count is at most . A frame with is empty. So the largest count over all frames is .
Termination. Training runs over finitely many traces and finitely many positions in each. The test runs once over the positions of the test trace. Each step does work to build and hash a window and work for the count.
By Lemma 1 and Theorems 1 and 2, the procedure computes exactly the database, the mismatch flags and the locality frame counts of the definition, and by the corollary it flags exactly the traces with a frame of at least mismatches.
Complexity
The cost is in the word-RAM model, with a call name as one word and a hash table for .
- Training. Each of the at most windows takes expected time to hash and insert, so training takes expected time.
- Space. The database stores distinct windows of words, so space. For real programs is small compared with , because programs repeat themselves.
- Test. Each window of a trace of length takes expected time at line L5 and at line L6, so . A rolling hash or a trie walk cuts this to expected.
Properties
- Online. The test reads the calls in order with memory and can raise the flag as soon as a frame passes the threshold.
- One model per program. The database is specific to a program and to its use on one site, which Forrest et al. saw as an advantage: a diverse set of models is harder to fool at once.
- Order only. The model ignores the arguments of the calls and the time between them.
- Deterministic and exact. Given the training traces, the database and the flags are fixed, with no randomness and no approximation.
Variants and improvements
- Lookahead pairs. The 1996 paper stored, for each call, the calls that follow it at distances to , rather than whole windows. This database is smaller and more general: it accepts some windows never seen as a whole.
- Hamming distance. Hofmeyr, Forrest and Somayaji (1998) scored each window by its Hamming distance to the closest window of , so that a window that differs in one call counts less than one that differs in all.
- Frequency threshold. Warrender et al. (1999) also counted windows that occur in but are rare in training as mismatches.
- Other models. Warrender et al. compared the database with rule learning and hidden Markov models. The models with more parameters were sometimes more accurate and always far more costly to train.
- Automata from the program. Later work builds the model of allowed call orders from the program itself, as a finite automaton or a pushdown automaton from the call graph, which gives no false alarms by construction for runs of the same code.
- Response. The pH system of Somayaji and Forrest delays the calls of a process more as its recent count of mismatches grows, instead of raising an alarm.
When to use it
Use it to watch a program with a stable set of behaviors, such as a network daemon or a privileged utility, where a change in the order of calls is a sign of a problem worth a look. It is cheap, needs no labels and no source code, and gives an alarm with a location in the trace. Training must cover the normal uses of the program well, or the frame count will give false alarms on rare but legitimate paths. For programs with very varied behavior, such as interpreters and shells, the database grows large and the method is weak.
Pitfalls
- Training that misses normal paths. A path used rarely, such as an error handler, gives mismatches at line L5 when it runs. Train on many runs that cover the normal uses, and set at line L7 above the counts of normal traces held out from training.
- The whole trace as one count. If line L6 counts the mismatches of the whole trace instead of the last windows, a long normal trace with scattered mismatches looks as bad as a short burst. The frame exists to find bursts.
- Mixing programs. One database for all programs on a host is large and accepts in one program the windows of another. Keep one database per program.
- Short traces. A trace shorter than has no window at line L4, so it is never flagged. Check these traces in another way, or pad each trace with a start and an end symbol.
- Mimicry. Wagner and Soto (2002) showed that an adversary who knows the database can make a run whose windows are all in , which the first theorem says the method cannot see. The method is a detector of the unusual, not a defense against an adaptive adversary.
Implementations
The code reads only traces of abstract symbols that the caller gives it. The tests build the traces from a stated automaton with a fixed seed; the code does not trace or run any process.
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/system-call-sequence-detection/. The authors are listed in prov/517GET.jsonl.
"""Short sequences of system calls as a model of normal behavior (Forrest et al. 1996).
The traces are lists of abstract symbols that the caller gives, such as the
synthetic traces of the tests. The code does not trace or run any process.
"""
from typing import Hashable, Iterable, Sequence
Window = tuple[Hashable, ...]
def train(traces: Iterable[Sequence[Hashable]], k: int) -> set[Window]:
"""The set of all windows of k consecutive calls in the normal traces.
A trace shorter than k gives no window. Precondition: k >= 1.
Cost: O(k) expected time per window with hashing, so O(k s) for traces
of total length s, and O(k u) space for u distinct windows.
"""
if k < 1:
raise ValueError("k must be at least 1")
db: set[Window] = set() # @line L1
for trace in traces: # @line L2
for i in range(len(trace) - k + 1): # @line L3
db.add(tuple(trace[i : i + k]))
return db
def mismatches(trace: Sequence[Hashable], db: set[Window], k: int) -> list[int]:
"""1 for each window of the trace that is not in the database, else 0. Cost: O(k |trace|) expected."""
out = []
for i in range(len(trace) - k + 1): # @line L4
out.append(0 if tuple(trace[i : i + k]) in db else 1) # @line L5
return out
def locality_frame_counts(flags: Sequence[int], frame: int) -> list[int]:
"""For each position, the number of mismatches among the last frame windows. Precondition: frame >= 1. Cost: O(len)."""
if frame < 1:
raise ValueError("frame must be at least 1")
counts = []
current = 0
for i, m in enumerate(flags):
current += m # @line L6
if i >= frame:
current -= flags[i - frame]
counts.append(current)
return counts
def is_anomalous(trace: Sequence[Hashable], db: set[Window], k: int, frame: int, threshold: int) -> bool:
"""True when some frame of the trace holds at least threshold mismatches.
The threshold is a choice of the operator. Cost: O(k |trace|) expected.
"""
counts = locality_frame_counts(mismatches(trace, db, k), frame)
return max(counts, default=0) >= threshold # @line L7
test_system_call_sequence_detection.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/system-call-sequence-detection/. The authors are listed in prov/517GET.jsonl.
import random
import pytest
from system_call_sequence_detection import is_anomalous, locality_frame_counts, mismatches, train
# A stated automaton over abstract call names: each call is followed by one of the listed calls, uniformly.
NEXT = {
"open": ["read", "stat"],
"stat": ["read"],
"read": ["read", "write", "close"],
"write": ["read", "close"],
"close": ["open", "exit"],
}
def normal_trace(rng: random.Random) -> list[str]:
trace = ["open"]
while trace[-1] != "exit" and len(trace) < 60:
trace.append(rng.choice(NEXT[trace[-1]]))
return trace
def occurs(window, traces):
k = len(window)
return any(tuple(t[i : i + k]) == window for t in traces for i in range(len(t) - k + 1))
def test_example() -> None:
db = train([["open", "read", "read", "write", "close"], ["open", "read", "write", "close"]], 3)
assert db == {
("open", "read", "read"),
("read", "read", "write"),
("read", "write", "close"),
("open", "read", "write"),
}
first = ["open", "read", "read", "read", "write", "close"]
second = ["open", "write", "read", "close"]
assert mismatches(first, db, 3) == [0, 1, 0, 0]
assert mismatches(second, db, 3) == [1, 1]
assert locality_frame_counts(mismatches(first, db, 3), 4) == [0, 1, 1, 1]
assert locality_frame_counts(mismatches(second, db, 3), 4) == [1, 2]
assert not is_anomalous(first, db, 3, 4, 2)
assert is_anomalous(second, db, 3, 4, 2)
def test_against_brute_force() -> None:
rng = random.Random(6)
symbols = "abcd"
for _ in range(500):
k = rng.randint(1, 4)
traces = [[rng.choice(symbols) for _ in range(rng.randint(0, 10))] for _ in range(rng.randint(1, 4))]
db = train(traces, k)
test = [rng.choice(symbols) for _ in range(rng.randint(0, 12))]
flags = mismatches(test, db, k)
want = [0 if occurs(tuple(test[i : i + k]), traces) else 1 for i in range(len(test) - k + 1)]
assert flags == want
frame = rng.randint(1, 6)
counts = locality_frame_counts(flags, frame)
assert counts == [sum(flags[max(0, i - frame + 1) : i + 1]) for i in range(len(flags))]
# Every window of a training trace is in the database, so a training trace has no mismatch.
assert all(sum(mismatches(t, db, k)) == 0 for t in traces)
threshold = rng.randint(1, 3)
assert is_anomalous(test, db, k, frame, threshold) == (max(counts, default=0) >= threshold)
def test_detection_on_synthetic_traces() -> None:
rng = random.Random(1)
k, frame, threshold = 6, 20, 2
db = train([normal_trace(rng) for _ in range(300)], k)
normal = [normal_trace(rng) for _ in range(300)]
false_alarms = sum(is_anomalous(t, db, k, frame, threshold) for t in normal) / len(normal)
assert false_alarms <= 0.02
detected = 0
for _ in range(300):
t = normal_trace(rng)
while len(t) < 8:
t = normal_trace(rng)
at = rng.randrange(1, len(t) - 1)
# Two calls in an order the automaton never produces: write cannot follow open.
detected += is_anomalous(t[:at] + ["open", "write"] + t[at:], db, k, frame, threshold)
assert detected / 300 >= 0.95
def test_edges() -> None:
db = train([["a", "b"]], 3)
assert db == set()
assert mismatches(["a", "b"], db, 3) == []
assert not is_anomalous(["a", "b"], db, 3, 5, 1)
assert train([["a", "b", "a"]], 1) == {("a",), ("b",)}
with pytest.raises(ValueError):
train([["a"]], 0)
with pytest.raises(ValueError):
locality_frame_counts([0, 1], 0)
History
Forrest, Hofmeyr, Somayaji and Longstaff (1996) took the idea of self and nonself from the immune system and showed that short call sequences separate the normal runs of privileged Unix programs from runs under known intrusions. Hofmeyr, Forrest and Somayaji (1998) moved to full windows and the Hamming distance and tested more programs. Warrender, Forrest and Pearlmutter (1999) compared the simple database with more complex models and found it competitive, and they introduced the locality frame count. Wagner and Soto (2002) showed mimicry against these models, and work on models derived from the program text and on richer models of calls and their arguments followed.
References
- Stephanie Forrest, Steven A. Hofmeyr, Anil Somayaji and Thomas A. Longstaff, A sense of self for Unix processes, IEEE Symposium on Security and Privacy 1996, pages 120 to 128, the database of short sequences of calls from normal runs, the count of mismatches, and the experiments on privileged Unix programs
- Steven A. Hofmeyr, Stephanie Forrest and Anil Somayaji, Intrusion detection using sequences of system calls, Journal of Computer Security 6(3), pages 151 to 180, 1998, the method with full sequences of calls and its evaluation on more programs
- Christina Warrender, Stephanie Forrest and Barak Pearlmutter, Detecting intrusions using system calls, alternative data models, IEEE Symposium on Security and Privacy 1999, the comparison of the sequence database with a frequency threshold, rule learning and hidden Markov models, and the locality frame count
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 517GET Edit this page History Report an error Markdown