Skip to content
Documentation

Rule engine (rules)

This page is published from the agent repository. Edit on GitHub View source

The rules crate holds the agent's built-in detections. Each one is a Rust function aimed at one ATT&CK technique. They come in two kinds:

  • Stateless rules, in stateless/ (one module per tactic) and a few small modules. A single event decides. They are pure functions of the event.
  • Stateful rules, the methods of RuleState and the helper modules it owns. They need a bounded history of recent events: a download followed by an execution, N connections to one host in a window, an authentication success after a run of failures.

The crate depends only on schema, policy and store, so it does no I/O of its own beyond a few explicit startup seeds and one /proc fallback (see Seeding at startup).

Public contract

Callers use the dispatchers and nothing else. The individual check_* functions are crate-internal; they are re-exported under #[cfg(test)] only, for the tests under src/tests/.

Entry pointEventKind
evaluate_execExecEventstateless
evaluate_file_open, evaluate_file_delete, evaluate_file_set_time, evaluate_raw_volume_openfile eventsstateless
evaluate_connect, evaluate_signal, evaluate_log_cleared, evaluate_kerberos_delegation_failureas namedstateless
evaluate_amsi_content, evaluate_defender_event, evaluate_ldap_search, evaluate_ntlm_auth, evaluate_package_changeWindows/inventory eventsstateless
RuleState::on_exec, on_connect, on_network_flow, on_dns_query, on_listen_port, on_file_open, on_file_delete, on_file_rename, on_file_write, on_file_set_time, on_memfd_create, on_auth, on_session, on_policy_denial, on_ldap_search, on_process_access, on_remote_thread, on_file_quarantine, on_bits_job, on_unit_stop, on_identity_changeas namedstateful
RuleState::on_exec_signature_gatedExecEventstateful, waits for the signature
RuleState::take_due_unit_stops, take_due_identity_alertsnone (clock-driven)deferred findings

Every dispatcher returns Vec<Alert> (or nothing, for the record-only methods). Alert carries a &'static str technique, a Severity set where the alert is built, and a human message. The sink turns each one into a DetectionSource::Rule { rule_id: technique } detection (DetectionSink::record_rule_alerts).

Two techniques get extra handling there:

  • T1620 (memfd exec) also asks for a YARA memory scan of the process (yara.md).
  • T1486 (ransomware burst) carries a damage manifest. That is the process incarnation's recent renames and deletions, from RuleState::touched_files. The burst can also trigger the ransomware reflex when a canary touch by the same process corroborates it.

How the agent calls it

sequenceDiagram
    participant S as Sensor thread
    participant D as DetectionSink
    participant R as rules (stateless)
    participant RS as Mutex<RuleState>
    participant W as enrichment worker
    S->>D: on_event(Exec)
    D->>R: evaluate_exec(&e)
    R-->>D: Vec<Alert>
    D->>RS: lock().on_exec(&e)
    RS-->>D: Vec<Alert>
    D->>RS: lock().take_due_identity_alerts()
    D->>RS: lock().on_exec_signature_gated(&e)
    RS-->>D: Option<SignatureGatedAlert>
    D->>W: enqueue(event, gated)
    W->>W: enrich (hash, signature)
    W->>D: gated.resolve(signature) → Option<Alert>

RuleState sits behind one Mutex in the sink. The EventSink trait only gives &self and must be Send + Sync. On Linux almost all events arrive on one thread, so the lock is uncontended. The DNS uprobe, conntrack and log-source threads take it too. Never hold the lock while calling record_rule_alerts: that path takes it again (for the damage manifest). Stateful steps go through DetectionSink::rule_alerts(event, |state| state.on_x(e)), which evaluates under the lock, drops the guard, then records, so the sink no longer writes the hazard.

RuleState internals

