diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac1c32b..b3a9445 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -429,6 +429,90 @@ jobs: - name: test installer upgrade and recovery paths if: matrix.name == 'linux-x64' run: bash install/test-install.sh + # Linux kernel sensor (#59). Runs the agent as an unprivileged user with + # exactly the systemd unit's capabilities (sudo setpriv), starts 50 + # short-lived /bin/true processes and expects at least 50 process_start + # events from audit netlink. If the runner refuses audit netlink the + # step proves the auditd log path instead and says so in the log. + - name: prove Linux kernel sensor (audit netlink, 50 short-lived processes) + if: matrix.name == 'linux-x64' + timeout-minutes: 5 + run: | + set -euo pipefail + bin="$PWD/zig-out/bin/tawny-agent" + caps="audit_control,audit_read,dac_read_search,kill,sys_ptrace" + plus="+${caps//,/,+}" + sudo useradd --system --no-create-home --shell /usr/sbin/nologin tawny-ci || true + out="$RUNNER_TEMP/sensor.out" + # On any failure, show the agent's own output (panics land there). + trap 'rc=$?; if [[ $rc -ne 0 ]]; then echo "--- sensor output ($out) ---"; cat "$out" 2>/dev/null || true; fi' EXIT + # Another audit daemon would own the socket; stop it if present. + sudo systemctl stop auditd 2>/dev/null || true + sudo setpriv --reuid=tawny-ci --regid=tawny-ci --init-groups \ + --inh-caps="$plus" --ambient-caps="$plus" --bounding-set="-all,$plus" \ + "$bin" --linux-sensor-dump --seconds 8 > "$out" 2>&1 & + dump=$! + for _ in $(seq 1 50); do + if grep -q '^READY' "$out" 2>/dev/null; then break; fi + sleep 0.1 + done + grep '^SENSOR_HEALTH' "$out" + source="$(sed -n 's/^READY\t\([a-z_]*\)\t.*/\1/p' "$out")" + echo "sensor source: $source" + for _ in $(seq 1 50); do /bin/true; done + wait "$dump" + tail -n 1 "$out" + if [[ "$source" == "audit_netlink" ]]; then + # /bin/true may resolve elsewhere (gnutrue on Ubuntu 26.04), so match the real path. + true_img="$(readlink -f /bin/true)" + # Count process_start lines only; process_exit carries the same image. + n="$(grep $'^EVENT\tprocess_start\t' "$out" | grep -cF "\"image\":\"$true_img\"" || true)" + echo "/bin/true resolves to $true_img" + echo "process_start events for /bin/true: $n" + test "$n" -ge 50 + grep -q $'^EVENT\tprocess_start\t.*"entity_id":"[a-z2-7]\\{26\\}"' "$out" + grep -q $'^EVENT\tprocess_exit\t' "$out" + # The agent's rules are gone after a clean stop. + if command -v auditctl >/dev/null 2>&1 && sudo auditctl -l | grep -q 'key=tawny'; then + echo "audit rules left behind after a clean stop" >&2 + exit 1 + fi + else + echo "::warning::audit netlink was not available to the sensor (source=$source); proving the auditd log path instead" + # /home/runner is not traversable by tawny-ci, so use a shared dir. + # The runner appends and tawny-ci only reads. + logdir="$(mktemp -d /tmp/tawny-audit.XXXXXX)" + chmod 0755 "$logdir" + log="$logdir/audit.log" + : > "$log" + chmod 0644 "$log" + sudo setpriv --reuid=tawny-ci --regid=tawny-ci --init-groups \ + --inh-caps=-all --ambient-caps=-all --bounding-set=-all \ + "$bin" --linux-sensor-dump --seconds 4 --source audit_log --audit-log "$log" > "$out" 2>&1 & + dump=$! + sleep 1 + python3 - "$log" <<'PY' + import sys + with open(sys.argv[1], "a") as f: + for i in range(50): + s = 7000 + i + t = f"1731200200.{i:03d}" + f.write(f'type=SYSCALL msg=audit({t}:{s}): arch=c000003e syscall=59 success=yes exit=0 ppid=1 pid={20000+i} uid=0 comm="true" exe="/usr/bin/true"\n') + f.write(f'type=EXECVE msg=audit({t}:{s}): argc=1 a0="/bin/true"\n') + PY + wait "$dump" + tail -n 1 "$out" + n="$(grep -c $'^EVENT\tprocess_start\t' "$out" || true)" + test "$n" -ge 50 + fi + # With no capabilities the sensor falls back and says degraded. + nocaps="$RUNNER_TEMP/sensor-nocaps.out" + sudo setpriv --reuid=tawny-ci --regid=tawny-ci --init-groups \ + --inh-caps=-all --ambient-caps=-all --bounding-set=-all \ + "$bin" --linux-sensor-dump --seconds 1 --audit-log /nonexistent --tetragon-export /nonexistent > "$nocaps" 2>&1 + cat "$nocaps" + grep -q $'^READY\tproc_poller\tdegraded' "$nocaps" + grep -q '"status":"degraded"' "$nocaps" - name: package CI artifact run: | set -euo pipefail diff --git a/.gitignore b/.gitignore index aec0016..e243d8a 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,5 @@ coverage/ # Zig 0.17 unpacks fetched packages into the project zig-pkg/ __pycache__/ +# Test fixtures named *.log are inputs, not logs. +!agent/src/platform/linux/testdata/*.log diff --git a/agent/install/install.sh b/agent/install/install.sh index d64e577..d7a3c3c 100755 --- a/agent/install/install.sh +++ b/agent/install/install.sh @@ -565,46 +565,14 @@ if [[ "$dry_run" -ne 1 ]]; then chmod 0755 "$binary_path" fi -if [[ "$os_family" == "macos" ]]; then - if [[ "$dry_run" -eq 1 ]]; then - plist_preview="$(mktemp "${TMPDIR:-/tmp}/tawny-agent.plist.XXXXXX")" - write_launchd_plist "$plist_preview" - if command -v plutil >/dev/null 2>&1; then - plutil -lint "$plist_preview" >/dev/null - fi - if [[ "$enable_macos_dns_logging" -eq 1 && "$service_scope" == "system" ]]; then - enable_mdns_private_logging - fi - printf '[dry-run] write and bootstrap %s launchd job %s (log %s):\n' \ - "$service_scope" "$plist_path" "$log_dir/agent.log" - sed 's/^/[dry-run] /' "$plist_preview" - rm -f "$plist_preview" - else - prepare_log_file - mkdir -p "$(dirname "$plist_path")" - plist_candidate="$(mktemp "$(dirname "$plist_path")/.tawny-agent.plist.XXXXXX")" - write_launchd_plist "$plist_candidate" - plutil -lint "$plist_candidate" >/dev/null - if [[ "$service_scope" == "system" ]]; then - chown root:wheel "$plist_candidate" - fi - chmod 0644 "$plist_candidate" - mv -f "$plist_candidate" "$plist_path" - if [[ "$enable_macos_dns_logging" -eq 1 && "$service_scope" == "system" ]]; then - enable_mdns_private_logging - fi - launchctl bootout "$launchd_domain/$launchd_label" >/dev/null 2>&1 || true - launchctl bootstrap "$launchd_domain" "$plist_path" - launchctl kickstart -k "$launchd_domain/$launchd_label" - launchctl print "$launchd_domain/$launchd_label" >/dev/null - fi -else - service_path="/etc/systemd/system/tawny-agent.service" - if [[ "$dry_run" -eq 1 ]]; then - printf '[dry-run] write and enable hardened systemd service %s\n' "$service_path" - else - service_candidate="$(mktemp --suffix=.service "$(dirname "$service_path")/tawny-agent.XXXXXX")" - cat > "$service_candidate" < "$dest" </dev/null 2>&1; then + plutil -lint "$plist_preview" >/dev/null + fi + if [[ "$enable_macos_dns_logging" -eq 1 && "$service_scope" == "system" ]]; then + enable_mdns_private_logging + fi + printf '[dry-run] write and bootstrap %s launchd job %s (log %s):\n' \ + "$service_scope" "$plist_path" "$log_dir/agent.log" + sed 's/^/[dry-run] /' "$plist_preview" + rm -f "$plist_preview" + else + prepare_log_file + mkdir -p "$(dirname "$plist_path")" + plist_candidate="$(mktemp "$(dirname "$plist_path")/.tawny-agent.plist.XXXXXX")" + write_launchd_plist "$plist_candidate" + plutil -lint "$plist_candidate" >/dev/null + if [[ "$service_scope" == "system" ]]; then + chown root:wheel "$plist_candidate" + fi + chmod 0644 "$plist_candidate" + mv -f "$plist_candidate" "$plist_path" + if [[ "$enable_macos_dns_logging" -eq 1 && "$service_scope" == "system" ]]; then + enable_mdns_private_logging + fi + launchctl bootout "$launchd_domain/$launchd_label" >/dev/null 2>&1 || true + launchctl bootstrap "$launchd_domain" "$plist_path" + launchctl kickstart -k "$launchd_domain/$launchd_label" + launchctl print "$launchd_domain/$launchd_label" >/dev/null + fi +else + service_path="/etc/systemd/system/tawny-agent.service" + if [[ "$dry_run" -eq 1 ]]; then + printf '[dry-run] write and enable hardened systemd service %s:\n' "$service_path" + unit_preview="$(mktemp "${TMPDIR:-/tmp}/tawny-agent.service.XXXXXX")" + write_systemd_unit "$unit_preview" + sed 's/^/[dry-run] /' "$unit_preview" + rm -f "$unit_preview" + else + service_candidate="$(mktemp --suffix=.service "$(dirname "$service_path")/tawny-agent.XXXXXX")" + write_systemd_unit "$service_candidate" systemd-analyze verify "$service_candidate" chown root:root "$service_candidate" chmod 0644 "$service_candidate" diff --git a/agent/install/test-install.sh b/agent/install/test-install.sh index 71c626e..6beba3f 100755 --- a/agent/install/test-install.sh +++ b/agent/install/test-install.sh @@ -106,4 +106,68 @@ if [[ "$(uname -s)" == "Darwin" ]]; then done fi +if [[ "$(uname -s)" == "Linux" ]]; then + # The dry run prints the systemd unit. It must keep User=tawny and every + # hardening line, and grant exactly the documented capabilities (#59). + unit_out="$test_dir/tawny-agent.service" + bash "$installer" \ + --install-dir "$install_dir" \ + --config-path "$config_path" \ + --state-dir "$state_dir" \ + --binary-path "$local_binary" \ + --sha256 "$sha256" \ + --skip-attestation \ + --dry-run | sed -n 's/^\[dry-run\] //p' > "$unit_out" + expected_caps="CAP_AUDIT_CONTROL CAP_AUDIT_READ CAP_DAC_READ_SEARCH CAP_KILL CAP_SYS_PTRACE" + for key in AmbientCapabilities CapabilityBoundingSet; do + lines="$(grep -c "^${key}=" "$unit_out" || true)" + if [[ "$lines" != "1" ]]; then + echo "unit has $lines ${key}= lines, want 1" >&2 + exit 1 + fi + got="$(sed -n "s/^${key}=//p" "$unit_out" | tr ' ' '\n' | sed '/^$/d' | sort | tr '\n' ' ' | sed 's/ $//')" + if [[ "$got" != "$expected_caps" ]]; then + echo "unit ${key} is '$got', want '$expected_caps'" >&2 + exit 1 + fi + done + for expected in \ + 'User=tawny' \ + 'Group=tawny' \ + 'UMask=0027' \ + 'NoNewPrivileges=true' \ + 'PrivateDevices=true' \ + 'PrivateTmp=true' \ + 'ProtectClock=true' \ + 'ProtectControlGroups=true' \ + 'ProtectHome=read-only' \ + 'ProtectKernelLogs=true' \ + 'ProtectKernelModules=true' \ + 'ProtectKernelTunables=true' \ + 'ProtectSystem=strict' \ + "ReadWritePaths=\"$state_dir\"" \ + 'LockPersonality=true' \ + 'MemoryDenyWriteExecute=true' \ + 'RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK' \ + 'RestrictNamespaces=true' \ + 'RestrictRealtime=true' \ + 'RestrictSUIDSGID=true' \ + 'SystemCallArchitectures=native'; do + if ! grep -Fx -- "$expected" "$unit_out" >/dev/null; then + echo "unit missing: $expected" >&2 + exit 1 + fi + done + if grep -E '^(User|Group)=root|^(PermissionsStartOnly|Privileged)' "$unit_out" >/dev/null; then + echo "unit runs with root privileges" >&2 + exit 1 + fi + if command -v systemd-analyze >/dev/null 2>&1; then + systemd-analyze verify "$unit_out" 2>&1 | grep -iE 'capabilit|unknown (key|lvalue)' && { + echo "systemd-analyze rejected the capability lines" >&2 + exit 1 + } + fi +fi + printf 'installer smoke tests passed\n' diff --git a/agent/src/collectors/linux_sensor.zig b/agent/src/collectors/linux_sensor.zig new file mode 100644 index 0000000..2787310 --- /dev/null +++ b/agent/src/collectors/linux_sensor.zig @@ -0,0 +1,496 @@ +//! Linux kernel event source (#59, docs/architecture/linux-sensor.md). +//! +//! Picks audit netlink, the auditd log, Tetragon's export or nothing (the +//! /proc poller only), drains it once per agent loop and reports the choice +//! through `sensor_health` and `agent_health.sensors`. +const std = @import("std"); +const builtin = @import("builtin"); +const iox = @import("../io_compat.zig"); +const entity = @import("../entity.zig"); +const config = @import("../config.zig"); +const process_events = @import("process_events.zig"); +const audit = @import("../platform/linux/audit.zig"); +const tetragon = @import("../platform/linux/tetragon.zig"); + +pub const Source = enum { + audit_netlink, + audit_multicast, + audit_log, + tetragon, + proc_poller, + + pub fn kernel(self: Source) bool { + return self != .proc_poller; + } + + /// Sources that see every exec on their own. The others depend on + /// rules or a log someone else controls, so the poller keeps its normal + /// interval beside them. + pub fn complete(self: Source) bool { + return self == .audit_netlink or self == .tetragon; + } +}; + +/// The /proc poller interval while a kernel source is running. +pub const reconcile_seconds: u32 = 600; +pub const default_audit_log = "/var/log/audit/audit.log"; +/// An event whose EOE never came is completed after this long. +const stale_seconds: u64 = 5; +/// Mapped events per drain at most; the rest wait for the next loop. +const max_items_per_collect: usize = 8192; + +pub const Item = struct { + event_type: []const u8, + payload: []u8, + occurred_at: i64, +}; + +pub const Options = struct { + mode: config.LinuxSensor = .auto, + audit_log_path: ?[]const u8 = null, + tetragon_export_path: ?[]const u8 = null, + watch_dirs: []const []const u8 = &.{}, + /// Register as the audit daemon when no other owns the socket. + allow_daemon: bool = true, +}; + +/// Bounded set of entity ids the kernel source reported, so the +/// reconciliation pass does not report them again. +const IdSet = struct { + map: std.AutoHashMapUnmanaged(entity.Id, void) = .empty, + const cap: usize = 16384; + + fn add(self: *IdSet, alloc: std.mem.Allocator, id: entity.Id) void { + if (self.map.count() >= cap) self.map.clearRetainingCapacity(); + self.map.put(alloc, id, {}) catch {}; + } + fn has(self: *const IdSet, id: entity.Id) bool { + return self.map.contains(id); + } +}; + +pub const Sensor = struct { + alloc: std.mem.Allocator, + table: ?*entity.Table = null, + hashes: process_events.HashCache, + source: Source = .proc_poller, + /// Why the source is not audit netlink as the audit daemon. + reason: []const u8 = "", + live: ?*audit.Live = null, + tail: ?audit.Tail = null, + tail_path: ?[]u8 = null, + asmb: audit.Assembler, + boot_time: ?u64 = null, + own_pid: u32 = 0, + events: u64 = 0, + last_event: i64 = 0, + rate_events: u64 = 0, + rate_since: i64 = 0, + started: IdSet = .{}, + exited: IdSet = .{}, + /// A sensor_health event is due (start, source change). + health_due: bool = true, + + pub fn init(alloc: std.mem.Allocator) Sensor { + return .{ + .alloc = alloc, + .hashes = process_events.HashCache.init(alloc), + .asmb = audit.Assembler.init(alloc, false), + }; + } + + pub fn deinit(self: *Sensor) void { + if (comptime builtin.target.os.tag == .linux) { + if (self.live) |l| l.close(); + } + self.live = null; + if (self.tail) |*t| t.deinit(); + if (self.tail_path) |p| self.alloc.free(p); + self.asmb.deinit(); + self.hashes.deinit(); + self.started.map.deinit(self.alloc); + self.exited.map.deinit(self.alloc); + } + + pub fn kernelActive(self: *const Sensor) bool { + return self.source.kernel(); + } + + /// /proc poller interval: a reconciliation pass beside a complete + /// source, the configured interval otherwise. + pub fn pollSeconds(self: *const Sensor, configured: u32) u32 { + return if (self.source.complete()) @max(configured, reconcile_seconds) else configured; + } + + /// Choose a source. Never fails: the fallback is the /proc poller. + pub fn start(self: *Sensor, opts: Options) void { + self.rate_since = iox.timestamp(); + if (comptime builtin.target.os.tag != .linux) { + self.reason = "not linux"; + return; + } + self.own_pid = @intCast(std.os.linux.getpid()); + self.boot_time = process_events.readLinuxBootTime() catch null; + const mode = opts.mode; + if (mode == .proc) { + self.reason = "linux_sensor = proc"; + return; + } + if (mode == .auto or mode == .audit) { + if (audit.Live.open(self.alloc, opts.watch_dirs, opts.allow_daemon)) |live| { + self.live = live; + self.source = if (live.mode == .daemon) .audit_netlink else .audit_multicast; + self.reason = if (live.mode == .daemon) "" else switch (live.daemon_error orelse error.AccessDenied) { + error.DaemonPresent => "another audit daemon owns the socket; reading its records read-only", + else => |e| multicastReason(e), + }; + return; + } else |err| { + self.reason = openReason(err); + } + } + if (mode == .auto or mode == .audit or mode == .audit_log) { + const log_path = opts.audit_log_path orelse default_audit_log; + if (self.openTail(log_path)) { + self.source = .audit_log; + self.asmb.complete_on_new_serial = true; + if (mode == .audit_log) self.reason = "linux_sensor = audit_log"; + return; + } + if (mode == .audit_log) self.reason = "audit log not readable"; + if (mode == .audit or mode == .audit_log) return; + } + if (mode == .auto or mode == .tetragon) { + const path = opts.tetragon_export_path orelse tetragon.default_export_path; + if (self.openTail(path)) { + self.source = .tetragon; + if (mode == .tetragon) self.reason = ""; + return; + } + if (mode == .tetragon) self.reason = "tetragon export file not readable"; + } + } + + fn openTail(self: *Sensor, path: []const u8) bool { + const owned = self.alloc.dupe(u8, path) catch return false; + self.tail = audit.Tail.open(self.alloc, owned, true) catch { + self.alloc.free(owned); + return false; + }; + self.tail_path = owned; + return true; + } + + fn liveStart(self: *const Sensor, pid: u32) ?u64 { + if (comptime builtin.target.os.tag != .linux) return null; + const boot = self.boot_time orelse return null; + const ticks = process_events.readProcessStartTime(self.alloc, pid) catch return null; + return process_events.linuxStart100ns(boot, ticks); + } + + /// Mapped events since the last call. Caller frees with `freeItems`. + pub fn collect(self: *Sensor) ![]Item { + var out: std.ArrayList(Item) = .empty; + errdefer freeList(self.alloc, &out); + switch (self.source) { + .proc_poller => {}, + .audit_netlink, .audit_multicast => { + try self.live.?.drain(&self.asmb); + try self.asmb.flushOlderThan(@as(u64, @intCast(@max(iox.timestamp(), 0))) -| stale_seconds); + try self.mapAudit(&out); + }, + .audit_log => { + if (self.tail.?.poll() catch null) |text| { + defer self.alloc.free(text); + try audit.feedLog(&self.asmb, text); + } + try self.asmb.flushOlderThan(@as(u64, @intCast(@max(iox.timestamp(), 0))) -| stale_seconds); + try self.mapAudit(&out); + }, + .tetragon => { + if (self.tail.?.poll() catch null) |text| { + defer self.alloc.free(text); + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (out.items.len >= max_items_per_collect) break; + const l = (tetragon.mapLine(self.alloc, line, .{ .table = self.table }) catch null) orelse continue; + if (l.pid == self.own_pid) { + self.alloc.free(l.mapped.payload); + continue; + } + self.note(l.mapped.event_type, l.mapped.payload); + try appendItem(self.alloc, &out, l.mapped); + } + } + }, + } + if (out.items.len > 0) { + self.events += out.items.len; + self.rate_events += out.items.len; + self.last_event = iox.timestamp(); + } + return out.toOwnedSlice(self.alloc); + } + + fn mapAudit(self: *Sensor, out: *std.ArrayList(Item)) !void { + const events = try self.asmb.take(); + defer { + for (events) |e| self.asmb.destroy(e); + self.alloc.free(events); + } + for (events) |e| { + if (out.items.len >= max_items_per_collect) break; + if (e.pid == self.own_pid and self.own_pid != 0) continue; + const live = if (e.kind() == .exec) self.liveStart(e.pid) else null; + const m = (audit.map(self.alloc, e, .{ + .table = self.table, + .hashes = &self.hashes, + .live_start_100ns = live, + }) catch continue) orelse continue; + self.note(m.event_type, m.payload); + try appendItem(self.alloc, out, m); + } + } + + /// Remember process ids this source reported. + fn note(self: *Sensor, event_type: []const u8, payload: []const u8) void { + const id = processEntity(payload) orelse return; + if (std.mem.eql(u8, event_type, "process_start")) self.started.add(self.alloc, id); + if (std.mem.eql(u8, event_type, "process_exit")) self.exited.add(self.alloc, id); + } + + /// True when the reconciliation pass should drop this payload because + /// the kernel source already reported it. + pub fn alreadyReported(self: *const Sensor, event_type: []const u8, payload: []const u8) bool { + if (!self.kernelActive()) return false; + const id = processEntity(payload) orelse return false; + if (std.mem.eql(u8, event_type, "process_start")) return self.started.has(id); + if (std.mem.eql(u8, event_type, "process_exit")) return self.exited.has(id); + return false; + } + + /// Events per minute since the previous call (one health interval). + pub fn takeRate(self: *Sensor) u64 { + const now = iox.timestamp(); + const elapsed: u64 = @intCast(@max(now - self.rate_since, 1)); + const rate = self.rate_events * 60 / elapsed; + self.rate_events = 0; + self.rate_since = now; + return rate; + } + + pub fn status(self: *const Sensor) []const u8 { + return if (self.source == .audit_netlink or (self.source == .tetragon and self.reason.len == 0)) "running" else "degraded"; + } + + /// `sensor_health` payload (schemas/events/sensor_health.v1.json). + pub fn healthPayload(self: *const Sensor, alloc: std.mem.Allocator) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: std.json.Stringify = .{ .writer = &out.writer }; + try jw.beginObject(); + try jw.objectField("sensor"); + try jw.write("linux_kernel"); + try jw.objectField("channel"); + try jw.write(@tagName(self.source)); + try jw.objectField("state"); + try jw.write(if (self.source.kernel()) "ok" else "missing"); + try jw.objectField("status"); + try jw.write(if (std.mem.eql(u8, self.status(), "running")) "ok" else "degraded"); + try jw.objectField("source"); + try jw.write(@tagName(self.source)); + if (self.reason.len > 0) { + try jw.objectField("reason"); + try jw.write(self.reason); + } + try jw.objectField("process_start_source"); + try jw.write(if (self.source.kernel()) @tagName(self.source) else "proc_poller"); + if (self.tail_path) |p| { + try jw.objectField("path"); + try jw.write(p); + } + try jw.objectField("counters"); + try jw.beginObject(); + try jw.objectField("events"); + try jw.write(self.events); + if (self.live) |l| { + try jw.objectField("dropped"); + try jw.write(l.dropped.load(.monotonic)); + try jw.objectField("records"); + try jw.write(l.received.load(.monotonic)); + } + try jw.objectField("assembler_evicted"); + try jw.write(self.asmb.evicted); + try jw.endObject(); + try jw.endObject(); + return out.toOwnedSlice(); + } +}; + +fn openReason(err: audit.OpenError) []const u8 { + return switch (err) { + error.AccessDenied => "audit netlink refused (needs CAP_AUDIT_CONTROL or CAP_AUDIT_READ)", + error.DaemonPresent => "another audit daemon owns the socket and the multicast group was refused", + error.AuditUnavailable => "audit netlink unavailable (no kernel audit, or not in the initial namespaces)", + error.UnsupportedArch => "audit rules not supported on this architecture", + error.ThreadStartFailed => switch (audit.last_spawn_errno) { + 1 => "audit reader thread refused (pthread_create EPERM)", + 11 => "audit reader thread refused (pthread_create EAGAIN, thread limit)", + 22 => "audit reader thread refused (pthread_create EINVAL)", + else => "audit reader thread refused (pthread_create failed)", + }, + else => "audit netlink failed to start", + }; +} + +fn multicastReason(err: audit.OpenError) []const u8 { + return switch (err) { + error.AccessDenied => "cannot register as the audit daemon (needs CAP_AUDIT_CONTROL); reading the multicast group, which carries only rules others load", + error.AuditUnavailable => "cannot register as the audit daemon (not in the initial namespaces); reading the multicast group, which carries only rules others load", + else => "cannot register as the audit daemon; reading the multicast group, which carries only rules others load", + }; +} + +fn appendItem(alloc: std.mem.Allocator, out: *std.ArrayList(Item), m: audit.Mapped) !void { + out.append(alloc, .{ .event_type = m.event_type, .payload = m.payload, .occurred_at = m.occurred_at }) catch |err| { + alloc.free(m.payload); + return err; + }; +} + +fn freeList(alloc: std.mem.Allocator, list: *std.ArrayList(Item)) void { + for (list.items) |i| alloc.free(i.payload); + list.deinit(alloc); +} + +pub fn freeItems(alloc: std.mem.Allocator, items: []Item) void { + for (items) |i| alloc.free(i.payload); + alloc.free(items); +} + +/// `process.entity_id` from a payload built by this agent. +pub fn processEntity(payload: []const u8) ?entity.Id { + const key = "\"process\":{\"entity_id\":\""; + const at = std.mem.indexOf(u8, payload, key) orelse return null; + const start = at + key.len; + if (start + entity.len > payload.len) return null; + return payload[start..][0..entity.len].*; +} + +/// `tawny-agent --linux-sensor-dump [--seconds N] [--source auto|audit|tetragon|proc] +/// [--audit-log PATH] [--tetragon-export PATH] [--watch DIR]`: start the +/// kernel source, print `SENSOR_HEALTHjson` and `READY`, then for N +/// seconds print each event as `EVENTtypejson`, then a SUMMARY line. +/// No server or enrolment. CI uses it to prove the capability set. +pub fn dumpCommand(alloc: std.mem.Allocator, args: []const []const u8) !void { + var opts = Options{}; + var seconds: u32 = 10; + var watch: std.ArrayList([]const u8) = .empty; + defer watch.deinit(alloc); + var i: usize = 0; + while (i < args.len) : (i += 2) { + if (i + 1 >= args.len) return error.InvalidArguments; + const a = args[i]; + const v = args[i + 1]; + if (std.mem.eql(u8, a, "--seconds")) { + seconds = try std.fmt.parseInt(u32, v, 10); + } else if (std.mem.eql(u8, a, "--source")) { + opts.mode = std.meta.stringToEnum(config.LinuxSensor, v) orelse return error.InvalidArguments; + } else if (std.mem.eql(u8, a, "--audit-log")) { + opts.audit_log_path = v; + } else if (std.mem.eql(u8, a, "--tetragon-export")) { + opts.tetragon_export_path = v; + } else if (std.mem.eql(u8, a, "--watch")) { + try watch.append(alloc, v); + } else return error.InvalidArguments; + } + opts.watch_dirs = watch.items; + + var boot = entity.readBootId(); + var table = entity.Table.init(alloc, entity.nil_uuid, &boot, entity.Table.default_capacity); + defer table.deinit(); + var sensor = Sensor.init(alloc); + defer sensor.deinit(); + sensor.table = &table; + sensor.start(opts); + + var out_buf: [64 * 1024]u8 = undefined; + var stdout = std.Io.File.stdout().writer(iox.current(), &out_buf); + const w = &stdout.interface; + const health = try sensor.healthPayload(alloc); + defer alloc.free(health); + try w.print("SENSOR_HEALTH\t{s}\n", .{health}); + try w.print("READY\t{s}\t{s}\n", .{ @tagName(sensor.source), sensor.status() }); + try w.flush(); + + var counts: [4]u64 = @splat(0); + const names = [_][]const u8{ "process_start", "process_exit", "network_connect", "file_create" }; + var timer = try iox.Timer.start(); + // One more drain after the deadline picks up the last records. + var last = false; + while (true) { + if (timer.read() / std.time.ns_per_s >= seconds) last = true; + if (last) iox.sleep(500 * std.time.ns_per_ms); + const items = try sensor.collect(); + defer freeItems(alloc, items); + for (items) |it| { + for (names, 0..) |n, k| if (std.mem.eql(u8, n, it.event_type)) { + counts[k] += 1; + }; + try w.print("EVENT\t{s}\t{s}\n", .{ it.event_type, it.payload }); + } + try w.flush(); + if (last) break; + iox.sleep(250 * std.time.ns_per_ms); + } + try w.print("SUMMARY\tsource={s}\tstatus={s}\tprocess_start={d}\tprocess_exit={d}\tnetwork_connect={d}\tfile_create={d}\n", .{ @tagName(sensor.source), sensor.status(), counts[0], counts[1], counts[2], counts[3] }); + try w.flush(); +} + +test "sensor health payload matches its schema in each state" { + const alloc = std.testing.allocator; + var s = Sensor.init(alloc); + defer s.deinit(); + s.reason = "audit netlink refused (needs CAP_AUDIT_CONTROL or CAP_AUDIT_READ)"; + const degraded = try s.healthPayload(alloc); + defer alloc.free(degraded); + try @import("../schema_check.zig").expectValid(alloc, "sensor_health", degraded); + try std.testing.expect(std.mem.indexOf(u8, degraded, "\"status\":\"degraded\"") != null); + try std.testing.expect(std.mem.indexOf(u8, degraded, "\"process_start_source\":\"proc_poller\"") != null); + try std.testing.expectEqualStrings("degraded", s.status()); + try std.testing.expect(!s.kernelActive()); + + s.source = .audit_netlink; + s.reason = ""; + const ok = try s.healthPayload(alloc); + defer alloc.free(ok); + try @import("../schema_check.zig").expectValid(alloc, "sensor_health", ok); + try std.testing.expect(std.mem.indexOf(u8, ok, "\"status\":\"ok\"") != null); + try std.testing.expectEqualStrings("running", s.status()); +} + +test "reconciliation drops processes the kernel source reported" { + const alloc = std.testing.allocator; + var s = Sensor.init(alloc); + defer s.deinit(); + const id: entity.Id = "abcdefghijklmnopqrstuvwxyz".*; + const p = "{\"process\":{\"entity_id\":\"abcdefghijklmnopqrstuvwxyz\",\"pid\":5}}"; + s.note("process_start", p); + try std.testing.expect(!s.alreadyReported("process_start", p)); // proc only + s.source = .audit_netlink; + try std.testing.expect(s.alreadyReported("process_start", p)); + try std.testing.expect(!s.alreadyReported("process_exit", p)); + try std.testing.expectEqual(id, processEntity(p).?); + try std.testing.expect(processEntity("{\"process\":{\"pid\":5}}") == null); +} + +test "fallback without a kernel source keeps the poller" { + const alloc = std.testing.allocator; + var s = Sensor.init(alloc); + defer s.deinit(); + s.start(.{ .mode = .proc }); + try std.testing.expectEqual(Source.proc_poller, s.source); + const items = try s.collect(); + defer freeItems(alloc, items); + try std.testing.expectEqual(@as(usize, 0), items.len); +} diff --git a/agent/src/collectors/process_events.zig b/agent/src/collectors/process_events.zig index 0c8f200..3d6a7aa 100644 --- a/agent/src/collectors/process_events.zig +++ b/agent/src/collectors/process_events.zig @@ -215,7 +215,7 @@ fn buildExitEvent(alloc: std.mem.Allocator, id: entity.Id, pid: u32, end_100ns: return std.fmt.allocPrint(alloc, "{{\"process\":{{\"entity_id\":\"{s}\",\"pid\":{d}}},\"end_time\":\"{s}\"}}", .{ &id, pid, entity.formatIso(&buf, end_100ns) }); } -fn linuxStart100ns(boot_unix: u64, start_ticks: u64) ?u64 { +pub fn linuxStart100ns(boot_unix: u64, start_ticks: u64) ?u64 { if (start_ticks == 0) return null; return boot_unix * entity.ticks_per_second + start_ticks * (entity.ticks_per_second / linux_user_hz); } @@ -326,7 +326,7 @@ fn buildLinuxLaunchEvent(alloc: std.mem.Allocator, hashes: *HashCache, table: ?* /// SHA-256 of executables keyed by path and invalidated on size/mtime change, /// so a burst of `git`/`zsh` launches hashes the binary once. Bounded: the /// cache is cleared when it reaches `max_hash_cache_entries`. -const HashCache = struct { +pub const HashCache = struct { allocator: std.mem.Allocator, map: std.StringHashMap(Entry), @@ -336,11 +336,11 @@ const HashCache = struct { digest: [32]u8, }; - fn init(alloc: std.mem.Allocator) HashCache { + pub fn init(alloc: std.mem.Allocator) HashCache { return .{ .allocator = alloc, .map = std.StringHashMap(Entry).init(alloc) }; } - fn deinit(self: *HashCache) void { + pub fn deinit(self: *HashCache) void { self.clear(); self.map.deinit(); } @@ -351,7 +351,7 @@ const HashCache = struct { self.map.clearRetainingCapacity(); } - fn get(self: *HashCache, path: []const u8) ?[32]u8 { + pub fn get(self: *HashCache, path: []const u8) ?[32]u8 { const io = iox.current(); var file = std.Io.Dir.openFileAbsolute(io, path, .{}) catch return null; defer file.close(io); @@ -425,7 +425,7 @@ fn readParentPid(alloc: std.mem.Allocator, pid: u32) !u32 { return std.fmt.parseInt(u32, ppid, 10); } -fn readProcessStartTime(alloc: std.mem.Allocator, pid: u32) !u64 { +pub fn readProcessStartTime(alloc: std.mem.Allocator, pid: u32) !u64 { const stat = try readProcText(alloc, pid, "stat"); defer alloc.free(stat); return parseProcessStartTime(stat); @@ -442,7 +442,7 @@ fn parseProcessStartTime(stat: []const u8) !u64 { return error.BadProcStat; } -fn readLinuxBootTime() !u64 { +pub fn readLinuxBootTime() !u64 { const io = iox.current(); var file = try std.Io.Dir.openFileAbsolute(io, "/proc/stat", .{}); defer file.close(io); diff --git a/agent/src/config.zig b/agent/src/config.zig index 66ebd90..f4de45f 100644 --- a/agent/src/config.zig +++ b/agent/src/config.zig @@ -4,6 +4,8 @@ const env = @import("env.zig"); const iox = @import("io_compat.zig"); const keystore = @import("keystore.zig"); +pub const LinuxSensor = enum { auto, audit, audit_log, tetragon, proc }; + pub const Config = struct { allocator: std.mem.Allocator, backend_url: []u8, @@ -39,6 +41,12 @@ pub const Config = struct { state_path: []u8, /// Dangerous: permit non-loopback HTTP backends. Default false. allow_insecure_http: bool = false, + /// Linux kernel event source (#59): auto, audit, tetragon or proc. + linux_sensor: LinuxSensor = .auto, + /// auditd log read when another daemon owns the audit socket. + audit_log_path: ?[]u8 = null, + /// Tetragon JSON export file. Unset: the Tetragon default path. + tetragon_export_path: ?[]u8 = null, /// Where the JWT and device seed live. `load` picks the platform default; /// literal Configs (tests) keep the plaintext-file behaviour. secret_store: keystore.Store = .{}, @@ -51,6 +59,8 @@ pub const Config = struct { if (self.enrollment_token) |t| self.allocator.free(t); if (self.agent_id) |t| self.allocator.free(t); if (self.yara_rule_key) |k| self.allocator.free(k); + if (self.audit_log_path) |p| self.allocator.free(p); + if (self.tetragon_export_path) |p| self.allocator.free(p); if (self.agent_jwt) |t| self.allocator.free(t); for (self.fim_paths) |p| self.allocator.free(p); if (self.fim_paths.len > 0) self.allocator.free(self.fim_paths); @@ -156,6 +166,14 @@ pub fn loadWith(alloc: std.mem.Allocator, options: LoadOptions) !Config { cfg.http_timeout_seconds = try std.fmt.parseInt(u32, val, 10); } else if (std.mem.eql(u8, key, "max_retry_backoff_seconds")) { cfg.max_retry_backoff_seconds = try std.fmt.parseInt(u32, val, 10); + } else if (std.mem.eql(u8, key, "linux_sensor")) { + cfg.linux_sensor = std.meta.stringToEnum(LinuxSensor, val) orelse return error.InvalidLinuxSensor; + } else if (std.mem.eql(u8, key, "audit_log_path")) { + if (cfg.audit_log_path) |old| alloc.free(old); + cfg.audit_log_path = if (val.len == 0) null else try alloc.dupe(u8, val); + } else if (std.mem.eql(u8, key, "tetragon_export_path")) { + if (cfg.tetragon_export_path) |old| alloc.free(old); + cfg.tetragon_export_path = if (val.len == 0) null else try alloc.dupe(u8, val); } else if (std.mem.eql(u8, key, "allow_insecure_http")) { cfg.allow_insecure_http = std.mem.eql(u8, val, "true") or std.mem.eql(u8, val, "1"); } else if (std.mem.eql(u8, key, "spill_path")) { diff --git a/agent/src/main.zig b/agent/src/main.zig index 8f6d59b..fde7a9d 100644 --- a/agent/src/main.zig +++ b/agent/src/main.zig @@ -17,6 +17,7 @@ const inventory_collector = @import("collectors/inventory.zig"); const extensions_collector = @import("collectors/extensions.zig"); const mcp_collector = @import("collectors/mcp_config.zig"); const windows_events = @import("collectors/windows_events.zig"); +const linux_sensor = @import("collectors/linux_sensor.zig"); const response_actions = @import("response_actions.zig"); const action_key = @import("action_key.zig"); const action_journal = @import("action_journal.zig"); @@ -41,6 +42,9 @@ pub fn main(init: std.process.Init) !void { if (args.len >= 2 and std.mem.eql(u8, args[1], "--eventlog-dump")) { return windows_events.dumpCommand(alloc, args[2..]); } + if (args.len >= 2 and std.mem.eql(u8, args[1], "--linux-sensor-dump")) { + return linux_sensor.dumpCommand(alloc, args[2..]); + } if (args.len >= 2 and @import("keystore_debug.zig").isDebugCommand(args[1])) { const code = @import("keystore_debug.zig").run(alloc, args[1..]); if (code != 0) std.process.exit(code); @@ -153,6 +157,24 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { std.debug.print("process baseline failed: {s}\n", .{@errorName(err)}); } + // Kernel events on Linux (#59): audit netlink, the auditd log or + // Tetragon. With one running the /proc poller becomes a 10 minute + // reconciliation pass; without one it stays the source and health says + // degraded. + var kernel_sensor = linux_sensor.Sensor.init(alloc); + defer kernel_sensor.deinit(); + kernel_sensor.table = &entities; + if (builtin.target.os.tag == .linux) { + kernel_sensor.start(.{ + .mode = cfg.linux_sensor, + .audit_log_path = cfg.audit_log_path, + .tetragon_export_path = cfg.tetragon_export_path, + .watch_dirs = cfg.fim_paths, + }); + std.debug.print("linux sensor: {s} ({s}) {s}\n", .{ @tagName(kernel_sensor.source), kernel_sensor.status(), kernel_sensor.reason }); + } + const process_poll_seconds = kernel_sensor.pollSeconds(cfg.process_events_interval_seconds); + var fs_watcher = try fs_events.Watcher.init(alloc, cfg.fim_paths); defer fs_watcher.deinit(); @@ -250,17 +272,25 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { var update_timer = try iox.Timer.start(); var first_update_check = true; + if (builtin.target.os.tag == .linux) { + if (kernel_sensor.healthPayload(alloc)) |p| { + defer alloc.free(p); + queueEvent(&buf, "sensor_health", p); + } else |_| {} + } + while (!lifecycle.shouldStop()) { if (heartbeat_timer.read() / std.time.ns_per_s >= cfg.heartbeat_interval_seconds) { heartbeat_timer.reset(); const uptime: i64 = @intCast(iox.timestamp() - start_time); + const sensors = sensorStatus(&kernel_sensor); if (healthPayloadFull(alloc, .{ .uptime = uptime, .depth = buf.totalLen(), .next_sequence = buf.next_sequence, .boot_id = &boot_id, .key_protection = cfg.secret_store.protection(), - .sensors = sensorStatus(&process_events_timer, process_tracker_last_event, cfg.process_events_interval_seconds), + .sensors = sensors.slice(), .update = upd.health(), })) |payload| { defer alloc.free(payload); @@ -402,16 +432,36 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { } if (lifecycle.shouldStop()) break; - if (process_events_timer.read() / std.time.ns_per_s >= cfg.process_events_interval_seconds) { + if (builtin.target.os.tag == .linux and kernel_sensor.kernelActive()) { + if (kernel_sensor.collect()) |items| { + defer linux_sensor.freeItems(alloc, items); + for (items) |item| { + buf.push(.{ + .event_type = item.event_type, + .occurred_at = item.occurred_at, + .payload = item.payload, + }) catch |err| { + std.debug.print("queue {s} failed: {s}\n", .{ item.event_type, @errorName(err) }); + break; + }; + } + } else |err| { + std.debug.print("linux sensor failed: {s}\n", .{@errorName(err)}); + } + } + + if (lifecycle.shouldStop()) break; + if (process_events_timer.read() / std.time.ns_per_s >= process_poll_seconds) { process_events_timer.reset(); if (process_tracker.collectLaunches()) |launches| { - if (launches.len > 0) process_tracker_last_event = iox.timestamp(); - emitBatch(&buf, "process_start", launches, alloc); + const fresh = dropReported(&kernel_sensor, "process_start", launches, alloc); + if (fresh.len > 0) process_tracker_last_event = iox.timestamp(); + emitBatch(&buf, "process_start", fresh, alloc); } else |err| { std.debug.print("process_events collector failed: {s}\n", .{@errorName(err)}); } if (process_tracker.takeExits()) |exits| { - emitBatch(&buf, "process_exit", exits, alloc); + emitBatch(&buf, "process_exit", dropReported(&kernel_sensor, "process_exit", exits, alloc), alloc); } else |_| {} } @@ -595,16 +645,62 @@ fn acceptOwnKeyWrite(alloc: std.mem.Allocator, mon: *tamper.Monitor, state_path: /// Per-sensor status for agent_health. Windows channels report their own /// sensor_health; here the launch tracker reports running with its last event -/// age. -fn sensorStatus(timer: *iox.Timer, last_event: i64, interval: u32) [1]SensorEntry { - _ = timer; - _ = interval; +/// age, and on Linux the kernel source reports which one is active, its +/// status and its event rate. +const SensorList = struct { + items: [2]SensorEntry, + len: usize, + fn slice(self: *const SensorList) []const SensorEntry { + return self.items[0..self.len]; + } +}; + +fn sensorStatus(kernel: *linux_sensor.Sensor) SensorList { const now = iox.timestamp(); - return .{.{ - .name = "process_events", - .status = "running", - .last_event_age_seconds = if (last_event == 0) null else @max(now - last_event, 0), - }}; + const age = struct { + fn of(n: i64, last: i64) ?i64 { + return if (last == 0) null else @max(n - last, 0); + } + }.of; + var out = SensorList{ .items = .{ + .{ .name = "process_events", .status = "running", .last_event_age_seconds = age(now, process_tracker_last_event) }, + .{ .name = "linux_kernel", .status = "unknown" }, + }, .len = 1 }; + if (builtin.target.os.tag == .linux) { + out.len = 2; + out.items[1] = .{ + .name = "linux_kernel", + .status = kernel.status(), + .last_event_age_seconds = age(now, kernel.last_event), + .source = @tagName(kernel.source), + .events_per_minute = kernel.takeRate(), + }; + } + return out; +} + +/// Drop reconciliation payloads the kernel source already reported. Frees +/// what it drops; returns the same slice, shortened. +fn dropReported(kernel: *const linux_sensor.Sensor, event_type: []const u8, payloads: [][]u8, alloc: std.mem.Allocator) [][]u8 { + var keep: usize = 0; + for (payloads) |p| { + if (kernel.alreadyReported(event_type, p)) { + alloc.free(p); + continue; + } + payloads[keep] = p; + keep += 1; + } + // emitBatch frees the slice; shrink in place keeps the allocation. + if (alloc.resize(payloads, keep)) return payloads[0..keep]; + const out = alloc.alloc([]u8, keep) catch { + for (payloads[0..keep]) |p| alloc.free(p); + alloc.free(payloads); + return &.{}; + }; + @memcpy(out, payloads[0..keep]); + alloc.free(payloads); + return out; } /// Quarantine directory. `%ProgramData%\Tawny\Quarantine` on Windows, @@ -762,9 +858,13 @@ test "main module loads" { _ = @import("keystore_debug.zig"); // Pure macOS parsers have no syscalls, so their tests run on every host. _ = @import("platform/macos/parse.zig"); + // Linux audit and Tetragon parsing and mapping are pure. + _ = @import("platform/linux/audit.zig"); + _ = @import("platform/linux/tetragon.zig"); // Windows event log parsing and mapping are pure too. _ = @import("platform/windows/evtxml.zig"); _ = windows_events; + _ = linux_sensor; if (builtin.target.os.tag == .macos) { _ = @import("platform/macos/fsevents.zig"); _ = @import("platform/macos/dnslog.zig"); @@ -871,6 +971,9 @@ pub const SensorEntry = struct { name: []const u8, status: []const u8, last_event_age_seconds: ?i64 = null, + /// Linux kernel source (#59): which one is active and its event rate. + source: ?[]const u8 = null, + events_per_minute: ?u64 = null, }; pub const HealthInput = struct { @@ -879,7 +982,7 @@ pub const HealthInput = struct { next_sequence: u64, boot_id: []const u8, key_protection: ?[]const u8 = null, - sensors: [1]SensorEntry = .{.{ .name = "process_events", .status = "unknown" }}, + sensors: []const SensorEntry = &.{.{ .name = "process_events", .status = "unknown" }}, update: ?updater.HealthState = null, }; @@ -891,7 +994,7 @@ fn healthPayloadFull(alloc: std.mem.Allocator, in: HealthInput) ![]u8 { .next_sequence = in.next_sequence, .boot_id = in.boot_id, .key_protection = in.key_protection, - .sensors = &in.sensors, + .sensors = in.sensors, .update = in.update, }, .{ .emit_null_optional_fields = false }); } @@ -906,7 +1009,10 @@ test "agent_health payload matches its schema" { .next_sequence = 9, .boot_id = entity.nil_uuid, .key_protection = "dpapi", - .sensors = .{.{ .name = "process_events", .status = "running", .last_event_age_seconds = 3 }}, + .sensors = &.{ + .{ .name = "process_events", .status = "running", .last_event_age_seconds = 3 }, + .{ .name = "linux_kernel", .status = "degraded", .source = "proc_poller", .events_per_minute = 0 }, + }, .update = .{ .state = .idle, .ring = "50", .bucket = 42 }, }); defer std.testing.allocator.free(full); diff --git a/agent/src/platform/linux/audit.zig b/agent/src/platform/linux/audit.zig new file mode 100644 index 0000000..863325c --- /dev/null +++ b/agent/src/platform/linux/audit.zig @@ -0,0 +1,1629 @@ +//! Linux kernel audit sensor (#59, docs/architecture/linux-sensor.md). +//! +//! Records come from a `NETLINK_AUDIT` socket (the agent registered as the +//! audit daemon, or the read-only multicast group when auditd owns the +//! socket) or from auditd's log file. Each record carries +//! `audit(.:)`; records with the same serial are one kernel +//! event. `Assembler` joins them, `map` turns a joined event into a v2 +//! `process_start`, `process_exit`, `network_connect` or `file_create` +//! payload. Parsing, joining and mapping are pure so the tests run on every +//! OS against captured records in testdata/. +const std = @import("std"); +const builtin = @import("builtin"); +const entity = @import("../../entity.zig"); +const privacy = @import("../../collectors/privacy.zig"); +const process_events = @import("../../collectors/process_events.zig"); +const iox = @import("../../io_compat.zig"); + +// --------------------------------------------------------------------------- +// Kernel constants, from include/uapi/linux/audit.h and linux/netlink.h. The +// pin test below checks them against the values in that header. + +pub const netlink_audit: u32 = 9; +/// AUDIT_NLGRP_READLOG, the read-only multicast group (needs CAP_AUDIT_READ). +pub const nlgrp_readlog: u32 = 1; + +pub const msg = struct { + pub const get: u16 = 1000; + pub const set: u16 = 1001; + pub const add_rule: u16 = 1011; + pub const del_rule: u16 = 1012; + pub const syscall: u16 = 1300; + pub const path: u16 = 1302; + pub const sockaddr: u16 = 1306; + pub const cwd: u16 = 1307; + pub const execve: u16 = 1309; + pub const eoe: u16 = 1320; + pub const proctitle: u16 = 1327; +}; + +const status_enabled: u32 = 0x0001; +const status_pid: u32 = 0x0004; +const status_backlog_limit: u32 = 0x0010; +const filter_exit: u32 = 0x04; +const action_always: u32 = 2; +const field_arch: u32 = 11; +const field_perm: u32 = 106; +const field_dir: u32 = 107; +const field_filterkey: u32 = 210; +const op_equal: u32 = 0x40000000; +const perm_write: u32 = 2; +const perm_attr: u32 = 8; +const max_fields: usize = 64; +const bitmask_words: usize = 64; + +pub const arch_x86_64: u32 = 62 | 0x80000000 | 0x40000000; +pub const arch_aarch64: u32 = 183 | 0x80000000 | 0x40000000; + +/// Filter key on every rule the agent loads, so a restart can remove them. +pub const rule_key = "tawny"; +const einprogress: i64 = -115; + +pub const Kind = enum { exec, connect, exit_group }; + +/// Syscalls the mapper cares about. PATH records with nametype=CREATE from +/// any other syscall become `file_create`. +pub fn syscallKind(arch: u32, nr: u32) ?Kind { + return switch (arch) { + arch_x86_64 => switch (nr) { + 59, 322 => .exec, + 42 => .connect, + 231 => .exit_group, + else => null, + }, + arch_aarch64 => switch (nr) { + 221, 281 => .exec, + 203 => .connect, + 94 => .exit_group, + else => null, + }, + else => null, + }; +} + +// --------------------------------------------------------------------------- +// Records + +pub const Record = struct { + type: u16, + sec: u64, + ms: u32, + serial: u64, + body: []const u8, +}; + +/// A netlink record: the message type from nlmsghdr and the payload +/// `audit(1731200000.123:4567): key=value ...`. +pub fn parseNetlink(msg_type: u16, payload: []const u8) ?Record { + const text = std.mem.trimEnd(u8, payload, "\x00\n"); + return parseStamped(msg_type, text); +} + +/// An auditd log line: `type=SYSCALL msg=audit(...): key=value ...`, with an +/// optional `node=` prefix and the enriched `\x1d` suffix. +pub fn parseLogLine(line: []const u8) ?Record { + const at = std.mem.indexOf(u8, line, "type=") orelse return null; + var rest = line[at + "type=".len ..]; + const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse return null; + const t = typeFromName(rest[0..sp]) orelse return null; + rest = rest[sp + 1 ..]; + if (!std.mem.startsWith(u8, rest, "msg=")) return null; + return parseStamped(t, rest["msg=".len..]); +} + +fn parseStamped(msg_type: u16, text: []const u8) ?Record { + if (!std.mem.startsWith(u8, text, "audit(")) return null; + const close = std.mem.indexOfScalar(u8, text, ')') orelse return null; + const stamp = text["audit(".len..close]; + const dot = std.mem.indexOfScalar(u8, stamp, '.') orelse return null; + const colon = std.mem.indexOfScalar(u8, stamp, ':') orelse return null; + if (colon < dot) return null; + const sec = std.fmt.parseInt(u64, stamp[0..dot], 10) catch return null; + const ms = std.fmt.parseInt(u32, stamp[dot + 1 .. colon], 10) catch return null; + const serial = std.fmt.parseInt(u64, stamp[colon + 1 ..], 10) catch return null; + var body = text[close + 1 ..]; + if (std.mem.startsWith(u8, body, ":")) body = body[1..]; + if (std.mem.indexOfScalar(u8, body, 0x1d)) |gs| body = body[0..gs]; + return .{ .type = msg_type, .sec = sec, .ms = ms, .serial = serial, .body = std.mem.trim(u8, body, " ") }; +} + +fn typeFromName(name: []const u8) ?u16 { + const names = [_]struct { []const u8, u16 }{ + .{ "SYSCALL", msg.syscall }, .{ "PATH", msg.path }, + .{ "SOCKADDR", msg.sockaddr }, .{ "CWD", msg.cwd }, + .{ "EXECVE", msg.execve }, .{ "EOE", msg.eoe }, + .{ "PROCTITLE", msg.proctitle }, + }; + for (names) |n| if (std.mem.eql(u8, n[0], name)) return n[1]; + return null; +} + +pub const Field = struct { + key: []const u8, + value: []const u8, + quoted: bool, +}; + +/// `key=value` pairs. Values are `"quoted"`, bare, or bare hex for untrusted +/// strings that hold spaces, quotes or control bytes. +pub const FieldIter = struct { + s: []const u8, + i: usize = 0, + + pub fn next(self: *FieldIter) ?Field { + while (self.i < self.s.len and self.s[self.i] == ' ') self.i += 1; + if (self.i >= self.s.len) return null; + const key_start = self.i; + while (self.i < self.s.len and self.s[self.i] != '=' and self.s[self.i] != ' ') self.i += 1; + const key = self.s[key_start..self.i]; + if (self.i >= self.s.len or self.s[self.i] != '=') return .{ .key = key, .value = "", .quoted = false }; + self.i += 1; + if (self.i < self.s.len and (self.s[self.i] == '"' or self.s[self.i] == '\'')) { + const q = self.s[self.i]; + self.i += 1; + const v_start = self.i; + while (self.i < self.s.len and self.s[self.i] != q) self.i += 1; + const v = self.s[v_start..self.i]; + if (self.i < self.s.len) self.i += 1; + return .{ .key = key, .value = v, .quoted = true }; + } + const v_start = self.i; + while (self.i < self.s.len and self.s[self.i] != ' ') self.i += 1; + return .{ .key = key, .value = self.s[v_start..self.i], .quoted = false }; + } +}; + +/// Decode an untrusted string field: quoted text as is, `(null)` as empty, +/// bare hex decoded. Appends to `out`, bounded by `limit`. +fn appendString(alloc: std.mem.Allocator, out: *std.ArrayList(u8), f: Field, limit: usize) !void { + const room = limit -| out.items.len; + if (room == 0) return; + if (f.quoted) return out.appendSlice(alloc, f.value[0..@min(f.value.len, room)]); + if (std.mem.eql(u8, f.value, "(null)")) return; + if (f.value.len % 2 == 0 and isHex(f.value)) { + const n = @min(f.value.len / 2, room); + try out.ensureUnusedCapacity(alloc, n); + var i: usize = 0; + while (i < n) : (i += 1) { + const b = std.fmt.parseInt(u8, f.value[i * 2 .. i * 2 + 2], 16) catch unreachable; + out.appendAssumeCapacity(b); + } + return; + } + return out.appendSlice(alloc, f.value[0..@min(f.value.len, room)]); +} + +fn isHex(s: []const u8) bool { + if (s.len == 0) return false; + for (s) |c| if (!std.ascii.isHex(c)) return false; + return true; +} + +// --------------------------------------------------------------------------- +// Joining records by serial + +const max_string_bytes: usize = 4096; +const max_args: usize = 256; +const max_arg_bytes: usize = 32 * 1024; +const max_paths: usize = 8; + +pub const PathItem = struct { + name: std.ArrayList(u8) = .empty, + create: bool = false, + parent: bool = false, +}; + +/// One kernel event: the records that share a serial. +pub const Event = struct { + serial: u64, + sec: u64, + ms: u32, + have_syscall: bool = false, + arch: u32 = 0, + syscall: u32 = 0, + success: ?bool = null, + exit: i64 = 0, + pid: u32 = 0, + ppid: u32 = 0, + uid: u32 = 0, + comm: std.ArrayList(u8) = .empty, + exe: std.ArrayList(u8) = .empty, + cwd: std.ArrayList(u8) = .empty, + proctitle: std.ArrayList(u8) = .empty, + args: std.ArrayList(std.ArrayList(u8)) = .empty, + arg_bytes: usize = 0, + paths: std.ArrayList(PathItem) = .empty, + saddr: std.ArrayList(u8) = .empty, + + pub fn deinit(self: *Event, alloc: std.mem.Allocator) void { + self.comm.deinit(alloc); + self.exe.deinit(alloc); + self.cwd.deinit(alloc); + self.proctitle.deinit(alloc); + for (self.args.items) |*a| a.deinit(alloc); + self.args.deinit(alloc); + for (self.paths.items) |*p| p.name.deinit(alloc); + self.paths.deinit(alloc); + self.saddr.deinit(alloc); + } + + pub fn time100ns(self: *const Event) u64 { + return self.sec * entity.ticks_per_second + @as(u64, self.ms) * entity.ticks_per_ms; + } + + pub fn kind(self: *const Event) ?Kind { + if (!self.have_syscall) return null; + return syscallKind(self.arch, self.syscall); + } + + fn add(self: *Event, alloc: std.mem.Allocator, rec: Record) !void { + var it = FieldIter{ .s = rec.body }; + switch (rec.type) { + msg.syscall => { + self.have_syscall = true; + while (it.next()) |f| { + if (eq(f.key, "arch")) { + self.arch = std.fmt.parseInt(u32, f.value, 16) catch 0; + } else if (eq(f.key, "syscall")) { + self.syscall = std.fmt.parseInt(u32, f.value, 10) catch 0; + } else if (eq(f.key, "success")) { + self.success = eq(f.value, "yes"); + } else if (eq(f.key, "exit")) { + self.exit = std.fmt.parseInt(i64, f.value, 10) catch 0; + } else if (eq(f.key, "pid")) { + self.pid = std.fmt.parseInt(u32, f.value, 10) catch 0; + } else if (eq(f.key, "ppid")) { + self.ppid = std.fmt.parseInt(u32, f.value, 10) catch 0; + } else if (eq(f.key, "uid")) { + self.uid = std.fmt.parseInt(u32, f.value, 10) catch 0; + } else if (eq(f.key, "comm")) { + self.comm.clearRetainingCapacity(); + try appendString(alloc, &self.comm, f, max_string_bytes); + } else if (eq(f.key, "exe")) { + self.exe.clearRetainingCapacity(); + try appendString(alloc, &self.exe, f, max_string_bytes); + } + } + }, + msg.execve => while (it.next()) |f| { + try self.addArg(alloc, f); + }, + msg.cwd => while (it.next()) |f| { + if (eq(f.key, "cwd")) { + self.cwd.clearRetainingCapacity(); + try appendString(alloc, &self.cwd, f, max_string_bytes); + } + }, + msg.proctitle => while (it.next()) |f| { + if (eq(f.key, "proctitle")) { + self.proctitle.clearRetainingCapacity(); + try appendString(alloc, &self.proctitle, f, max_arg_bytes); + } + }, + msg.sockaddr => while (it.next()) |f| { + if (eq(f.key, "saddr") and f.value.len <= 256 and f.value.len % 2 == 0 and isHex(f.value)) { + self.saddr.clearRetainingCapacity(); + try appendString(alloc, &self.saddr, f, 128); + } + }, + msg.path => { + if (self.paths.items.len >= max_paths) return; + var item = PathItem{}; + errdefer item.name.deinit(alloc); + while (it.next()) |f| { + if (eq(f.key, "name")) { + try appendString(alloc, &item.name, f, max_string_bytes); + } else if (eq(f.key, "nametype")) { + item.create = eq(f.value, "CREATE"); + item.parent = eq(f.value, "PARENT"); + } + } + try self.paths.append(alloc, item); + }, + else => {}, + } + } + + /// EXECVE fields: `argc`, `aN`, and for long arguments `aN_len` plus + /// chunks `aN[i]`. + fn addArg(self: *Event, alloc: std.mem.Allocator, f: Field) !void { + if (f.key.len < 2 or f.key[0] != 'a' or !std.ascii.isDigit(f.key[1])) return; + var end: usize = 1; + while (end < f.key.len and std.ascii.isDigit(f.key[end])) end += 1; + const rest = f.key[end..]; + if (std.mem.eql(u8, rest, "_len")) return; + if (rest.len > 0 and rest[0] != '[') return; + const index = std.fmt.parseInt(usize, f.key[1..end], 10) catch return; + if (index >= max_args) return; + while (self.args.items.len <= index) try self.args.append(alloc, .empty); + const before = self.args.items[index].items.len; + try appendString(alloc, &self.args.items[index], f, before + (max_arg_bytes -| self.arg_bytes)); + self.arg_bytes += self.args.items[index].items.len - before; + } +}; + +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +/// Joins records into events by serial. Netlink delivers an EOE record after +/// each multi-record event; auditd's log does not, so with +/// `complete_on_new_serial` a record with a new serial completes the others. +/// `flushOlderThan` bounds how long a lost EOE can hold an event. +pub const Assembler = struct { + alloc: std.mem.Allocator, + complete_on_new_serial: bool = false, + pending: std.AutoArrayHashMapUnmanaged(u64, *Event) = .empty, + done: std.ArrayList(*Event) = .empty, + /// Records for serials past the pending cap, completed early. + evicted: u64 = 0, + + pub const max_pending: usize = 1024; + + pub fn init(alloc: std.mem.Allocator, complete_on_new_serial: bool) Assembler { + return .{ .alloc = alloc, .complete_on_new_serial = complete_on_new_serial }; + } + + pub fn deinit(self: *Assembler) void { + for (self.pending.values()) |e| self.destroy(e); + self.pending.deinit(self.alloc); + for (self.done.items) |e| self.destroy(e); + self.done.deinit(self.alloc); + } + + pub fn destroy(self: *Assembler, e: *Event) void { + e.deinit(self.alloc); + self.alloc.destroy(e); + } + + pub fn feed(self: *Assembler, rec: Record) !void { + switch (rec.type) { + msg.syscall, msg.execve, msg.cwd, msg.path, msg.sockaddr, msg.proctitle, msg.eoe => {}, + else => return, + } + if (self.complete_on_new_serial and !self.pending.contains(rec.serial)) try self.completeAll(); + if (rec.type == msg.eoe) { + if (self.pending.fetchOrderedRemove(rec.serial)) |kv| try self.finish(kv.value); + return; + } + const gop = try self.pending.getOrPut(self.alloc, rec.serial); + if (!gop.found_existing) { + const e = self.alloc.create(Event) catch |err| { + _ = self.pending.orderedRemove(rec.serial); + return err; + }; + e.* = .{ .serial = rec.serial, .sec = rec.sec, .ms = rec.ms }; + gop.value_ptr.* = e; + } + try gop.value_ptr.*.add(self.alloc, rec); + if (self.pending.count() > max_pending) { + const oldest = self.pending.values()[0]; + self.pending.orderedRemoveAt(0); + self.evicted += 1; + try self.finish(oldest); + } + } + + fn finish(self: *Assembler, e: *Event) !void { + self.done.append(self.alloc, e) catch |err| { + self.destroy(e); + return err; + }; + } + + pub fn completeAll(self: *Assembler) !void { + while (self.pending.count() > 0) { + const e = self.pending.values()[0]; + self.pending.orderedRemoveAt(0); + try self.finish(e); + } + } + + /// Complete events whose first record is older than `sec`. + pub fn flushOlderThan(self: *Assembler, sec: u64) !void { + while (self.pending.count() > 0) { + const e = self.pending.values()[0]; + if (e.sec >= sec) break; + self.pending.orderedRemoveAt(0); + try self.finish(e); + } + } + + /// Completed events in arrival order. Free each with `destroy`. + pub fn take(self: *Assembler) ![]*Event { + return self.done.toOwnedSlice(self.alloc); + } +}; + +/// Feed every line of an auditd log chunk. +pub fn feedLog(asmb: *Assembler, text: []const u8) !void { + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (parseLogLine(line)) |rec| try asmb.feed(rec); + } +} + +// --------------------------------------------------------------------------- +// Mapping to v2 events + +pub const Mapped = struct { + event_type: []const u8, + payload: []u8, + occurred_at: i64, +}; + +pub const MapContext = struct { + table: ?*entity.Table = null, + hashes: ?*process_events.HashCache = null, + /// Start of the process read from /proc while it is still alive, so the + /// entity id matches the poller's. Otherwise the event time is used. + live_start_100ns: ?u64 = null, + /// `sensor` field value. + sensor: []const u8 = "linux_audit", +}; + +/// Map one joined event. Null when it is not one we report. +pub fn map(alloc: std.mem.Allocator, ev: *const Event, ctx: MapContext) !?Mapped { + const occurred: i64 = @intCast(ev.sec); + if (ev.kind()) |k| switch (k) { + .exec => { + if (ev.success != true) return null; + return .{ .event_type = "process_start", .payload = try processStart(alloc, ev, ctx), .occurred_at = occurred }; + }, + .connect => { + if (!(ev.success == true or ev.exit == einprogress)) return null; + const peer = parseSockaddr(ev.saddr.items) orelse return null; + return .{ .event_type = "network_connect", .payload = try networkConnect(alloc, ev, ctx, peer), .occurred_at = occurred }; + }, + .exit_group => return .{ .event_type = "process_exit", .payload = try processExit(alloc, ev, ctx), .occurred_at = occurred }, + }; + if (!ev.have_syscall or ev.success == false) return null; + for (ev.paths.items) |p| { + if (!p.create or p.name.items.len == 0) continue; + const full = try createdPath(alloc, ev, p.name.items); + defer alloc.free(full); + return .{ .event_type = "file_create", .payload = try fileCreate(alloc, ev, ctx, full), .occurred_at = occurred }; + } + return null; +} + +/// Audit records always carry Linux paths, so join and split with '/' even +/// when these tests run on Windows. +fn joinPosix(alloc: std.mem.Allocator, dir: []const u8, name: []const u8) ![]u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + const n = std.mem.trimStart(u8, name, "/"); + if (d.len == 0) return std.fmt.allocPrint(alloc, "/{s}", .{n}); + return std.fmt.allocPrint(alloc, "{s}/{s}", .{ d, n }); +} + +fn extensionPosix(name: []const u8) []const u8 { + const base = std.fs.path.basenamePosix(name); + const dot = std.mem.lastIndexOfScalar(u8, base, '.') orelse return ""; + if (dot == 0) return ""; + return base[dot..]; +} + +test "posix path helpers ignore the host separator" { + const a = testing.allocator; + const p1 = try joinPosix(a, "/etc/cron.d/", "backdoor"); + defer a.free(p1); + try testing.expectEqualStrings("/etc/cron.d/backdoor", p1); + const p2 = try joinPosix(a, "/", "x"); + defer a.free(p2); + try testing.expectEqualStrings("/x", p2); + try testing.expectEqualStrings(".sh", extensionPosix("/var/tmp/payload.sh")); + try testing.expectEqualStrings("", extensionPosix(".bashrc")); +} + +/// Absolute path of a created file: as given, else under the PARENT item, else +/// under the CWD record. +fn createdPath(alloc: std.mem.Allocator, ev: *const Event, name: []const u8) ![]u8 { + if (name.len > 0 and name[0] == '/') return alloc.dupe(u8, name); + for (ev.paths.items) |p| { + if (p.parent and p.name.items.len > 0 and p.name.items[0] == '/') { + return joinPosix(alloc, p.name.items, std.fs.path.basenamePosix(name)); + } + } + if (ev.cwd.items.len > 0) return joinPosix(alloc, ev.cwd.items, name); + return alloc.dupe(u8, name); +} + +pub const Peer = struct { + ip_buf: [64]u8 = undefined, + ip_len: usize = 0, + port: u16, + + pub fn ip(self: *const Peer) []const u8 { + return self.ip_buf[0..self.ip_len]; + } +}; + +/// `struct sockaddr` bytes in host order (little-endian on every supported +/// arch). AF_INET and AF_INET6 only; port 0 is skipped. +pub fn parseSockaddr(b: []const u8) ?Peer { + if (b.len < 2) return null; + const family = std.mem.readInt(u16, b[0..2], .little); + var p = Peer{ .port = 0 }; + var w: std.Io.Writer = .fixed(&p.ip_buf); + switch (family) { + 2 => { + if (b.len < 8) return null; + p.port = std.mem.readInt(u16, b[2..4], .big); + w.print("{d}.{d}.{d}.{d}", .{ b[4], b[5], b[6], b[7] }) catch return null; + }, + 10 => { + if (b.len < 24) return null; + p.port = std.mem.readInt(u16, b[2..4], .big); + const addr: [16]u8 = b[8..24].*; + const v4_mapped = std.mem.allEqual(u8, addr[0..10], 0) and addr[10] == 0xff and addr[11] == 0xff; + if (v4_mapped) { + w.print("{d}.{d}.{d}.{d}", .{ addr[12], addr[13], addr[14], addr[15] }) catch return null; + } else { + const unresolved = std.Io.net.Ip6Address.Unresolved{ .bytes = addr, .interface_name = null }; + w.print("{f}", .{unresolved}) catch return null; + } + }, + else => return null, + } + if (p.port == 0) return null; + p.ip_len = w.buffered().len; + return p; +} + +const Jw = std.json.Stringify; + +fn beginPayload(jw: *Jw, ev: *const Event, ctx: MapContext) !void { + try jw.beginObject(); + try jw.objectField("sensor"); + try jw.write(ctx.sensor); + try jw.objectField("record_id"); + try jw.write(ev.serial); + var buf: [24]u8 = undefined; + try jw.objectField("ts"); + try jw.write(entity.formatIso(&buf, ev.time100ns())); +} + +/// The acting process for connect and file events: entity from the table +/// when the pid is known, otherwise pid only. +fn actor(jw: *Jw, ev: *const Event, ctx: MapContext) !void { + try jw.objectField("process"); + try jw.beginObject(); + if (ctx.table) |t| if (t.lookup(ev.pid, "")) |id| { + try jw.objectField("entity_id"); + try jw.write(&id); + }; + try jw.objectField("pid"); + try jw.write(ev.pid); + if (ev.comm.items.len > 0) { + try jw.objectField("name"); + try jw.write(ev.comm.items); + } + if (ev.exe.items.len > 0) { + try jw.objectField("image"); + try jw.write(ev.exe.items); + } + try jw.objectField("user"); + try jw.beginObject(); + try jw.objectField("uid"); + try jw.write(ev.uid); + try jw.endObject(); + try jw.endObject(); +} + +/// Arguments joined with spaces, else the proctitle (NUL separated), else +/// comm. +fn commandLine(alloc: std.mem.Allocator, ev: *const Event) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(alloc); + if (ev.args.items.len > 0) { + for (ev.args.items, 0..) |a, i| { + if (i > 0) try out.append(alloc, ' '); + try out.appendSlice(alloc, a.items); + } + } else if (ev.proctitle.items.len > 0) { + try out.appendSlice(alloc, std.mem.trimEnd(u8, ev.proctitle.items, "\x00")); + for (out.items) |*c| if (c.* == 0) { + c.* = ' '; + }; + } else { + try out.appendSlice(alloc, ev.comm.items); + } + return out.toOwnedSlice(alloc); +} + +fn processStart(alloc: std.mem.Allocator, ev: *const Event, ctx: MapContext) ![]u8 { + const start = ctx.live_start_100ns orelse ev.time100ns(); + const id: ?entity.Id = if (ctx.table) |t| try t.observe(ev.pid, start, "") else null; + const parent_id: ?entity.Id = if (ctx.table) |t| (if (ev.ppid != 0) t.parentOf(ev.ppid, start) else null) else null; + const raw_cmd = try commandLine(alloc, ev); + defer alloc.free(raw_cmd); + const cmd = try privacy.sanitizeCommandLine(alloc, raw_cmd); + defer alloc.free(cmd); + const digest: ?[32]u8 = if (ctx.hashes) |h| (if (ev.exe.items.len > 0) h.get(ev.exe.items) else null) else null; + + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try beginPayload(&jw, ev, ctx); + try jw.objectField("process"); + try jw.beginObject(); + if (id) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(ev.pid); + var tbuf: [24]u8 = undefined; + try jw.objectField("start_time"); + try jw.write(entity.formatIso(&tbuf, start)); + try jw.objectField("name"); + try jw.write(ev.comm.items); + if (ev.exe.items.len > 0) { + try jw.objectField("image"); + try jw.write(ev.exe.items); + } + try jw.objectField("command_line"); + try jw.write(cmd); + if (ev.cwd.items.len > 0) { + try jw.objectField("cwd"); + try jw.write(ev.cwd.items); + } + try jw.objectField("user"); + try jw.beginObject(); + try jw.objectField("uid"); + try jw.write(ev.uid); + try jw.endObject(); + if (digest) |d| { + const hex = std.fmt.bytesToHex(d, .lower); + try jw.objectField("hashes"); + try jw.beginObject(); + try jw.objectField("sha256"); + try jw.write(&hex); + try jw.endObject(); + } + try jw.endObject(); + try jw.objectField("parent"); + try jw.beginObject(); + if (parent_id) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(ev.ppid); + try jw.endObject(); + try jw.endObject(); + return out.toOwnedSlice(); +} + +fn processExit(alloc: std.mem.Allocator, ev: *const Event, ctx: MapContext) ![]u8 { + var id: ?entity.Id = null; + if (ctx.table) |t| { + id = t.lookup(ev.pid, ""); + if (id != null) t.forget(ev.pid); + } + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try beginPayload(&jw, ev, ctx); + try jw.objectField("process"); + try jw.beginObject(); + if (id) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(ev.pid); + if (ev.comm.items.len > 0) { + try jw.objectField("name"); + try jw.write(ev.comm.items); + } + if (ev.exe.items.len > 0) { + try jw.objectField("image"); + try jw.write(ev.exe.items); + } + try jw.endObject(); + var tbuf: [24]u8 = undefined; + try jw.objectField("end_time"); + try jw.write(entity.formatIso(&tbuf, ev.time100ns())); + try jw.endObject(); + return out.toOwnedSlice(); +} + +fn networkConnect(alloc: std.mem.Allocator, ev: *const Event, ctx: MapContext, peer: Peer) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try beginPayload(&jw, ev, ctx); + try actor(&jw, ev, ctx); + try jw.objectField("network"); + try jw.beginObject(); + try jw.objectField("direction"); + try jw.write("outbound"); + try jw.objectField("dst_ip"); + try jw.write(peer.ip()); + try jw.objectField("dst_port"); + try jw.write(peer.port); + try jw.endObject(); + try jw.endObject(); + return out.toOwnedSlice(); +} + +fn fileCreate(alloc: std.mem.Allocator, ev: *const Event, ctx: MapContext, path: []const u8) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try beginPayload(&jw, ev, ctx); + try actor(&jw, ev, ctx); + try jw.objectField("file"); + try jw.beginObject(); + try jw.objectField("path"); + try jw.write(path); + const name = std.fs.path.basenamePosix(path); + try jw.objectField("name"); + try jw.write(name); + const ext = extensionPosix(name); + if (ext.len > 1) { + try jw.objectField("extension"); + try jw.write(ext[1..]); + } + try jw.endObject(); + try jw.endObject(); + return out.toOwnedSlice(); +} + +// --------------------------------------------------------------------------- +// Rule encoding (struct audit_rule_data), pure so it is tested everywhere + +pub const RuleSpec = union(enum) { + /// `-a always,exit -F arch= -S -k tawny` + syscalls: struct { arch: u32, numbers: []const u32 }, + /// `-w -p wa -k tawny` + watch_dir: []const u8, +}; + +/// `struct audit_rule_data` with its string buffer, little-endian. +pub fn encodeRule(alloc: std.mem.Allocator, spec: RuleSpec) ![]u8 { + const fixed = 4 * (3 + bitmask_words + 3 * max_fields + 1); + var strings: std.ArrayList(u8) = .empty; + defer strings.deinit(alloc); + var mask: [bitmask_words]u32 = @splat(0); + var fields: [max_fields]u32 = @splat(0); + var values: [max_fields]u32 = @splat(0); + var flags: [max_fields]u32 = @splat(0); + var n: usize = 0; + switch (spec) { + .syscalls => |s| { + for (s.numbers) |nr| mask[nr / 32] |= @as(u32, 1) << @intCast(nr % 32); + fields[n] = field_arch; + values[n] = s.arch; + flags[n] = op_equal; + n += 1; + }, + .watch_dir => |dir| { + mask = @splat(0xffffffff); + fields[n] = field_dir; + values[n] = @intCast(dir.len); + flags[n] = op_equal; + try strings.appendSlice(alloc, dir); + n += 1; + fields[n] = field_perm; + values[n] = perm_write | perm_attr; + flags[n] = op_equal; + n += 1; + }, + } + fields[n] = field_filterkey; + values[n] = rule_key.len; + flags[n] = op_equal; + try strings.appendSlice(alloc, rule_key); + n += 1; + + const out = try alloc.alloc(u8, fixed + strings.items.len); + var o: usize = 0; + const put = struct { + fn f(buf: []u8, at: *usize, v: u32) void { + std.mem.writeInt(u32, buf[at.*..][0..4], v, .little); + at.* += 4; + } + }.f; + put(out, &o, filter_exit); + put(out, &o, action_always); + put(out, &o, @intCast(n)); + for (mask) |m| put(out, &o, m); + for (fields) |v| put(out, &o, v); + for (values) |v| put(out, &o, v); + for (flags) |v| put(out, &o, v); + put(out, &o, @intCast(strings.items.len)); + @memcpy(out[o..], strings.items); + return out; +} + +/// Rules for the native architecture: exec, connect and exit_group, plus a +/// write watch per folder. +pub fn nativeRules(alloc: std.mem.Allocator, watch_dirs: []const []const u8) ![][]u8 { + var list: std.ArrayList([]u8) = .empty; + errdefer { + for (list.items) |r| alloc.free(r); + list.deinit(alloc); + } + const native: ?struct { u32, [4]u32 } = switch (builtin.target.cpu.arch) { + .x86_64 => .{ arch_x86_64, .{ 59, 322, 42, 231 } }, + .aarch64 => .{ arch_aarch64, .{ 221, 281, 203, 94 } }, + else => null, + }; + const nat = native orelse return error.UnsupportedArch; + try list.append(alloc, try encodeRule(alloc, .{ .syscalls = .{ .arch = nat[0], .numbers = &nat[1] } })); + for (watch_dirs) |d| { + if (d.len == 0 or d[0] != '/' or d.len > 1024) continue; + try list.append(alloc, try encodeRule(alloc, .{ .watch_dir = d })); + } + return list.toOwnedSlice(alloc); +} + +// --------------------------------------------------------------------------- +// Live netlink reader (Linux only) + +pub const Mode = enum { daemon, multicast }; + +/// errno from the last failed reader thread start, for health reasons. +pub var last_spawn_errno: u16 = 0; + +pub const OpenError = error{ + ThreadStartFailed, + /// No audit in this kernel, or not the initial namespaces (containers). + AuditUnavailable, + /// Neither CAP_AUDIT_CONTROL nor CAP_AUDIT_READ. + AccessDenied, + /// Another audit daemon (auditd) is registered. + DaemonPresent, + UnsupportedArch, + OutOfMemory, + SystemResources, +}; + +const Raw = struct { type: u16, bytes: []u8 }; + +/// Spin lock: the reader thread holds it for a list append only. +const SpinLock = struct { + held: std.atomic.Value(bool) = .init(false), + fn lock(self: *SpinLock) void { + while (self.held.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint(); + } + fn unlock(self: *SpinLock) void { + self.held.store(false, .release); + } +}; + +pub const Live = struct { + alloc: std.mem.Allocator, + fd: i32, + mode: Mode, + thread: ?std.c.pthread_t = null, + stop_flag: std.atomic.Value(bool) = .init(false), + lock: SpinLock = .{}, + queue: std.ArrayList(Raw) = .empty, + queued_bytes: usize = 0, + dropped: std.atomic.Value(u64) = .init(0), + received: std.atomic.Value(u64) = .init(0), + kernel_lost: u32 = 0, + rules: [][]u8 = &.{}, + restore_enabled: ?u32 = null, + /// Why registering as the audit daemon failed, in multicast mode. + daemon_error: ?OpenError = null, + seq: u32 = 1, + + const max_queue_records: usize = 65536; + const max_queue_bytes: usize = 32 * 1024 * 1024; + + /// Register as the audit daemon and load rules; if another daemon owns + /// audit, or CAP_AUDIT_CONTROL is missing, join the multicast group. + pub fn open(alloc: std.mem.Allocator, watch_dirs: []const []const u8, allow_daemon: bool) OpenError!*Live { + if (comptime builtin.target.os.tag != .linux) return error.AuditUnavailable; + const self = try alloc.create(Live); + errdefer alloc.destroy(self); + self.* = .{ .alloc = alloc, .fd = -1, .mode = .daemon }; + + var daemon_err: OpenError = error.AccessDenied; + if (allow_daemon) { + if (self.openDaemon(watch_dirs)) { + self.spawn() catch |err| { + // Unload our rules and unregister before giving up. The + // errdefer above frees self. + self.shutdownNoFree(); + return err; + }; + return self; + } else |err| daemon_err = err; + self.closeFd(); + } + self.openMulticast() catch |err| { + self.closeFd(); + return if (allow_daemon) daemon_err else err; + }; + self.mode = .multicast; + self.daemon_error = if (allow_daemon) daemon_err else null; + self.spawn() catch |err| { + self.shutdownNoFree(); + return err; + }; + return self; + } + + /// Start the reader thread. Calls pthread_create directly because + /// std.Thread.spawn treats EPERM and EINVAL as unreachable, and on the + /// CI runner, under setpriv with only the audit capabilities, it got one + /// of them and aborted the agent. Any failure here is reported so the + /// sensor falls back to polling instead of crashing. + fn spawn(self: *Live) OpenError!void { + const c = std.c; + var attr: c.pthread_attr_t = undefined; + if (c.pthread_attr_init(&attr) != .SUCCESS) return error.SystemResources; + defer _ = c.pthread_attr_destroy(&attr); + _ = c.pthread_attr_setstacksize(&attr, 256 * 1024); + var handle: c.pthread_t = undefined; + var rc = c.pthread_create(&handle, &attr, readerEntry, @ptrCast(self)); + // EINVAL here means the attributes were refused (seen on the CI + // runner). Retry with libc defaults before giving up. + if (rc == .INVAL) rc = c.pthread_create(&handle, null, readerEntry, @ptrCast(self)); + if (rc != .SUCCESS) { + last_spawn_errno = @intFromEnum(rc); + std.log.warn("audit: reader thread not started: {s}", .{@tagName(rc)}); + return error.ThreadStartFailed; + } + self.thread = handle; + } + + fn readerEntry(arg: ?*anyopaque) callconv(.c) ?*anyopaque { + const self: *Live = @ptrCast(@alignCast(arg)); + self.readerMain(); + return null; + } + + fn closeFd(self: *Live) void { + if (self.fd >= 0) _ = std.os.linux.close(self.fd); + self.fd = -1; + } + + fn socketOpen(self: *Live, groups: u32) OpenError!void { + const linux = std.os.linux; + const rc = linux.socket(linux.AF.NETLINK, linux.SOCK.RAW | linux.SOCK.CLOEXEC, netlink_audit); + switch (linux.errno(rc)) { + .SUCCESS => {}, + .ACCES, .PERM => return error.AccessDenied, + .PROTONOSUPPORT, .AFNOSUPPORT => return error.AuditUnavailable, + .NOMEM, .NOBUFS, .MFILE, .NFILE => return error.SystemResources, + else => return error.AuditUnavailable, + } + self.fd = @intCast(rc); + // 1 s receive timeout so the reader notices stop. + const tv = linux.timeval{ .sec = 1, .usec = 0 }; + _ = linux.setsockopt(self.fd, linux.SOL.SOCKET, linux.SO.RCVTIMEO, std.mem.asBytes(&tv), @sizeOf(linux.timeval)); + const rcvbuf: i32 = 4 * 1024 * 1024; + _ = linux.setsockopt(self.fd, linux.SOL.SOCKET, linux.SO.RCVBUF, std.mem.asBytes(&rcvbuf), @sizeOf(i32)); + var addr = linux.sockaddr.nl{ .pid = 0, .groups = groups }; + switch (linux.errno(linux.bind(self.fd, @ptrCast(&addr), @sizeOf(linux.sockaddr.nl)))) { + .SUCCESS => {}, + .PERM, .ACCES => return error.AccessDenied, + else => return error.AuditUnavailable, + } + } + + fn openMulticast(self: *Live) OpenError!void { + try self.socketOpen(@as(u32, 1) << @intCast(nlgrp_readlog - 1)); + } + + const Status = extern struct { + mask: u32 = 0, + enabled: u32 = 0, + failure: u32 = 0, + pid: u32 = 0, + rate_limit: u32 = 0, + backlog_limit: u32 = 0, + lost: u32 = 0, + backlog: u32 = 0, + feature_bitmap: u32 = 0, + backlog_wait_time: u32 = 0, + backlog_wait_time_actual: u32 = 0, + }; + + fn openDaemon(self: *Live, watch_dirs: []const []const u8) OpenError!void { + try self.socketOpen(0); + // AUDIT_GET tells us whether another daemon is registered. + const status = try self.getStatus(); + if (status.pid != 0 and status.pid != @as(u32, @intCast(std.os.linux.getpid())) and pidAlive(status.pid)) { + return error.DaemonPresent; + } + if (status.enabled == 2) return error.AccessDenied; // rules locked + self.rules = nativeRules(self.alloc, watch_dirs) catch |err| + return if (err == error.OutOfMemory) error.OutOfMemory else error.UnsupportedArch; + // Remove rules a crashed run left behind, then load ours. + for (self.rules) |r| self.request(msg.del_rule, r) catch {}; + // The syscall rule (first) must load. A watch rule for a folder that + // is missing or refused is dropped and logged, not fatal. + for (self.rules, 0..) |*r, i| { + self.request(msg.add_rule, r.*) catch |err| switch (err) { + error.DaemonPresent => {}, // EEXIST: the rule is already loaded + else => { + if (i == 0) { + self.unloadRules(); + return err; + } + std.log.warn("audit: watch rule {d} not loaded: {s}", .{ i, @errorName(err) }); + self.alloc.free(r.*); + r.* = &.{}; + }, + }; + } + var set = Status{ .mask = status_pid | status_backlog_limit, .pid = @intCast(std.os.linux.getpid()), .backlog_limit = @max(status.backlog_limit, 8192) }; + if (status.enabled == 0) { + set.mask |= status_enabled; + set.enabled = 1; + self.restore_enabled = 0; + } + self.request(msg.set, std.mem.asBytes(&set)) catch |err| { + self.unloadRules(); + return err; + }; + self.kernel_lost = status.lost; + } + + fn unloadRules(self: *Live) void { + for (self.rules) |r| if (r.len > 0) self.sendOnly(msg.del_rule, r); + for (self.rules) |r| self.alloc.free(r); + if (self.rules.len > 0) self.alloc.free(self.rules); + self.rules = &.{}; + } + + fn sendOnly(self: *Live, t: u16, payload: []const u8) void { + _ = self.send(t, payload, false) catch {}; + } + + fn send(self: *Live, t: u16, payload: []const u8, ack: bool) OpenError!u32 { + const linux = std.os.linux; + const hdr_len = @sizeOf(linux.nlmsghdr); + var buf: [16 * 1024]u8 align(4) = undefined; + const total = hdr_len + payload.len; + if (total > buf.len) return error.SystemResources; + self.seq += 1; + const hdr = linux.nlmsghdr{ + .len = @intCast(total), + .type = @enumFromInt(t), + .flags = linux.NLM_F_REQUEST | (if (ack) @as(u16, linux.NLM_F_ACK) else 0), + .seq = self.seq, + .pid = 0, + }; + @memcpy(buf[0..hdr_len], std.mem.asBytes(&hdr)); + @memcpy(buf[hdr_len..total], payload); + var addr = linux.sockaddr.nl{ .pid = 0, .groups = 0 }; + const rc = linux.sendto(self.fd, &buf, total, 0, @ptrCast(&addr), @sizeOf(linux.sockaddr.nl)); + switch (linux.errno(rc)) { + .SUCCESS => return self.seq, + .PERM, .ACCES => return error.AccessDenied, + else => return error.AuditUnavailable, + } + } + + /// Send and wait for the kernel's ack. Records that arrive meanwhile go + /// to the queue. + fn request(self: *Live, t: u16, payload: []const u8) OpenError!void { + const seq = try self.send(t, payload, true); + var st: ?Status = null; + return self.awaitReply(seq, false, &st); + } + + fn getStatus(self: *Live) OpenError!Status { + const seq = try self.send(msg.get, "", true); + var st: ?Status = null; + try self.awaitReply(seq, true, &st); + return st orelse error.AuditUnavailable; + } + + fn awaitReply(self: *Live, seq: u32, want_status: bool, status: *?Status) OpenError!void { + const linux = std.os.linux; + var buf: [9000]u8 align(4) = undefined; + var acked = false; + var tries: usize = 0; + while (tries < 64) : (tries += 1) { + if (acked and (!want_status or status.* != null)) return; + const rc = linux.recvfrom(self.fd, &buf, buf.len, 0, null, null); + switch (linux.errno(rc)) { + .SUCCESS => {}, + .INTR => continue, + .AGAIN => return error.AuditUnavailable, // timed out + else => return error.AuditUnavailable, + } + var off: usize = 0; + const n: usize = rc; + while (off + @sizeOf(linux.nlmsghdr) <= n) { + const hdr: *align(1) const linux.nlmsghdr = @ptrCast(buf[off..].ptr); + const len: usize = @max(hdr.len, @sizeOf(linux.nlmsghdr)); + const end = @min(off + len, n); + const body = buf[off + @sizeOf(linux.nlmsghdr) .. end]; + const t: u16 = @intFromEnum(hdr.type); + if (t == 2 and hdr.seq == seq) { // NLMSG_ERROR + const code: i32 = if (body.len >= 4) std.mem.readInt(i32, body[0..4], .little) else 0; + if (code == 0) { + acked = true; + } else if (code == -1 or code == -13) { + return error.AccessDenied; + } else if (code == -17) { + return error.DaemonPresent; // EEXIST: another daemon + } else { + return error.AuditUnavailable; + } + } else if (t == msg.get and want_status) { + var s = Status{}; + const take = @min(body.len, @sizeOf(Status)); + @memcpy(std.mem.asBytes(&s)[0..take], body[0..take]); + status.* = s; + } else if (t >= 1100) { + self.push(t, body); + } + off += std.mem.alignForward(usize, len, 4); + } + } + return error.AuditUnavailable; + } + + fn push(self: *Live, t: u16, body: []const u8) void { + _ = self.received.fetchAdd(1, .monotonic); + self.lock.lock(); + defer self.lock.unlock(); + if (self.queue.items.len >= max_queue_records or self.queued_bytes + body.len > max_queue_bytes) { + _ = self.dropped.fetchAdd(1, .monotonic); + return; + } + const copy = self.alloc.dupe(u8, body) catch { + _ = self.dropped.fetchAdd(1, .monotonic); + return; + }; + self.queue.append(self.alloc, .{ .type = t, .bytes = copy }) catch { + self.alloc.free(copy); + _ = self.dropped.fetchAdd(1, .monotonic); + return; + }; + self.queued_bytes += copy.len; + } + + fn readerMain(self: *Live) void { + const linux = std.os.linux; + var buf: [9000]u8 align(4) = undefined; + while (!self.stop_flag.load(.acquire)) { + const rc = linux.recvfrom(self.fd, &buf, buf.len, 0, null, null); + switch (linux.errno(rc)) { + .SUCCESS => {}, + .NOBUFS => { + _ = self.dropped.fetchAdd(1, .monotonic); + continue; + }, + .AGAIN, .INTR => continue, + else => return, + } + const n: usize = rc; + var off: usize = 0; + while (off + @sizeOf(linux.nlmsghdr) <= n) { + const hdr: *align(1) const linux.nlmsghdr = @ptrCast(buf[off..].ptr); + const len: usize = @max(hdr.len, @sizeOf(linux.nlmsghdr)); + const end = @min(off + len, n); + const t: u16 = @intFromEnum(hdr.type); + if (t >= 1100) self.push(t, buf[off + @sizeOf(linux.nlmsghdr) .. end]); + off += std.mem.alignForward(usize, len, 4); + } + } + } + + /// Move queued records into the assembler. + pub fn drain(self: *Live, asmb: *Assembler) !void { + self.lock.lock(); + var taken = self.queue; + self.queue = .empty; + self.queued_bytes = 0; + self.lock.unlock(); + defer { + for (taken.items) |r| self.alloc.free(r.bytes); + taken.deinit(self.alloc); + } + for (taken.items) |r| { + if (parseNetlink(r.type, r.bytes)) |rec| try asmb.feed(rec); + } + } + + pub fn close(self: *Live) void { + self.shutdownNoFree(); + self.alloc.destroy(self); + } + + /// Stop the reader, unload rules, unregister and close the socket, + /// without freeing self. + fn shutdownNoFree(self: *Live) void { + self.stop_flag.store(true, .release); + if (self.thread) |t| _ = std.c.pthread_join(t, null); + self.thread = null; + if (self.mode == .daemon and self.fd >= 0) { + self.unloadRules(); + var set = Status{ .mask = status_pid, .pid = 0 }; + if (self.restore_enabled) |v| { + set.mask |= status_enabled; + set.enabled = v; + } + self.sendOnly(msg.set, std.mem.asBytes(&set)); + } else { + self.unloadRules(); + } + self.closeFd(); + for (self.queue.items) |r| self.alloc.free(r.bytes); + self.queue.deinit(self.alloc); + self.queue = .empty; + } +}; + +fn pidAlive(pid: u32) bool { + if (comptime builtin.target.os.tag != .linux) return false; + var buf: [32]u8 = undefined; + const path = std.fmt.bufPrint(&buf, "/proc/{d}", .{pid}) catch return false; + var d = std.Io.Dir.openDirAbsolute(iox.current(), path, .{}) catch |err| return err != error.FileNotFound; + d.close(iox.current()); + return true; +} + +// --------------------------------------------------------------------------- +// Tail of a growing text file (auditd log, Tetragon export) + +pub const Tail = struct { + alloc: std.mem.Allocator, + path: []const u8, + offset: u64 = 0, + inode: u64 = 0, + partial: std.ArrayList(u8) = .empty, + /// Bytes read per poll at most. + max_chunk: usize = 4 * 1024 * 1024, + + /// Start at the end of the file so old history is not replayed. + pub fn open(alloc: std.mem.Allocator, path: []const u8, from_end: bool) !Tail { + const io = iox.current(); + var f = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer f.close(io); + const st = try f.stat(io); + return .{ .alloc = alloc, .path = path, .offset = if (from_end) st.size else 0, .inode = @intCast(st.inode) }; + } + + pub fn deinit(self: *Tail) void { + self.partial.deinit(self.alloc); + } + + /// Complete lines appended since the last poll, or null. A rotated or + /// truncated file is read again from the start. + pub fn poll(self: *Tail) !?[]u8 { + const io = iox.current(); + var f = try std.Io.Dir.cwd().openFile(io, self.path, .{}); + defer f.close(io); + const st = try f.stat(io); + if (@as(u64, @intCast(st.inode)) != self.inode or st.size < self.offset) { + self.inode = @intCast(st.inode); + self.offset = 0; + self.partial.clearRetainingCapacity(); + } + if (st.size == self.offset) return null; + const want: usize = @intCast(@min(st.size - self.offset, self.max_chunk)); + const start = self.partial.items.len; + try self.partial.ensureUnusedCapacity(self.alloc, want); + const dest = self.partial.unusedCapacitySlice()[0..want]; + const n = try f.readPositionalAll(io, dest, self.offset); + self.partial.items.len += n; + self.offset += n; + _ = start; + const last_nl = std.mem.lastIndexOfScalar(u8, self.partial.items, '\n') orelse { + if (self.partial.items.len > self.max_chunk) self.partial.clearRetainingCapacity(); + return null; + }; + const lines = try self.alloc.dupe(u8, self.partial.items[0 .. last_nl + 1]); + const rest = self.partial.items.len - (last_nl + 1); + std.mem.copyForwards(u8, self.partial.items[0..rest], self.partial.items[last_nl + 1 ..]); + self.partial.items.len = rest; + return lines; + } +}; + +// --------------------------------------------------------------------------- +// Tests + +const testing = std.testing; +const samples = struct { + const netlink = @embedFile("testdata/netlink_exec_connect.txt"); + const log = @embedFile("testdata/audit.log"); +}; + +/// Captured netlink records, one per line: ` `. +fn feedNetlinkCapture(asmb: *Assembler, text: []const u8) !void { + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + const sp = std.mem.indexOfScalar(u8, line, ' ') orelse continue; + const t = std.fmt.parseInt(u16, line[0..sp], 10) catch continue; + if (parseNetlink(t, line[sp + 1 ..])) |rec| try asmb.feed(rec); + } +} + +fn mapAll(alloc: std.mem.Allocator, asmb: *Assembler, ctx: MapContext) !std.ArrayList(Mapped) { + var out: std.ArrayList(Mapped) = .empty; + errdefer { + for (out.items) |m| alloc.free(m.payload); + out.deinit(alloc); + } + const events = try asmb.take(); + defer { + for (events) |e| asmb.destroy(e); + alloc.free(events); + } + for (events) |e| if (try map(alloc, e, ctx)) |m| try out.append(alloc, m); + return out; +} + +fn freeMapped(alloc: std.mem.Allocator, list: *std.ArrayList(Mapped)) void { + for (list.items) |m| alloc.free(m.payload); + list.deinit(alloc); +} + +test "kernel constants match linux/audit.h and the syscall tables" { + // include/uapi/linux/audit.h + try testing.expectEqual(@as(u16, 1000), msg.get); + try testing.expectEqual(@as(u16, 1001), msg.set); + try testing.expectEqual(@as(u16, 1011), msg.add_rule); + try testing.expectEqual(@as(u16, 1012), msg.del_rule); + try testing.expectEqual(@as(u16, 1300), msg.syscall); + try testing.expectEqual(@as(u16, 1302), msg.path); + try testing.expectEqual(@as(u16, 1306), msg.sockaddr); + try testing.expectEqual(@as(u16, 1307), msg.cwd); + try testing.expectEqual(@as(u16, 1309), msg.execve); + try testing.expectEqual(@as(u16, 1320), msg.eoe); + try testing.expectEqual(@as(u16, 1327), msg.proctitle); + try testing.expectEqual(@as(u32, 0x04), filter_exit); + try testing.expectEqual(@as(u32, 2), action_always); + try testing.expectEqual(@as(u32, 11), field_arch); + try testing.expectEqual(@as(u32, 106), field_perm); + try testing.expectEqual(@as(u32, 107), field_dir); + try testing.expectEqual(@as(u32, 210), field_filterkey); + try testing.expectEqual(@as(u32, 0x40000000), op_equal); + try testing.expectEqual(@as(u32, 0xC000003E), arch_x86_64); + try testing.expectEqual(@as(u32, 0xC00000B7), arch_aarch64); + // Netlink family and the std library agree. (std.os.linux.AUDIT.ARCH does + // not compile in Zig 0.17, so the arch values are pinned above.) + try testing.expectEqual(@as(u32, std.os.linux.NETLINK.AUDIT), netlink_audit); + // Syscall numbers in syscallKind and nativeRules. + const X64 = std.os.linux.syscalls.X64; + const A64 = std.os.linux.syscalls.Arm64; + try testing.expectEqual(@as(usize, 59), @intFromEnum(X64.execve)); + try testing.expectEqual(@as(usize, 322), @intFromEnum(X64.execveat)); + try testing.expectEqual(@as(usize, 42), @intFromEnum(X64.connect)); + try testing.expectEqual(@as(usize, 231), @intFromEnum(X64.exit_group)); + try testing.expectEqual(@as(usize, 221), @intFromEnum(A64.execve)); + try testing.expectEqual(@as(usize, 281), @intFromEnum(A64.execveat)); + try testing.expectEqual(@as(usize, 203), @intFromEnum(A64.connect)); + try testing.expectEqual(@as(usize, 94), @intFromEnum(A64.exit_group)); +} + +test "record headers parse from netlink and the auditd log" { + const r = parseNetlink(1300, "audit(1731200000.123:4567): arch=c000003e syscall=59\x00").?; + try testing.expectEqual(@as(u64, 1731200000), r.sec); + try testing.expectEqual(@as(u32, 123), r.ms); + try testing.expectEqual(@as(u64, 4567), r.serial); + try testing.expectEqualStrings("arch=c000003e syscall=59", r.body); + const l = parseLogLine("node=web1 type=CWD msg=audit(1731200000.123:4567): cwd=\"/tmp\"\x1dEXTRA=1").?; + try testing.expectEqual(msg.cwd, l.type); + try testing.expectEqualStrings("cwd=\"/tmp\"", l.body); + try testing.expect(parseLogLine("type=USER_LOGIN msg=audit(1.2:3): pid=1") == null); + try testing.expect(parseNetlink(1300, "garbage") == null); + try testing.expect(parseNetlink(1300, "audit(1:2.3): x") == null); +} + +test "field values: quoted, bare hex and null" { + const alloc = testing.allocator; + var it = FieldIter{ .s = "comm=\"ls\" exe=2F746D702F6120622F78 name=(null) key=\"tawny\" bare" }; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(alloc); + const comm = it.next().?; + try appendString(alloc, &out, comm, 100); + try testing.expectEqualStrings("ls", out.items); + out.clearRetainingCapacity(); + try appendString(alloc, &out, it.next().?, 100); + try testing.expectEqualStrings("/tmp/a b/x", out.items); + out.clearRetainingCapacity(); + try appendString(alloc, &out, it.next().?, 100); + try testing.expectEqualStrings("", out.items); + try testing.expectEqualStrings("key", it.next().?.key); + try testing.expectEqualStrings("bare", it.next().?.key); + try testing.expect(it.next() == null); +} + +test "sockaddr: ipv4, ipv6, v4-mapped, unix and port 0" { + var buf: [64]u8 = undefined; + const v4 = try std.fmt.hexToBytes(&buf, "020001BBCB00710A0000000000000000"); + const p4 = parseSockaddr(v4).?; + try testing.expectEqualStrings("203.0.113.10", p4.ip()); + try testing.expectEqual(@as(u16, 443), p4.port); + const v6 = try std.fmt.hexToBytes(&buf, "0A0000500000000020010DB8000000000000000000000001" ++ "00000000"); + const p6 = parseSockaddr(v6).?; + try testing.expectEqualStrings("2001:db8::1", p6.ip()); + try testing.expectEqual(@as(u16, 80), p6.port); + const mapped = try std.fmt.hexToBytes(&buf, "0A00003500000000" ++ "00000000000000000000FFFF08080808" ++ "00000000"); + try testing.expectEqualStrings("8.8.8.8", parseSockaddr(mapped).?.ip()); + try testing.expect(parseSockaddr(try std.fmt.hexToBytes(&buf, "01002F746D70")) == null); + try testing.expect(parseSockaddr(try std.fmt.hexToBytes(&buf, "02000000C0A80101")) == null); +} + +test "netlink capture joins by serial and maps to v2 events with entity ids" { + const alloc = testing.allocator; + var table = entity.Table.init(alloc, "0f8fad5b-d9cb-469f-a165-70867728950e", "3c1c4b5e-6d2a-4f0e-9b7a-2d1e5f6a7b8c", 64); + defer table.deinit(); + // The parent shell is already in the table, as the poller's first pass + // would leave it. + _ = try table.observe(4100, 1731199000 * entity.ticks_per_second, ""); + + var asmb = Assembler.init(alloc, false); + defer asmb.deinit(); + try feedNetlinkCapture(&asmb, samples.netlink); + var got = try mapAll(alloc, &asmb, .{ .table = &table }); + defer freeMapped(alloc, &got); + + try testing.expectEqual(@as(usize, 4), got.items.len); + try testing.expectEqualStrings("process_start", got.items[0].event_type); + try testing.expectEqualStrings("network_connect", got.items[1].event_type); + try testing.expectEqualStrings("network_connect", got.items[2].event_type); + try testing.expectEqualStrings("process_exit", got.items[3].event_type); + for (got.items) |m| try @import("../../schema_check.zig").expectValid(alloc, m.event_type, m.payload); + + const start = got.items[0].payload; + const child_id = table.idFor(4242, 1731200000 * entity.ticks_per_second + 123 * entity.ticks_per_ms); + const parent_id = table.idFor(4100, 1731199000 * entity.ticks_per_second); + try testing.expect(std.mem.indexOf(u8, start, &child_id) != null); + try testing.expect(std.mem.indexOf(u8, start, &parent_id) != null); + try testing.expect(std.mem.indexOf(u8, start, "\"command_line\":\"curl -s https://example.com/a b\"") != null); + try testing.expect(std.mem.indexOf(u8, start, "\"cwd\":\"/home/alice\"") != null); + try testing.expect(std.mem.indexOf(u8, start, "\"image\":\"/usr/bin/curl\"") != null); + try testing.expect(std.mem.indexOf(u8, start, "\"record_id\":4567") != null); + + // Owning process on connect, including a non-blocking EINPROGRESS one. + try testing.expect(std.mem.indexOf(u8, got.items[1].payload, &child_id) != null); + try testing.expect(std.mem.indexOf(u8, got.items[1].payload, "\"dst_ip\":\"93.184.215.14\",\"dst_port\":443") != null); + try testing.expect(std.mem.indexOf(u8, got.items[2].payload, "\"dst_ip\":\"2001:db8::10\",\"dst_port\":443") != null); + try testing.expect(std.mem.indexOf(u8, got.items[3].payload, &child_id) != null); + // Exit forgets the pid. + try testing.expect(table.lookup(4242, "") == null); +} + +test "auditd log lines join without EOE and map exec, connect, create, exit" { + const alloc = testing.allocator; + var table = entity.Table.init(alloc, entity.nil_uuid, entity.nil_uuid, 64); + defer table.deinit(); + var asmb = Assembler.init(alloc, true); + defer asmb.deinit(); + try feedLog(&asmb, samples.log); + try asmb.completeAll(); + var got = try mapAll(alloc, &asmb, .{ .table = &table }); + defer freeMapped(alloc, &got); + + const want = [_][]const u8{ "process_start", "process_start", "network_connect", "file_create", "file_create", "process_exit" }; + try testing.expectEqual(want.len, got.items.len); + for (want, got.items) |w, m| { + try testing.expectEqualStrings(w, m.event_type); + try @import("../../schema_check.zig").expectValid(alloc, m.event_type, m.payload); + } + // Long argument split in chunks, hex-encoded argument with a space. + try testing.expect(std.mem.indexOf(u8, got.items[0].payload, "\"command_line\":\"python3 -c print('hello world')\"") != null); + // execveat with only a PROCTITLE. + try testing.expect(std.mem.indexOf(u8, got.items[1].payload, "\"command_line\":\"sh -c id\"") != null); + // Relative name under the PARENT item, and under the CWD. + try testing.expect(std.mem.indexOf(u8, got.items[3].payload, "\"path\":\"/etc/cron.d/backdoor\",\"name\":\"backdoor\"") != null); + try testing.expect(std.mem.indexOf(u8, got.items[4].payload, "\"path\":\"/var/tmp/x/payload.sh\",\"name\":\"payload.sh\",\"extension\":\"sh\"") != null); +} + +test "failed exec, refused connect and unix sockets are not reported" { + const alloc = testing.allocator; + var asmb = Assembler.init(alloc, false); + defer asmb.deinit(); + const text = + \\1300 audit(1731200100.000:9001): arch=c000003e syscall=59 success=no exit=-2 ppid=1 pid=50 uid=0 comm="sh" exe="/usr/bin/sh" + \\1320 audit(1731200100.000:9001): + \\1300 audit(1731200100.000:9002): arch=c000003e syscall=42 success=no exit=-111 ppid=1 pid=51 uid=0 comm="nc" exe="/usr/bin/nc" + \\1306 audit(1731200100.000:9002): saddr=020001BBCB00710A0000000000000000 + \\1320 audit(1731200100.000:9002): + \\1300 audit(1731200100.000:9003): arch=c000003e syscall=42 success=yes exit=0 ppid=1 pid=52 uid=0 comm="ls" exe="/usr/bin/ls" + \\1306 audit(1731200100.000:9003): saddr=01002F72756E2F6E7363642F736F636B6574 + \\1320 audit(1731200100.000:9003): + ; + try feedNetlinkCapture(&asmb, text); + var got = try mapAll(alloc, &asmb, .{}); + defer freeMapped(alloc, &got); + try testing.expectEqual(@as(usize, 0), got.items.len); +} + +test "assembler bounds pending events and flushes stale ones" { + const alloc = testing.allocator; + var asmb = Assembler.init(alloc, false); + defer asmb.deinit(); + var i: u64 = 0; + while (i < Assembler.max_pending + 5) : (i += 1) { + try asmb.feed(.{ .type = msg.syscall, .sec = 100 + i, .ms = 0, .serial = i, .body = "arch=c000003e syscall=231 pid=7" }); + } + try testing.expectEqual(@as(u64, 5), asmb.evicted); + try asmb.flushOlderThan(100 + 10); + try testing.expectEqual(@as(usize, Assembler.max_pending - 5), asmb.pending.count()); + const done = try asmb.take(); + defer { + for (done) |e| asmb.destroy(e); + alloc.free(done); + } + try testing.expectEqual(@as(usize, 10), done.len); + try testing.expectEqual(Kind.exit_group, done[0].kind().?); +} + +test "audit rule encoding matches struct audit_rule_data" { + const alloc = testing.allocator; + const r = try encodeRule(alloc, .{ .syscalls = .{ .arch = arch_x86_64, .numbers = &.{ 59, 42 } } }); + defer alloc.free(r); + const fixed = 4 * (3 + 64 + 3 * 64 + 1); + try testing.expectEqual(@as(usize, fixed + rule_key.len), r.len); + const word = struct { + fn at(b: []const u8, i: usize) u32 { + return std.mem.readInt(u32, b[i * 4 ..][0..4], .little); + } + }.at; + try testing.expectEqual(filter_exit, word(r, 0)); + try testing.expectEqual(action_always, word(r, 1)); + try testing.expectEqual(@as(u32, 2), word(r, 2)); + // mask[1] bit 27 (59) and mask[1] bit 10 (42). + try testing.expectEqual((@as(u32, 1) << 27) | (@as(u32, 1) << 10), word(r, 3 + 1)); + try testing.expectEqual(field_arch, word(r, 3 + 64)); + try testing.expectEqual(field_filterkey, word(r, 3 + 64 + 1)); + try testing.expectEqual(arch_x86_64, word(r, 3 + 128)); + try testing.expectEqual(@as(u32, rule_key.len), word(r, 3 + 128 + 1)); + try testing.expectEqual(op_equal, word(r, 3 + 192)); + try testing.expectEqual(@as(u32, rule_key.len), word(r, 3 + 256)); + try testing.expectEqualStrings(rule_key, r[fixed..]); + + const w = try encodeRule(alloc, .{ .watch_dir = "/etc/cron.d" }); + defer alloc.free(w); + try testing.expectEqual(@as(u32, 3), word(w, 2)); + try testing.expectEqual(@as(u32, 0xffffffff), word(w, 3)); + try testing.expectEqualStrings("/etc/cron.dtawny", w[fixed..]); +} + +test "tail returns complete lines and follows truncation" { + const alloc = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = testing.io; + const rel = try std.fs.path.join(alloc, &.{ ".zig-cache", "tmp", &tmp.sub_path, "audit.log" }); + defer alloc.free(rel); + { + var f = try tmp.dir.createFile(io, "audit.log", .{}); + defer f.close(io); + try f.writePositionalAll(io, "old line\n", 0); + } + var t = try Tail.open(alloc, rel, true); + defer t.deinit(); + try testing.expect((try t.poll()) == null); + { + var f = try tmp.dir.openFile(io, "audit.log", .{ .mode = .read_write }); + defer f.close(io); + try f.writePositionalAll(io, "one\ntw", 9); + } + const a = (try t.poll()).?; + defer alloc.free(a); + try testing.expectEqualStrings("one\n", a); + { + var f = try tmp.dir.openFile(io, "audit.log", .{ .mode = .read_write }); + defer f.close(io); + try f.writePositionalAll(io, "o\n", 15); + } + const b = (try t.poll()).?; + defer alloc.free(b); + try testing.expectEqualStrings("two\n", b); + { + var f = try tmp.dir.createFile(io, "audit.log", .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, "new\n", 0); + } + const c = (try t.poll()).?; + defer alloc.free(c); + try testing.expectEqualStrings("new\n", c); +} diff --git a/agent/src/platform/linux/testdata/README.md b/agent/src/platform/linux/testdata/README.md new file mode 100644 index 0000000..81d77ac --- /dev/null +++ b/agent/src/platform/linux/testdata/README.md @@ -0,0 +1,15 @@ +# Linux audit samples + +Records in the shape the kernel emits them, used by the parsing and mapping +tests in `../audit.zig` and `../tetragon.zig`. Hosts, users and addresses are +made up (documentation ranges); nothing here comes from a real machine. + +- `netlink_exec_connect.txt`: netlink records as ` `, + one per line, as the agent reads them from `NETLINK_AUDIT`: an `execve` of + `curl`, an IPv4 `connect`, a non-blocking IPv6 `connect` (`EINPROGRESS`), + `exit_group`, and an unrelated AppArmor record. +- `audit.log`: auditd log lines (no `EOE` records, some with `node=` and the + enriched `\x1d` suffix): a long split argument, `execveat` with only a + `PROCTITLE`, a `connect`, two file creations (one under a `PARENT` path, + one under the `CWD`) and an `exit_group`. +- `tetragon.jsonl`: Tetragon JSON export lines. diff --git a/agent/src/platform/linux/testdata/audit.log b/agent/src/platform/linux/testdata/audit.log new file mode 100644 index 0000000..693ca4d --- /dev/null +++ b/agent/src/platform/linux/testdata/audit.log @@ -0,0 +1,23 @@ +node=web1 type=SYSCALL msg=audit(1731200100.010:5001): arch=c000003e syscall=59 success=yes exit=0 a0=3 a1=7ffd a2=0 a3=0 items=1 ppid=4100 pid=5001 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="python3" exe="/usr/bin/python3.12" subj=unconfined key="tawny"ARCH=x86_64 SYSCALL=execve UID="alice" +node=web1 type=EXECVE msg=audit(1731200100.010:5001): argc=3 a0="python3" a1="-c" a2_len=40 a2[0]=7072696E74282768656C a2[1]=6C6F20776F726C642729 +node=web1 type=CWD msg=audit(1731200100.010:5001): cwd="/home/alice" +node=web1 type=PATH msg=audit(1731200100.010:5001): item=0 name="/usr/bin/python3" inode=12 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL +node=web1 type=PROCTITLE msg=audit(1731200100.010:5001): proctitle=707974686F6E33002D63007072696E74282768656C6C6F20776F726C642729 +type=SYSCALL msg=audit(1731200100.020:5002): arch=c000003e syscall=322 success=yes exit=0 a0=3 a1=7ffd a2=0 a3=0 items=0 ppid=4100 pid=5002 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="sh" exe="/usr/bin/dash" subj=unconfined key="tawny" +type=CWD msg=audit(1731200100.020:5002): cwd="/tmp" +type=PROCTITLE msg=audit(1731200100.020:5002): proctitle=7368002D63006964 +type=SYSCALL msg=audit(1731200100.030:5003): arch=c000003e syscall=42 success=yes exit=0 a0=3 a1=7ffd a2=0 a3=0 items=0 ppid=4100 pid=5001 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="python3" exe="/usr/bin/python3.12" subj=unconfined key="tawny" +type=SOCKADDR msg=audit(1731200100.030:5003): saddr=020001BBCB00710A0000000000000000SADDR={ fam=inet laddr=203.0.113.10 lport=443 } +type=PROCTITLE msg=audit(1731200100.030:5003): proctitle=707974686F6E33 +type=SYSCALL msg=audit(1731200100.040:5004): arch=c000003e syscall=257 success=yes exit=3 a0=3 a1=7ffd a2=0 a3=0 items=2 ppid=4100 pid=5003 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="tee" exe="/usr/bin/tee" subj=unconfined key="tawny" +type=CWD msg=audit(1731200100.040:5004): cwd="/home/alice" +type=PATH msg=audit(1731200100.040:5004): item=0 name="/etc/cron.d/" inode=40 dev=08:01 mode=040755 ouid=0 ogid=0 rdev=00:00 nametype=PARENT +type=PATH msg=audit(1731200100.040:5004): item=1 name="backdoor" inode=41 dev=08:01 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=CREATE +type=PROCTITLE msg=audit(1731200100.040:5004): proctitle=746565002F6574632F63726F6E2E642F6261636B646F6F72 +type=SYSCALL msg=audit(1731200100.050:5005): arch=c000003e syscall=257 success=yes exit=3 a0=3 a1=7ffd a2=0 a3=0 items=2 ppid=4100 pid=5004 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="cp" exe="/usr/bin/cp" subj=unconfined key="tawny" +type=CWD msg=audit(1731200100.050:5005): cwd="/var/tmp/x" +type=PATH msg=audit(1731200100.050:5005): item=0 name="." inode=50 dev=08:01 mode=040755 ouid=1000 ogid=1000 rdev=00:00 nametype=PARENT +type=PATH msg=audit(1731200100.050:5005): item=1 name="payload.sh" inode=51 dev=08:01 mode=0100644 ouid=1000 ogid=1000 rdev=00:00 nametype=CREATE +type=PROCTITLE msg=audit(1731200100.050:5005): proctitle=63700061007061796C6F61642E7368 +type=SYSCALL msg=audit(1731200100.060:5006): arch=c000003e syscall=231 success=yes exit=0 a0=3 a1=7ffd a2=0 a3=0 items=0 ppid=4100 pid=5001 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="python3" exe="/usr/bin/python3.12" subj=unconfined key="tawny" +type=PROCTITLE msg=audit(1731200100.060:5006): proctitle=707974686F6E33 diff --git a/agent/src/platform/linux/testdata/netlink_exec_connect.txt b/agent/src/platform/linux/testdata/netlink_exec_connect.txt new file mode 100644 index 0000000..1204eb5 --- /dev/null +++ b/agent/src/platform/linux/testdata/netlink_exec_connect.txt @@ -0,0 +1,18 @@ +1300 audit(1731200000.123:4567): arch=c000003e syscall=59 success=yes exit=0 a0=55d0c8 a1=55d0e0 a2=55d100 a3=8 items=2 ppid=4100 pid=4242 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="curl" exe="/usr/bin/curl" subj=unconfined key="tawny" +1309 audit(1731200000.123:4567): argc=3 a0="curl" a1="-s" a2=68747470733A2F2F6578616D706C652E636F6D2F612062 +1307 audit(1731200000.123:4567): cwd="/home/alice" +1302 audit(1731200000.123:4567): item=0 name="/usr/bin/curl" inode=393551 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0 +1302 audit(1731200000.123:4567): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=393220 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0 +1327 audit(1731200000.123:4567): proctitle=6375726C002D73 +1320 audit(1731200000.123:4567): +1400 audit(1731200000.200:4568): apparmor="STATUS" operation="profile_load" +1300 audit(1731200000.240:4569): arch=c000003e syscall=42 success=yes exit=0 a0=5 a1=7ffd2a10 a2=10 a3=0 items=0 ppid=4100 pid=4242 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="curl" exe="/usr/bin/curl" subj=unconfined key="tawny" +1306 audit(1731200000.240:4569): saddr=020001BB5DB8D70E0000000000000000 +1327 audit(1731200000.240:4569): proctitle=6375726C +1320 audit(1731200000.240:4569): +1300 audit(1731200000.250:4570): arch=c000003e syscall=42 success=no exit=-115 a0=6 a1=7ffd2a20 a2=1c a3=0 items=0 ppid=4100 pid=4242 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="curl" exe="/usr/bin/curl" subj=unconfined key="tawny" +1306 audit(1731200000.250:4570): saddr=0A0001BB0000000020010DB800000000000000000000001000000000 +1320 audit(1731200000.250:4570): +1300 audit(1731200000.900:4571): arch=c000003e syscall=231 a0=0 a1=e7 a2=3c a3=7f items=0 ppid=4100 pid=4242 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="curl" exe="/usr/bin/curl" subj=unconfined key="tawny" +1327 audit(1731200000.900:4571): proctitle=6375726C +1320 audit(1731200000.900:4571): diff --git a/agent/src/platform/linux/testdata/tetragon.jsonl b/agent/src/platform/linux/testdata/tetragon.jsonl new file mode 100644 index 0000000..cd28919 --- /dev/null +++ b/agent/src/platform/linux/testdata/tetragon.jsonl @@ -0,0 +1,4 @@ +{"process_exec":{"process":{"exec_id":"d2ViMTo0MjQyMDAwMDAwMDA6NDI0Mg==","pid":4242,"uid":1000,"cwd":"/home/alice","binary":"/usr/bin/curl","arguments":"-s https://example.com","flags":"execve clone","start_time":"2026-11-10T01:00:00.123456789Z","auid":1000,"parent_exec_id":"d2ViMTo0MTAwMDAwMDAwMDA6NDEwMA==","tid":4242},"parent":{"exec_id":"d2ViMTo0MTAwMDAwMDAwMDA6NDEwMA==","pid":4100,"uid":1000,"cwd":"/home/alice","binary":"/usr/bin/bash","flags":"procFS auid","start_time":"2026-11-10T00:59:00.000000000Z","auid":1000,"tid":4100}},"node_name":"web1","time":"2026-11-10T01:00:00.123500000Z"} +{"process_kprobe":{"process":{"exec_id":"d2ViMTo0MjQyMDAwMDAwMDA6NDI0Mg==","pid":4242,"uid":1000,"cwd":"/home/alice","binary":"/usr/bin/curl","arguments":"-s https://example.com","flags":"execve clone","start_time":"2026-11-10T01:00:00.123456789Z","auid":1000,"tid":4242},"parent":{"exec_id":"d2ViMTo0MTAwMDAwMDAwMDA6NDEwMA==","pid":4100,"binary":"/usr/bin/bash","start_time":"2026-11-10T00:59:00.000000000Z"},"function_name":"tcp_connect","args":[{"sock_arg":{"family":"AF_INET","type":"SOCK_STREAM","protocol":"IPPROTO_TCP","saddr":"192.0.2.7","daddr":"93.184.215.14","sport":51234,"dport":443,"cookie":"18446616195423431232","state":"TCP_SYN_SENT"}}],"action":"KPROBE_ACTION_POST","policy_name":"connect"},"node_name":"web1","time":"2026-11-10T01:00:00.300000000Z"} +{"process_kprobe":{"process":{"pid":4242,"binary":"/usr/bin/curl","start_time":"2026-11-10T01:00:00.123456789Z"},"function_name":"security_file_permission","args":[]},"node_name":"web1","time":"2026-11-10T01:00:00.400000000Z"} +{"process_exit":{"process":{"exec_id":"d2ViMTo0MjQyMDAwMDAwMDA6NDI0Mg==","pid":4242,"uid":1000,"cwd":"/home/alice","binary":"/usr/bin/curl","arguments":"-s https://example.com","flags":"execve clone","start_time":"2026-11-10T01:00:00.123456789Z","auid":1000,"tid":4242},"parent":{"pid":4100,"binary":"/usr/bin/bash"},"status":0,"time":"2026-11-10T01:00:01.000000000Z"},"node_name":"web1","time":"2026-11-10T01:00:01.000000000Z"} diff --git a/agent/src/platform/linux/tetragon.zig b/agent/src/platform/linux/tetragon.zig new file mode 100644 index 0000000..404452a --- /dev/null +++ b/agent/src/platform/linux/tetragon.zig @@ -0,0 +1,310 @@ +//! Optional Tetragon source (#59). Tetragon writes one JSON object per line +//! to its export file (`--export-filename`, default +//! /var/run/cilium/tetragon/tetragon.log). The agent tails that file with +//! `audit.Tail` and maps `process_exec`, `process_exit` and +//! `process_kprobe` for `tcp_connect` to the same v2 events as the audit +//! source. Mapping is pure; the tests use testdata/tetragon.jsonl. +const std = @import("std"); +const entity = @import("../../entity.zig"); +const privacy = @import("../../collectors/privacy.zig"); +const audit = @import("audit.zig"); + +pub const default_export_path = "/var/run/cilium/tetragon/tetragon.log"; + +pub const Kind = enum { exec, exit, connect }; + +/// One mapped line. `pid` and `start_100ns` let the caller keep the entity +/// table and the poller in step. +pub const Line = struct { + mapped: audit.Mapped, + kind: Kind, + pid: u32, +}; + +pub const MapContext = struct { + table: ?*entity.Table = null, + /// /proc start of a live process, so ids match the poller's. + live_start: ?*const fn (pid: u32) ?u64 = null, +}; + +const V = std.json.Value; + +fn get(v: V, key: []const u8) ?V { + if (v != .object) return null; + return v.object.get(key); +} + +fn str(v: V, key: []const u8) []const u8 { + const x = get(v, key) orelse return ""; + return if (x == .string) x.string else ""; +} + +fn int(v: V, key: []const u8) ?i64 { + const x = get(v, key) orelse return null; + return switch (x) { + .integer => |n| n, + .number_string => |s| std.fmt.parseInt(i64, s, 10) catch null, + else => null, + }; +} + +fn pidOf(v: V) ?u32 { + const n = int(v, "pid") orelse return null; + if (n < 0 or n > std.math.maxInt(u32)) return null; + return @intCast(n); +} + +/// Map one export line. Null for lines we do not report. +pub fn mapLine(alloc: std.mem.Allocator, line: []const u8, ctx: MapContext) !?Line { + const trimmed = std.mem.trim(u8, line, " \r\t"); + if (trimmed.len == 0 or trimmed[0] != '{') return null; + var arena = std.heap.ArenaAllocator.init(alloc); + defer arena.deinit(); + const root = std.json.parseFromSliceLeaky(V, arena.allocator(), trimmed, .{}) catch return null; + const time = entity.parseIso(str(root, "time")); + const occurred: i64 = if (time) |t| @intCast(t / entity.ticks_per_second) else 0; + + if (get(root, "process_exec")) |ev| { + const p = get(ev, "process") orelse return null; + const pid = pidOf(p) orelse return null; + const payload = try processStart(alloc, ev, p, pid, ctx); + return .{ .mapped = .{ .event_type = "process_start", .payload = payload, .occurred_at = occurred }, .kind = .exec, .pid = pid }; + } + if (get(root, "process_exit")) |ev| { + const p = get(ev, "process") orelse return null; + const pid = pidOf(p) orelse return null; + const payload = try processExit(alloc, ev, p, pid, time, ctx); + return .{ .mapped = .{ .event_type = "process_exit", .payload = payload, .occurred_at = occurred }, .kind = .exit, .pid = pid }; + } + if (get(root, "process_kprobe")) |ev| { + if (!std.mem.eql(u8, str(ev, "function_name"), "tcp_connect")) return null; + const p = get(ev, "process") orelse return null; + const pid = pidOf(p) orelse return null; + const args = get(ev, "args") orelse return null; + if (args != .array or args.array.items.len == 0) return null; + const sock = get(args.array.items[0], "sock_arg") orelse return null; + const daddr = str(sock, "daddr"); + const dport = int(sock, "dport") orelse return null; + if (daddr.len == 0 or dport <= 0 or dport > 65535) return null; + const payload = try networkConnect(alloc, p, pid, sock, daddr, dport, ctx); + return .{ .mapped = .{ .event_type = "network_connect", .payload = payload, .occurred_at = occurred }, .kind = .connect, .pid = pid }; + } + return null; +} + +fn startOf(p: V, pid: u32, ctx: MapContext) ?u64 { + if (ctx.live_start) |f| if (f(pid)) |s| return s; + return entity.parseIso(str(p, "start_time")); +} + +fn idOf(p: V, pid: u32, ctx: MapContext) ?entity.Id { + const t = ctx.table orelse return null; + return t.idFor(pid, startOf(p, pid, ctx) orelse return null); +} + +const Jw = std.json.Stringify; + +fn header(jw: *Jw) !void { + try jw.beginObject(); + try jw.objectField("sensor"); + try jw.write("tetragon"); +} + +fn processStart(alloc: std.mem.Allocator, ev: V, p: V, pid: u32, ctx: MapContext) ![]u8 { + const start = startOf(p, pid, ctx); + var id: ?entity.Id = null; + if (ctx.table) |t| if (start) |s| { + id = try t.observe(pid, s, ""); + }; + const binary = str(p, "binary"); + const args = str(p, "arguments"); + const raw_cmd = if (args.len > 0) try std.fmt.allocPrint(alloc, "{s} {s}", .{ binary, args }) else try alloc.dupe(u8, binary); + defer alloc.free(raw_cmd); + const cmd = try privacy.sanitizeCommandLine(alloc, raw_cmd); + defer alloc.free(cmd); + + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try header(&jw); + try jw.objectField("process"); + try jw.beginObject(); + if (id) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(pid); + if (start) |s| { + var buf: [24]u8 = undefined; + try jw.objectField("start_time"); + try jw.write(entity.formatIso(&buf, s)); + } + try jw.objectField("name"); + try jw.write(std.fs.path.basenamePosix(binary)); + if (binary.len > 0) { + try jw.objectField("image"); + try jw.write(binary); + } + try jw.objectField("command_line"); + try jw.write(cmd); + const cwd = str(p, "cwd"); + if (cwd.len > 0) { + try jw.objectField("cwd"); + try jw.write(cwd); + } + if (int(p, "uid")) |uid| if (uid >= 0) { + try jw.objectField("user"); + try jw.beginObject(); + try jw.objectField("uid"); + try jw.write(uid); + try jw.endObject(); + }; + try jw.endObject(); + if (get(ev, "parent")) |parent| { + try jw.objectField("parent"); + try jw.beginObject(); + if (pidOf(parent)) |ppid| { + if (idOf(parent, ppid, ctx)) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(ppid); + } + const pbin = str(parent, "binary"); + if (pbin.len > 0) { + try jw.objectField("image"); + try jw.write(pbin); + try jw.objectField("name"); + try jw.write(std.fs.path.basenamePosix(pbin)); + } + try jw.endObject(); + } + try jw.endObject(); + return out.toOwnedSlice(); +} + +fn processExit(alloc: std.mem.Allocator, ev: V, p: V, pid: u32, time: ?u64, ctx: MapContext) ![]u8 { + _ = ev; + const id = idOf(p, pid, ctx); + if (ctx.table) |t| if (id != null) t.forget(pid); + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try header(&jw); + try jw.objectField("process"); + try jw.beginObject(); + if (id) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(pid); + const binary = str(p, "binary"); + if (binary.len > 0) { + try jw.objectField("image"); + try jw.write(binary); + } + try jw.endObject(); + if (time) |t| { + var buf: [24]u8 = undefined; + try jw.objectField("end_time"); + try jw.write(entity.formatIso(&buf, t)); + } + try jw.endObject(); + return out.toOwnedSlice(); +} + +fn networkConnect(alloc: std.mem.Allocator, p: V, pid: u32, sock: V, daddr: []const u8, dport: i64, ctx: MapContext) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); + var jw: Jw = .{ .writer = &out.writer }; + try header(&jw); + try jw.objectField("process"); + try jw.beginObject(); + if (idOf(p, pid, ctx)) |v| { + try jw.objectField("entity_id"); + try jw.write(&v); + } + try jw.objectField("pid"); + try jw.write(pid); + const binary = str(p, "binary"); + if (binary.len > 0) { + try jw.objectField("image"); + try jw.write(binary); + try jw.objectField("name"); + try jw.write(std.fs.path.basenamePosix(binary)); + } + try jw.endObject(); + try jw.objectField("network"); + try jw.beginObject(); + try jw.objectField("protocol"); + try jw.write("tcp"); + try jw.objectField("direction"); + try jw.write("outbound"); + const saddr = str(sock, "saddr"); + if (saddr.len > 0) { + try jw.objectField("src_ip"); + try jw.write(saddr); + } + if (int(sock, "sport")) |sp| if (sp > 0) { + try jw.objectField("src_port"); + try jw.write(sp); + }; + try jw.objectField("dst_ip"); + try jw.write(daddr); + try jw.objectField("dst_port"); + try jw.write(dport); + try jw.endObject(); + try jw.endObject(); + return out.toOwnedSlice(); +} + +// --------------------------------------------------------------------------- +// Tests + +const testing = std.testing; + +test "tetragon export lines map to v2 events with entity ids" { + const alloc = testing.allocator; + var table = entity.Table.init(alloc, "0f8fad5b-d9cb-469f-a165-70867728950e", "3c1c4b5e-6d2a-4f0e-9b7a-2d1e5f6a7b8c", 64); + defer table.deinit(); + const text = @embedFile("testdata/tetragon.jsonl"); + var got: std.ArrayList(Line) = .empty; + defer { + for (got.items) |l| alloc.free(l.mapped.payload); + got.deinit(alloc); + } + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (try mapLine(alloc, line, .{ .table = &table })) |l| try got.append(alloc, l); + } + const want = [_][]const u8{ "process_start", "network_connect", "process_exit" }; + try testing.expectEqual(want.len, got.items.len); + for (want, got.items) |w, l| { + try testing.expectEqualStrings(w, l.mapped.event_type); + try @import("../../schema_check.zig").expectValid(alloc, l.mapped.event_type, l.mapped.payload); + } + const start = entity.parseIso("2026-11-10T01:00:00.123456789Z").?; + const child = table.idFor(4242, start); + const parent = table.idFor(4100, entity.parseIso("2026-11-10T00:59:00.000000000Z").?); + const exec = got.items[0].mapped.payload; + try testing.expect(std.mem.indexOf(u8, exec, &child) != null); + try testing.expect(std.mem.indexOf(u8, exec, &parent) != null); + try testing.expect(std.mem.indexOf(u8, exec, "\"command_line\":\"/usr/bin/curl -s https://example.com\"") != null); + try testing.expect(std.mem.indexOf(u8, got.items[1].mapped.payload, &child) != null); + try testing.expect(std.mem.indexOf(u8, got.items[1].mapped.payload, "\"dst_ip\":\"93.184.215.14\",\"dst_port\":443") != null); + try testing.expect(std.mem.indexOf(u8, got.items[2].mapped.payload, &child) != null); + try testing.expect(std.mem.indexOf(u8, got.items[2].mapped.payload, "\"end_time\":\"2026-11-10T01:00:01.000Z\"") != null); + try testing.expectEqual(@as(u32, 4242), got.items[2].pid); +} + +test "tetragon lines we do not report and bad input" { + const alloc = testing.allocator; + try testing.expect((try mapLine(alloc, "", .{})) == null); + try testing.expect((try mapLine(alloc, "not json", .{})) == null); + try testing.expect((try mapLine(alloc, "{\"process_kprobe\":{\"function_name\":\"security_file_permission\",\"process\":{\"pid\":1}}}", .{})) == null); + try testing.expect((try mapLine(alloc, "{\"process_exec\":{\"process\":{\"binary\":\"/bin/x\"}}}", .{})) == null); + try testing.expect((try mapLine(alloc, "{\"process_kprobe\":{\"function_name\":\"tcp_connect\",\"process\":{\"pid\":1},\"args\":[{\"sock_arg\":{\"daddr\":\"1.2.3.4\",\"dport\":0}}]}}", .{})) == null); +} diff --git a/docs/architecture/linux-sensor.md b/docs/architecture/linux-sensor.md new file mode 100644 index 0000000..81c0113 --- /dev/null +++ b/docs/architecture/linux-sensor.md @@ -0,0 +1,92 @@ +# Linux kernel sensor: decision record (#59) + +Status: accepted, November 2026. + +## Problem + +Linux telemetry came from a `/proc` diff every few seconds and non-recursive +inotify. A process that starts and exits between two polls is never seen, and +an outbound connection is only visible if it is still open at the next +`/proc/net` snapshot. The agent ran as the unprivileged `tawny` user with no +capabilities, so it could not read or signal other users' processes. + +## Options + +| Option | What it gives | Cost to run | Fit for Tawny | +|---|---|---|---| +| Tetragon (Cilium, Apache-2.0) | exec, exit, kprobe (`tcp_connect`) and file events with ancestry, JSON export to a file | a separate privileged daemon, kernel with BTF (most distros from 5.x), Helm or package install | good data, but a second privileged daemon to install, patch and watch | +| Falco (CNCF, Apache-2.0) | rule-driven syscall events, JSON to a file, HTTP or gRPC | a separate privileged daemon with the modern eBPF probe | its events are rule outputs, not a raw event stream, so mapping to our types needs Falco rules we would also have to ship | +| auditd netlink in the agent | `execve`, `execveat`, `connect`, `exit_group` and directory watches from the kernel audit subsystem | `CAP_AUDIT_READ` and `CAP_AUDIT_CONTROL`; only one process can own the audit socket, so it can clash with an existing auditd | no extra daemon, works on every kernel we support (3.x and later), and the record format is stable and documented | + +## Decision + +The agent reads the kernel audit subsystem itself over `NETLINK_AUDIT` +(`agent/src/platform/linux/audit.zig`). Tetragon is an optional second source: +when Tetragon is already installed and writing its JSON export, the agent can +tail that file instead (`agent/src/platform/linux/tetragon.zig`). Falco is not +used. + +Why auditd netlink: + +- Nothing else to install. The agent binary and its systemd unit are the whole + footprint, which matters for the one-line installer. +- It works without BTF or eBPF, so older kernels and locked-down hosts still + get kernel events. +- Records carry a per-event serial, so `SYSCALL`, `EXECVE`, `CWD`, `PATH` and + `SOCKADDR` records join into one Tawny event without guessing. +- The capability cost is two capabilities, which the unit grants through + `AmbientCapabilities=` while keeping `User=tawny` and `NoNewPrivileges`. + +Costs we accept: + +- Audit adds per-syscall overhead on the audited syscalls. The rules are kept + narrow: native architecture only, `exit,always` on exec, connect and + `exit_group`, plus write watches on `fim_paths`. Connects on Unix sockets + are recorded by the kernel and dropped by the agent. +- 32-bit (compat) processes on a 64-bit kernel are not audited by these rules. +- If the agent is killed with `SIGKILL` its rules stay loaded until the next + start, and the kernel logs those records to the kernel log meanwhile. A clean + stop removes them. + +## How the agent picks a source + +`linux_sensor = auto` (the default) tries, in order: + +1. Audit netlink as the audit daemon. No other daemon owns the socket: the + agent registers itself, raises the backlog limit, and loads its rules (key + `tawny`). `sensor_health` state `ok`, status `ok`. +2. Audit multicast. auditd already owns the socket: the agent joins the + read-only multicast group with `CAP_AUDIT_READ` and sees whatever auditd's + rules produce. It does not add or remove rules. Status `degraded`, because + coverage depends on the host's audit rules. +3. The audit log (`audit_log_path`, default `/var/log/audit/audit.log`) when + multicast is refused and the log is readable. Status `degraded`. +4. The Tetragon JSON export (`tetragon_export_path`) when it exists. +5. The `/proc` poller only. `sensor_health` status `degraded` with the reason. + +`linux_sensor = audit`, `audit_log`, `tetragon` or `proc` forces one source. With a kernel +source running, the `/proc` poller stays on as a reconciliation pass every 10 +minutes; without one it keeps its normal interval. + +## What is tested where + +- Record parsing, the serial join and mapping to `process_start`, + `process_exit`, `network_connect` and `file_create` are pure functions with + captured records under `agent/src/platform/linux/testdata/`. They run on + every OS in `zig build test`. +- Kernel constants (message types, field ids, netlink family, syscall numbers) + have a pin test against `linux/audit.h`. +- CI `agent (linux-x64)` runs the agent's sensor dump with exactly the unit's + capabilities through `sudo setpriv`, runs `/bin/true` 50 times and expects at + least 50 `process_start` events. It also runs the dump with no capabilities + and expects the degraded fallback. +- Docker containers (including OrbStack) refuse audit netlink because the + container is not in the initial PID namespace, so live audit is only proved + on the CI VM. + +## Not in this change + +- nftables host isolation (`isolate_host` on Linux) is a follow-up. The agent + still answers "isolate_host is not supported on linux yet". +- fanotify file events and eBPF in the agent itself. +- Falco. diff --git a/docs/production-agent-hardening.md b/docs/production-agent-hardening.md index 48875d1..7433ce4 100644 --- a/docs/production-agent-hardening.md +++ b/docs/production-agent-hardening.md @@ -74,7 +74,8 @@ the installers as before. To turn self-update on: `TawnyAgent`. Other users can query it. Check with `sc.exe sdshow TawnyAgent`. - **systemd (Linux).** The unit's hardening in `install.sh` is unchanged (`NoNewPrivileges`, `ProtectSystem=strict` and the rest). Only root can stop - a system unit. + a system unit. Since #59 the unit grants five capabilities, listed in + [Linux capabilities](#linux-capabilities). ## Key protection @@ -142,6 +143,54 @@ file permissions can reduce process and FIM visibility for the unprivileged service. Grant only the specific read access required by the agreed collection scope; do not switch to root without a documented threat-model decision. +### Linux capabilities + +The agent still runs as `User=tawny` with every other hardening line in the +unit. It gets exactly these capabilities, through `AmbientCapabilities=` and +`CapabilityBoundingSet=` (the bounding set holds nothing else, so the process +can never gain more). `agent/install/test-install.sh` fails if the unit lists +any other set. + +| Capability | Why the agent needs it | Without it | +|---|---|---| +| `CAP_AUDIT_CONTROL` | Register as the audit daemon over `NETLINK_AUDIT`, load the agent's rules (key `tawny`: `execve`, `execveat`, `connect`, `exit_group` and write watches on `fim_paths`) and remove them on stop | No rules of its own; the agent falls back to the multicast group, the audit log or `/proc` polling, and reports `sensor_health` degraded | +| `CAP_AUDIT_READ` | Join the read-only audit multicast group when auditd already owns the socket | Falls back to `/var/log/audit/audit.log` if readable, else `/proc` polling | +| `CAP_SYS_PTRACE` | Read the `/proc//exe` link and `/proc//fd` of other users' processes, for image paths and hashes. The agent never calls `ptrace` | Image path and hash are missing for processes owned by other users | +| `CAP_DAC_READ_SEARCH` | Read other users' `/proc/` entries and files under watched folders for hashing and YARA, where file modes would refuse the `tawny` user | Those reads fail and the fields are left out | +| `CAP_KILL` | The signed `kill_process` response action against processes owned by other users | `kill_process` only works on processes owned by `tawny` | + +Not granted: `CAP_NET_ADMIN` (nftables isolation is a follow-up and will be an +opt-in flag), `CAP_SYS_ADMIN`, `CAP_BPF` and `CAP_PERFMON` (no eBPF in the +agent). Tetragon, when used, runs as its own daemon and the agent only reads +its export file. + +Audit notes: + +- Only one process can be the audit daemon. If auditd is running, leave it: + the agent reads its records read-only and does not touch its rules. Check + with `sudo auditctl -s` (`pid` is the owner) and the agent's + `sensor_health` event (`source` and `reason`). +- Choose the source with `linux_sensor = auto | audit | audit_log | tetragon | proc` + in `config.toml`. `audit_log_path` and `tetragon_export_path` override the + default paths. With `audit_log` the `tawny` group needs read access to the + log (`log_group = tawny` in `auditd.conf`). +- The agent's rules carry the key `tawny`. `sudo auditctl -l -k tawny` lists + them; a clean stop removes them. +- Containers cannot use audit netlink (the kernel only allows it in the + initial namespaces), so a containerised agent falls back to polling. + +Check the running unit: + +```bash +grep Cap /proc/$(systemctl show -p MainPID --value tawny-agent)/status +# Same user and capabilities as the unit, without the server: +sudo setpriv --reuid=tawny --regid=tawny --init-groups \ + --inh-caps=+audit_control,+audit_read,+dac_read_search,+kill,+sys_ptrace \ + --ambient-caps=+audit_control,+audit_read,+dac_read_search,+kill,+sys_ptrace \ + --bounding-set=-all,+audit_control,+audit_read,+dac_read_search,+kill,+sys_ptrace \ + /usr/local/tawny/tawny-agent --linux-sensor-dump --seconds 5 +``` + Use an instance role and IMDSv2-required EC2 metadata options. Do not place AWS access keys in agent config or service environment. Restrict backend egress with security groups, Network Firewall, or an authenticated proxy. Keep host time