Skip to content

Linux host telemetry detection lab

Runs nine SQL detection rules over a deterministic synthetic corpus with labeled benign look-alikes and known evasions, then over real syscalls captured with strace from a throwaway container.

Linux Security 4 min read

Implementation

engine.py Python · 244 lines
labs/linux-host-telemetry/engine.py
1#!/usr/bin/env python3
2"""Detection engine for labs/linux-host-telemetry: events in, deduplicated alerts out.
3 
4Rules are plain SQL files in rules/ run against an in-memory SQLite table, so every
5detection is a readable query with no hidden logic. The engine adds only what SQL
6should not carry: schema validation, allowlist evaluation (owner + expiry), source
7coverage ("blind" instead of "clean"), batching clocks, and deduplication.
8 
9Usage: engine.py --events events.jsonl [--scenarios scenarios.json] [--sources exec,file,net]
10"""
11import argparse
12import datetime as dt
13import json
14import os
15import pathlib
16import re
17import sqlite3
18import sys
19 
20HERE = pathlib.Path(__file__).resolve().parent
21EVENT_TYPES = {"process_start": "exec", "file_read": "file", "file_write": "file", "file_chmod": "file",
22               "file_truncate": "file", "file_delete": "file", "net_connect": "net"}
23REQUIRED = ["id", "ts", "ingest_ts", "host", "boot_id", "source", "event", "synthetic", "origin"]
24ORIGINS = {"synthetic-generator": True, "strace-capture": False}  # origin -> value of the synthetic flag
25COLUMNS = ["id", "ts", "ingest_ts", "host", "boot_id", "source", "event", "pid", "pstart", "ppid", "ppstart", "uid",
26           "exe", "cmdline", "tty", "path", "mode", "dest_ip", "dest_port", "dest_class", "exec_start", "is_dir", "scenario", "synthetic", "origin"]
27BATCH_SECONDS = 5          # the engine evaluates in 5 s micro-batches (synthetic clock)
28DEDUP_WINDOW_SECONDS = 300 # identical (rule, host, subject) alerts within 5 min collapse into one
29 
30 
31class ValidationError(ValueError):
32    pass
33 
34 
35def parse_ts(value):
36    return dt.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=dt.timezone.utc)
37 
38 
39def validate(event, line_no):
40    for field in REQUIRED:
41        if field not in event:
42            raise ValidationError(f"line {line_no}: missing required field {field!r}")
43    if event["event"] not in EVENT_TYPES:
44        raise ValidationError(f"line {line_no}: unknown event type {event['event']!r}")
45    if EVENT_TYPES[event["event"]] != event["source"]:
46        raise ValidationError(f"line {line_no}: event {event['event']!r} cannot come from source {event['source']!r}")
47    if event["origin"] not in ORIGINS:
48        raise ValidationError(f"line {line_no}: unknown origin {event['origin']!r}")
49    if event["synthetic"] is not ORIGINS[event["origin"]]:
50        raise ValidationError(f"line {line_no}: synthetic={event['synthetic']!r} contradicts origin {event['origin']!r}")
51    for field in ("ts", "ingest_ts"):
52        parse_ts(event[field])
53    if parse_ts(event["ingest_ts"]) < parse_ts(event["ts"]):
54        raise ValidationError(f"line {line_no}: ingest_ts precedes ts")
55    if event["event"] == "process_start":
56        for field in ("pid", "pstart", "ppid", "ppstart", "exe"):
57            if event.get(field) is None:
58                raise ValidationError(f"line {line_no}: process_start without {field}")
59 
60 
61def load_events(path):
62    events = []
63    with open(path) as fh:
64        for line_no, line in enumerate(fh, 1):
65            if not line.strip():
66                continue
67            event = json.loads(line)
68            validate(event, line_no)
69            events.append(event)
70    return events
71 
72 
73class Allowlist:
74    def __init__(self, path=HERE / "allowlist.json"):
75        self.entries = json.loads(pathlib.Path(path).read_text())["entries"] if path else []
76        for entry in self.entries:
77            for key in ("rule", "pattern", "owner", "reason", "expires"):
78                if not entry.get(key):
79                    raise ValidationError(f"allowlist entry {entry} lacks {key}: exceptions need an owner, a reason and an expiry")
80            re.compile(entry["pattern"])
81 
82    def allowed(self, rule, ts, exe, cmdline, path, parent_exe):
83        day = ts[:10]
84        for entry in self.entries:
85            if entry["rule"] != rule or day > entry["expires"]:
86                continue
87            value = {"exe": exe, "cmdline": cmdline, "path": path}.get(entry.get("field", "exe"), "") or ""
88            if not re.search(entry["pattern"], value):
89                continue
90            if entry.get("parent_exe") and entry["parent_exe"] != (parent_exe or ""):
91                continue
92            if entry.get("cmdline_pattern") and not re.search(entry["cmdline_pattern"], cmdline or ""):
93                continue
94            return True
95        return False
96 
97 
98def parse_rule(path):
99    text = path.read_text()
100    meta = dict(re.findall(r"^-- (\w+): (.*)$", text, re.M))
101    for key in ("id", "title", "severity", "requires", "response"):
102        if key not in meta:
103            raise ValidationError(f"{path.name}: missing '-- {key}:' header")
104    meta["requires"] = {s.strip() for s in meta["requires"].split(",")}
105    # Optional: event fields the rule cannot work without (a source can be present but lack a field).
106    meta["requires_fields"] = {s.strip() for s in meta.get("requires_fields", "").split(",") if s.strip()}
107    meta["sql"] = text
108    return meta
109 
110 
111def load_rules(rules_dir=HERE / "rules"):
112    return sorted((parse_rule(p) for p in pathlib.Path(rules_dir).glob("*.sql")), key=lambda r: r["id"])
113 
114 
115def connect(events, allowlist):
116    db = sqlite3.connect(":memory:")
117    db.row_factory = sqlite3.Row
118    db.create_function("basename", 1, lambda p: (p or "").rsplit("/", 1)[-1].split(" (deleted)")[0])
119    db.create_function("regexp", 2, lambda pattern, value: 1 if value is not None and re.search(pattern, value) else 0)
120    db.create_function("is_allowed", 6, lambda rule, ts, exe, cmd, path, parent: 1 if allowlist.allowed(rule, ts, exe, cmd, path, parent) else 0)
121    db.execute(f"CREATE TABLE events ({', '.join(c + (' INTEGER PRIMARY KEY' if c == 'id' else '') for c in COLUMNS)})")
122    db.execute("CREATE INDEX proc_identity ON events (host, boot_id, pid, pstart)")
123    rows = [[(1 if e.get(c) is True else 0 if e.get(c) is False else e.get(c)) for c in COLUMNS] for e in events]
124    db.executemany(f"INSERT INTO events VALUES ({','.join('?' * len(COLUMNS))})", rows)
125    return db
126 
127 
128def run(events, rules, allowlist, sources=None):
129    """Return (alerts, coverage). sources=None means: whatever the events contain."""
130    available = set(sources) if sources is not None else {e["source"] for e in events}
131    usable = [e for e in events if e["source"] in available]
132    db = connect(usable, allowlist)
133    by_id = {e["id"]: e for e in usable}
134    coverage, hits = {}, []
135    for rule in rules:
136        missing = sorted(rule["requires"] - available)
137        missing_fields = sorted(f for f in rule["requires_fields"] if not any(e.get(f) is not None for e in usable))
138        if missing or missing_fields:
139            coverage[rule["id"]] = {"status": "blind", "missing_sources": missing, "missing_fields": missing_fields}
140            continue
141        coverage[rule["id"]] = {"status": "evaluated", "missing_sources": [], "missing_fields": []}
142        for row in db.execute(rule["sql"]):
143            hits.append({"rule": rule["id"], "severity": rule["severity"], "event_id": row["event_id"], "host": row["host"],
144                         "subject": row["subject"], "detail": row["detail"]})
145    # Deduplicate: same (rule, host, subject) within the window collapses into one alert with a count.
146    hits.sort(key=lambda h: by_id[h["event_id"]]["ingest_ts"])
147    alerts, open_alert = [], {}
148    for hit in hits:
149        event = by_id[hit["event_id"]]
150        key = (hit["rule"], hit["host"], hit["subject"])
151        ingest = parse_ts(event["ingest_ts"])
152        current = open_alert.get(key)
153        if current and (ingest - current["_last"]).total_seconds() <= DEDUP_WINDOW_SECONDS:
154            current["count"] += 1
155            current["_last"] = ingest
156            current["event_ids"].append(hit["event_id"])
157            # Evaluation-only: which labeled scenarios were folded into this alert. A real
158            # pipeline has no such field - the folded activity is visible only as the count.
159            current["_scenarios"].add(event.get("scenario"))
160            continue
161        batch_end = dt.datetime.fromtimestamp(((ingest.timestamp() // BATCH_SECONDS) + 1) * BATCH_SECONDS, dt.timezone.utc)
162        alert = dict(hit, scenario=event.get("scenario"), count=1, event_ids=[hit["event_id"]], _last=ingest,
163                     _scenarios={event.get("scenario")},
164                     event_ts=event["ts"], ingest_ts=event["ingest_ts"],
165                     alert_ts=batch_end.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
166                     synthetic_latency_seconds=round((batch_end - parse_ts(event["ts"])).total_seconds(), 1))
167        open_alert[key] = alert
168        alerts.append(alert)
169    for alert in alerts:
170        alert.pop("_last")
171        alert["scenarios"] = sorted(alert.pop("_scenarios"))
172    return alerts, coverage
173 
174 
175def score(alerts, scenarios, rules, coverage):
176    """Scenario-level confusion matrix per rule; background noise is counted separately.
177 
178    Class semantics (see generator.py):
179      malicious_pattern   rule in expected_rules -> TP if it fired else FN
180      evasion             rule in evades         -> FN if it stayed silent else TP (the known miss closed)
181      benign_lookalike    any rule               -> FP if it fired else TN (expected_rules lists KNOWN residual FPs)
182      control             any rule               -> FP if it fired else TN
183    A rule firing on a malicious scenario it is not responsible for is "incidental" (neither TP nor FP).
184    unexpected_outcomes compares the actual result with the DOCUMENTED one, so a documented false
185    positive or miss that silently changes (better or worse) is surfaced.
186    """
187    fired = {}
188    for alert in alerts:
189        for scenario in alert["scenarios"]:  # includes scenarios folded in by deduplication
190            fired.setdefault(scenario, set()).add(alert["rule"])
191    table = {r["id"]: {"TP": 0, "FP": 0, "FN": 0, "TN": 0, "incidental": 0, "blind": coverage[r["id"]]["status"] == "blind"} for r in rules}
192    unexpected = []
193    for sc in scenarios:
194        for rule in rules:
195            rid = rule["id"]
196            if table[rid]["blind"]:
197                continue
198            did = rid in fired.get(sc["id"], set())
199            documented = rid in sc["expected_rules"]
200            if sc["class"] == "malicious_pattern":
201                if documented:
202                    table[rid]["TP" if did else "FN"] += 1
203                elif did:
204                    table[rid]["incidental"] += 1
205            elif sc["class"] == "evasion":
206                if rid in sc.get("evades", []):
207                    table[rid]["TP" if did else "FN"] += 1
208                elif did:
209                    table[rid]["FP"] += 1
210                else:
211                    table[rid]["TN"] += 1
212            else:  # benign_lookalike, control
213                table[rid]["FP" if did else "TN"] += 1
214            if sc["class"] == "evasion" and rid in sc.get("evades", []):
215                documented = False
216            if did != documented and not (sc["class"] == "malicious_pattern" and not documented):
217                unexpected.append({"scenario": sc["id"], "rule": rid, "documented_to_fire": documented, "fired": did, "class": sc["class"]})
218    background = [a for a in alerts if "bg" in a["scenarios"]]
219    return table, unexpected, background
220 
221 
222def main():
223    ap = argparse.ArgumentParser()
224    ap.add_argument("--events", required=True)
225    ap.add_argument("--scenarios")
226    ap.add_argument("--sources", help="comma-separated telemetry sources actually collected (default: those present)")
227    ap.add_argument("--allowlist", default=str(HERE / "allowlist.json"))
228    ap.add_argument("--json", action="store_true")
229    args = ap.parse_args()
230    events = load_events(args.events)
231    rules = load_rules()
232    sources = set(args.sources.split(",")) if args.sources else None
233    alerts, coverage = run(events, rules, Allowlist(args.allowlist), sources)
234    out = {"events": len(events), "alerts": alerts, "coverage": coverage}
235    if args.scenarios:
236        scen = json.loads(pathlib.Path(args.scenarios).read_text())["scenarios"]
237        table, outcomes, background = score(alerts, scen, rules, coverage)
238        out.update(confusion=table, unexpected_outcomes=outcomes, background_alerts=len(background))
239    print(json.dumps(out, indent=2, sort_keys=True) if args.json else f"{len(events)} events -> {len(alerts)} alerts")
240    return 0
241 
242 
243if __name__ == "__main__":
244    sys.exit(main())

Run it

  • python3 labs/linux-host-telemetry/tests/test_detections.py
  • bash labs/linux-host-telemetry/scripts/run-lab.sh

Status: partially tested. The engine, the nine rules and the 23 unit tests run anywhere with Python 3 and are part of npm run validate. The real-kernel capture ran once on 2026-11-05 on a disposable VM and is not in CI. The analysis, false-positive reasoning, response actions and diagrams are in the article: Host Telemetry Detection Lab.

Every event the generator produces is synthetic. Nothing in this lab records, simulates or reproduces a real intrusion. Events are data: a path, an executable name, a destination in a documentation address range. No malicious code exists here, no payload is executed, and the real-kernel capture runs only harmless placeholders inside a throwaway container.

Evidence labels: tested locally (executed here, output in evidence/), policy model (a rule evaluated by a local test, not by a production sensor), source-reviewed, requires-review.

Scope

Detection logic over host telemetry: process ancestry, file writes, file reads, permission changes and outbound connections. Not in scope: collecting telemetry at fleet scale, kernel sensors (auditd, eBPF, Falco, Tetragon), a SIEM, enrichment, or any response automation. Rules are tested on labeled data the rule author wrote, so the numbers describe the rules' behaviour on that corpus, not how they would perform on a real fleet.

What I built

Path Purpose
generator.py Deterministic (seeded) synthetic corpus: 855 events in 42 labeled scenarios; every event has "synthetic": true
engine.py Loads events into SQLite, validates the schema, runs rules/*.sql, applies the allowlist, deduplicates, reports missing sources and fields as blind, scores against labels
rules/ Nine rules, each a readable SQL file with a header: id, title, severity, required sources, response guidance
allowlist.json Exceptions; the engine refuses an entry without an owner, a reason and an expiry, and ignores an entry after it expires
capture/ workload.sh (harmless analogs in a busybox container), capture.sh (host strace), normalize_strace.py
scripts/ run-lab.sh (everything), summarize.py (assertions and the scored table)
tests/test_detections.py 23 tests: determinism, schema rejection, pinned confusion matrix, PID reuse, exception expiry, deduplication, blind coverage, clocks, label leakage, parser
evidence/ Sanitized output of the run below

Validation

Recorded run (evidence/versions.txt): Python 3.13.18, SQLite 3.53.1, Linux 6.18.44, strace 6.8, Docker 29.9.2.

python3 labs/linux-host-telemetry/tests/test_detections.py        # 23 tests, standard library only
bash labs/linux-host-telemetry/scripts/run-lab.sh                 # corpus + rules + (if available) real capture
Check Observed
Unit tests 23 passed
Synthetic corpus 855 events, 42 scenarios (17 malicious-pattern, 17 benign look-alike, 6 control, 2 evasion), 27 deduplicated alerts, 0 alerts on 400 background-noise iterations
Scenario-level totals over nine rules TP 19, FP 7, FN 2, TN 216
Documented residual false positives 7 look-alikes (S04, S13, S23, S33, S44, S54, S82) alert by design and are pinned in the tests
Documented misses 2 (S14 per-user crontab, S34 outbound from system bash) stay silent and are pinned
Network sensor removed LNX-004 reported blind, no alert, and not scored as a true negative
Real capture (strace, busybox container) 176 trace lines → 28 events → alerts from exactly LNX-002, 005, 006, 007, 009; LNX-004 silent on a private-address connect from /tmp; LNX-003 blind (strace cannot supply ExecStart)

Full per-rule table, residual-false-positive analysis and response actions: see the article.

What was not tested

  • Any production sensor: auditd, eBPF, Falco, Tetragon, osquery. The schema is inspired by what they emit; none was run.
  • Detection on real fleet data, real adversary tradecraft, or adversaries who know the rules. Evasion is represented by two hand-written cases.
  • strace as a sensor: its overhead and blind spots were not measured; it is a capture convenience.
  • Rules LNX-001, 003, 004 and 008 against real kernel data (the capture exercises 002, 005, 006, 007, 009 and one negative for 004).
  • Time to detect and time to contain: the lab reports synthetic latency from synthetic clocks only.
  • Response actions: they are written guidance, never executed.

Production considerations

See the article for rollout, detection, operability, false positives, blast radius and rollback. In short: ship rules to a few hosts in report-only mode, own every exception (owner + expiry), page on nothing until the residual false-positive sources for your environment are known, and treat a blind rule as an incident in the telemetry pipeline, not as a quiet host.

References

  • Linux man-pages, proc(5): /proc/[pid]/stat field 22, starttime, the time the process started after system boot.
  • strace project, strace(1): trace-line format (name, arguments, return value, errno on failure, octal modes).
  • Tool versions: each tool's own version output, in evidence/versions.txt.