RuleState is one struct with one field per stateful concern. Each field is a store::BoundedMap or a small dedicated type. The struct's field docs say which rule reads each table. A family that has been split out keeps its tables in its own type, held by RuleState as one field: the network rules (beacon, beacon_flow_dedup, scan_*, egress_*, dns_class, archive_*, staged_archives) live in NetworkState, and the file-impact rules (ransomware_*, recent_creates, pending_unlinks, write_volume, rename_count, touched_files, set_time_alerted) in ImpactState, the authentication rules (auth_failures, logon_baseline, odd_hours, rdp_success, sudo_success, session_hijack) in AuthState, and SETUID-ROOT-REQUEST's deferred judgement (pending_identity, exec_history, setuid_root_alerted) in IdentityRequests (privesc.rs), the download-to-execution joins (recent_writes, recent_quarantines, recent_bits_downloads, recent_motw_removals) in DownloadState, the T1620 memfd-exec correlation (recent_memfd_creates, pending_proc_fd_exec) in MemfdState, LISTENER-DRIFT and POLICY-DENIAL-DRIFT (known_listeners, known_policy_denials, policy_denial_budgets) in DriftState, and the file-open readers in their rule's module: STAGING-DIR's reads and creates in StagingState, CREDENTIAL-READ's alert windows in CredentialReads, and the T1053.005 registration dedup in TaskRegistrations. The main families:

FamilyFields (examples)KeyFeeds
Process factspid_comm, pid_image_path, exec_history, exec_lineagepid (PidFact carries the generation)parent-name checks (T1059), rename exclusions, SETUID-ROOT-REQUEST
Download provenancerecent_writes, recent_quarantines, recent_bits_downloads, recent_motw_removalscase-folded pathT1105, T1204.002, T1197, T1553.005
Sliding countersself_spawn, beacon, auth_failures, ransomware_rename, credential_reads, lsass_accessrule-specificthreshold-in-window rules
Distinct setsscan_vertical, scan_spread, ssh_fanout, security_discovery, service_stoppid or lineageN distinct things in a window
Exfiltration chainarchive_writers, staged_archives, archive_readers, egress_flow_last, egress_volume, dns_class, stagingpid / path / (comm, addr)ARCHIVE-EXFIL, EGRESS-VOLUME, EGRESS-DOMAIN, STAGING-DIR
First-seen shapesknown_listeners, known_policy_denials, logon_baselineshape tupleLISTENER-DRIFT, POLICY-DENIAL-DRIFT, FIRST-SEEN-LOGON
Joinsrdp_success, sudo_success, session_hijack, unit_stops, pending_identityper modulefailure-then-success, deferred judgements

Calibration lives in exclusions.rs

Thresholds, windows, process lists and false-positive exclusions are constants in exclusions.rs, not in the rule bodies. Examples: DOWNLOAD_EXEC_WINDOW_NS (60 s), BEACON_THRESHOLD/BEACON_WINDOW_NS (3 in 60 s), SELF_SPAWN_THRESHOLD (3). Each exclusion entry is data with provenance. It records why it exists: the false positive it removes and the lab scenario that produced it. Do not trim it as noise.

Name-keyed exclusions are gated on the image path. An entry such as "svchost.exe may do X" applies only when the process's image is under a trusted system location (policy::name_exclusion_applies). A copy of a trusted name running from %TEMP% or /tmp does not inherit the exclusion. An unknown image path keeps the exclusion, because a sensor limitation is not evidence of masquerade.

Incarnation-aware facts

The process-fact tables store PidFact values: the fact and the process_generation it was recorded for. PidFact::current misses when both generations are known and differ, so a recycled pid never inherits its predecessor's name or image. See Process incarnations.

RuleState::resolve_comm looks up a parent's name in this order: the cache, then a live /proc/<ppid>/comm read. The fallback covers processes that forked after startup and never exec'd, such as a web server's respawned workers. Without it, a shell spawned by such a worker would not be recognised as a web-server child.

IdentityRequests::image_as_of(pid, generation, t) answers "which image did this pid run at time t", from the last few execs per pid (exec_history). SETUID-ROOT-REQUEST needs it, because an identity change can be judged after the process exec'd again.

Sliding windows

sliding.rs has the shared window types:

  • SlidingCounter is a true sliding window. record(ts, window) drops timestamps older than the window, pushes the new one and returns the in-window count. try_alert(ts, window) allows one alert per window. A reset-bucket scheme would lose events that straddle a bucket boundary (spawns at 0 s, 29 s and 31 s never reach 3-in-30 s), which is why it is not used. Each key keeps at most 256 timestamps: enough to prove the threshold, not to archive a burst.
  • FlowPortDedup is for poll-based sources (conntrack). A live flow is reported on every poll, so one long SSH session would otherwise count as many connections. The local port identifies one flow for its lifetime, so a port counts once per window.
  • SlidingSum sums a value (bytes written) over a window, in coalesced time slots. The ransomware write-volume signal uses it.
  • SlidingDistinct<T> counts distinct values (ports, destinations, commands) in a window.

