Self-protection
This page is published from the agent repository. Edit on GitHub View source
How the agent and its watchdog defend themselves: staying alive, noticing when they
are blinded or frozen, noticing when their own files change, and recording who tried
to stop them. This page covers the watchdog binary, the tamper crate, the agent
modules that wire it (silence, integrity, protected, kill_loudness,
heartbeat), and the planned mesh crate. The wider threat model, privileges and
attack surface are in Security model.
Threat model in one paragraph
The adversary is assumed to hold administrator or root, but not to run code in the kernel. A kernel-level adversary defeats any user-mode control, these included; that ceiling only moves with kernel-side work (a Windows driver with PPL/ELAM, BPF-LSM on Linux, an Endpoint Security system extension on macOS). Above the kernel, the goal is not "cannot be tampered with" but "cannot be tampered with silently": every path that stops the agent, blinds a sensor or changes its files ends either in an automatic restart or in an alert. Hiding from the operator who installed the agent is out of scope by design: every restart anchor is a declared, visible service, and every hardening step can be undone by an administrator through the documented commands.
| Attack | Defense | Where |
|---|---|---|
| Kill the agent | watchdog respawns it | supervise.rs |
| Kill the watchdog | service manager respawns it; the agent dies with it | service/, die_with_parent |
| Freeze or wedge the agent | progress heartbeat stalls, watchdog kills and restarts it | heartbeat.rs, HeartbeatMonitor |
| Detach or stop one sensor | sensor-silence alert (T1562) | tamper::heartbeat, silence.rs |
| Swap the binary on disk | watchdog refuses to launch it; periodic manifest check alerts (T1601) | BinaryPin, integrity.rs |
| Edit or disable the service definition | drift report (Linux) | drift_report |
| Write, delete or rename the agent's own files | protected-resource alert (T1562) | protected.rs |
Send SIGTERM/SIGHUP/SIGQUIT | sender recorded before exit (T1562) | kill_loudness.rs |
| Broken release after an update | probation, rollback and ban | probation.rs, recovery.rs |
Two layers of kill resistance
flowchart TD
SM[Service manager: systemd / OpenRC / SCM / launchd] -->|restarts| W[watchdog run]
W -->|spawns, watches, respawns| A[agent run --alerts ...]
A -->|writes progress counter every 2 s| HB[(heartbeat file)]
HB -->|polled| W
W -->|SELF-PROTECTION lines| AL[(alerts.ndjson)]
A -->|T1562 / T1601 lines| ALLayer 2: the service manager runs the watchdog, never the agent. On Linux the
packaged unit starts current/watchdog run with Restart=always, RestartSec=5s,
as the synthaea user with an ambient capability set
(synthaea-agent.service).
watchdog install uses that packaged unit when present and otherwise generates a
development unit (also Restart=always), or an OpenRC script under
supervise-daemon (service/linux.rs). On
Windows the watchdog is an SCM service with an sc failure restart policy and a
hardened service ACL (service/windows.rs);
on macOS a launchd daemon with KeepAlive
(service/macos.rs). Stopping for good goes
through the service manager. On Unix a stop arrives as SIGTERM; the watchdog kills
the agent and exits.
Layer 1: the watchdog's supervision loop
(supervise_loop) spawns agent run --alerts <path>
with its working directory set to the agent's folder (a Windows service would
otherwise start in System32), watches it every 500 ms, and respawns it on exit.
- Crash-loop backoff (
Backoff). An exit after less than 10 s is a fast crash: the delay doubles from--restart-delay(default 5 s) up to 300 s. An exit after a longer run resets the delay to the floor, so a one-off crash does not inherit a stale long delay. Spawn failures, refused binaries and hung agents feed the same backoff. The service manager keeps its own fixed cadence for the watchdog; the two layers do not compound. - The agent dies with the watchdog on Linux
(
die_with_parent):PR_SET_PDEATHSIG(SIGKILL)in the child beforeexec, then agetppid()check that aborts the spawn if the watchdog already died betweenforkandprctl. Without it a killed watchdog leaves an unsupervised agent reparented to pid 1; systemd's cgroup sweep hides this, OpenRC by default does not. - Counters for the fleet. Each spawn passes how many times this watchdog has
started the agent and how many self-protection events it has reported, through two
environment variables (
agent_command, names inconfig::identity). The agent reads them (host_counters.rs) and reports them in its health beacon. Both restart from zero when the watchdog restarts.
Liveness and hang detection
A process can be alive and still collect nothing: deadlocked, wedged on a poisoned lock, its capture thread dead while the main thread parks. A plain "is it running" check misses all of these.
- Writer.
DetectionSinkincrements a progress counter onceon_eventhas fully processed an event. A thread inheartbeat.rswrites it to a file next to the alert log every 2 s (WRITE_INTERVAL). The path transform (heartbeat_path_for) is duplicated inwatchdog::paths::heartbeat_path_for, because the watchdog cannot depend on the agent binary; the two must stay identical. - Reader.
HeartbeatMonitorreads the file every--heartbeat-interval-secs(default 5 s), counted in 500 ms poll ticks so the state machine needs no clock and is unit-tested with hand-fed readings. After--heartbeat-miss-limit(default 6) consecutive reads with no advance, the watchdog kills the agent and restarts it through the backoff. A missing or unparsable file is never a miss (start-up grace, filesystem hiccups). - The file is a plain counter, not IPC: cross-platform with no
cfgsplit, and the watchdog needs none of the agent's types to read it.
Limit: the counter advances only when events reach the sink. With the defaults, a pipeline that processes no event at all for about 30 s (6 checks of 5 s) is treated as hung and restarted, whatever the reason the stream was empty.
Sensor silence: "silence is a detection"
An adversary who cannot beat the detections tries to switch a sensor off instead:
stop the ETW session, detach an eBPF program, kill a poller thread. All of these have
the same observable, telemetry stops, and
tamper::heartbeat turns it into an alert.
- Each sensor holds a
SensorHeartbeat, a sharedAtomicU64it pulses with one relaxed increment per event (or per batch withpulse_n). Sensor crates may not depend ontamper, so a sensor exposes a plain counter and the binary wraps it withSensorHeartbeat::from_counter. On the main Linux path,PulsingSinkpulses before forwarding each event to the sink. - A
SilenceMonitorholds a deadline per sensor.SilenceMonitor::pollreports aSilenceVerdictonce per silence episode for a counter static past its deadline, and re-arms when it advances. A sensor that never pulses is caught one deadline after registration. A sensor switched off on purpose is unregistered first, so it is not reported. silence::spawn_monitorpolls every 10 s (POLL_INTERVAL) on its own thread and emits each verdict as aT1562alert throughDetectionSink::emit_tamper, which also counts it for the health beacon. The same monitor feeds per-sensor health to the beacon (SilenceHealthSource).- A source that is down for a reason the agent knows (a socket that failed to open)
is reported as degraded through the beacon via
SourceStatus, not as tampering.
Determinism. A healthy sensor on an idle host is indistinguishable from a blinded one unless it can generate its own traffic. Where a sensor has a canary (a poller that ticks regardless of host activity, a driver ping) the deadline is tight; where it has none it is generous:
| Sensor | Deadline | Canary |
|---|---|---|
| Linux eBPF, journal tail | 120 s | none: relies on incidental host activity |
| Linux netlink poller | 3 poll intervals | the poll itself |
| Linux AVC reader | 3 poll timeouts (in practice 10–20 s, the monitor's cadence) | each drain return |
| Windows ETW | 120 s | the sensor writes its own temp file every 2 s and fails itself after 30 s with no events (sensor.rs) |
| Windows minifilter | 30 s | driver reachability |
| Windows event log channels | 60 s | |
| Windows socket poller | 3 poll intervals | the poll itself |
Deadlines are constants in commands/linux.rs and
commands/windows.rs. Without a canary, an
eBPF detach on a truly idle host is caught only as a 120 s stall. The monitor runs on
an agent thread: a suspend of the whole agent freezes it too, and that case is caught
by the watchdog's hang detection instead. macOS wires no silence monitoring yet
(#34).
Integrity of the installed artifacts
Two independent checks, at two privilege points.
Watchdog binary pin (BinaryPin, all platforms).
At start the watchdog hashes the agent binary. Before every spawn it re-hashes it;
a mismatch writes a SELF-PROTECTION line and the binary is not launched (the
loop backs off and retries, so a restored binary starts again). If pinning fails at
start (binary momentarily missing), the check is disabled for that run rather than
refusing to supervise.
Service definition drift (Linux). The watchdog snapshots the installed unit or
OpenRC script and its enablement at start
(snapshot_definition) and, before each spawn,
reports each difference (drift_report) as a
SELF-PROTECTION line.
Install-surface hardening (watchdog::tamper).
At install time on Unix (resolve_paths in service/mod.rs),
refuse_world_writable_dir refuses an agent or watchdog binary whose directory is
world-writable, because anyone who can write there can drop a replacement right after
the pin check. harden_permissions and harden_ownership set modes and root ownership on
what install writes. On Windows, install applies a service SDDL in which only
LocalSystem may stop, pause or delete the service; administrators keep WRITE_DAC
so watchdog uninstall can reset it first
(HARDENED_SERVICE_SDDL). This is friction
against a hand-typed sc stop, not a boundary.
Agent manifest check (tamper::integrity,
wired by apps/agent/src/integrity.rs, Linux).
Every 300 s (CHECK_INTERVAL) a thread reads the active release's signed manifest
from the updater layout, verifies its signature, and hashes every listed file
(Manifest::verify). Each
IntegrityViolation (Modified, Missing,
Unreadable, Oversized) becomes a T1601 alert through emit_tamper.
- Only regular files are hashed: a FIFO or device planted at a protected path would
block the check or feed it forever. A file larger than
MAX_VERIFY_BYTES(256 MiB) is itself a violation, not read to the end, and hashing is bounded by the same limit. - The manifest is the root of trust; its authenticity is the updater's signature
check. A build without a provisioned release key cannot verify any manifest, and
that case is not reported as tampering
(
signature_failure_is_tamper). - Before the first promoted release (package-installed bootstrap binaries) there is no manifest and nothing is checked.
- The cadence is coarse on purpose: it is real I/O, and an on-disk swap is not a race that needs sub-minute detection.
Protected resources
ProtectedResourceGuard wraps the main Linux sink and
watches the live event stream for another process touching the agent's own files:
- a
FileOpenwith write intent, aFileDelete, or aFileRenamewith either side on a protected path, by any pid other than the agent's own, raises aT1562alert; - protected paths (
protected_paths) are the agent executable, the resolved config file, and the alert, events and heartbeat files it was started with, all made absolute first, because matching is a path-component suffix comparison (matches_protected) that tolerates the eBPF sensor's dirfd-relative fragments without matchingmyagentagainstagent.
No updater exception is needed: a self-update writes a new versions/<N>/ directory
and swaps the current symlink; it never writes into the running version's directory,
the config, or the runtime files. The watchdog binary and the unit file are not in
this list; the watchdog's own checks above cover them. These alerts go through
emit, not emit_tamper, so they are not counted in the beacon's tamper counter.
Kill loudness
kill_loudness.rs, Linux: before the agent dies
from a catchable termination signal, it records who sent it.
block_termination_signalsblocksSIGTERM,SIGHUPandSIGQUITon the main thread before any other thread is spawned, so every thread inherits the mask.SIGINTis left alone: the sensor uses Ctrl-C for its own clean stop.- A dedicated thread waits in
sigwaitinfo(2), which returns the sender's pid in ordinary thread context (no async-signal-safety constraints), reads itscomm, and appends aT1562line to the alert log. - Because blocking removed the default disposition, the thread then terminates the
process (
128 + signo) after giving the enrichment queue at most 200 ms (SHUTDOWN_FLUSH_BUDGET) to drain. The bound keeps this from becoming a shutdown path a wedged process could use to outlast the signal.
The flow is tested end to end by termination_signal_flow_records_sender_and_exits:
the test re-executes its own binary, the child forks a process that runs steps 1 to 3,
and the parent sends each of the three signals and checks the exit code
(128 + signo) and an alert line naming the parent as the sender. The fork matters:
libtest's main thread does not block the signals, which the real agent never has.
SIGKILL and SIGSTOP cannot be caught or attributed by the dying process. The eBPF
sensor covers that from the kernel side: its signal probes record a SIGKILL aimed
at the agent, and the restarted agent reports the sender through a rule. Under the
audit fallback sensor that gap remains: no test covers it, and whether it is a permanent
limit is open until a lab capture (tracked by #275).
Kernel-mediated stops that involve no signal
from a process (a CPU rlimit, a cgroup memory limit, cgroup.freeze) are read from how
they are set: the command (systemctl freeze|set-property, a memory or task limit, or a
CPUQuota below 10 %, in %, ‰ or ‱, on a listed tool is Medium, also after any systemctl option that takes a separate value
(-M, -H, -t, -p, --job-mode, --what and the others, alone or last in a cluster such as
-qM, and by any unambiguous long prefix) and that value: the value is not the verb. A command
that names a machine or host is read, not skipped, because -M .host and -H localhost reach
this host; prlimit --pid <pid> --cpu|--as, with --pid abbreviated
to --p or --pi, is Medium when the pid is a listed tool, from its comm or image name, and Low
otherwise), or a write to a cgroup limit file of a listed unit. The kill that a memory limit then
causes is not reported (#49). The full
mask-wait-exit flow is not unit-tested because it terminates the test runner; only the
pure helpers are.
Release probation and recovery
On Linux, where versioned self-update exists:
- Probation (
probation.rs). A watchdog started from a freshly promoted release (it identifies its release from its own executable path, never fromcurrent) requires the agent's heartbeat to advance withinPROBATION_DEADLINE(120 s). Progress observed at the deadline counts as life. If it never advances, the release is rolled back to the previous one (or tobootstrap/) and banned, aSELF-PROTECTIONline is written, and the watchdog exits so the service manager restarts it from the rolled-backcurrent. A rollback that itself fails is reported and the watchdog stays on the running release rather than loop. A watchdog started frombootstrap/has no probation: it is the floor. - Pre-start recovery (
recovery.rs). The packaged unit'sExecStartPrerunsbootstrap/watchdog recover, which execscurrent/watchdog --help; if that fails,currentis rolled back and the release banned before systemd tries to start it.
Peer mesh (planned)
crates/mesh is a design with no code. Its intent: a
killed or silenced agent cannot report its own death, but its neighbours can. Agents
on one segment would exchange signed attestation heartbeats and gossip posture
changes, authenticated with their enrollment identities. The guardrails are part of
the design: messages are signed, typed and read-only, there is no command channel,
posture hints can only raise alertness and are dropped unless signed and fresh, and
fan-out and rates are bounded so the mesh cannot become a scanning signature or an
amplifier. Tracked in #29.
Platform coverage
| Control | Linux | Windows | macOS |
|---|---|---|---|
| Service restart (layer 2) | systemd / OpenRC | SCM sc failure | launchd KeepAlive |
| Supervision, backoff, hang detection | yes | yes | yes |
| Agent dies with watchdog | PR_SET_PDEATHSIG | no | no |
| Binary pin before spawn | yes | yes | yes |
| Service definition drift | yes | no | no |
| Service ACL hardening | n/a | yes | no (#42) |
| Sensor silence | yes | yes | no (#34) |
| Manifest integrity check | yes | no | no |
| Protected resources | yes | no | no |
| Kill loudness | yes (eBPF covers SIGKILL) | no | no |
| Probation and recovery | yes | no (#60) | no (#60) |
| Kernel-level protection (PPL/ELAM, LSM, ES extension) | no | no (#27) | no (#42) |
Audit lines
| Technique | Source | Meaning |
|---|---|---|
SELF-PROTECTION | watchdog (report_self_protection_event) | binary pin mismatch, definition drift, probation rollback or its failure |
T1562 | agent | sensor silent, protected resource touched, termination signal received |
T1601 | agent | an installed artifact no longer matches the signed manifest |
The watchdog and the kill-loudness thread append their own JSON lines with the same
timestamp_ns/technique/message shape as the agent's alert log, without depending
on the agent's types.
Configuration
| Knob | Where | Default |
|---|---|---|
--restart-delay | watchdog run | 5 s (backoff floor) |
--heartbeat-interval-secs | watchdog run | 5 |
--heartbeat-miss-limit | watchdog run | 6 |
--alerts | watchdog run / install | platform default; also locates the heartbeat file |
--config / SYNTHAEA_CONFIG | watchdog | OS default path; the watchdog fails fast if it is missing or invalid |
Silence deadlines, the integrity cadence, the probation deadline and the backoff cap are compile-time constants.
Testing
- Backoff, hang detection, spawn counters,
SELF-PROTECTIONline shape, the agent dying with aSIGKILLed watchdog, probation rollback and ban: tests insupervise.rsandprobation.rs. - Pin, world-writable refusal, permission hardening:
apps/watchdog/src/tamper.rs. - Service SDDL:
service/windows.rs. - Silence monitor episodes, re-arming, unregister:
tamper/src/heartbeat.rs; silence to alert:apps/agent/src/silence.rs. - Manifest verification:
tamper/src/integrity.rsandapps/agent/src/integrity.rs. - Protected resources (write, delete, rename, relative config path):
protected.rs.