All windows run on event time (meta.timestamp_ns), never on the wall clock. That makes the rules deterministic under replay and in tests.

First-seen shapes

LISTENER-DRIFT and POLICY-DENIAL-DRIFT alert on a new shape, not on volume:

  • Listeners are keyed on (local_addr, local_port, protocol). The protocol is part of the key because a UDP and a TCP listener on the same port are different services. RuleState::seed_listen_ports fills the baseline from one startup snapshot. Otherwise every service already listening when the agent starts would look like a planted backdoor on the first poll.
  • Policy denials are keyed per mechanism. SELinux keys on (scontext, tcontext, class, normalised permissions); the permission set is sorted and deduplicated by normalized_permissions. AppLocker and WDAC events carry no object context, so they key on the file (lowercased) and the collection or loading process instead. Keyed like SELinux, they would collapse to a handful of classes and only the first blocked binary would ever alert. There is no startup baseline, because past denials cannot be enumerated. Alerts are budgeted per subject type (POLICY_DENIAL_ALERT_CAP per window, POLICY_DENIAL_SUBJECT_CAP subjects), so one noisy domain cannot spend another's budget. A shed shape is not remembered and can alert again in a later window. Sheds and evictions are counted and logged once per rise.

Deferred findings

Some judgements need events that may arrive after the one that triggers them:

  • Identity changes to uid 0 (SETUID-ROOT-REQUEST, privesc.rs) wait in pending_identity until an exec or identity event moves the stream clock past them. Only then is the process's image as of that time known. The sink drains them with take_due_identity_alerts after every exec.
  • Security-unit stops (UNEXPLAINED-UNIT-STOP, unitstop.rs) are held until the clock passes a grace window. During that window an exec that explains the stop (systemctl stop by an administrator, a package upgrade) cancels it. Drained with take_due_unit_stops.

Seeding at startup

These are called once, before the sensors start (RuleState):

MethodFillsWhy
seed_processes (Linux, fed by the agent binary from /proc) / seed_pid_comm (Windows)pid_comm, pid_image_pathservices started before the agent (nginx at boot) must be known as parents
seed_listen_portsknown_listenersexisting listeners are the baseline
seed_ld_trust_from_systemextra trusted library dirs from /etc/ld.so.conf (includes followed)LD_PRELOAD of an ldconfig-registered vendor directory is not a hijack (T1574.006)
seed_own_pidown_pidthe Event Log sensor's own wevtutil/auditpol children are excluded narrowly, still requiring a trusted image path

Every seed is best effort. A missing file or an unreadable /proc entry only means the rule judges against its built-in baseline.

Linux browser downloads (T1204.002)

Linux browsers leave no usable xattr mark, so on_file_rename marks the finished download instead (on_browser_download_rename, #221). A FileRename marks new_path when old_path ends in .crdownload, .opdownload (Opera) or .part, new_path does not, and the event's executable_path is a browser image (is_browser_download_image: the exact list BROWSER_DOWNLOAD_IMAGES, or the Firefox family by shape). The mark is the one a FileQuarantine records (agent = the image's file name, no origin URL), so check_quarantined_exec joins a later exec of that path inside the same window and the same signature gate applies.

  • The key is the image, not comm: the rename runs on a thread-pool worker (ThreadPoolForeg in Chromium, BgIOThr~Pool #N in Firefox).
  • Chromium's first rename (/tmp/... -> .crdownload, EXDEV across devices) and cache renames have no partial-suffix old_path and mark nothing.
  • The Firefox family is also matched by shape (decision of 2026-11-12 on #221): the file name is firefox, firefox-bin or firefox-esr and the parent directory is named firefox or firefox-esr. That covers a Mozilla tarball (<dir>/firefox/firefox-bin), the Snap (/snap/firefox/<rev>/usr/lib/firefox/firefox), Debian's /usr/lib/firefox-esr/firefox-esr (Debian 13 VM, 2026-11-12: read from /proc under strace and confirmed in the sensor's file_rename event, kernel 6.12; an end-to-end run there, headless firefox-esr downloading an ELF that was then run, raised T1204.002 marked by firefox-esr in 2 of 2 runs, and nothing for a curl plus mv control) and a Flatpak-shaped /app/lib/firefox/firefox; not /usr/bin/firefox (the launcher, parent bin), not /tmp/other/firefox, not a fork under another directory name (librewolf, firefox-developer-edition; the Developer Edition tarball under /opt/firefox-developer-edition/ was captured on 2026-11-16 and raises nothing). A false match only arms the signature-gated T1204.002 on an exec of the renamed file; a miss hides a real download. Case-sensitive.
  • The Chromium Snap is matched by its layout, not by the list: /snap/chromium/<revision>/usr/lib/chromium-browser/chrome, the revision being digits only (captured 2026-11-16 on Ubuntu 26.04.1, #267). The file is chrome there, so the distribution entry does not cover it. current, a non-numeric revision and any other file or depth do not match. That Snap reports the rename under its own home, <home>/snap/chromium/<revision>/Downloads/<file>, a symlink to <home>/Downloads; the mark is also recorded at <home>/Downloads/<file> so that a run from the real directory joins. The alias is made only for that Snap's own image (another browser renaming into a snap/chromium directory gets none), and the two records are twins: an exec from either path alerts once, and a re-download re-arms both. The alert reaches the other record only while that record still points back; one replaced by another download of the same name (a different file) is not silenced. Only the default Downloads name: on a non-English desktop the directory has the localized name (Téléchargements) and no alias is made, so that case is not covered. No path is resolved, the alias is a guess about the symlink.
  • Adding another browser is one line in BROWSER_DOWNLOAD_IMAGES. It holds only the images a capture showed (2026-11-10, Fedora 43 lab VM): Chromium and Firefox from the distribution packages, and the vendor packages of Chrome (/opt/google/chrome/chrome), Edge (/opt/microsoft/msedge/msedge), Brave (/opt/brave.com/brave/brave), Opera (/usr/lib64/opera-stable/opera) and Vivaldi (/opt/vivaldi/vivaldi-bin).
  • An empty or absent executable_path (the sensor lost the /proc/<pid>/exe race) is read from the lineage, in this order: the image of the exec the agent recorded for the renaming pid, if its incarnation stamp matches; otherwise the image recorded for the parent, if the parent's stamp matches (a process forked without an exec, such as a Chromium zygote child). A process already running when the agent started has no exec event: seed_processes records its /proc/<pid>/exe at start-up, with the incarnation stamp the sensor puts on that process's events (a link the agent cannot read, or one ending in (deleted) because the file was replaced, is left out). A recorded image that is empty counts as lost, at each step: it falls through to the parent. A pid with no recorded image and no known parent marks nothing. Two consequences of seeding, both outside T1204.002. The seeded image fills pid_image_path, which the credential-read, impact, network-flow, LSASS and set-time rules also read: for a process that started before the agent, their image-based exclusions now apply, where the name alone decided before (pinned for the credential read by an_image_seeded_at_startup_applies_the_image_based_exclusion; the other readers share the lookup and are not pinned one by one). And a seeded fact carries the stamp of its process, derived once, by the sensor's primed_generation (the agent binary reads /proc with the sensor's read_seed_processes, and rules takes the result without reading /proc itself), so it answers for that incarnation only: a seeded pid that dies and is reused by a process that forks without an exec inherits neither the image nor the comm, and falls back to its parent (a_fact_seeded_at_startup_matches_its_own_incarnation_only); a seeded auth-stack pid (sshd, su, unix_chkpwd) keeps no /etc/shadow exclusion for a reused pid (a_seeded_auth_stack_pid_is_not_inherited_by_a_reused_pid_that_reads_etc_shadow). Where a stamp is unreadable (starttime missing) or the event has none (macOS), the lookup cannot tell and the seeded fact answers, as for the other pid tables. A resolved image always wins, even when it is not a browser, and the pid's own non-browser exec wins over a browser parent (a helper such as cp run from the browser marks nothing). Unit-tested, and run on a lab VM on 2026-11-19 with a synthetic renamer at the Firefox ESR path (Debian 13): 56 of 60 renames arrived with an empty image, 32 execs raised T1204.002 (28 of them on such a rename) and the same helper from a non-browser path raised none. The fallback needs the renamer's exec to be recorded before its rename, and the downloaded file's exec to come after the rename. No capture shows a real browser losing the race. What is still unchecked is listed under "Not verified" in attack-coverage.md.

Signature-gated findings

Some findings are only true when the executed image is not validly signed. T1204.002 (a downloaded file run within the provenance window) is the current one: almost every installer a user downloads and runs is signed. But the signature is computed on the enrichment worker, after the rules have run (enrichment.md). So the rule returns a SignatureGatedAlert instead of an Alert:

flowchart LR
    R[check_quarantined_exec] -->|SignatureGatedAlert| Q{EnrichQueue full?}
    Q -->|yes| U[unverified → Alert now]
    Q -->|no| W[worker: Enricher::enrich_uncached]
    W --> I{image identity at exec == verified file?}
    I -->|no / unknown| X[unconfirmed_image → Alert]
    I -->|yes| V{Valid && chain_verified?}
    V -->|yes| N[no alert]
    V -->|no| A[Alert, message names the verdict]

resolve(ImageSignature) suppresses the alert only for Signature::Valid with chain_verified. That is Authenticode on Windows. On macOS Valid also covers ad-hoc signatures, which the linker puts on every arm64 binary, attacker-built ones included. Losing the verdict (queue full, unreadable image) raises the alert; it never drops it.

The verdict describes the file at the image path when the worker opens it. A dropper on Windows can rename itself and put a signed binary at its old path before the worker gets there. To catch that, the sensor records the image's file identity at exec (ExecEvent::image_file_id). The worker compares it with the identity of the file it verified (image_confirmed in enrich_queue.rs), and on a mismatch the alert resolves as not verified. Identity is captured on Windows only, and only as early as the ETW callback. The window between process start and that callback is still open (#46).

Configuration

The rules read only the [detection] table of agent.toml (DetectionConfig). All three knobs serve ODD-HOUR-LOGON:

KeyDefaultEffect
utc_offset_minutesabsent (platform zone used)fixed offset, -720..=840, overrides the platform zone; does not follow daylight saving
work_hours[7, 20]ordinary local hours [start, end); start > end wraps midnight
odd_hour_exempt_accountsemptyNAME or NAME|SID (SID prefix with *); at most 64

Each setter (set_local_utc_offset_minutes, set_work_hours, set_odd_hour_exempt_accounts, set_local_zone) refuses an invalid value and keeps the previous one. Platform time-zone verification and window calibration are tracked in #15.

Failure modes

ConditionBehaviour
A table reaches its capLRU eviction. A forgotten key can re-alert once; first-seen tables log each eviction rise
Parent not in the cache and gone from /procparent-name rules cannot fire for that exec
Linux comm truncated to 15 bytesT1105 compares comm to the downloaded file's basename, so a longer name does not match
Linux browser download, resolved image not a browser image (is_browser_download_image), or no image anywhere in the lineageno T1204.002 mark: the join is keyed on the renaming process's image, never comm. An empty image falls back to the lineage (the pid's own recorded exec, then its parent's); a pid nobody saw exec marks nothing
A downloaded script run through an interpreterimage is the interpreter; T1204.002 and T1105 do not join
Events out of order across sensor threadswindows tolerate it; deferred findings wait for the clock
No generation stamp (macOS)pid-only behaviour, recycled pids possible

Testing

  • crates/rules/src/tests/ has about 30 files, one per rule family (linux.rs, windows.rs, logon.rs, privesc.rs, ...), with over 800 tests. tests/mod.rs holds the event builders. Each family pins the positive case, its benign lookalikes (one per exclusion) and the window edges.
  • rdp.rs and sudo.rs carry proptest suites for the failure-then-success joins.
  • Sink-level tests in apps/agent/src/sink/tests.rs check that each event type reaches its rule through the real dispatcher, for example set_time_event_reaches_the_timestomp_rule_through_the_real_sink.