From d3cbdf872f84830c980e1a6904f77356fed2f897 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:03 +1100 Subject: [PATCH 1/8] feat(server): Agent silent, Sensor silent and Agent tamper alerts Migration 0007 adds the clean shutdown notice, update ring and state columns, release ring columns and a per-sensor status table. - jobs/agent_alerts.zig: an agent offline without a clean shutdown notice raises Agent silent (never for revoked agents); the next heartbeat closes it. A sensor that was running and stops, or a continuous sensor quiet for 15 minutes, raises Sensor silent; delivery closes it. Every agent_tamper event raises Agent tamper. - Heartbeat accepts shutdown and shutdown_reason. Ingest feeds sensor_health and agent_health into sensor status and records key_protection and update state. - agent_tamper schema; agent_health gains key_protection, sensors and update. New types appended to the backup and sink name lists. Co-Authored-By: Claude Opus 5.5 --- schemas/events/agent_health.v1.json | 82 ++ schemas/events/agent_tamper.v1.json | 41 + schemas/events/golden/agent_health.json | 15 +- schemas/events/golden/agent_tamper.json | 4 + server/src/db/migrate.zig | 3 + .../db/migrations/0007_agent_hardening.sql | 63 ++ server/src/ingest/schema_check.zig | 1 + server/src/ingest/v2.zig | 1 + server/src/jobs/agent_alerts.zig | 741 ++++++++++++++++++ server/src/jobs/backup.zig | 5 + server/src/jobs/deliver.zig | 3 + server/src/main.zig | 13 + server/src/routes/agents.zig | 54 ++ 13 files changed, 1025 insertions(+), 1 deletion(-) create mode 100644 schemas/events/agent_tamper.v1.json create mode 100644 schemas/events/golden/agent_tamper.json create mode 100644 server/src/db/migrations/0007_agent_hardening.sql create mode 100644 server/src/jobs/agent_alerts.zig diff --git a/schemas/events/agent_health.v1.json b/schemas/events/agent_health.v1.json index 842b786..15ef8e2 100644 --- a/schemas/events/agent_health.v1.json +++ b/schemas/events/agent_health.v1.json @@ -26,6 +26,88 @@ }, "boot_id": { "type": "string" + }, + "key_protection": { + "enum": [ + "keychain", + "dpapi", + "tpm", + "file" + ] + }, + "sensors": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "status" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "status": { + "enum": [ + "running", + "degraded", + "stopped", + "silent", + "failed", + "missing", + "unknown" + ] + }, + "last_event_age_seconds": { + "type": "integer", + "minimum": 0 + } + } + } + }, + "update": { + "type": "object", + "required": [ + "state" + ], + "properties": { + "state": { + "enum": [ + "disabled_no_release_key", + "idle", + "checking", + "downloading", + "staged", + "restarting", + "health_check", + "committed", + "rolled_back", + "refused", + "failed" + ] + }, + "version": { + "type": "string" + }, + "ring": { + "enum": [ + "canary", + "internal", + "10", + "50", + "100" + ] + }, + "bucket": { + "type": "integer", + "minimum": 0 + }, + "reason": { + "type": "string" + } + } } } } diff --git a/schemas/events/agent_tamper.v1.json b/schemas/events/agent_tamper.v1.json new file mode 100644 index 0000000..59690a2 --- /dev/null +++ b/schemas/events/agent_tamper.v1.json @@ -0,0 +1,41 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "agent_tamper.v1.json", + "title": "AGENT_TAMPER", + "type": "object", + "required": [ + "check", + "detail" + ], + "properties": { + "check": { + "enum": [ + "unexpected_stop", + "binary_changed", + "config_changed", + "identity_changed", + "sysmon_stopped", + "defender_exclusion" + ] + }, + "detail": { + "type": "string", + "maxLength": 2048 + }, + "path": { + "type": "string" + }, + "expected_sha256": { + "type": "string" + }, + "actual_sha256": { + "type": "string" + }, + "service": { + "type": "string" + }, + "exclusion": { + "type": "string" + } + } +} diff --git a/schemas/events/golden/agent_health.json b/schemas/events/golden/agent_health.json index 5bb57a3..6ae759e 100644 --- a/schemas/events/golden/agent_health.json +++ b/schemas/events/golden/agent_health.json @@ -3,5 +3,18 @@ "buffer_depth": 3, "uptime_seconds": 120, "next_sequence": 42, - "boot_id": "3c1c4b5e-6d2a-4f0e-9b7a-2d1e5f6a7b8c" + "boot_id": "3c1c4b5e-6d2a-4f0e-9b7a-2d1e5f6a7b8c", + "key_protection": "dpapi", + "sensors": [ + { + "name": "Microsoft-Windows-Sysmon/Operational", + "status": "running", + "last_event_age_seconds": 3 + } + ], + "update": { + "state": "idle", + "ring": "100", + "bucket": 42 + } } diff --git a/schemas/events/golden/agent_tamper.json b/schemas/events/golden/agent_tamper.json new file mode 100644 index 0000000..40ed98a --- /dev/null +++ b/schemas/events/golden/agent_tamper.json @@ -0,0 +1,4 @@ +{ + "check": "unexpected_stop", + "detail": "The agent started without the clean shutdown marker from its last run." +} diff --git a/server/src/db/migrate.zig b/server/src/db/migrate.zig index 6bba630..529e534 100644 --- a/server/src/db/migrate.zig +++ b/server/src/db/migrate.zig @@ -13,6 +13,8 @@ const detection_engine_sql = @embedFile("migrations/0005_detection_engine.sql"); const detection_engine_version = "0005_detection_engine"; const windows_response_sql = @embedFile("migrations/0006_windows_response.sql"); const windows_response_version = "0006_windows_response"; +const agent_hardening_sql = @embedFile("migrations/0007_agent_hardening.sql"); +const agent_hardening_version = "0007_agent_hardening"; pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try conn.execSimple( @@ -31,6 +33,7 @@ pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try applyScript(allocator, conn, process_entities_version, process_entities_sql, true); try applyScript(allocator, conn, detection_engine_version, detection_engine_sql, true); try applyScript(allocator, conn, windows_response_version, windows_response_sql, true); + try applyScript(allocator, conn, agent_hardening_version, agent_hardening_sql, true); try conn.execSimple("GRANT EXECUTE ON FUNCTION tawny_purge_expired(timestamptz) TO tawny_jobs"); try ensurePartitions(conn); } diff --git a/server/src/db/migrations/0007_agent_hardening.sql b/server/src/db/migrations/0007_agent_hardening.sql new file mode 100644 index 0000000..fd8f716 --- /dev/null +++ b/server/src/db/migrations/0007_agent_hardening.sql @@ -0,0 +1,63 @@ +-- Agent hardening (#58): quiet agent and quiet sensor alerts, update rings, +-- update state. Applied as one simple-query script in a transaction. + +-- Clean shutdown notice. Set by a heartbeat with "shutdown": true and cleared +-- by the next normal heartbeat. jobs/stale.zig raises "Agent silent" when an +-- agent goes offline while this is null. +ALTER TABLE agents ADD COLUMN clean_shutdown_at timestamptz; +ALTER TABLE agents ADD COLUMN clean_shutdown_reason text; + +-- Update ring override and the last update state the agent reported in +-- agent_health. Ring is null for the default: bucket = hash(agent_id) mod 100. +ALTER TABLE agents ADD COLUMN update_ring text + CHECK (update_ring IS NULL OR update_ring IN ('canary', 'internal', '10', '50', '100')); +ALTER TABLE agents ADD COLUMN update_state text; +ALTER TABLE agents ADD COLUMN update_version text; +ALTER TABLE agents ADD COLUMN update_state_at timestamptz; +ALTER TABLE agents ADD COLUMN key_protection text; + +-- Release rings. `ring` is the widest ring the release is open to. Existing +-- rows were already offered to everyone, so they start at '100'. New rows +-- from the release sync start at 'canary' and are promoted by +-- releases.promote when the previous ring stays healthy for the soak period. +ALTER TABLE agent_releases ADD COLUMN ring text NOT NULL DEFAULT '100' + CHECK (ring IN ('canary', 'internal', '10', '50', '100')); +ALTER TABLE agent_releases ADD COLUMN ring_opened_at timestamptz NOT NULL DEFAULT now(); +ALTER TABLE agent_releases ADD COLUMN size bigint; +ALTER TABLE agent_releases ADD COLUMN manifest text; +ALTER TABLE agent_releases ADD COLUMN manifest_signature text; + +-- Per-sensor delivery, fed by sensor_health and agent_health events. The +-- quiet-sensor job alerts when a sensor that was running has delivered +-- nothing for 15 minutes while the agent itself is still heartbeating. +CREATE TABLE sensor_status ( + tenant_id uuid NOT NULL REFERENCES tenants (id), + agent_id uuid NOT NULL REFERENCES agents (id) ON DELETE CASCADE, + sensor text NOT NULL CHECK (length(sensor) BETWEEN 1 AND 200), + state text NOT NULL, + state_since timestamptz NOT NULL, + was_running boolean NOT NULL DEFAULT false, + -- Continuous sensors (Sysmon, Security, the launch tracker) alert on 15 + -- minutes without events. Sparse ones (PowerShell, System 7045) only + -- alert when they stop or fail, because a quiet hour is normal for them. + continuous boolean NOT NULL DEFAULT false, + last_event_at timestamptz, + open_alert_id bigint, + updated_at timestamptz NOT NULL, + PRIMARY KEY (tenant_id, agent_id, sensor) +); + +ALTER TABLE sensor_status ENABLE ROW LEVEL SECURITY; +ALTER TABLE sensor_status FORCE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS tenant_isolation ON sensor_status; +CREATE POLICY tenant_isolation ON sensor_status + USING (tenant_id = tawny_current_tenant()) + WITH CHECK (tenant_id = tawny_current_tenant()); + +GRANT SELECT, INSERT, UPDATE, DELETE ON sensor_status TO tawny_app, tawny_jobs; + +-- Server-raised alerts (Agent silent, Sensor silent, Agent tamper) hang off +-- one disabled rule per tenant, found by external id. +CREATE UNIQUE INDEX alert_rules_system_idx ON alert_rules (tenant_id, external_id) + WHERE external_id LIKE 'tawny-system:%'; +CREATE INDEX alerts_open_rule_agent_idx ON alerts (tenant_id, alert_rule_id, agent_id) WHERE status = 'open'; diff --git a/server/src/ingest/schema_check.zig b/server/src/ingest/schema_check.zig index edadf01..bf87bb2 100644 --- a/server/src/ingest/schema_check.zig +++ b/server/src/ingest/schema_check.zig @@ -207,6 +207,7 @@ pub const schema_types = [_][]const u8{ "process_start", "process_exit", "network_connect", "dns_query", "file_create", "registry_set", "user_logon", "service_create", "powershell_script_block", "agent_health", "sensor_health", + "agent_tamper", }; test "golden payloads match their schemas" { diff --git a/server/src/ingest/v2.zig b/server/src/ingest/v2.zig index ef3e000..e3ef32a 100644 --- a/server/src/ingest/v2.zig +++ b/server/src/ingest/v2.zig @@ -130,6 +130,7 @@ pub fn checkData(event_type: []const u8, d: std.json.Value) ?[]const u8 { if (eq(u8, event_type, "agent_health")) { return if (get(d, "sensor_version") != null and get(d, "buffer_depth") != null and get(d, "uptime_seconds") != null) null else "agent_health fields are required."; } + if (eq(u8, event_type, "agent_tamper")) return if (needString(d, "check") and needString(d, "detail")) null else "check and detail are required."; return null; } diff --git a/server/src/jobs/agent_alerts.zig b/server/src/jobs/agent_alerts.zig new file mode 100644 index 0000000..15288f9 --- /dev/null +++ b/server/src/jobs/agent_alerts.zig @@ -0,0 +1,741 @@ +//! Server-raised agent alerts (#58, target-edr §10): +//! +//! - `Agent silent`: an agent went offline without a clean shutdown notice. +//! Closed by its next heartbeat. Never raised for revoked agents. +//! - `Sensor silent`: a sensor that was running (from `sensor_health` or +//! `agent_health.sensors`) delivered nothing for 15 minutes while the agent +//! kept heartbeating, or moved from running to a stopped or failed state. +//! Closed when the sensor delivers again. +//! - `Agent tamper`: every `agent_tamper` event from the agent. +//! +//! Alerts need a rule and a telemetry event (foreign keys). Each tenant gets +//! one disabled system rule per kind (`tawny-system:`), and each alert +//! is anchored on a server-written `agent_silent` / `sensor_silent` event, or +//! the agent's own `agent_tamper` event. + +const std = @import("std"); +const pg = @import("../db/pg/conn.zig"); +const util = @import("../http/util.zig"); + +pub const Kind = enum { + agent_silent, + sensor_silent, + agent_tamper, + + pub fn externalId(self: Kind) []const u8 { + return switch (self) { + .agent_silent => "tawny-system:agent-silent", + .sensor_silent => "tawny-system:sensor-silent", + .agent_tamper => "tawny-system:agent-tamper", + }; + } + + pub fn ruleName(self: Kind) []const u8 { + return switch (self) { + .agent_silent => "Agent silent", + .sensor_silent => "Sensor silent", + .agent_tamper => "Agent tamper", + }; + } + + pub fn severity(self: Kind) []const u8 { + return switch (self) { + .agent_silent => "high", + .sensor_silent => "medium", + .agent_tamper => "high", + }; + } +}; + +/// A sensor with no events for this long while its agent heartbeats is quiet. +pub const sensor_silence_seconds: i64 = 15 * 60; + +const Rows = struct { + allocator: std.mem.Allocator, + rows: []pg.Row, + fn deinit(self: Rows) void { + for (self.rows) |r| r.deinit(self.allocator); + self.allocator.free(self.rows); + } +}; + +fn query(allocator: std.mem.Allocator, conn: *pg.Conn, sql: []const u8, params: []const pg.Value) !Rows { + return .{ .allocator = allocator, .rows = try conn.exec(allocator, sql, params) }; +} + +/// Id of the tenant's system rule for `kind`, creating it when missing. +/// Caller frees. +pub fn ensureRule(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, tenant: []const u8, kind: Kind) ![]u8 { + { + const found = try query(allocator, conn, + \\SELECT id::text FROM alert_rules WHERE tenant_id = $1::uuid AND external_id = $2 LIMIT 1 + , &.{ .{ .text = tenant }, .{ .text = kind.externalId() } }); + defer found.deinit(); + if (found.rows.len > 0) if (found.rows[0].cols[0]) |id| return allocator.dupe(u8, id); + } + var idbuf: [36]u8 = undefined; + const id = util.newUuid(io, &idbuf); + // Disabled, so the detect job never evaluates it against events. + const ins = try query(allocator, conn, + \\INSERT INTO alert_rules (id, tenant_id, name, format, external_id, description, severity, operator, + \\ is_enabled, created_at, updated_at) + \\VALUES ($1::uuid, $2::uuid, $3, 'tawny_predicate', $4, 'Raised by the Tawny server, not by event matching.', + \\ $5, 'exists', false, now(), now()) + \\ON CONFLICT (tenant_id, external_id) WHERE external_id LIKE 'tawny-system:%' DO NOTHING + \\RETURNING id::text + , &.{ + .{ .text = id }, + .{ .text = tenant }, + .{ .text = kind.ruleName() }, + .{ .text = kind.externalId() }, + .{ .text = kind.severity() }, + }); + defer ins.deinit(); + if (ins.rows.len > 0) return allocator.dupe(u8, ins.rows[0].cols[0].?); + // Lost a race with another writer: read theirs. + const again = try query(allocator, conn, + \\SELECT id::text FROM alert_rules WHERE tenant_id = $1::uuid AND external_id = $2 LIMIT 1 + , &.{ .{ .text = tenant }, .{ .text = kind.externalId() } }); + defer again.deinit(); + if (again.rows.len == 0) return error.SystemRuleMissing; + return allocator.dupe(u8, again.rows[0].cols[0].?); +} + +pub const Anchor = struct { + event_id: []const u8, + received_at: []const u8, +}; + +/// Insert the alert and queue it for the sinks. Returns the alert id (caller +/// frees). +pub fn raise( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + tenant: []const u8, + agent_id: []const u8, + kind: Kind, + title: []const u8, + description: []const u8, + anchor: Anchor, + now_rfc3339: []const u8, +) ![]u8 { + const rule_id = try ensureRule(allocator, io, conn, tenant, kind); + defer allocator.free(rule_id); + const ins = try query(allocator, conn, + \\INSERT INTO alerts (tenant_id, alert_rule_id, agent_id, telemetry_event_id, telemetry_received_at, + \\ severity, status, title, description, created_at) + \\VALUES ($1::uuid, $2::uuid, $3::uuid, $4::bigint, $5::timestamptz, $6, 'open', $7, $8, $9::timestamptz) + \\RETURNING id::text + , &.{ + .{ .text = tenant }, + .{ .text = rule_id }, + .{ .text = agent_id }, + .{ .text = anchor.event_id }, + .{ .text = anchor.received_at }, + .{ .text = kind.severity() }, + .{ .text = title }, + .{ .text = description }, + .{ .text = now_rfc3339 }, + }); + defer ins.deinit(); + const alert_id = try allocator.dupe(u8, ins.rows[0].cols[0].?); + errdefer allocator.free(alert_id); + const payload = try std.fmt.allocPrint(allocator, "{{\"alert_id\":\"{s}\",\"tenant_id\":\"{s}\"}}", .{ alert_id, tenant }); + defer allocator.free(payload); + try conn.execNoRows( + \\INSERT INTO work_queue (kind, tenant_id, payload) VALUES ('sink', $1::uuid, $2::jsonb) + , &.{ .{ .text = tenant }, .{ .text = payload } }); + return alert_id; +} + +/// Write a server-side marker event to anchor an alert. Not queued for +/// detection. Returns the anchor (caller frees both fields). +fn writeMarker(allocator: std.mem.Allocator, conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, event_type: []const u8, payload: []const u8, now_rfc3339: []const u8) !Anchor { + const rows = try query(allocator, conn, + \\INSERT INTO telemetry_events (received_at, tenant_id, agent_id, event_type, occurred_at, confidence, payload) + \\VALUES ($1::timestamptz, $2::uuid, $3::uuid, $4, $1::timestamptz, 'server_observed', $5::jsonb) + \\RETURNING id::text, received_at::text + , &.{ + .{ .text = now_rfc3339 }, + .{ .text = tenant }, + .{ .text = agent_id }, + .{ .text = event_type }, + .{ .text = payload }, + }); + defer rows.deinit(); + const ev = try allocator.dupe(u8, rows.rows[0].cols[0].?); + errdefer allocator.free(ev); + return .{ .event_id = ev, .received_at = try allocator.dupe(u8, rows.rows[0].cols[1].?) }; +} + +/// Close open alerts of `kind` for an agent. Returns how many were closed. +pub fn close(allocator: std.mem.Allocator, conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, kind: Kind) !usize { + const rows = try query(allocator, conn, + \\UPDATE alerts a SET status = 'resolved' + \\FROM alert_rules r + \\WHERE r.id = a.alert_rule_id AND r.tenant_id = a.tenant_id AND r.external_id = $3 + \\ AND a.tenant_id = $1::uuid AND a.agent_id = $2::uuid AND a.status = 'open' + \\RETURNING a.id::text + , &.{ .{ .text = tenant }, .{ .text = agent_id }, .{ .text = kind.externalId() } }); + defer rows.deinit(); + return rows.rows.len; +} + +// --------------------------------------------------------------------------- +// Agent silent + +/// Raise `Agent silent` for every agent that is offline, was not revoked, did +/// not send a clean shutdown notice, and has no open `Agent silent` alert. +/// Run after `stale.mark`. Returns how many alerts were raised. +pub fn raiseSilentAgents(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, now_rfc3339: []const u8) !u32 { + const candidates = try query(allocator, conn, + \\SELECT ag.tenant_id::text, ag.id::text, ag.hostname, ag.last_heartbeat_at::text + \\FROM agents ag + \\WHERE ag.status = 'offline' AND ag.revoked_at IS NULL + \\ AND ag.clean_shutdown_at IS NULL AND ag.last_heartbeat_at IS NOT NULL + \\ AND NOT EXISTS ( + \\ SELECT 1 FROM alerts a JOIN alert_rules r ON r.id = a.alert_rule_id + \\ WHERE a.tenant_id = ag.tenant_id AND a.agent_id = ag.id AND a.status = 'open' + \\ AND r.external_id = 'tawny-system:agent-silent') + \\ORDER BY ag.last_heartbeat_at + \\LIMIT 500 + , &.{}); + defer candidates.deinit(); + var raised: u32 = 0; + for (candidates.rows) |row| { + const tenant = row.cols[0] orelse continue; + const agent_id = row.cols[1] orelse continue; + const hostname = row.cols[2] orelse ""; + const last = row.cols[3] orelse ""; + const host_j = try util.escapeJson(allocator, hostname); + defer allocator.free(host_j); + const last_j = try util.escapeJson(allocator, last); + defer allocator.free(last_j); + const payload = try std.fmt.allocPrint(allocator, "{{\"hostname\":{s},\"last_heartbeat_at\":{s},\"reason\":\"offline without a clean shutdown notice\"}}", .{ host_j, last_j }); + defer allocator.free(payload); + const anchor = try writeMarker(allocator, conn, tenant, agent_id, "agent_silent", payload, now_rfc3339); + defer { + allocator.free(anchor.event_id); + allocator.free(anchor.received_at); + } + const title = try std.fmt.allocPrint(allocator, "Agent silent on {s}", .{hostname}); + defer allocator.free(title); + const desc = try std.fmt.allocPrint(allocator, "{s} stopped sending heartbeats without a clean shutdown notice. Last heartbeat {s}.", .{ hostname, last }); + defer allocator.free(desc); + const id = try raise(allocator, io, conn, tenant, agent_id, .agent_silent, title, desc, anchor, now_rfc3339); + allocator.free(id); + raised += 1; + } + return raised; +} + +/// Heartbeat hook. `shutdown` is true for the clean shutdown notice. A normal +/// heartbeat clears an earlier notice and closes any open `Agent silent`. +pub fn onHeartbeat(allocator: std.mem.Allocator, conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, shutdown: bool, reason: []const u8, now_rfc3339: []const u8) !void { + if (shutdown) { + try conn.execNoRows( + \\UPDATE agents SET clean_shutdown_at = $3::timestamptz, clean_shutdown_reason = $4 + \\WHERE id = $1::uuid AND tenant_id = $2::uuid + , &.{ .{ .text = agent_id }, .{ .text = tenant }, .{ .text = now_rfc3339 }, .{ .text = reason } }); + return; + } + try conn.execNoRows( + \\UPDATE agents SET clean_shutdown_at = NULL, clean_shutdown_reason = NULL + \\WHERE id = $1::uuid AND tenant_id = $2::uuid AND clean_shutdown_at IS NOT NULL + , &.{ .{ .text = agent_id }, .{ .text = tenant } }); + _ = try close(allocator, conn, tenant, agent_id, .agent_silent); +} + +// --------------------------------------------------------------------------- +// Sensors + +/// What a sensor reported, normalised. `running` covers ok and degraded +/// states that still deliver. `stopped` covers stopped, failed, missing and +/// access_denied. `silent` is the agent's own 15 minute silence verdict. +pub const SensorState = enum { running, silent, stopped, unknown }; + +pub fn classify(state: []const u8) SensorState { + const running = [_][]const u8{ "ok", "running", "degraded" }; + const stopped = [_][]const u8{ "stopped", "failed", "missing", "access_denied" }; + for (running) |s| if (std.ascii.eqlIgnoreCase(s, state)) return .running; + for (stopped) |s| if (std.ascii.eqlIgnoreCase(s, state)) return .stopped; + if (std.ascii.eqlIgnoreCase(state, "silent")) return .silent; + return .unknown; +} + +/// Sensors that deliver all the time on a working host. The others are +/// event-driven and can be quiet for hours. +pub fn isContinuous(sensor: []const u8) bool { + const continuous = [_][]const u8{ + "Microsoft-Windows-Sysmon/Operational", + "Security", + }; + for (continuous) |c| if (std.mem.eql(u8, c, sensor)) return true; + return false; +} + +pub const SensorReport = struct { + sensor: []const u8, + state: []const u8, + /// Seconds since the sensor's last event, when the agent knows it. + last_event_age_seconds: ?i64 = null, +}; + +/// Ingest hook for `sensor_health` and `agent_health`. Upserts the per-sensor +/// row; a sensor that was running and is now stopped (or silent by the +/// agent's own clock) raises `Sensor silent`, and one that runs again closes +/// it. +pub fn recordSensor( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + tenant: []const u8, + agent_id: []const u8, + hostname: []const u8, + report: SensorReport, + anchor: Anchor, + now_unix: i64, +) !void { + var nbuf: [32]u8 = undefined; + const now_s = util.formatRfc3339(&nbuf, now_unix); + const state = classify(report.state); + var lbuf: [32]u8 = undefined; + // Only agent_health carries a last event age, refreshed every heartbeat. + // sensor_health fires on state changes only, so it never feeds the + // server-side quiet check (that would alert 15 minutes after any "ok"). + const last_event: ?[]const u8 = if (report.last_event_age_seconds) |age| + util.formatRfc3339(&lbuf, now_unix - @max(age, 0)) + else + null; + + const prev = try query(allocator, conn, + \\SELECT state, was_running::text, open_alert_id::text FROM sensor_status + \\WHERE tenant_id = $1::uuid AND agent_id = $2::uuid AND sensor = $3 + , &.{ .{ .text = tenant }, .{ .text = agent_id }, .{ .text = report.sensor } }); + defer prev.deinit(); + const had = prev.rows.len > 0; + const was_running = had and std.mem.eql(u8, prev.rows[0].cols[1] orelse "false", "true"); + const open_alert = if (had) prev.rows[0].cols[2] else null; + const state_text = @tagName(state); + const changed = !had or !std.mem.eql(u8, prev.rows[0].cols[0] orelse "", state_text); + + try conn.execNoRows( + \\INSERT INTO sensor_status (tenant_id, agent_id, sensor, state, state_since, was_running, continuous, last_event_at, updated_at) + \\VALUES ($1::uuid, $2::uuid, $3, $4, $5::timestamptz, $6::boolean, $7::boolean, $8::timestamptz, $5::timestamptz) + \\ON CONFLICT (tenant_id, agent_id, sensor) DO UPDATE SET + \\ state = EXCLUDED.state, + \\ state_since = CASE WHEN sensor_status.state = EXCLUDED.state THEN sensor_status.state_since ELSE EXCLUDED.state_since END, + \\ was_running = sensor_status.was_running OR EXCLUDED.was_running, + \\ last_event_at = COALESCE(EXCLUDED.last_event_at, sensor_status.last_event_at), + \\ updated_at = EXCLUDED.updated_at + , &.{ + .{ .text = tenant }, + .{ .text = agent_id }, + .{ .text = report.sensor }, + .{ .text = state_text }, + .{ .text = now_s }, + .{ .text = if (state == .running) "true" else "false" }, + .{ .text = if (isContinuous(report.sensor)) "true" else "false" }, + if (last_event) |l| .{ .text = l } else .{ .null = {} }, + }); + + if (state == .running) { + if (open_alert) |id| try resolveSensorAlert(conn, tenant, agent_id, report.sensor, id); + return; + } + if (!changed or !was_running or open_alert != null) return; + if (state != .stopped and state != .silent) return; + // Sparse channels (PowerShell, System) are often quiet for hours; only a + // stop or failure is news for them. + if (state == .silent and !isContinuous(report.sensor)) return; + const why = if (state == .silent) "reported no events for 15 minutes" else "stopped"; + const id = try raiseSensor(allocator, io, conn, tenant, agent_id, hostname, report.sensor, report.state, why, anchor, now_s); + allocator.free(id); +} + +fn raiseSensor( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + tenant: []const u8, + agent_id: []const u8, + hostname: []const u8, + sensor: []const u8, + state: []const u8, + why: []const u8, + anchor: Anchor, + now_s: []const u8, +) ![]u8 { + const title = try std.fmt.allocPrint(allocator, "Sensor silent on {s}: {s}", .{ hostname, sensor }); + defer allocator.free(title); + const desc = try std.fmt.allocPrint(allocator, "Sensor {s} on {s} was running and {s} (state {s}).", .{ sensor, hostname, why, state }); + defer allocator.free(desc); + const id = try raise(allocator, io, conn, tenant, agent_id, .sensor_silent, title, desc, anchor, now_s); + errdefer allocator.free(id); + try conn.execNoRows( + \\UPDATE sensor_status SET open_alert_id = $4::bigint + \\WHERE tenant_id = $1::uuid AND agent_id = $2::uuid AND sensor = $3 + , &.{ .{ .text = tenant }, .{ .text = agent_id }, .{ .text = sensor }, .{ .text = id } }); + return id; +} + +fn resolveSensorAlert(conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, sensor: []const u8, alert_id: []const u8) !void { + try conn.execNoRows( + \\UPDATE alerts SET status = 'resolved' WHERE id = $1::bigint AND tenant_id = $2::uuid AND status = 'open' + , &.{ .{ .text = alert_id }, .{ .text = tenant } }); + try conn.execNoRows( + \\UPDATE sensor_status SET open_alert_id = NULL + \\WHERE tenant_id = $1::uuid AND agent_id = $2::uuid AND sensor = $3 + , &.{ .{ .text = tenant }, .{ .text = agent_id }, .{ .text = sensor } }); +} + +/// Periodic check: a continuous sensor that was running, whose agent is +/// online, and that has no event for 15 minutes raises `Sensor silent`. This +/// catches a sensor that stops without the agent noticing, for example when +/// the agent's own channel health is wedged. Returns alerts raised. +pub fn raiseQuietSensors(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, now_unix: i64) !u32 { + var nbuf: [32]u8 = undefined; + const now_s = util.formatRfc3339(&nbuf, now_unix); + const rows = try query(allocator, conn, + \\SELECT s.tenant_id::text, s.agent_id::text, ag.hostname, s.sensor, s.state, s.last_event_at::text + \\FROM sensor_status s JOIN agents ag ON ag.id = s.agent_id AND ag.tenant_id = s.tenant_id + \\WHERE s.was_running AND s.continuous AND s.open_alert_id IS NULL + \\ AND ag.status = 'online' AND ag.revoked_at IS NULL + \\ AND s.last_event_at IS NOT NULL + \\ AND s.last_event_at <= $1::timestamptz - interval '15 minutes' + \\LIMIT 500 + , &.{.{ .text = now_s }}); + defer rows.deinit(); + var raised: u32 = 0; + for (rows.rows) |row| { + const tenant = row.cols[0] orelse continue; + const agent_id = row.cols[1] orelse continue; + const hostname = row.cols[2] orelse ""; + const sensor = row.cols[3] orelse continue; + const last = row.cols[5] orelse ""; + const sensor_j = try util.escapeJson(allocator, sensor); + defer allocator.free(sensor_j); + const last_j = try util.escapeJson(allocator, last); + defer allocator.free(last_j); + const payload = try std.fmt.allocPrint(allocator, "{{\"sensor\":{s},\"last_event_at\":{s},\"silent_seconds_threshold\":{d}}}", .{ sensor_j, last_j, sensor_silence_seconds }); + defer allocator.free(payload); + const anchor = try writeMarker(allocator, conn, tenant, agent_id, "sensor_silent", payload, now_s); + defer { + allocator.free(anchor.event_id); + allocator.free(anchor.received_at); + } + const why = try std.fmt.allocPrint(allocator, "has delivered no events since {s}", .{last}); + defer allocator.free(why); + const id = try raiseSensor(allocator, io, conn, tenant, agent_id, hostname, sensor, row.cols[4] orelse "", why, anchor, now_s); + allocator.free(id); + raised += 1; + } + return raised; +} + +/// Pull sensor reports out of a `sensor_health` or `agent_health` payload. +/// `sensor_health` names one channel; `agent_health.sensors` is an array of +/// `{name, status, last_event_age_seconds}`. +pub fn sensorReports(allocator: std.mem.Allocator, event_type: []const u8, payload: std.json.Value) ![]SensorReport { + var out: std.ArrayList(SensorReport) = .empty; + errdefer out.deinit(allocator); + if (payload != .object) return out.toOwnedSlice(allocator); + const obj = payload.object; + if (std.mem.eql(u8, event_type, "sensor_health")) { + const ch = obj.get("channel") orelse return out.toOwnedSlice(allocator); + const st = obj.get("state") orelse return out.toOwnedSlice(allocator); + if (ch != .string or st != .string) return out.toOwnedSlice(allocator); + try out.append(allocator, .{ .sensor = ch.string, .state = st.string }); + } else if (std.mem.eql(u8, event_type, "agent_health")) { + const list = obj.get("sensors") orelse return out.toOwnedSlice(allocator); + if (list != .array) return out.toOwnedSlice(allocator); + for (list.array.items) |item| { + if (item != .object) continue; + const name = item.object.get("name") orelse continue; + const st = item.object.get("status") orelse continue; + if (name != .string or st != .string) continue; + if (name.string.len == 0 or name.string.len > 200) continue; + const age: ?i64 = if (item.object.get("last_event_age_seconds")) |a| switch (a) { + .integer => |n| n, + else => null, + } else null; + try out.append(allocator, .{ .sensor = name.string, .state = st.string, .last_event_age_seconds = age }); + if (out.items.len == 32) break; + } + } + return out.toOwnedSlice(allocator); +} + +/// Ingest hook for `agent_tamper`: one alert per event. +pub fn onTamper(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, hostname: []const u8, payload: std.json.Value, anchor: Anchor, now_unix: i64) !void { + var nbuf: [32]u8 = undefined; + const now_s = util.formatRfc3339(&nbuf, now_unix); + var kind_buf: []const u8 = "unknown"; + var detail: []const u8 = ""; + if (payload == .object) { + if (payload.object.get("check")) |v| if (v == .string) { + kind_buf = v.string; + }; + if (payload.object.get("detail")) |v| if (v == .string) { + detail = v.string; + }; + } + const title = try std.fmt.allocPrint(allocator, "Agent tamper on {s}: {s}", .{ hostname, kind_buf }); + defer allocator.free(title); + const desc = try std.fmt.allocPrint(allocator, "{s}", .{detail}); + defer allocator.free(desc); + const id = try raise(allocator, io, conn, tenant, agent_id, .agent_tamper, title, desc, anchor, now_s); + allocator.free(id); +} + +/// Ingest hook for `agent_health`: record update state and key protection. +pub fn recordHealth(conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, payload: std.json.Value, now_rfc3339: []const u8) !void { + if (payload != .object) return; + const obj = payload.object; + const key = strField(obj, "key_protection"); + var state: ?[]const u8 = null; + var version: ?[]const u8 = null; + if (obj.get("update")) |u| if (u == .object) { + state = strField(u.object, "state"); + version = strField(u.object, "version"); + }; + if (key == null and state == null) return; + try conn.execNoRows( + \\UPDATE agents SET + \\ key_protection = COALESCE($3, key_protection), + \\ update_state = COALESCE($4, update_state), + \\ update_version = CASE WHEN $4 IS NULL THEN update_version ELSE $5 END, + \\ update_state_at = CASE WHEN $4 IS NULL THEN update_state_at ELSE $6::timestamptz END + \\WHERE id = $1::uuid AND tenant_id = $2::uuid + , &.{ + .{ .text = agent_id }, + .{ .text = tenant }, + if (key) |k| .{ .text = k } else .{ .null = {} }, + if (state) |s| .{ .text = s } else .{ .null = {} }, + if (version) |v| .{ .text = v } else .{ .null = {} }, + .{ .text = now_rfc3339 }, + }); +} + +fn strField(obj: std.json.ObjectMap, name: []const u8) ?[]const u8 { + const v = obj.get(name) orelse return null; + if (v != .string or v.string.len == 0 or v.string.len > 64) return null; + return v.string; +} + +// --------------------------------------------------------------------------- +// Tests + +test "sensor states classify and continuous sensors are named" { + try std.testing.expectEqual(SensorState.running, classify("ok")); + try std.testing.expectEqual(SensorState.running, classify("degraded")); + try std.testing.expectEqual(SensorState.stopped, classify("missing")); + try std.testing.expectEqual(SensorState.stopped, classify("failed")); + try std.testing.expectEqual(SensorState.silent, classify("silent")); + try std.testing.expectEqual(SensorState.unknown, classify("unknown")); + try std.testing.expect(isContinuous("Microsoft-Windows-Sysmon/Operational")); + try std.testing.expect(!isContinuous("Microsoft-Windows-PowerShell/Operational")); +} + +test "sensor reports come from sensor_health and agent_health" { + const a = std.testing.allocator; + var p1 = try std.json.parseFromSlice(std.json.Value, a, + \\{"sensor":"windows_eventlog","channel":"Security","state":"silent"} + , .{}); + defer p1.deinit(); + const r1 = try sensorReports(a, "sensor_health", p1.value); + defer a.free(r1); + try std.testing.expectEqual(@as(usize, 1), r1.len); + try std.testing.expectEqualStrings("Security", r1[0].sensor); + + var p2 = try std.json.parseFromSlice(std.json.Value, a, + \\{"sensors":[{"name":"process_events","status":"running","last_event_age_seconds":4},{"name":7},{"name":"dns","status":"stopped"}]} + , .{}); + defer p2.deinit(); + const r2 = try sensorReports(a, "agent_health", p2.value); + defer a.free(r2); + try std.testing.expectEqual(@as(usize, 2), r2.len); + try std.testing.expectEqual(@as(?i64, 4), r2[0].last_event_age_seconds); + try std.testing.expectEqualStrings("dns", r2[1].sensor); +} + +const default_tenant = "00000000-0000-0000-0000-000000000001"; +const silent_agent = "00000000-0000-0000-0000-00000000e801"; +const clean_agent = "00000000-0000-0000-0000-00000000e802"; +const revoked_agent = "00000000-0000-0000-0000-00000000e803"; +const sensor_agent = "00000000-0000-0000-0000-00000000e804"; + +fn testConn(allocator: std.mem.Allocator) !?*pg.Conn { + const url = std.testing.environ.getPosix("TAWNY_DATABASE_URL") orelse return null; + if (url.len == 0) return null; + return try pg.Conn.connect(allocator, std.testing.io, url); +} + +fn insertAgent(conn: *pg.Conn, id: []const u8, host: []const u8, status: []const u8, heartbeat: []const u8, revoked: bool, clean: bool) !void { + try conn.execNoRows( + \\INSERT INTO agents (id, tenant_id, hostname, operating_system, os_version, agent_version, + \\ architecture, enrolled_at, last_heartbeat_at, status, revoked_at, clean_shutdown_at) + \\VALUES ($1, $2, $3, 'windows', 'test', '0', 'x64', '2026-05-14T07:00:00Z', $4::timestamptz, $5, + \\ CASE WHEN $6::boolean THEN '2026-05-14T07:30:00Z'::timestamptz END, + \\ CASE WHEN $7::boolean THEN $4::timestamptz END) + , &.{ + .{ .text = id }, + .{ .text = default_tenant }, + .{ .text = host }, + .{ .text = heartbeat }, + .{ .text = status }, + .{ .text = if (revoked) "true" else "false" }, + .{ .text = if (clean) "true" else "false" }, + }); +} + +fn countOpen(allocator: std.mem.Allocator, conn: *pg.Conn, agent_id: []const u8, kind: Kind) !usize { + const rows = try query(allocator, conn, + \\SELECT count(*)::text FROM alerts a JOIN alert_rules r ON r.id = a.alert_rule_id + \\WHERE a.agent_id = $1::uuid AND a.status = 'open' AND r.external_id = $2 + , &.{ .{ .text = agent_id }, .{ .text = kind.externalId() } }); + defer rows.deinit(); + return std.fmt.parseInt(usize, rows.rows[0].cols[0].?, 10); +} + +test "offline agent without a shutdown notice raises Agent silent, heartbeat closes it" { + const allocator = std.testing.allocator; + const conn = (try testConn(allocator)) orelse return; + defer { + conn.close(); + allocator.destroy(conn); + } + try conn.execSimple("BEGIN"); + errdefer conn.execSimple("ROLLBACK") catch {}; + const stale = @import("stale.zig"); + + try insertAgent(conn, silent_agent, "silent-host", "online", "2026-05-14T07:40:00Z", false, false); + try insertAgent(conn, clean_agent, "clean-host", "online", "2026-05-14T07:40:00Z", false, true); + try insertAgent(conn, revoked_agent, "revoked-host", "revoked", "2026-05-14T07:40:00Z", true, false); + + try stale.mark(conn, "2026-05-14T08:00:00Z"); + const io = std.testing.io; + try std.testing.expectEqual(@as(u32, 1), try raiseSilentAgents(allocator, io, conn, "2026-05-14T08:00:00Z")); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, silent_agent, .agent_silent)); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, clean_agent, .agent_silent)); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, revoked_agent, .agent_silent)); + + // The title names the host and the description the last heartbeat. + { + const rows = try query(allocator, conn, + \\SELECT a.title || '|' || a.description || '|' || te.event_type FROM alerts a + \\JOIN telemetry_events te ON te.id = a.telemetry_event_id AND te.received_at = a.telemetry_received_at + \\WHERE a.agent_id = $1::uuid + , &.{.{ .text = silent_agent }}); + defer rows.deinit(); + const text = rows.rows[0].cols[0].?; + try std.testing.expect(std.mem.indexOf(u8, text, "Agent silent on silent-host") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "2026-05-14 07:40:00") != null); + try std.testing.expect(std.mem.endsWith(u8, text, "|agent_silent")); + } + + // Second pass raises nothing new. + try std.testing.expectEqual(@as(u32, 0), try raiseSilentAgents(allocator, io, conn, "2026-05-14T08:01:00Z")); + + // Next heartbeat closes it. + try onHeartbeat(allocator, conn, default_tenant, silent_agent, false, "", "2026-05-14T08:05:00Z"); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, silent_agent, .agent_silent)); + + // Clean shutdown notice, then offline: no alert. + try onHeartbeat(allocator, conn, default_tenant, silent_agent, true, "service_stop", "2026-05-14T08:06:00Z"); + try conn.execNoRows("UPDATE agents SET status = 'offline' WHERE id = $1::uuid", &.{.{ .text = silent_agent }}); + try std.testing.expectEqual(@as(u32, 0), try raiseSilentAgents(allocator, io, conn, "2026-05-14T08:30:00Z")); + try conn.execSimple("ROLLBACK"); +} + +test "a running sensor that goes quiet raises Sensor silent, and delivery closes it" { + const allocator = std.testing.allocator; + const conn = (try testConn(allocator)) orelse return; + defer { + conn.close(); + allocator.destroy(conn); + } + try conn.execSimple("BEGIN"); + errdefer conn.execSimple("ROLLBACK") catch {}; + const io = std.testing.io; + try insertAgent(conn, sensor_agent, "sensor-host", "online", "2026-05-14T08:00:00Z", false, false); + const ev = try query(allocator, conn, + \\INSERT INTO telemetry_events (received_at, tenant_id, agent_id, event_type, occurred_at, payload) + \\VALUES ('2026-05-14T08:00:00Z', $1::uuid, $2::uuid, 'sensor_health', '2026-05-14T08:00:00Z', '{}') + \\RETURNING id::text, received_at::text + , &.{ .{ .text = default_tenant }, .{ .text = sensor_agent } }); + defer ev.deinit(); + const anchor: Anchor = .{ .event_id = ev.rows[0].cols[0].?, .received_at = ev.rows[0].cols[1].? }; + const sysmon = "Microsoft-Windows-Sysmon/Operational"; + const t0: i64 = 1778745600; // 2026-05-14T08:00:00Z + + // A sensor that was never running does not alert when it reports missing. + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = "Microsoft-Windows-PowerShell/Operational", .state = "missing" }, anchor, t0); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + + // Sysmon running, then the agent reports it silent: one alert. + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = sysmon, .state = "ok" }, anchor, t0); + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = sysmon, .state = "silent" }, anchor, t0 + 900); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + // Repeating the report adds nothing. + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = sysmon, .state = "silent" }, anchor, t0 + 960); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + // Delivery again closes it. + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = sysmon, .state = "ok" }, anchor, t0 + 1000); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + + // A sparse channel going quiet is not news; stopping is. + const ps = "Microsoft-Windows-PowerShell/Operational"; + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = ps, .state = "ok" }, anchor, t0); + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = ps, .state = "silent" }, anchor, t0 + 900); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = ps, .state = "failed" }, anchor, t0 + 960); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = ps, .state = "ok" }, anchor, t0 + 990); + try std.testing.expectEqual(@as(usize, 0), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + + // Server-side check: Security running per agent_health, nothing for 20 minutes. + try recordSensor(allocator, io, conn, default_tenant, sensor_agent, "sensor-host", .{ .sensor = "Security", .state = "running", .last_event_age_seconds = 0 }, anchor, t0); + try std.testing.expectEqual(@as(u32, 0), try raiseQuietSensors(allocator, io, conn, t0 + 600)); + try std.testing.expectEqual(@as(u32, 1), try raiseQuietSensors(allocator, io, conn, t0 + 1200)); + try std.testing.expectEqual(@as(u32, 0), try raiseQuietSensors(allocator, io, conn, t0 + 1300)); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, sensor_agent, .sensor_silent)); + try conn.execSimple("ROLLBACK"); +} + +test "agent_tamper raises one alert per event and health records update state" { + const allocator = std.testing.allocator; + const conn = (try testConn(allocator)) orelse return; + defer { + conn.close(); + allocator.destroy(conn); + } + try conn.execSimple("BEGIN"); + errdefer conn.execSimple("ROLLBACK") catch {}; + const io = std.testing.io; + try insertAgent(conn, sensor_agent, "tamper-host", "online", "2026-05-14T08:00:00Z", false, false); + const ev = try query(allocator, conn, + \\INSERT INTO telemetry_events (received_at, tenant_id, agent_id, event_type, occurred_at, payload) + \\VALUES ('2026-05-14T08:00:00Z', $1::uuid, $2::uuid, 'agent_tamper', '2026-05-14T08:00:00Z', '{}') + \\RETURNING id::text, received_at::text + , &.{ .{ .text = default_tenant }, .{ .text = sensor_agent } }); + defer ev.deinit(); + const anchor: Anchor = .{ .event_id = ev.rows[0].cols[0].?, .received_at = ev.rows[0].cols[1].? }; + var p = try std.json.parseFromSlice(std.json.Value, allocator, + \\{"check":"unexpected_stop","detail":"no clean shutdown marker from the last run"} + , .{}); + defer p.deinit(); + try onTamper(allocator, io, conn, default_tenant, sensor_agent, "tamper-host", p.value, anchor, 1778745600); + try std.testing.expectEqual(@as(usize, 1), try countOpen(allocator, conn, sensor_agent, .agent_tamper)); + + var h = try std.json.parseFromSlice(std.json.Value, allocator, + \\{"key_protection":"dpapi","update":{"state":"staged","version":"0.2.0"}} + , .{}); + defer h.deinit(); + try recordHealth(conn, default_tenant, sensor_agent, h.value, "2026-05-14T08:00:00Z"); + const rows = try query(allocator, conn, "SELECT key_protection || '|' || update_state || '|' || update_version FROM agents WHERE id = $1::uuid", &.{.{ .text = sensor_agent }}); + defer rows.deinit(); + try std.testing.expectEqualStrings("dpapi|staged|0.2.0", rows.rows[0].cols[0].?); + try conn.execSimple("ROLLBACK"); +} diff --git a/server/src/jobs/backup.zig b/server/src/jobs/backup.zig index a65db38..0693fa3 100644 --- a/server/src/jobs/backup.zig +++ b/server/src/jobs/backup.zig @@ -147,6 +147,9 @@ fn eventTypeNumber(kind: []const u8) ?u8 { "sensor_health", "agent_health", "yara_match", + "agent_tamper", + "agent_silent", + "sensor_silent", }; for (names, 0..) |name, i| if (std.mem.eql(u8, name, kind)) return @intCast(i); return null; @@ -160,6 +163,8 @@ test "event type numbers are stable and cover the Windows event log types" { try std.testing.expectEqual(@as(?u8, 30), eventTypeNumber("sensor_health")); try std.testing.expectEqual(@as(?u8, 31), eventTypeNumber("agent_health")); try std.testing.expectEqual(@as(?u8, 32), eventTypeNumber("yara_match")); + try std.testing.expectEqual(@as(?u8, 33), eventTypeNumber("agent_tamper")); + try std.testing.expectEqual(@as(?u8, 35), eventTypeNumber("sensor_silent")); try std.testing.expectEqual(@as(?u8, null), eventTypeNumber("not_a_type")); } diff --git a/server/src/jobs/deliver.zig b/server/src/jobs/deliver.zig index fb7ae2d..ffd717d 100644 --- a/server/src/jobs/deliver.zig +++ b/server/src/jobs/deliver.zig @@ -272,6 +272,9 @@ fn pascalEvent(event_type: []const u8) []const u8 { if (std.mem.eql(u8, event_type, "sensor_health")) return "SensorHealth"; if (std.mem.eql(u8, event_type, "agent_health")) return "AgentHealth"; if (std.mem.eql(u8, event_type, "yara_match")) return "YaraMatch"; + if (std.mem.eql(u8, event_type, "agent_tamper")) return "AgentTamper"; + if (std.mem.eql(u8, event_type, "agent_silent")) return "AgentSilent"; + if (std.mem.eql(u8, event_type, "sensor_silent")) return "SensorSilent"; return event_type; } diff --git a/server/src/main.zig b/server/src/main.zig index 73ff430..f07fce7 100644 --- a/server/src/main.zig +++ b/server/src/main.zig @@ -8,6 +8,7 @@ const detect = @import("jobs/detect.zig"); const deliver = @import("jobs/deliver.zig"); const purge = @import("jobs/purge.zig"); const stale = @import("jobs/stale.zig"); +const agent_alerts = @import("jobs/agent_alerts.zig"); const hunts = @import("jobs/hunts.zig"); const threat_intel = @import("jobs/threat_intel.zig"); const reputation = @import("jobs/reputation.zig"); @@ -290,6 +291,10 @@ fn runJobs( })) |_| {} else |err| { std.debug.print("release check failed: {s}\n", .{@errorName(err)}); } + // Gated ring promotion (#58). + if (releases.promote(allocator, conn, now, .{})) |n| { + if (n > 0) std.debug.print("promoted {d} release ring(s)\n", .{n}); + } else |err| std.debug.print("release promotion failed: {s}\n", .{@errorName(err)}); } if (now - last_stale.* >= 60) { last_stale.* = now; @@ -298,6 +303,13 @@ fn runJobs( stale.mark(conn, stamp) catch |err| { std.debug.print("stale job failed: {s}\n", .{@errorName(err)}); }; + // #58: offline without a clean shutdown notice, and quiet sensors. + if (agent_alerts.raiseSilentAgents(allocator, io, conn, stamp)) |n| { + if (n > 0) std.debug.print("raised {d} Agent silent alert(s)\n", .{n}); + } else |err| std.debug.print("agent silent job failed: {s}\n", .{@errorName(err)}); + if (agent_alerts.raiseQuietSensors(allocator, io, conn, now)) |n| { + if (n > 0) std.debug.print("raised {d} Sensor silent alert(s)\n", .{n}); + } else |err| std.debug.print("quiet sensor job failed: {s}\n", .{@errorName(err)}); } if (now - last_ai.* >= 30) { last_ai.* = now; @@ -481,6 +493,7 @@ comptime { _ = @import("jobs/deliver.zig"); _ = @import("jobs/purge.zig"); _ = @import("jobs/stale.zig"); + _ = @import("jobs/agent_alerts.zig"); _ = @import("jobs/hunts.zig"); _ = @import("hunts/query.zig"); _ = @import("jobs/threat_intel.zig"); diff --git a/server/src/routes/agents.zig b/server/src/routes/agents.zig index ae2980c..89fc3c2 100644 --- a/server/src/routes/agents.zig +++ b/server/src/routes/agents.zig @@ -11,6 +11,7 @@ const ingest_v2 = @import("../ingest/v2.zig"); const ingest_entity = @import("../ingest/entity.zig"); const legacy = @import("../ingest/legacy.zig"); const process_store = @import("../ingest/process_store.zig"); +const agent_alerts = @import("../jobs/agent_alerts.zig"); const Sha256 = std.crypto.hash.sha2.Sha256; pub fn createEnrollmentToken( @@ -352,6 +353,9 @@ pub fn heartbeat( agent_version: []const u8, uptime_seconds: i64, buffer_depth: i64, + /// Clean shutdown notice (#58): sent once as the agent stops. + shutdown: bool = false, + shutdown_reason: []const u8 = "", }; var parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch { return util.problem(request, allocator, .bad_request, "Invalid heartbeat body."); @@ -394,6 +398,18 @@ pub fn heartbeat( try audit.add(allocator, io, conn, agent.tenant_id, null, "agent.heartbeat_change", agent.agent_id, null); } + // Clean shutdown notice, or a normal heartbeat that closes Agent silent. + { + const reason = parsed.value.shutdown_reason; + const safe_reason = if (reason.len <= 64 and !util.hasControlChars(reason)) reason else ""; + try agent_alerts.onHeartbeat(allocator, conn, agent.tenant_id, agent.agent_id, parsed.value.shutdown, safe_reason, now_s); + if (parsed.value.shutdown) { + try audit.add(allocator, io, conn, agent.tenant_id, null, "agent.clean_shutdown", agent.agent_id, null); + // A stopping agent gets no actions and no rotated token. + return util.respondJson(request, .ok, "{\"actions\":[]}"); + } + } + // Expire stale actions try conn.execNoRows( \\UPDATE response_actions SET status = 'expired', completed_at = $2::timestamptz, execution_token_hash = NULL @@ -740,6 +756,43 @@ fn loadIngestAgent(allocator: std.mem.Allocator, conn: *pg.Conn, request: *std.h }; } +/// #58 hooks: sensor status from sensor_health and agent_health, update and +/// key state from agent_health, and an alert for every agent_tamper. Errors +/// are logged, never fatal to ingest. +fn onHardeningEvent( + allocator: std.mem.Allocator, + io: std.Io, + conn: *pg.Conn, + agent: auth.AgentAuth, + hostname: []const u8, + ev: IngestEvent, + anchor: agent_alerts.Anchor, + now: i64, +) !void { + const eq = std.mem.eql; + const t = ev.event_type; + if (eq(u8, t, "agent_tamper")) { + agent_alerts.onTamper(allocator, io, conn, agent.tenant_id, agent.agent_id, hostname, ev.payload, anchor, now) catch |err| { + std.debug.print("agent_tamper alert failed: {s}\n", .{@errorName(err)}); + }; + return; + } + if (!eq(u8, t, "sensor_health") and !eq(u8, t, "agent_health")) return; + if (eq(u8, t, "agent_health")) { + var nbuf: [32]u8 = undefined; + agent_alerts.recordHealth(conn, agent.tenant_id, agent.agent_id, ev.payload, util.formatRfc3339(&nbuf, now)) catch |err| { + std.debug.print("agent_health record failed: {s}\n", .{@errorName(err)}); + }; + } + const reports = try agent_alerts.sensorReports(allocator, t, ev.payload); + defer allocator.free(reports); + for (reports) |r| { + agent_alerts.recordSensor(allocator, io, conn, agent.tenant_id, agent.agent_id, hostname, r, anchor, now) catch |err| { + std.debug.print("sensor status {s} failed: {s}\n", .{ r.sensor, @errorName(err) }); + }; + } +} + /// Store a batch of either schema: dedupe, insert, process entities, detect /// queue, sequence bookkeeping. Both schemas end here, so v1 and v2 agents /// ingest side by side. @@ -845,6 +898,7 @@ fn storeBatch( } inserted += 1; try detect.enqueue(allocator, conn, agent.tenant_id, agent.agent_id, ctx.hostname, ev.event_type, event_id, recv_at); + try onHardeningEvent(allocator, io, conn, agent, ctx.hostname, ev, .{ .event_id = event_id, .received_at = recv_at }, now); } if (!rollback) { From b966e7669345637db0baa5efff7971e068349184 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:03 +1100 Subject: [PATCH 2/8] feat(server): release rings, update-check and gated promotion - GET /api/releases/latest takes an optional ring query. - POST /api/agent/update-check returns the signed manifest, signature and download URL when the latest release is open to the agent's ring (update_ring override, else sha256(agent_id) mod 100). - The release sync stores published .manifest.json and .minisig assets and starts new releases in canary. promote() widens a ring after a 24 hour soak while no more than 5% of reporting agents rolled back. Co-Authored-By: Claude Opus 5.5 --- server/src/http/dispatch.zig | 4 + server/src/jobs/releases.zig | 150 +++++++++++++++++++++++- server/src/routes/agent_releases.zig | 165 ++++++++++++++++++++++++++- 3 files changed, 308 insertions(+), 11 deletions(-) diff --git a/server/src/http/dispatch.zig b/server/src/http/dispatch.zig index d4554d3..9f60d68 100644 --- a/server/src/http/dispatch.zig +++ b/server/src/http/dispatch.zig @@ -112,6 +112,10 @@ fn route( const agent = try needAgent(request, resolved) orelse return; return yara_rules.agentPack(allocator, io, conn, request, agent); } + if (parts.len == 3 and std.mem.eql(u8, parts[0], "api") and std.mem.eql(u8, parts[1], "agent") and std.mem.eql(u8, parts[2], "update-check") and method == .POST) { + const agent = try needAgent(request, resolved) orelse return; + return agent_releases.updateCheck(allocator, conn, request, agent); + } if (parts.len == 3 and std.mem.eql(u8, parts[0], "api") and std.mem.eql(u8, parts[1], "yara") and std.mem.eql(u8, parts[2], "rule-key") and method == .GET) { _ = try needWeb(request, resolved) orelse return; return yara_rules.ruleKey(allocator, io, request); diff --git a/server/src/jobs/releases.zig b/server/src/jobs/releases.zig index 9e36bd1..4b6198d 100644 --- a/server/src/jobs/releases.zig +++ b/server/src/jobs/releases.zig @@ -29,6 +29,10 @@ const Row = struct { platform: []const u8, url: []const u8, sha256: [64]u8, + /// Signed release manifest and its minisign signature, when the release + /// carries `.manifest.json` and `.manifest.json.minisig`. + manifest: ?[]u8 = null, + signature: ?[]u8 = null, }; pub const ParsedAsset = struct { @@ -135,7 +139,13 @@ pub fn run(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, options: Op } var rows: std.ArrayList(Row) = .empty; - defer rows.deinit(allocator); + defer { + for (rows.items) |r| { + if (r.manifest) |m| allocator.free(m); + if (r.signature) |g| allocator.free(g); + } + rows.deinit(allocator); + } for (copied.items) |asset| { if (std.ascii.endsWithIgnoreCase(asset.name, ".sha256")) continue; const parsed_name = parseAsset(asset.name) orelse continue; @@ -152,12 +162,30 @@ pub fn run(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, options: Op std.debug.print("skipping release asset {s}: invalid sha256 sidecar\n", .{asset.name}); continue; }; - try rows.append(allocator, .{ + var row: Row = .{ .version = parsed_name.version, .platform = parsed_name.platform, .url = asset.url, .sha256 = sha, - }); + }; + // Optional signed manifest (#58). Stored as published; the agent + // verifies it with its compiled-in key, the server never trusts it. + var man_buf: [256]u8 = undefined; + if (manifestName(&man_buf, asset.name, "")) |mname| { + var sig_buf: [256]u8 = undefined; + const sname = manifestName(&sig_buf, asset.name, ".minisig").?; + if (findAsset(copied.items, mname)) |murl| if (findAsset(copied.items, sname)) |surl| { + row.manifest = fetchSmall(allocator, io, murl, options.allow_private) catch null; + row.signature = fetchSmall(allocator, io, surl, options.allow_private) catch null; + if (row.manifest == null or row.signature == null) { + if (row.manifest) |m| allocator.free(m); + if (row.signature) |g| allocator.free(g); + row.manifest = null; + row.signature = null; + } + }; + } + try rows.append(allocator, row); } if (rows.items.len == 0) return 0; @@ -182,23 +210,31 @@ pub fn run(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, options: Op } var released_buf: [32]u8 = undefined; + var now_buf: [32]u8 = undefined; const released = if (published.len > 0) published else util.formatRfc3339(&released_buf, options.now_unix); for (rows.items) |row| { var sha_text: [64]u8 = row.sha256; + // New releases start in the canary ring; promote() widens it. try conn.execNoRows( - \\INSERT INTO agent_releases (version, platform, download_url, sha256, released_at, is_latest) - \\VALUES ($1, $2, $3, $4, $5::timestamptz, true) + \\INSERT INTO agent_releases (version, platform, download_url, sha256, released_at, is_latest, + \\ ring, ring_opened_at, manifest, manifest_signature) + \\VALUES ($1, $2, $3, $4, $5::timestamptz, true, 'canary', $6::timestamptz, $7, $8) \\ON CONFLICT (platform, version) DO UPDATE SET \\ download_url = EXCLUDED.download_url, \\ sha256 = EXCLUDED.sha256, \\ released_at = EXCLUDED.released_at, - \\ is_latest = true + \\ is_latest = true, + \\ manifest = COALESCE(EXCLUDED.manifest, agent_releases.manifest), + \\ manifest_signature = COALESCE(EXCLUDED.manifest_signature, agent_releases.manifest_signature) , &.{ .{ .text = row.version }, .{ .text = row.platform }, .{ .text = row.url }, .{ .text = &sha_text }, .{ .text = released }, + .{ .text = util.formatRfc3339(&now_buf, options.now_unix) }, + if (row.manifest) |m| .{ .text = m } else .{ .null = {} }, + if (row.signature) |g| .{ .text = g } else .{ .null = {} }, }); } if (nested) try conn.execSimple("RELEASE SAVEPOINT tawny_release_check") else try conn.execSimple("COMMIT"); @@ -206,6 +242,95 @@ pub fn run(allocator: std.mem.Allocator, io: std.Io, conn: *pg.Conn, options: Op return @intCast(rows.items.len); } +/// `tawny-agent-1.2.3-windows-x64.exe` -> `tawny-agent-1.2.3-windows-x64.manifest.json`. +pub fn manifestName(buf: *[256]u8, asset_name: []const u8, suffix: []const u8) ?[]const u8 { + const stem = if (std.ascii.endsWithIgnoreCase(asset_name, ".exe")) asset_name[0 .. asset_name.len - 4] else asset_name; + return std.fmt.bufPrint(buf, "{s}.manifest.json{s}", .{ stem, suffix }) catch null; +} + +fn fetchSmall(allocator: std.mem.Allocator, io: std.Io, url: []const u8, allow_private: bool) ![]u8 { + var res = try http_get.get(allocator, io, url, &.{}, "tawny-release-check/1.0", allow_private, 16 * 1024); + defer res.deinit(allocator); + if (res.status < 200 or res.status >= 300) return error.ReleaseHttp; + return allocator.dupe(u8, res.body); +} + +// --------------------------------------------------------------------------- +// Ring promotion (#58, target-edr §10 "Updates") + +pub const rings = [_][]const u8{ "canary", "internal", "10", "50", "100" }; + +pub const PromotionPolicy = struct { + /// How long a ring must run the release before the next ring opens. + soak_seconds: i64 = 24 * 3600, + /// Highest share of agents in the current ring that may have rolled back + /// (or reported a failed update) for promotion to go ahead. + max_failure_ratio: f64 = 0.05, + /// Agents in the ring that must report the version (committed) first. + /// Rings with fewer agents promote on soak time alone. + min_reports: u32 = 1, +}; + +pub fn nextRing(ring: []const u8) ?[]const u8 { + for (rings, 0..) |r, i| if (std.mem.eql(u8, r, ring)) { + return if (i + 1 < rings.len) rings[i + 1] else null; + }; + return null; +} + +pub const Verdict = enum { promote, wait_soak, wait_reports, hold_failures, at_widest }; + +/// Pure promotion gate. +pub fn gate(ring: []const u8, opened_at: i64, now: i64, committed: u32, failed: u32, p: PromotionPolicy) Verdict { + if (nextRing(ring) == null) return .at_widest; + if (now - opened_at < p.soak_seconds) return .wait_soak; + const total = committed + failed; + if (total > 0) { + const ratio = @as(f64, @floatFromInt(failed)) / @as(f64, @floatFromInt(total)); + if (ratio > p.max_failure_ratio) return .hold_failures; + } + if (committed < p.min_reports and total > 0) return .wait_reports; + return .promote; +} + +/// Promote every latest release whose ring has soaked without too many +/// failures. Counts come from agents' reported update state. Returns how +/// many rows moved. +pub fn promote(allocator: std.mem.Allocator, conn: *pg.Conn, now_unix: i64, policy: PromotionPolicy) !u32 { + const rows = try conn.exec(allocator, + \\SELECT r.platform, r.version, r.ring, extract(epoch FROM r.ring_opened_at)::bigint::text, + \\ (SELECT count(*) FROM agents a WHERE (a.operating_system || '-' || a.architecture) = r.platform + \\ AND a.update_version = r.version AND a.update_state = 'committed')::text, + \\ (SELECT count(*) FROM agents a WHERE (a.operating_system || '-' || a.architecture) = r.platform + \\ AND a.update_version = r.version AND a.update_state IN ('rolled_back', 'failed'))::text + \\FROM agent_releases r WHERE r.is_latest AND r.ring <> '100' + , &.{}); + defer { + for (rows) |r| r.deinit(allocator); + allocator.free(rows); + } + var moved: u32 = 0; + var nbuf: [32]u8 = undefined; + const now_s = util.formatRfc3339(&nbuf, now_unix); + for (rows) |row| { + const ring = row.cols[2] orelse continue; + const opened = std.fmt.parseInt(i64, row.cols[3] orelse "0", 10) catch 0; + const ok = std.fmt.parseInt(u32, row.cols[4] orelse "0", 10) catch 0; + const bad = std.fmt.parseInt(u32, row.cols[5] orelse "0", 10) catch 0; + const verdict = gate(ring, opened, now_unix, ok, bad, policy); + if (verdict == .hold_failures) { + std.debug.print("release {s} {s} held in ring {s}: {d} of {d} agents rolled back or failed\n", .{ row.cols[1].?, row.cols[0].?, ring, bad, ok + bad }); + } + if (verdict != .promote) continue; + try conn.execNoRows( + \\UPDATE agent_releases SET ring = $3, ring_opened_at = $4::timestamptz + \\WHERE platform = $1 AND version = $2 + , &.{ .{ .text = row.cols[0].? }, .{ .text = row.cols[1].? }, .{ .text = nextRing(ring).? }, .{ .text = now_s } }); + moved += 1; + } + return moved; +} + fn findAsset(assets: []const Asset, name: []const u8) ?[]const u8 { for (assets) |asset| if (std.ascii.eqlIgnoreCase(asset.name, name)) return asset.url; return null; @@ -305,6 +430,19 @@ const release_py = \\ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever() ; +test "ring promotion waits for the soak, holds on failures, stops at 100" { + const p: PromotionPolicy = .{ .soak_seconds = 100, .max_failure_ratio = 0.05, .min_reports = 1 }; + try std.testing.expectEqual(Verdict.wait_soak, gate("canary", 0, 50, 0, 0, p)); + try std.testing.expectEqual(Verdict.promote, gate("canary", 0, 100, 0, 0, p)); + try std.testing.expectEqual(Verdict.promote, gate("10", 0, 200, 40, 2, p)); + try std.testing.expectEqual(Verdict.hold_failures, gate("10", 0, 200, 10, 2, p)); + try std.testing.expectEqual(Verdict.at_widest, gate("100", 0, 200, 0, 0, p)); + try std.testing.expectEqualStrings("internal", nextRing("canary").?); + try std.testing.expectEqualStrings("100", nextRing("50").?); + var buf: [256]u8 = undefined; + try std.testing.expectEqualStrings("tawny-agent-1.2.3-windows-x64.manifest.json.minisig", manifestName(&buf, "tawny-agent-1.2.3-windows-x64.exe", ".minisig").?); +} + test "release check upserts agent assets and ignores bad sidecars" { const url = std.testing.environ.getPosix("TAWNY_DATABASE_URL") orelse return; if (url.len == 0) return; diff --git a/server/src/routes/agent_releases.zig b/server/src/routes/agent_releases.zig index c9b1930..df35520 100644 --- a/server/src/routes/agent_releases.zig +++ b/server/src/routes/agent_releases.zig @@ -19,7 +19,12 @@ pub fn latest( if (!validPlatform(platform)) { return util.problem(request, allocator, .bad_request, "platform is required."); } - const body = lookupJson(allocator, conn, platform) catch |err| switch (err) { + // Optional ring (#58): only a release already open to that ring. + const ring = util.queryParam(target, "ring"); + if (ring) |r| if (ringRank(r) == null) { + return util.problem(request, allocator, .bad_request, "ring must be canary, internal, 10, 50 or 100."); + }; + const body = lookupJsonRing(allocator, conn, platform, ring) catch |err| switch (err) { error.NotFound => return util.problem(request, allocator, .not_found, "No release is published for that platform."), else => return err, }; @@ -34,13 +39,53 @@ fn validPlatform(platform: []const u8) bool { } pub fn lookupJson(allocator: std.mem.Allocator, conn: *pg.Conn, platform: []const u8) ![]u8 { + return lookupJsonRing(allocator, conn, platform, null); +} + +/// Ring order. A release open to ring R is offered to agents in R and every +/// earlier ring (agent/src/updater.zig `ringAllows`). +pub const rings = [_][]const u8{ "canary", "internal", "10", "50", "100" }; + +pub fn ringRank(ring: []const u8) ?u8 { + for (rings, 0..) |r, i| if (std.mem.eql(u8, r, ring)) return @intCast(i); + return null; +} + +/// Same bucket as the agent: first four bytes of sha256(lower-case agent +/// id), big-endian, mod 100. +pub fn bucket(agent_id: []const u8) u8 { + var lower: [64]u8 = undefined; + const n = @min(agent_id.len, lower.len); + for (agent_id[0..n], 0..) |c, i| lower[i] = std.ascii.toLower(c); + var d: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(lower[0..n], &d, .{}); + return @intCast(std.mem.readInt(u32, d[0..4], .big) % 100); +} + +pub fn ringForAgent(agent_id: []const u8, override: ?[]const u8) []const u8 { + if (override) |o| if (ringRank(o) != null) return o; + const b = bucket(agent_id); + if (b < 10) return "10"; + if (b < 50) return "50"; + return "100"; +} + +/// SQL predicate: the release ring rank is at least the agent ring rank. +/// Leading and trailing spaces matter: `\\` lines joined with `++` get no +/// newline between them. +const ring_rank_sql = " array_position(ARRAY['canary','internal','10','50','100'], ring) >= array_position(ARRAY['canary','internal','10','50','100'], $2::text) "; + +pub fn lookupJsonRing(allocator: std.mem.Allocator, conn: *pg.Conn, platform: []const u8, ring: ?[]const u8) ![]u8 { const rows = try conn.exec(allocator, - \\SELECT version, platform, download_url, sha256, released_at::text + \\SELECT version, platform, download_url, sha256, released_at::text, ring \\FROM agent_releases \\WHERE is_latest AND platform = $1 + \\ AND ($2::text IS NULL OR + ++ ring_rank_sql ++ + \\) \\ORDER BY released_at DESC \\LIMIT 1 - , &.{.{ .text = platform }}); + , &.{ .{ .text = platform }, if (ring) |r| .{ .text = r } else .{ .null = {} } }); defer { for (rows) |row| row.deinit(allocator); allocator.free(rows); @@ -57,9 +102,119 @@ pub fn lookupJson(allocator: std.mem.Allocator, conn: *pg.Conn, platform: []cons defer allocator.free(sha); const released = try util.nullOrJsonString(allocator, c[4]); defer allocator.free(released); + const ring_j = try util.escapeJson(allocator, c[5] orelse "100"); + defer allocator.free(ring_j); return std.fmt.allocPrint(allocator, - \\{{"version":{s},"platform":{s},"download_url":{s},"sha256":{s},"released_at":{s}}} - , .{ version, plat, url, sha, released }); + \\{{"version":{s},"platform":{s},"download_url":{s},"sha256":{s},"released_at":{s},"ring":{s}}} + , .{ version, plat, url, sha, released, ring_j }); +} + +/// `POST /api/agent/update-check` (agent JWT). Body `{"platform": ...}`. +/// The server picks the ring (override, else bucket) and replies with the +/// signed manifest, its signature and the download URL, or 204 when nothing +/// signed is offered to this agent. The agent verifies the signature with +/// its compiled-in key; the server only passes the bytes on. +pub fn updateCheck( + allocator: std.mem.Allocator, + conn: *pg.Conn, + request: *std.http.Server.Request, + agent: auth.AgentAuth, +) !void { + const body = try util.readBody(allocator, request, 4096); + defer allocator.free(body); + const Req = struct { platform: []const u8 }; + const parsed = std.json.parseFromSlice(Req, allocator, body, .{ .ignore_unknown_fields = true }) catch + return util.problem(request, allocator, .bad_request, "platform is required."); + defer parsed.deinit(); + if (!validPlatform(parsed.value.platform)) return util.problem(request, allocator, .bad_request, "platform is required."); + const reply = try offerJson(allocator, conn, agent.tenant_id, agent.agent_id, parsed.value.platform); + defer if (reply) |r| allocator.free(r); + if (reply) |r| return util.respondJson(request, .ok, r); + try request.respond("", .{ .status = .no_content, .keep_alive = false }); +} + +pub fn offerJson(allocator: std.mem.Allocator, conn: *pg.Conn, tenant: []const u8, agent_id: []const u8, platform: []const u8) !?[]u8 { + const ov = try conn.exec(allocator, "SELECT update_ring FROM agents WHERE id = $1::uuid AND tenant_id = $2::uuid", &.{ .{ .text = agent_id }, .{ .text = tenant } }); + defer { + for (ov) |r| r.deinit(allocator); + allocator.free(ov); + } + const override: ?[]const u8 = if (ov.len > 0) ov[0].cols[0] else null; + const ring = ringForAgent(agent_id, override); + const rows = try conn.exec(allocator, + \\SELECT manifest, manifest_signature, download_url, ring FROM agent_releases + \\WHERE is_latest AND platform = $1 AND manifest IS NOT NULL AND manifest_signature IS NOT NULL AND + ++ ring_rank_sql ++ + \\ + \\ORDER BY released_at DESC LIMIT 1 + , &.{ .{ .text = platform }, .{ .text = ring } }); + defer { + for (rows) |r| r.deinit(allocator); + allocator.free(rows); + } + if (rows.len == 0) return null; + const m = try util.escapeJson(allocator, rows[0].cols[0].?); + defer allocator.free(m); + const sg = try util.escapeJson(allocator, rows[0].cols[1].?); + defer allocator.free(sg); + const u = try util.escapeJson(allocator, rows[0].cols[2] orelse ""); + defer allocator.free(u); + const rj = try util.escapeJson(allocator, ring); + defer allocator.free(rj); + return try std.fmt.allocPrint(allocator, + \\{{"manifest":{s},"signature":{s},"download_url":{s},"agent_ring":{s}}} + , .{ m, sg, u, rj }); +} + +test "bucket matches the agent vector and rings map from it" { + try std.testing.expectEqual(@as(u8, 19), bucket("00000000-0000-0000-0000-000000000001")); + try std.testing.expectEqual(@as(u8, 16), bucket("00000000-0000-0000-0000-000000000042")); + try std.testing.expectEqualStrings("50", ringForAgent("00000000-0000-0000-0000-000000000001", null)); + try std.testing.expectEqualStrings("canary", ringForAgent("00000000-0000-0000-0000-000000000001", "canary")); + try std.testing.expectEqualStrings("50", ringForAgent("00000000-0000-0000-0000-000000000001", "bogus")); + try std.testing.expectEqual(@as(?u8, null), ringRank("25")); +} + +test "ring query and update-check only offer releases open to the ring" { + const url = std.testing.environ.getPosix("TAWNY_DATABASE_URL") orelse return; + if (url.len == 0) return; + const allocator = std.testing.allocator; + const conn = try pg.Conn.connect(allocator, std.testing.io, url); + defer { + conn.close(); + allocator.destroy(conn); + } + try conn.execSimple("BEGIN"); + errdefer conn.execSimple("ROLLBACK") catch {}; + const tenant = "00000000-0000-0000-0000-000000000001"; + const agent_id = "00000000-0000-0000-0000-000000000001"; // bucket 19, ring 50 + try conn.execNoRows( + \\INSERT INTO agents (id, tenant_id, hostname, operating_system, os_version, agent_version, architecture, enrolled_at, status) + \\VALUES ($1::uuid, $2::uuid, 'ring-host', 'linux', 't', '0.1.0', 'x64', now(), 'online') + \\ON CONFLICT (id) DO UPDATE SET update_ring = NULL + , &.{ .{ .text = agent_id }, .{ .text = tenant } }); + try conn.execNoRows( + \\INSERT INTO agent_releases (version, platform, download_url, sha256, released_at, is_latest, ring, manifest, manifest_signature) + \\VALUES ('9.9.9', 'ringtest-x64', 'https://example.invalid/a', 'ab', now(), true, 'canary', '{"version":"9.9.9"}', 'sig') + , &.{}); + const plat = "ringtest-x64"; + + try std.testing.expectError(error.NotFound, lookupJsonRing(allocator, conn, plat, "50")); + const canary = try lookupJsonRing(allocator, conn, plat, "canary"); + allocator.free(canary); + try std.testing.expect((try offerJson(allocator, conn, tenant, agent_id, plat)) == null); + + // Promote to 50: the agent (ring 50) is now offered it. + try conn.execNoRows("UPDATE agent_releases SET ring = '50' WHERE platform = $1", &.{.{ .text = plat }}); + const offer = (try offerJson(allocator, conn, tenant, agent_id, plat)).?; + defer allocator.free(offer); + try std.testing.expect(std.mem.indexOf(u8, offer, "\"agent_ring\":\"50\"") != null); + try std.testing.expect(std.mem.indexOf(u8, offer, "\"signature\":\"sig\"") != null); + + // An override to ring 100 hides it again. + try conn.execNoRows("UPDATE agents SET update_ring = '100' WHERE id = $1::uuid", &.{.{ .text = agent_id }}); + try std.testing.expect((try offerJson(allocator, conn, tenant, agent_id, plat)) == null); + try conn.execSimple("ROLLBACK"); } test "latest release lookup returns the current row for a platform" { From f6143b8f0564386e37625768b6f063bec502deba Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:03 +1100 Subject: [PATCH 3/8] feat(agent): Windows DPAPI keystore with optional TPM wrap - windows_dpapi backend: CryptProtectData machine scope with fixed entropy, one \\.dpapi file per secret, protected DACL for SYSTEM and Administrators set before the rename. - When the Microsoft Platform Crypto Provider opens, the DPAPI blob is wrapped with RSA-OAEP SHA-256 under a non-exportable machine key and checked by unwrapping before it is trusted; otherwise DPAPI alone. TAWNY_KEYSTORE_TPM=off turns the wrap off. - Existing migration moves plaintext JWT and seed in, reads back, then deletes. Store.protection() reports keychain, dpapi, tpm or file. - --keystore-selftest for CI. Link crypt32 and ncrypt. Constants pinned against windows-rs in a test that runs on every OS. Co-Authored-By: Claude Opus 5.5 --- agent/build.zig | 3 + agent/src/config.zig | 4 +- agent/src/keystore.zig | 79 ++++- agent/src/keystore_debug.zig | 95 ++++++ agent/src/platform/windows/dpapi.zig | 463 +++++++++++++++++++++++++++ 5 files changed, 637 insertions(+), 7 deletions(-) create mode 100644 agent/src/keystore_debug.zig create mode 100644 agent/src/platform/windows/dpapi.zig diff --git a/agent/build.zig b/agent/build.zig index 65ac171..79907b4 100644 --- a/agent/build.zig +++ b/agent/build.zig @@ -62,6 +62,9 @@ fn linkPlatformLibraries(mod: *std.Build.Module, os: std.Target.Os.Tag) void { mod.linkSystemLibrary("wtsapi32", .{}); mod.linkSystemLibrary("ntdll", .{}); mod.linkSystemLibrary("wevtapi", .{}); + // DPAPI keystore and TPM wrap (#58). + mod.linkSystemLibrary("crypt32", .{}); + mod.linkSystemLibrary("ncrypt", .{}); // WFP user-mode API for network isolation (#57). mod.linkSystemLibrary("fwpuclnt", .{}); }, diff --git a/agent/src/config.zig b/agent/src/config.zig index dbbe637..66ebd90 100644 --- a/agent/src/config.zig +++ b/agent/src/config.zig @@ -184,7 +184,9 @@ pub fn loadWith(alloc: std.mem.Allocator, options: LoadOptions) !Config { } try validate(&cfg); - cfg.secret_store = keystore.platformDefault(alloc); + // The DPAPI files sit next to state.toml. dirname is a slice of + // cfg.state_path, which lives as long as cfg. + cfg.secret_store = keystore.platformDefaultIn(alloc, std.fs.path.dirname(cfg.state_path) orelse "."); const state = try loadState(&cfg); if (state == .missing and cfg.agent_id != null and cfg.agent_jwt != null) { // One-time migration from legacy config files which stored mutable diff --git a/agent/src/keystore.zig b/agent/src/keystore.zig index 081b02e..c661e96 100644 --- a/agent/src/keystore.zig +++ b/agent/src/keystore.zig @@ -4,9 +4,15 @@ //! - macOS: Security.framework generic passwords, service //! `dev.jusso.tawny-agent`, account = secret name. Root (LaunchDaemon) uses //! the System keychain; a per-user LaunchAgent uses the login keychain. -//! - Everything else (and macOS with `TAWNY_KEYSTORE=file`): `file`, meaning -//! callers keep the legacy plaintext files (state.toml / `.devicekey`). -//! Windows DPAPI and Linux keyring/TPM are later phases. +//! - Windows: `windows_dpapi` (#58). DPAPI machine scope with fixed entropy, +//! one `\.dpapi` file per secret, ACL SYSTEM and +//! Administrators only, wrapped by a TPM key in the Platform Crypto +//! Provider when one is usable (platform/windows/dpapi.zig). +//! `TAWNY_KEYSTORE_TPM=off` keeps DPAPI alone. +//! - Linux and everything else (and any OS with `TAWNY_KEYSTORE=file`): +//! `file`, meaning callers keep the plaintext files (state.toml / +//! `.devicekey`), owner-only 0600 under a root-owned 0750 state directory. +//! tpm2-tss sealing is not done yet (docs/production-agent-hardening.md). //! //! File precedence: when a plaintext copy exists it is authoritative, because //! it is only ever written as a fallback after a keystore write failed, or by @@ -18,6 +24,7 @@ const builtin = @import("builtin"); const env = @import("env.zig"); const iox = @import("io_compat.zig"); const keychain = if (builtin.target.os.tag == .macos) @import("platform/macos/keychain.zig") else struct {}; +const dpapi = @import("platform/windows/dpapi.zig"); pub const default_service = "dev.jusso.tawny-agent"; pub const seed_len = std.crypto.sign.Ed25519.KeyPair.seed_length; @@ -53,6 +60,8 @@ pub const Backend = enum { macos_system_keychain, /// The calling user's default (login) keychain. macos_user_keychain, + /// DPAPI machine scope files, TPM-wrapped when available (Windows). + windows_dpapi, /// In-memory store for tests. test_vault, }; @@ -61,6 +70,10 @@ pub const Store = struct { backend: Backend = .file, service: []const u8 = default_service, vault: ?*TestVault = null, + /// windows_dpapi: directory holding the `.dpapi` files (state dir). + dir: []const u8 = "", + /// windows_dpapi: try the TPM wrap first. + use_tpm: bool = true, /// True when secrets go to an OS keystore rather than plaintext files. pub fn isOs(self: Store) bool { @@ -72,10 +85,25 @@ pub const Store = struct { .file => "plaintext state files", .macos_system_keychain => "macOS System keychain", .macos_user_keychain => "macOS login keychain", + .windows_dpapi => if (self.use_tpm) "Windows DPAPI (TPM-wrapped when available)" else "Windows DPAPI", .test_vault => "test vault", }; } + /// `key_protection` for agent_health: keychain, dpapi, tpm or file. + /// For DPAPI this reads which wrap the device seed actually has. + pub fn protection(self: Store) []const u8 { + return switch (self.backend) { + .file, .test_vault => "file", + .macos_system_keychain, .macos_user_keychain => "keychain", + .windows_dpapi => blk: { + if (comptime builtin.target.os.tag != .windows) break :blk "dpapi"; + if (last_wrap) |w| break :blk if (w == .tpm) "tpm" else "dpapi"; + break :blk "dpapi"; + }, + }; + } + /// Caller owns the returned bytes. Null when no such secret exists. pub fn get(self: Store, alloc: std.mem.Allocator, secret: Secret) Error!?[]u8 { return switch (self.backend) { @@ -85,6 +113,12 @@ pub const Store = struct { if (comptime builtin.target.os.tag != .macos) return error.KeystoreUnavailable; return keychain.get(alloc, self.location(), self.service, secret.account()) catch |err| mapKeychainError(err); }, + .windows_dpapi => { + var w: dpapi.Wrap = .dpapi; + const got = dpapi.get(alloc, self.dir, secret.account(), &w) catch |err| return mapDpapiError(err); + if (got != null and secret == .device_seed) last_wrap = w; + return got; + }, }; } @@ -96,6 +130,11 @@ pub const Store = struct { if (comptime builtin.target.os.tag != .macos) return error.KeystoreUnavailable; return keychain.put(self.location(), self.service, secret.account(), value) catch |err| mapKeychainError(err); }, + .windows_dpapi => { + const alloc = std.heap.page_allocator; + const w = dpapi.put(alloc, self.dir, secret.account(), value, if (self.use_tpm) .auto else .dpapi_only) catch |err| return mapDpapiError(err); + if (secret == .device_seed) last_wrap = w; + }, }; } @@ -108,6 +147,7 @@ pub const Store = struct { if (comptime builtin.target.os.tag != .macos) return error.KeystoreUnavailable; return keychain.delete(self.location(), self.service, secret.account()) catch |err| mapKeychainError(err); }, + .windows_dpapi => dpapi.delete(std.heap.page_allocator, self.dir, secret.account()) catch |err| return mapDpapiError(err), }; } @@ -137,16 +177,34 @@ fn mapKeychainError(err: anyerror) Error { }; } -/// OSStatus of the last failing keychain call (0 elsewhere), for log lines. +/// Wrap of the device seed last read or written through DPAPI. +var last_wrap: ?dpapi.Wrap = null; + +fn mapDpapiError(err: dpapi.Error) Error { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.KeystoreUnavailable, error.TpmUnavailable => error.KeystoreUnavailable, + error.DpapiFailed, error.TpmFailed, error.CorruptBlob => error.KeystoreFailure, + }; +} + +/// OSStatus of the last failing keychain call, or the Win32 / NCrypt code of +/// the last failing DPAPI or TPM call (0 elsewhere), for log lines. pub fn lastOsStatus() i32 { + if (comptime builtin.target.os.tag == .windows) return @bitCast(dpapi.last_error); if (comptime builtin.target.os.tag != .macos) return 0; return keychain.last_status; } /// Store for this process. macOS: System keychain when running as root -/// (LaunchDaemon), login keychain otherwise (LaunchAgent). `TAWNY_KEYSTORE=file` -/// forces the plaintext-file backend (containers, debugging). +/// (LaunchDaemon), login keychain otherwise (LaunchAgent). Windows: DPAPI +/// files in `state_dir`. `TAWNY_KEYSTORE=file` forces the plaintext-file +/// backend (containers, debugging). `state_dir` must outlive the Store. pub fn platformDefault(alloc: std.mem.Allocator) Store { + return platformDefaultIn(alloc, ""); +} + +pub fn platformDefaultIn(alloc: std.mem.Allocator, state_dir: []const u8) Store { if (env.getEnvVarOwned(alloc, "TAWNY_KEYSTORE")) |value| { defer alloc.free(value); if (std.ascii.eqlIgnoreCase(value, "file")) return .{ .backend = .file }; @@ -154,6 +212,15 @@ pub fn platformDefault(alloc: std.mem.Allocator) Store { if (comptime builtin.target.os.tag == .macos) { return .{ .backend = if (std.c.geteuid() == 0) .macos_system_keychain else .macos_user_keychain }; } + if (comptime builtin.target.os.tag == .windows) { + if (state_dir.len == 0) return .{ .backend = .file }; + var use_tpm = true; + if (env.getEnvVarOwned(alloc, "TAWNY_KEYSTORE_TPM")) |value| { + defer alloc.free(value); + if (std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0")) use_tpm = false; + } else |_| {} + return .{ .backend = .windows_dpapi, .dir = state_dir, .use_tpm = use_tpm }; + } return .{ .backend = .file }; } diff --git a/agent/src/keystore_debug.zig b/agent/src/keystore_debug.zig new file mode 100644 index 0000000..9fdd2f0 --- /dev/null +++ b/agent/src/keystore_debug.zig @@ -0,0 +1,95 @@ +//! `--keystore-selftest `: CI plumbing for #58, like `--eventlog-dump`. +//! Uses the platform keystore with its files under `` (never the real +//! state directory) and proves, on the machine it runs on: +//! +//! 1. a secret round-trips (put, read back, delete); +//! 2. a plaintext `\state.toml.devicekey` is migrated into the keystore, +//! read back, and the plaintext file is gone afterwards; +//! 3. on Windows, the `.dpapi` file holds no plaintext copy of the seed. +//! +//! Prints `KEYSTORE\t=` lines and returns 0 when every check +//! passes. The secrets are random bytes made for the run. + +const std = @import("std"); +const builtin = @import("builtin"); +const keystore = @import("keystore.zig"); +const iox = @import("io_compat.zig"); + +pub fn isDebugCommand(arg: []const u8) bool { + return std.mem.eql(u8, arg, "--keystore-selftest"); +} + +pub fn run(alloc: std.mem.Allocator, args: []const []const u8) u8 { + if (args.len != 2) { + std.debug.print("usage: tawny-agent --keystore-selftest \n", .{}); + return 2; + } + return selftest(alloc, args[1]) catch |err| { + std.debug.print("KEYSTORE\tresult=failed\terror={s}\tos_status={d}\n", .{ @errorName(err), keystore.lastOsStatus() }); + return 1; + }; +} + +fn selftest(alloc: std.mem.Allocator, dir: []const u8) !u8 { + const io = iox.current(); + try std.Io.Dir.cwd().createDirPath(io, dir); + const store = keystore.platformDefaultIn(alloc, dir); + std.debug.print("KEYSTORE\tbackend={s}\n", .{@tagName(store.backend)}); + if (!store.isOs()) { + std.debug.print("KEYSTORE\tresult=skipped\treason=no OS keystore on this platform\n", .{}); + return 0; + } + // macOS would touch a real keychain service name; this command is for + // the Windows runner. + if (builtin.target.os.tag != .windows) { + std.debug.print("KEYSTORE\tresult=skipped\treason=windows only\n", .{}); + return 0; + } + + // 1. Round trip. + var jwt_bytes: [24]u8 = undefined; + io.random(&jwt_bytes); + var jwt_hex: [48]u8 = undefined; + _ = try std.fmt.bufPrint(&jwt_hex, "{x}", .{jwt_bytes}); + try store.putVerified(alloc, .agent_jwt, &jwt_hex); + const back = (try store.get(alloc, .agent_jwt)) orelse return error.RoundTripMissing; + defer alloc.free(back); + if (!std.mem.eql(u8, back, &jwt_hex)) return error.RoundTripMismatch; + try store.delete(.agent_jwt); + if (try store.get(alloc, .agent_jwt)) |left| { + alloc.free(left); + return error.DeleteLeftSecret; + } + std.debug.print("KEYSTORE\tround_trip=ok\n", .{}); + + // 2. Plaintext seed migration. + const state_path = try std.fs.path.join(alloc, &.{ dir, "state.toml" }); + defer alloc.free(state_path); + const seed_path = try keystore.deviceSeedPath(alloc, state_path); + defer alloc.free(seed_path); + var seed: keystore.Seed = undefined; + io.random(&seed); + try keystore.writeSecretFile(seed_path, &seed); + if (!try keystore.migrateDeviceSeed(alloc, store, seed_path)) return error.NotMigrated; + const still_there = blk: { + const f = std.Io.Dir.cwd().openFile(io, seed_path, .{}) catch break :blk false; + f.close(io); + break :blk true; + }; + if (still_there) return error.PlaintextRemains; + const loaded = (try keystore.loadDeviceSeed(alloc, store, seed_path)) orelse return error.SeedMissing; + if (!std.mem.eql(u8, &loaded, &seed)) return error.SeedMismatch; + std.debug.print("KEYSTORE\tmigration=ok\tplaintext_removed=true\n", .{}); + + // 3. No plaintext in the protected file. + const blob_path = try std.fmt.allocPrint(alloc, "{s}\\device-seed.dpapi", .{dir}); + defer alloc.free(blob_path); + const blob = try std.Io.Dir.cwd().readFileAlloc(io, blob_path, alloc, .limited(64 * 1024)); + defer alloc.free(blob); + if (std.mem.indexOf(u8, blob, &seed) != null) return error.PlaintextInBlob; + std.debug.print("KEYSTORE\tblob_bytes={d}\tkey_protection={s}\n", .{ blob.len, store.protection() }); + + try store.delete(.device_seed); + std.debug.print("KEYSTORE\tresult=ok\n", .{}); + return 0; +} diff --git a/agent/src/platform/windows/dpapi.zig b/agent/src/platform/windows/dpapi.zig new file mode 100644 index 0000000..8492c11 --- /dev/null +++ b/agent/src/platform/windows/dpapi.zig @@ -0,0 +1,463 @@ +//! Windows secret storage for the agent JWT and device seed (#58). +//! +//! Layer 1, always: DPAPI machine scope. `CryptProtectData` with +//! `CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN` and a fixed +//! entropy value. Any process on the machine can call `CryptUnprotectData` +//! on a machine-scope blob, so the file ACL (SYSTEM and Administrators only) +//! is what keeps other users out, and the entropy stops a generic DPAPI +//! dumper from decrypting it blind. +//! +//! Layer 2, when a TPM is usable: the DPAPI blob is wrapped with RSA-OAEP +//! (SHA-256) under a non-exportable 2048-bit RSA key in the Microsoft +//! Platform Crypto Provider (`NCryptOpenStorageProvider` with +//! `MS_PLATFORM_KEY_STORAGE_PROVIDER`), machine key `TawnyAgentWrap`. The +//! secrets are at most a few hundred bytes after DPAPI, so the blob is split +//! into OAEP-sized chunks. Copying the file to another machine is useless +//! without that TPM. When the provider or key can't be used, the agent +//! falls back to DPAPI alone and says so in `key_protection`. +//! +//! File: `\.dpapi`, written by temp file and rename, ACL +//! `D:PAI(A;;FA;;;SY)(A;;FA;;;BA)`. Layout: +//! magic "TWNK" | version u8 = 1 | wrap u8 (0 = DPAPI, 1 = TPM) | body +//! For wrap = 1 the body is a sequence of `u16 LE length | RSA ciphertext`. +//! +//! Constants and signatures are checked against windows-rs +//! (`Win32/dpapi`, `Win32/ncrypt`, `Win32/bcrypt`, `Win32/winerror`) and +//! pinned by a test that runs on every OS. + +const std = @import("std"); +const builtin = @import("builtin"); +const iox = @import("../../io_compat.zig"); + +pub const CRYPTPROTECT_UI_FORBIDDEN: u32 = 0x1; +pub const CRYPTPROTECT_LOCAL_MACHINE: u32 = 0x4; +pub const NCRYPT_SILENT_FLAG: u32 = 0x40; +pub const NCRYPT_MACHINE_KEY_FLAG: u32 = 0x20; +pub const NCRYPT_OVERWRITE_KEY_FLAG: u32 = 0x80; +pub const NCRYPT_PAD_OAEP_FLAG: u32 = 0x4; +pub const NTE_BAD_KEYSET: u32 = 0x80090016; +pub const NTE_EXISTS: u32 = 0x8009000F; +pub const ms_platform_provider = "Microsoft Platform Crypto Provider"; +pub const wrap_key_name = "TawnyAgentWrap"; +pub const rsa_bits: u32 = 2048; +/// RSA-OAEP with SHA-256: k - 2*hLen - 2 = 256 - 64 - 2. +pub const oaep_max_plain: usize = rsa_bits / 8 - 2 * 32 - 2; + +/// Fixed DPAPI entropy. Not a secret: it only ties blobs to this purpose. +pub const entropy = "tawny-agent-keystore-v1"; + +pub const file_acl = "D:PAI(A;;FA;;;SY)(A;;FA;;;BA)"; +const magic = "TWNK"; +const format_version: u8 = 1; + +pub const Wrap = enum(u8) { dpapi = 0, tpm = 1 }; + +pub const Error = error{ + DpapiFailed, + TpmUnavailable, + TpmFailed, + CorruptBlob, + OutOfMemory, + KeystoreUnavailable, +}; + +pub var last_error: u32 = 0; + +const WINAPI: std.lang.CallingConvention = .winapi; +const DATA_BLOB = extern struct { + cbData: u32, + pbData: ?[*]u8, +}; +const BCRYPT_OAEP_PADDING_INFO = extern struct { + pszAlgId: [*:0]const u16, + pbLabel: ?[*]u8, + cbLabel: u32, +}; +const NCRYPT_HANDLE = usize; + +const win = if (builtin.target.os.tag == .windows) struct { + extern "crypt32" fn CryptProtectData( + in: *const DATA_BLOB, + descr: ?[*:0]const u16, + entropy: ?*const DATA_BLOB, + reserved: ?*anyopaque, + prompt: ?*anyopaque, + flags: u32, + out: *DATA_BLOB, + ) callconv(WINAPI) i32; + extern "crypt32" fn CryptUnprotectData( + in: *const DATA_BLOB, + descr: ?*?[*:0]u16, + entropy: ?*const DATA_BLOB, + reserved: ?*anyopaque, + prompt: ?*anyopaque, + flags: u32, + out: *DATA_BLOB, + ) callconv(WINAPI) i32; + extern "kernel32" fn LocalFree(mem: ?*anyopaque) callconv(WINAPI) ?*anyopaque; + extern "kernel32" fn GetLastError() callconv(WINAPI) u32; + + extern "ncrypt" fn NCryptOpenStorageProvider(prov: *NCRYPT_HANDLE, name: [*:0]const u16, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptOpenKey(prov: NCRYPT_HANDLE, key: *NCRYPT_HANDLE, name: [*:0]const u16, legacy_spec: u32, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptCreatePersistedKey(prov: NCRYPT_HANDLE, key: *NCRYPT_HANDLE, alg: [*:0]const u16, name: [*:0]const u16, legacy_spec: u32, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptSetProperty(obj: NCRYPT_HANDLE, prop: [*:0]const u16, input: [*]const u8, len: u32, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptFinalizeKey(key: NCRYPT_HANDLE, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptEncrypt(key: NCRYPT_HANDLE, input: [*]const u8, in_len: u32, padding: ?*const anyopaque, output: ?[*]u8, out_len: u32, result: *u32, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptDecrypt(key: NCRYPT_HANDLE, input: [*]const u8, in_len: u32, padding: ?*const anyopaque, output: ?[*]u8, out_len: u32, result: *u32, flags: u32) callconv(WINAPI) i32; + extern "ncrypt" fn NCryptFreeObject(obj: NCRYPT_HANDLE) callconv(WINAPI) i32; +} else struct {}; + +const W = std.unicode.utf8ToUtf16LeStringLiteral; + +// --------------------------------------------------------------------------- +// DPAPI + +/// DPAPI machine-scope protect. Caller frees. +pub fn protect(alloc: std.mem.Allocator, plain: []const u8) Error![]u8 { + if (builtin.target.os.tag != .windows) return error.KeystoreUnavailable; + var in = DATA_BLOB{ .cbData = @intCast(plain.len), .pbData = @constCast(plain.ptr) }; + var ent = DATA_BLOB{ .cbData = entropy.len, .pbData = @constCast(entropy.ptr) }; + var out = DATA_BLOB{ .cbData = 0, .pbData = null }; + if (win.CryptProtectData(&in, W("tawny-agent"), &ent, null, null, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &out) == 0) { + last_error = win.GetLastError(); + return error.DpapiFailed; + } + defer _ = win.LocalFree(out.pbData); + return alloc.dupe(u8, out.pbData.?[0..out.cbData]); +} + +/// DPAPI unprotect. Caller frees (and should secureZero). +pub fn unprotect(alloc: std.mem.Allocator, blob: []const u8) Error![]u8 { + if (builtin.target.os.tag != .windows) return error.KeystoreUnavailable; + var in = DATA_BLOB{ .cbData = @intCast(blob.len), .pbData = @constCast(blob.ptr) }; + var ent = DATA_BLOB{ .cbData = entropy.len, .pbData = @constCast(entropy.ptr) }; + var out = DATA_BLOB{ .cbData = 0, .pbData = null }; + if (win.CryptUnprotectData(&in, null, &ent, null, null, CRYPTPROTECT_UI_FORBIDDEN, &out) == 0) { + last_error = win.GetLastError(); + return error.DpapiFailed; + } + defer { + if (out.pbData) |p| std.crypto.secureZero(u8, p[0..out.cbData]); + _ = win.LocalFree(out.pbData); + } + return alloc.dupe(u8, out.pbData.?[0..out.cbData]); +} + +// --------------------------------------------------------------------------- +// TPM wrap through the Platform Crypto Provider + +pub const Tpm = struct { + prov: NCRYPT_HANDLE = 0, + key: NCRYPT_HANDLE = 0, + + /// Open (or create on first use) the wrap key. `error.TpmUnavailable` + /// when the provider or key cannot be used; callers fall back to DPAPI. + pub fn open() Error!Tpm { + if (builtin.target.os.tag != .windows) return error.TpmUnavailable; + var t: Tpm = .{}; + var rc = win.NCryptOpenStorageProvider(&t.prov, W(ms_platform_provider), 0); + if (rc != 0) return noteTpm(rc, error.TpmUnavailable); + errdefer _ = win.NCryptFreeObject(t.prov); + rc = win.NCryptOpenKey(t.prov, &t.key, W(wrap_key_name), 0, NCRYPT_MACHINE_KEY_FLAG | NCRYPT_SILENT_FLAG); + if (rc == 0) return t; + if (@as(u32, @bitCast(rc)) != NTE_BAD_KEYSET) return noteTpm(rc, error.TpmUnavailable); + // First use: create a non-exportable machine RSA key. No export + // policy is set, so the provider's default (not exportable) applies. + rc = win.NCryptCreatePersistedKey(t.prov, &t.key, W("RSA"), W(wrap_key_name), 0, NCRYPT_MACHINE_KEY_FLAG); + if (rc != 0) return noteTpm(rc, error.TpmUnavailable); + errdefer _ = win.NCryptFreeObject(t.key); + const bits: u32 = rsa_bits; + rc = win.NCryptSetProperty(t.key, W("Length"), std.mem.asBytes(&bits), 4, 0); + if (rc != 0) return noteTpm(rc, error.TpmUnavailable); + rc = win.NCryptFinalizeKey(t.key, NCRYPT_SILENT_FLAG); + if (rc != 0) return noteTpm(rc, error.TpmUnavailable); + return t; + } + + pub fn close(self: *Tpm) void { + if (builtin.target.os.tag != .windows) return; + if (self.key != 0) _ = win.NCryptFreeObject(self.key); + if (self.prov != 0) _ = win.NCryptFreeObject(self.prov); + self.* = .{}; + } + + fn padding() BCRYPT_OAEP_PADDING_INFO { + return .{ .pszAlgId = W("SHA256"), .pbLabel = null, .cbLabel = 0 }; + } + + /// RSA-OAEP encrypt `plain` in chunks. Caller frees. + pub fn wrap(self: *Tpm, alloc: std.mem.Allocator, plain: []const u8) Error![]u8 { + if (builtin.target.os.tag != .windows) return error.TpmUnavailable; + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(alloc); + const pad = padding(); + var cipher: [rsa_bits / 8]u8 = undefined; + var off: usize = 0; + while (off < plain.len) { + const n = @min(oaep_max_plain, plain.len - off); + var got: u32 = 0; + const rc = win.NCryptEncrypt(self.key, plain[off..].ptr, @intCast(n), &pad, &cipher, cipher.len, &got, NCRYPT_PAD_OAEP_FLAG | NCRYPT_SILENT_FLAG); + if (rc != 0) return noteTpm(rc, error.TpmFailed); + var len_le: [2]u8 = undefined; + std.mem.writeInt(u16, &len_le, @intCast(got), .little); + try out.appendSlice(alloc, &len_le); + try out.appendSlice(alloc, cipher[0..got]); + off += n; + } + return out.toOwnedSlice(alloc); + } + + /// Reverse of `wrap`. Caller frees. + pub fn unwrap(self: *Tpm, alloc: std.mem.Allocator, body: []const u8) Error![]u8 { + if (builtin.target.os.tag != .windows) return error.TpmUnavailable; + var out: std.ArrayList(u8) = .empty; + errdefer { + std.crypto.secureZero(u8, out.items); + out.deinit(alloc); + } + const pad = padding(); + var plain: [rsa_bits / 8]u8 = undefined; + defer std.crypto.secureZero(u8, &plain); + var off: usize = 0; + while (off < body.len) { + if (body.len - off < 2) return error.CorruptBlob; + const n = std.mem.readInt(u16, body[off..][0..2], .little); + off += 2; + if (n == 0 or n > plain.len or body.len - off < n) return error.CorruptBlob; + var got: u32 = 0; + const rc = win.NCryptDecrypt(self.key, body[off..].ptr, n, &pad, &plain, plain.len, &got, NCRYPT_PAD_OAEP_FLAG | NCRYPT_SILENT_FLAG); + if (rc != 0) return noteTpm(rc, error.TpmFailed); + try out.appendSlice(alloc, plain[0..got]); + off += n; + } + return out.toOwnedSlice(alloc); + } +}; + +fn noteTpm(rc: i32, err: Error) Error { + last_error = @bitCast(rc); + return err; +} + +// --------------------------------------------------------------------------- +// Blob file format (pure, tested on every OS) + +/// Frame a protected body. Caller frees. +pub fn encodeFile(alloc: std.mem.Allocator, wrap_kind: Wrap, body: []const u8) ![]u8 { + const out = try alloc.alloc(u8, magic.len + 2 + body.len); + @memcpy(out[0..magic.len], magic); + out[magic.len] = format_version; + out[magic.len + 1] = @backingInt(wrap_kind); + @memcpy(out[magic.len + 2 ..], body); + return out; +} + +pub const Decoded = struct { wrap: Wrap, body: []const u8 }; + +pub fn decodeFile(bytes: []const u8) Error!Decoded { + if (bytes.len < magic.len + 2) return error.CorruptBlob; + if (!std.mem.eql(u8, bytes[0..magic.len], magic)) return error.CorruptBlob; + if (bytes[magic.len] != format_version) return error.CorruptBlob; + const w = std.enums.fromInt(Wrap, bytes[magic.len + 1]) orelse return error.CorruptBlob; + return .{ .wrap = w, .body = bytes[magic.len + 2 ..] }; +} + +// --------------------------------------------------------------------------- +// Store: one file per secret under `dir` + +pub const Mode = enum { + /// Use the TPM when it opens, else DPAPI alone. + auto, + /// DPAPI alone (TAWNY_KEYSTORE_TPM=off, or tests). + dpapi_only, +}; + +pub fn filePath(alloc: std.mem.Allocator, dir: []const u8, account: []const u8) ![]u8 { + return std.fmt.allocPrint(alloc, "{s}\\{s}.dpapi", .{ dir, account }); +} + +/// Protect and write. Returns how it was wrapped. +pub fn put(alloc: std.mem.Allocator, dir: []const u8, account: []const u8, value: []const u8, mode: Mode) Error!Wrap { + const dp = try protect(alloc, value); + defer alloc.free(dp); + var wrap_kind: Wrap = .dpapi; + var body: []const u8 = dp; + var wrapped: ?[]u8 = null; + defer if (wrapped) |w| alloc.free(w); + if (mode == .auto) { + if (Tpm.open()) |t| { + var tpm = t; + defer tpm.close(); + if (tpm.wrap(alloc, dp)) |w| { + // Check the TPM can unwrap it before trusting the TPM copy. + if (tpm.unwrap(alloc, w)) |back| { + defer alloc.free(back); + if (std.mem.eql(u8, back, dp)) { + wrapped = w; + body = w; + wrap_kind = .tpm; + } else alloc.free(w); + } else |_| alloc.free(w); + } else |_| {} + } else |_| {} + } + const framed = encodeFile(alloc, wrap_kind, body) catch return error.OutOfMemory; + defer alloc.free(framed); + writeProtectedFile(alloc, dir, account, framed) catch return error.KeystoreUnavailable; + return wrap_kind; +} + +/// Read and unprotect. Null when the file does not exist. Caller frees. +pub fn get(alloc: std.mem.Allocator, dir: []const u8, account: []const u8, wrap_out: ?*Wrap) Error!?[]u8 { + const path = filePath(alloc, dir, account) catch return error.OutOfMemory; + defer alloc.free(path); + const io = iox.current(); + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(64 * 1024)) catch |err| switch (err) { + error.FileNotFound => return null, + error.OutOfMemory => return error.OutOfMemory, + else => return error.KeystoreUnavailable, + }; + defer alloc.free(bytes); + const d = try decodeFile(bytes); + if (wrap_out) |w| w.* = d.wrap; + switch (d.wrap) { + .dpapi => return try unprotect(alloc, d.body), + .tpm => { + var tpm = try Tpm.open(); + defer tpm.close(); + const dp = try tpm.unwrap(alloc, d.body); + defer { + std.crypto.secureZero(u8, dp); + alloc.free(dp); + } + return try unprotect(alloc, dp); + }, + } +} + +pub fn delete(alloc: std.mem.Allocator, dir: []const u8, account: []const u8) Error!void { + const path = filePath(alloc, dir, account) catch return error.OutOfMemory; + defer alloc.free(path); + std.Io.Dir.cwd().deleteFile(iox.current(), path) catch |err| switch (err) { + error.FileNotFound => {}, + else => return error.KeystoreUnavailable, + }; +} + +fn writeProtectedFile(alloc: std.mem.Allocator, dir: []const u8, account: []const u8, bytes: []const u8) !void { + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir); + const path = try filePath(alloc, dir, account); + defer alloc.free(path); + const tmp = try std.fmt.allocPrint(alloc, "{s}.tmp", .{path}); + defer alloc.free(tmp); + { + var f = try cwd.createFile(io, tmp, .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, bytes, 0); + try f.sync(io); + } + // Restrict before the rename so the final name is never readable more + // widely. Failure here is fatal: an unrestricted blob is not acceptable. + applyAcl(alloc, tmp) catch |err| { + cwd.deleteFile(io, tmp) catch {}; + return err; + }; + cwd.rename(tmp, cwd, path, io) catch |err| { + cwd.deleteFile(io, tmp) catch {}; + return err; + }; +} + +// SDDL helpers (advapi32), same calls as quarantine.zig. +const acl = if (builtin.target.os.tag == .windows) struct { + extern "advapi32" fn ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl: [*:0]const u16, revision: u32, psd: *?*anyopaque, size: ?*usize) callconv(WINAPI) i32; + extern "advapi32" fn GetSecurityDescriptorDacl(sd: *anyopaque, present: *i32, dacl: *?*anyopaque, defaulted: *i32) callconv(WINAPI) i32; + extern "advapi32" fn SetNamedSecurityInfoW(name: [*:0]u16, object_type: u32, info: u32, owner: ?*anyopaque, group: ?*anyopaque, dacl: ?*anyopaque, sacl: ?*anyopaque) callconv(WINAPI) u32; +} else struct {}; + +const SE_FILE_OBJECT: u32 = 1; +const DACL_SECURITY_INFORMATION: u32 = 0x4; +const PROTECTED_DACL_SECURITY_INFORMATION: u32 = 0x80000000; + +fn applyAcl(alloc: std.mem.Allocator, path: []const u8) !void { + if (builtin.target.os.tag != .windows) return; + const wpath = try std.unicode.utf8ToUtf16LeAllocZ(alloc, path); + defer alloc.free(wpath); + var psd: ?*anyopaque = null; + if (acl.ConvertStringSecurityDescriptorToSecurityDescriptorW(W(file_acl), 1, &psd, null) == 0) return error.SddlParseFailed; + defer _ = win.LocalFree(psd); + var present: i32 = 0; + var dacl: ?*anyopaque = null; + var defaulted: i32 = 0; + if (acl.GetSecurityDescriptorDacl(psd.?, &present, &dacl, &defaulted) == 0) return error.SddlParseFailed; + const rc = acl.SetNamedSecurityInfoW(wpath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, null, null, dacl, null); + if (rc != 0) { + last_error = rc; + return error.SetAclFailed; + } +} + +// --------------------------------------------------------------------------- +// Tests + +test "Windows crypto constants match windows-rs" { + try std.testing.expectEqual(@as(u32, 4), CRYPTPROTECT_LOCAL_MACHINE); + try std.testing.expectEqual(@as(u32, 1), CRYPTPROTECT_UI_FORBIDDEN); + try std.testing.expectEqual(@as(u32, 32), NCRYPT_MACHINE_KEY_FLAG); + try std.testing.expectEqual(@as(u32, 64), NCRYPT_SILENT_FLAG); + try std.testing.expectEqual(@as(u32, 128), NCRYPT_OVERWRITE_KEY_FLAG); + try std.testing.expectEqual(@as(u32, 4), NCRYPT_PAD_OAEP_FLAG); + try std.testing.expectEqual(@as(u32, 0x80090016), NTE_BAD_KEYSET); + try std.testing.expectEqual(@as(u32, 0x8009000F), NTE_EXISTS); + try std.testing.expectEqualStrings("Microsoft Platform Crypto Provider", ms_platform_provider); + try std.testing.expectEqual(@as(usize, 190), oaep_max_plain); + try std.testing.expectEqual(@as(u32, 4), DACL_SECURITY_INFORMATION); + try std.testing.expectEqual(@as(u32, 0x80000000), PROTECTED_DACL_SECURITY_INFORMATION); + try std.testing.expectEqual(@as(u32, 1), SE_FILE_OBJECT); + // DATA_BLOB is { DWORD cbData; BYTE *pbData; }. + try std.testing.expectEqual(@as(usize, 0), @offsetOf(DATA_BLOB, "cbData")); + try std.testing.expectEqual(@as(usize, @sizeOf(usize)), @offsetOf(DATA_BLOB, "pbData")); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(BCRYPT_OAEP_PADDING_INFO, "pszAlgId")); +} + +test "blob framing round-trips and refuses junk" { + const a = std.testing.allocator; + const f = try encodeFile(a, .tpm, "body"); + defer a.free(f); + const d = try decodeFile(f); + try std.testing.expectEqual(Wrap.tpm, d.wrap); + try std.testing.expectEqualStrings("body", d.body); + try std.testing.expectError(error.CorruptBlob, decodeFile("TWN")); + try std.testing.expectError(error.CorruptBlob, decodeFile("XXXX\x01\x00body")); + try std.testing.expectError(error.CorruptBlob, decodeFile("TWNK\x02\x00body")); + try std.testing.expectError(error.CorruptBlob, decodeFile("TWNK\x01\x07body")); +} + +test "DPAPI round trip and TPM wrap (Windows only)" { + if (builtin.target.os.tag != .windows) return error.SkipZigTest; + const a = std.testing.allocator; + const secret = "tawny test secret \x00\x01\xff"; + const blob = try protect(a, secret); + defer a.free(blob); + try std.testing.expect(std.mem.indexOf(u8, blob, "tawny test secret") == null); + const back = try unprotect(a, blob); + defer a.free(back); + try std.testing.expectEqualSlices(u8, secret, back); + // Wrong entropy is refused: flip the blob instead (same effect, no API). + var bad = try a.dupe(u8, blob); + defer a.free(bad); + bad[bad.len - 1] ^= 0xff; + try std.testing.expectError(error.DpapiFailed, unprotect(a, bad)); + + // The TPM is optional; the hosted runner usually has none. + var tpm = Tpm.open() catch return; + defer tpm.close(); + const big: [400]u8 = @splat(0x5a); + const w = try tpm.wrap(a, &big); + defer a.free(w); + const u = try tpm.unwrap(a, w); + defer a.free(u); + try std.testing.expectEqualSlices(u8, &big, u); +} From 4701bde2eff3b70ad37feb7d78326a5e7dce4840 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:03 +1100 Subject: [PATCH 4/8] feat(agent): minisign-verified self-update with rings and rollback - minisign.zig verifies ED (BLAKE2b-512 prehashed) and legacy Ed signatures and the trusted comment's global signature. Cross-checked against a signature made by an independent implementation. - update_key.zig holds an obvious placeholder; the updater refuses every update while it is there (state disabled_no_release_key). - updater.zig: decide (platform, ring, min_from, downgrade refused unless a signed rollback, never retry a rolled-back version), verify size and SHA-256, stage, swap with .previous (rename the running exe), restart through the service manager, 5 minute health window, commit or roll back. Tests sign with a key made inside the test. - --update-selftest runs the same scenarios through real file renames. Co-Authored-By: Claude Opus 5.5 --- agent/src/minisign.zig | 249 ++++++++++++ agent/src/update_key.zig | 37 ++ agent/src/updater.zig | 852 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 1138 insertions(+) create mode 100644 agent/src/minisign.zig create mode 100644 agent/src/update_key.zig create mode 100644 agent/src/updater.zig diff --git a/agent/src/minisign.zig b/agent/src/minisign.zig new file mode 100644 index 0000000..fb9dda7 --- /dev/null +++ b/agent/src/minisign.zig @@ -0,0 +1,249 @@ +//! Minisign signature verification (https://jedisct1.github.io/minisign/). +//! +//! Public key: two lines, an untrusted comment then base64 of +//! `"Ed" || key_id[8] || ed25519_public[32]`. +//! +//! Signature: four lines. +//! untrusted comment: +//! base64(sig_alg[2] || key_id[8] || signature[64]) +//! trusted comment: +//! base64(global_signature[64]) +//! +//! `sig_alg` is `ED` for the current default, where the signature covers the +//! BLAKE2b-512 hash of the file (prehashed), or `Ed` for the legacy form that +//! signs the file bytes directly. Both are accepted. The global signature +//! covers `signature || trusted_comment` and is always checked, so the trusted +//! comment cannot be swapped. + +const std = @import("std"); +const Ed25519 = std.crypto.sign.Ed25519; +const Blake2b512 = std.crypto.hash.blake2.Blake2b512; + +pub const key_id_len = 8; + +pub const PublicKey = struct { + key_id: [key_id_len]u8, + key: Ed25519.PublicKey, +}; + +pub const Algorithm = enum { prehashed, legacy }; + +pub const Signature = struct { + algorithm: Algorithm, + key_id: [key_id_len]u8, + signature: [Ed25519.Signature.encoded_length]u8, + /// Slice into the signature text, without the `trusted comment: ` prefix. + trusted_comment: []const u8, + global_signature: [Ed25519.Signature.encoded_length]u8, +}; + +pub const Error = error{ + InvalidPublicKey, + InvalidSignatureFormat, + UnsupportedAlgorithm, + KeyIdMismatch, + SignatureVerificationFailed, + TrustedCommentVerificationFailed, +}; + +const trusted_prefix = "trusted comment: "; +const untrusted_prefix = "untrusted comment: "; + +/// Parse a public key: the two-line `.pub` file, or the bare base64 line. +pub fn parsePublicKey(text: []const u8) Error!PublicKey { + var lines = std.mem.tokenizeAny(u8, text, "\r\n"); + var b64: ?[]const u8 = null; + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t"); + if (line.len == 0 or std.mem.startsWith(u8, line, untrusted_prefix)) continue; + b64 = line; + break; + } + var raw: [2 + key_id_len + 32]u8 = undefined; + decodeExact(&raw, b64 orelse return error.InvalidPublicKey) catch return error.InvalidPublicKey; + if (!std.mem.eql(u8, raw[0..2], "Ed")) return error.UnsupportedAlgorithm; + return .{ + .key_id = raw[2..10].*, + .key = Ed25519.PublicKey.fromBytes(raw[10..42].*) catch return error.InvalidPublicKey, + }; +} + +/// Parse a `.minisig` file. The returned trusted comment points into `text`. +pub fn parseSignature(text: []const u8) Error!Signature { + var lines = std.mem.splitScalar(u8, text, '\n'); + const l1 = trimCr(lines.next() orelse return error.InvalidSignatureFormat); + const l2 = trimCr(lines.next() orelse return error.InvalidSignatureFormat); + const l3 = trimCr(lines.next() orelse return error.InvalidSignatureFormat); + const l4 = trimCr(lines.next() orelse return error.InvalidSignatureFormat); + if (!std.mem.startsWith(u8, l1, untrusted_prefix)) return error.InvalidSignatureFormat; + if (!std.mem.startsWith(u8, l3, trusted_prefix)) return error.InvalidSignatureFormat; + + var sig_raw: [2 + key_id_len + 64]u8 = undefined; + decodeExact(&sig_raw, l2) catch return error.InvalidSignatureFormat; + const algorithm: Algorithm = if (std.mem.eql(u8, sig_raw[0..2], "ED")) + .prehashed + else if (std.mem.eql(u8, sig_raw[0..2], "Ed")) + .legacy + else + return error.UnsupportedAlgorithm; + + var global: [64]u8 = undefined; + decodeExact(&global, l4) catch return error.InvalidSignatureFormat; + return .{ + .algorithm = algorithm, + .key_id = sig_raw[2..10].*, + .signature = sig_raw[10..74].*, + .trusted_comment = l3[trusted_prefix.len..], + .global_signature = global, + }; +} + +/// Verify `message` against a parsed signature and key. Returns the trusted +/// comment on success. +pub fn verify(pk: PublicKey, sig: Signature, message: []const u8) Error![]const u8 { + if (!std.mem.eql(u8, &pk.key_id, &sig.key_id)) return error.KeyIdMismatch; + const s = Ed25519.Signature.fromBytes(sig.signature); + switch (sig.algorithm) { + .prehashed => { + var digest: [Blake2b512.digest_length]u8 = undefined; + Blake2b512.hash(message, &digest, .{}); + s.verify(&digest, pk.key) catch return error.SignatureVerificationFailed; + }, + .legacy => s.verify(message, pk.key) catch return error.SignatureVerificationFailed, + } + // Global signature: signature bytes followed by the trusted comment. + const g = Ed25519.Signature.fromBytes(sig.global_signature); + var v = g.verifier(pk.key) catch return error.TrustedCommentVerificationFailed; + v.update(&sig.signature); + v.update(sig.trusted_comment); + v.verify() catch return error.TrustedCommentVerificationFailed; + return sig.trusted_comment; +} + +/// Parse both texts and verify. Returns the trusted comment (a slice of +/// `signature_text`). +pub fn verifyText(public_key_text: []const u8, signature_text: []const u8, message: []const u8) Error![]const u8 { + const pk = try parsePublicKey(public_key_text); + const sig = try parseSignature(signature_text); + return verify(pk, sig, message); +} + +fn trimCr(line: []const u8) []const u8 { + return std.mem.trimEnd(u8, line, "\r"); +} + +fn decodeExact(out: []u8, b64: []const u8) !void { + const dec = std.base64.standard.Decoder; + const n = try dec.calcSizeForSlice(b64); + if (n != out.len) return error.InvalidLength; + try dec.decode(out, b64); +} + +// --------------------------------------------------------------------------- +// Test signer. Produces the same four-line format as `minisign -S` from a key +// pair generated inside the test. Never used outside tests. + +pub const TestSigner = struct { + kp: Ed25519.KeyPair, + key_id: [key_id_len]u8, + + pub fn generate(io: std.Io) TestSigner { + var id: [key_id_len]u8 = undefined; + io.random(&id); + return .{ .kp = Ed25519.KeyPair.generate(io), .key_id = id }; + } + + /// Two-line public key text. Caller frees. + pub fn publicKeyText(self: TestSigner, alloc: std.mem.Allocator) ![]u8 { + var raw: [42]u8 = undefined; + raw[0..2].* = "Ed".*; + raw[2..10].* = self.key_id; + raw[10..42].* = self.kp.public_key.bytes; + var b64: [56]u8 = undefined; + const enc = std.base64.standard.Encoder.encode(&b64, &raw); + return std.fmt.allocPrint(alloc, "untrusted comment: test key {x}\n{s}\n", .{ self.key_id, enc }); + } + + /// Four-line signature text. Caller frees. + pub fn sign(self: TestSigner, alloc: std.mem.Allocator, message: []const u8, trusted_comment: []const u8, algorithm: Algorithm) ![]u8 { + const sig = switch (algorithm) { + .prehashed => blk: { + var digest: [Blake2b512.digest_length]u8 = undefined; + Blake2b512.hash(message, &digest, .{}); + break :blk try self.kp.sign(&digest, null); + }, + .legacy => try self.kp.sign(message, null), + }; + const sig_bytes = sig.toBytes(); + var raw: [74]u8 = undefined; + raw[0..2].* = if (algorithm == .prehashed) "ED".* else "Ed".*; + raw[2..10].* = self.key_id; + raw[10..74].* = sig_bytes; + + const global_msg = try std.mem.concat(alloc, u8, &.{ &sig_bytes, trusted_comment }); + defer alloc.free(global_msg); + const global = (try self.kp.sign(global_msg, null)).toBytes(); + + var b1: [100]u8 = undefined; + var b2: [88]u8 = undefined; + const e1 = std.base64.standard.Encoder.encode(&b1, &raw); + const e2 = std.base64.standard.Encoder.encode(&b2, &global); + return std.fmt.allocPrint(alloc, "untrusted comment: signature from tawny test key\n{s}\ntrusted comment: {s}\n{s}\n", .{ e1, trusted_comment, e2 }); + } +}; + +// --------------------------------------------------------------------------- +// Tests + +const testing = std.testing; + +test "prehashed and legacy minisign signatures verify" { + const a = testing.allocator; + const signer = TestSigner.generate(testing.io); + const pub_text = try signer.publicKeyText(a); + defer a.free(pub_text); + const msg = "{\"version\":\"1.2.3\"}"; + for ([_]Algorithm{ .prehashed, .legacy }) |alg| { + const sig_text = try signer.sign(a, msg, "timestamp:1700000000\tfile:manifest.json", alg); + defer a.free(sig_text); + const tc = try verifyText(pub_text, sig_text, msg); + try testing.expectEqualStrings("timestamp:1700000000\tfile:manifest.json", tc); + const parsed = try parseSignature(sig_text); + try testing.expectEqual(alg, parsed.algorithm); + } +} + +test "minisign refuses a changed message, a changed trusted comment and another key" { + const a = testing.allocator; + const signer = TestSigner.generate(testing.io); + const other = TestSigner.generate(testing.io); + const pub_text = try signer.publicKeyText(a); + defer a.free(pub_text); + const other_pub = try other.publicKeyText(a); + defer a.free(other_pub); + const sig_text = try signer.sign(a, "payload", "comment", .prehashed); + defer a.free(sig_text); + + try testing.expectError(error.SignatureVerificationFailed, verifyText(pub_text, sig_text, "payloaD")); + try testing.expectError(error.KeyIdMismatch, verifyText(other_pub, sig_text, "payload")); + + // Same key id, different key: the signature itself fails. + var forged = other; + forged.key_id = signer.key_id; + const forged_pub = try forged.publicKeyText(a); + defer a.free(forged_pub); + try testing.expectError(error.SignatureVerificationFailed, verifyText(forged_pub, sig_text, "payload")); + + // Swap the trusted comment line: the global signature catches it. + const swapped = try std.mem.replaceOwned(u8, a, sig_text, "trusted comment: comment", "trusted comment: rollback"); + defer a.free(swapped); + try testing.expectError(error.TrustedCommentVerificationFailed, verifyText(pub_text, swapped, "payload")); +} + +test "minisign parser refuses malformed input" { + try testing.expectError(error.InvalidSignatureFormat, parseSignature("only one line")); + try testing.expectError(error.InvalidPublicKey, parsePublicKey("untrusted comment: x\nnot base64!!\n")); + // A real minisign public key line (from the minisign README) parses. + const pk = try parsePublicKey("RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3"); + try testing.expectEqualSlices(u8, &.{ 0x1f, 0xe8, 0xb4, 0x42, 0x18, 0x0f, 0x62, 0xe7 }, &pk.key_id); +} diff --git a/agent/src/update_key.zig b/agent/src/update_key.zig new file mode 100644 index 0000000..e2b6795 --- /dev/null +++ b/agent/src/update_key.zig @@ -0,0 +1,37 @@ +//! Release signing public key, compiled into the agent (target-edr §10 +//! "Updates"). The private half is an offline minisign key held by the +//! project owner. CI only signs through a protected GitHub environment. +//! +//! PLACEHOLDER: no release key exists yet. While `public_key` is the +//! placeholder below, `isPlaceholder()` is true and the updater refuses to +//! update (state `disabled_no_release_key`). To turn updates on, replace the +//! base64 line with the second line of the real `minisign.pub` and rebuild. +//! Never put a private key in this repository. + +const std = @import("std"); +const minisign = @import("minisign.zig"); + +/// Base64 public key line (`"Ed" || key_id || key`). The all-`A` value +/// decodes to a zero key id and a zero key, which is not a usable Ed25519 +/// point, so it can never verify a signature even by accident. +pub const public_key = "RWQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + +pub const placeholder = "RWQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + +pub fn isPlaceholder() bool { + return std.mem.eql(u8, public_key, placeholder); +} + +/// The compiled-in key, or `error.NoReleaseKey` while it is the placeholder. +pub fn get() !minisign.PublicKey { + if (isPlaceholder()) return error.NoReleaseKey; + return minisign.parsePublicKey(public_key); +} + +test "release key is still the placeholder and refuses to load" { + // When the real key lands, this test changes with it on purpose. + try std.testing.expect(isPlaceholder()); + try std.testing.expectError(error.NoReleaseKey, get()); + // The placeholder is the right length for a minisign key line. + try std.testing.expectEqual(@as(usize, 56), public_key.len); +} diff --git a/agent/src/updater.zig b/agent/src/updater.zig new file mode 100644 index 0000000..2746830 --- /dev/null +++ b/agent/src/updater.zig @@ -0,0 +1,852 @@ +//! Signed self-update in rings (#58, target-edr §10 "Updates"). +//! +//! Flow: check the release endpoint on a timer, verify the manifest's +//! minisign signature with the compiled-in release key (update_key.zig), +//! refuse a version at or below the current one unless the manifest is a +//! signed `rollback`, download, check size and SHA-256, stage beside the +//! binary, swap (rename the running exe to `.previous`, which Windows +//! allows), then exit non-zero so the service manager starts the new binary +//! (SCM failure actions, systemd `Restart=on-failure`, launchd `KeepAlive`). +//! The new binary runs a health window: the first successful heartbeat +//! commits. Three starts without one, or the window running out, roll back +//! to `.previous` and restart again. +//! +//! While update_key.zig still holds the placeholder key, `Updater.check` +//! does nothing and reports `disabled_no_release_key`. +//! +//! Manifest (JSON, signed as a file with minisign): +//! {"version":"0.2.0","platform":"windows-x64","sha256":"","size":123, +//! "min_from_version":"0.1.0","ring":"canary","rollback":false} +//! +//! Rings: canary, internal, 10, 50, 100. An agent's ring is its server-side +//! `update_ring` override, else from its bucket: sha256(agent_id) first four +//! bytes big-endian mod 100; below 10 is ring 10, below 50 is ring 50, the +//! rest ring 100. A release open to ring R is offered to agents whose ring is +//! R or earlier. The server applies the same rule (routes/agent_releases.zig). + +const std = @import("std"); +const builtin = @import("builtin"); +const minisign = @import("minisign.zig"); +const update_key = @import("update_key.zig"); +const iox = @import("io_compat.zig"); + +const Sha256 = std.crypto.hash.sha2.Sha256; + +// --------------------------------------------------------------------------- +// Rings + +pub const Ring = enum { + canary, + internal, + @"10", + @"50", + @"100", + + pub fn rank(self: Ring) u8 { + return @backingInt(self); + } + + pub fn parse(text: []const u8) ?Ring { + return std.meta.stringToEnum(Ring, text); + } +}; + +/// Stable bucket 0..99 for an agent id (canonical lower-case UUID text). +pub fn bucket(agent_id: []const u8) u8 { + var lower: [64]u8 = undefined; + const n = @min(agent_id.len, lower.len); + for (agent_id[0..n], 0..) |c, i| lower[i] = std.ascii.toLower(c); + var d: [32]u8 = undefined; + Sha256.hash(lower[0..n], &d, .{}); + return @intCast(std.mem.readInt(u32, d[0..4], .big) % 100); +} + +pub fn ringForBucket(b: u8) Ring { + if (b < 10) return .@"10"; + if (b < 50) return .@"50"; + return .@"100"; +} + +/// A release open to `release_ring` is offered to `agent_ring`. +pub fn ringAllows(release_ring: Ring, agent_ring: Ring) bool { + return agent_ring.rank() <= release_ring.rank(); +} + +// --------------------------------------------------------------------------- +// Manifest + +pub const Manifest = struct { + version: []const u8, + platform: []const u8, + sha256: []const u8, + size: u64, + min_from_version: []const u8 = "0.0.0", + ring: []const u8 = "100", + rollback: bool = false, +}; + +pub const Decision = enum { + update, + up_to_date, + downgrade_refused, + wrong_platform, + below_min_from, + refused_version, + not_in_ring, + bad_manifest, +}; + +pub const Context = struct { + current_version: []const u8, + platform: []const u8, + agent_ring: Ring, + /// A version this agent already rolled back from; never retried. + refused_version: ?[]const u8 = null, +}; + +/// Whether a verified manifest should be installed. Pure. +pub fn decide(m: Manifest, ctx: Context) Decision { + if (!std.mem.eql(u8, m.platform, ctx.platform)) return .wrong_platform; + if (m.sha256.len != 64 or m.size == 0 or m.size > max_binary_bytes) return .bad_manifest; + const ring = Ring.parse(m.ring) orelse return .bad_manifest; + if (!ringAllows(ring, ctx.agent_ring)) return .not_in_ring; + const want = std.SemanticVersion.parse(m.version) catch return .bad_manifest; + const have = std.SemanticVersion.parse(ctx.current_version) catch return .bad_manifest; + const min_from = std.SemanticVersion.parse(m.min_from_version) catch return .bad_manifest; + if (ctx.refused_version) |r| if (std.mem.eql(u8, r, m.version)) return .refused_version; + const order = want.order(have); + if (m.rollback) { + // A signed rollback may go down, never sideways or up. + return if (order == .lt) .update else .up_to_date; + } + if (order != .gt) return if (order == .eq) .up_to_date else .downgrade_refused; + if (have.order(min_from) == .lt) return .below_min_from; + return .update; +} + +pub const max_binary_bytes: u64 = 256 * 1024 * 1024; + +pub const VerifyError = error{ + NoReleaseKey, + BadSignature, + BadManifest, + HashMismatch, + SizeMismatch, +} || std.mem.Allocator.Error; + +/// Verify the manifest signature and parse it. `key` null means the +/// placeholder is still compiled in. The parsed value borrows `manifest`. +pub fn verifyManifest(alloc: std.mem.Allocator, key: ?minisign.PublicKey, manifest: []const u8, signature: []const u8) VerifyError!std.json.Parsed(Manifest) { + const pk = key orelse return error.NoReleaseKey; + const sig = minisign.parseSignature(signature) catch return error.BadSignature; + _ = minisign.verify(pk, sig, manifest) catch return error.BadSignature; + return std.json.parseFromSlice(Manifest, alloc, manifest, .{ .ignore_unknown_fields = true }) catch |err| switch (err) { + error.OutOfMemory => error.OutOfMemory, + else => error.BadManifest, + }; +} + +/// Check downloaded bytes against the manifest. +pub fn verifyPayload(m: Manifest, bytes: []const u8) VerifyError!void { + if (bytes.len != m.size) return error.SizeMismatch; + var d: [32]u8 = undefined; + Sha256.hash(bytes, &d, .{}); + var hex: [64]u8 = undefined; + _ = std.fmt.bufPrint(&hex, "{x}", .{d}) catch unreachable; + if (!std.ascii.eqlIgnoreCase(&hex, m.sha256)) return error.HashMismatch; +} + +// --------------------------------------------------------------------------- +// Persisted state (`.update.json`) + +pub const State = enum { + disabled_no_release_key, + idle, + checking, + downloading, + staged, + restarting, + health_check, + committed, + rolled_back, + refused, + failed, +}; + +pub const Persisted = struct { + state: State = .idle, + version: []const u8 = "", + previous_version: []const u8 = "", + sha256: []const u8 = "", + /// Unix seconds by which the new binary must have a good heartbeat. + deadline: i64 = 0, + /// Starts of the new binary inside the health window. + attempts: u32 = 0, + refused_version: []const u8 = "", + reason: []const u8 = "", +}; + +pub const health_window_seconds: i64 = 300; +pub const max_health_attempts: u32 = 3; + +pub const StartAction = enum { none, health_check, rollback }; + +/// What a fresh start must do given the persisted state. Pure; the caller +/// bumps `attempts` before acting on `.health_check`. +pub fn onStart(p: Persisted, running_version: []const u8, now: i64) StartAction { + if (p.state != .restarting and p.state != .health_check) return .none; + // Still the old binary (the swap did not take): nothing to check. + if (!std.mem.eql(u8, running_version, p.version)) return .none; + if (p.attempts + 1 >= max_health_attempts) return .rollback; + if (now > p.deadline) return .rollback; + return .health_check; +} + +/// Health window tick: commit on a good heartbeat, roll back after the +/// deadline. Pure. +pub fn onTick(p: Persisted, heartbeat_ok: bool, now: i64) StartAction { + if (p.state != .health_check) return .none; + if (heartbeat_ok) return .none; // caller commits + if (now > p.deadline) return .rollback; + return .health_check; +} + +pub fn statePath(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { + return alloc.print("{s}.update.json", .{state_path}); +} + +/// Read the persisted state. Missing or unreadable is `idle`. The strings +/// live in the returned arena. +pub fn load(alloc: std.mem.Allocator, state_path: []const u8) !std.json.Parsed(Persisted) { + const path = try statePath(alloc, state_path); + defer alloc.free(path); + const text = std.Io.Dir.cwd().readFileAlloc(iox.current(), path, alloc, .limited(16 * 1024)) catch + return std.json.parseFromSlice(Persisted, alloc, "{}", .{}); + defer alloc.free(text); + return std.json.parseFromSlice(Persisted, alloc, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch + std.json.parseFromSlice(Persisted, alloc, "{}", .{}); +} + +pub fn save(alloc: std.mem.Allocator, state_path: []const u8, p: Persisted) !void { + const path = try statePath(alloc, state_path); + defer alloc.free(path); + const body = try std.json.Stringify.valueAlloc(alloc, p, .{}); + defer alloc.free(body); + const tmp = try alloc.print("{s}.tmp", .{path}); + defer alloc.free(tmp); + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + try cwd.writeFile(io, .{ .sub_path = tmp, .data = body }); + try cwd.rename(tmp, cwd, path, io); +} + +// --------------------------------------------------------------------------- +// Files: stage, swap, roll back + +pub const Paths = struct { + exe: []const u8, + staged: []u8, + previous: []u8, + failed: []u8, + + pub fn init(alloc: std.mem.Allocator, exe: []const u8) !Paths { + const dir = std.fs.path.dirname(exe) orelse "."; + const win = std.mem.endsWith(u8, exe, ".exe"); + const sep = if (builtin.target.os.tag == .windows) "\\" else "/"; + const staged = try std.fmt.allocPrint(alloc, "{s}{s}tawny-agent.staged{s}", .{ dir, sep, if (win) ".exe" else "" }); + errdefer alloc.free(staged); + const previous = try std.fmt.allocPrint(alloc, "{s}{s}tawny-agent.previous{s}", .{ dir, sep, if (win) ".exe" else "" }); + errdefer alloc.free(previous); + const failed = try std.fmt.allocPrint(alloc, "{s}{s}tawny-agent.failed{s}", .{ dir, sep, if (win) ".exe" else "" }); + return .{ .exe = exe, .staged = staged, .previous = previous, .failed = failed }; + } + + pub fn deinit(self: Paths, alloc: std.mem.Allocator) void { + alloc.free(self.staged); + alloc.free(self.previous); + alloc.free(self.failed); + } +}; + +/// Write the verified bytes next to the binary, executable, synced. +pub fn stage(paths: Paths, bytes: []const u8) !void { + const io = iox.current(); + var f = try std.Io.Dir.cwd().createFile(io, paths.staged, .{ + .truncate = true, + .permissions = if (builtin.target.os.tag == .windows) .default_file else @fromBackingInt(@intCast(0o755)), + }); + defer f.close(io); + try f.writePositionalAll(io, bytes, 0); + try f.sync(io); +} + +/// exe -> previous, staged -> exe. On Windows the running image can be +/// renamed but not overwritten, hence the two renames. If the second rename +/// fails the first is undone. +pub fn swap(paths: Paths) !void { + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + cwd.deleteFile(io, paths.previous) catch {}; + try cwd.rename(paths.exe, cwd, paths.previous, io); + cwd.rename(paths.staged, cwd, paths.exe, io) catch |err| { + cwd.rename(paths.previous, cwd, paths.exe, io) catch {}; + return err; + }; +} + +/// exe -> failed, previous -> exe. +pub fn rollback(paths: Paths) !void { + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + // Without a previous binary there is nothing to go back to. + { + const f = cwd.openFile(io, paths.previous, .{}) catch return error.NoPreviousBinary; + f.close(io); + } + cwd.deleteFile(io, paths.failed) catch {}; + try cwd.rename(paths.exe, cwd, paths.failed, io); + cwd.rename(paths.previous, cwd, paths.exe, io) catch |err| { + cwd.rename(paths.failed, cwd, paths.exe, io) catch {}; + return err; + }; +} + +// --------------------------------------------------------------------------- +// Runtime + +pub const HealthState = struct { + state: State, + version: ?[]const u8 = null, + ring: ?[]const u8 = null, + bucket: ?u8 = null, + reason: ?[]const u8 = null, +}; + +pub const Fetcher = struct { + ctx: *anyopaque, + /// Returns `{manifest, signature, download_url}` JSON from the server, + /// or null when no release is offered. Caller frees. + release: *const fn (ctx: *anyopaque, alloc: std.mem.Allocator, platform: []const u8) anyerror!?[]u8, + /// Download `url` (at most `max` bytes). Caller frees. + download: *const fn (ctx: *anyopaque, alloc: std.mem.Allocator, url: []const u8, max: u64) anyerror![]u8, +}; + +pub const Outcome = enum { nothing, restart_now }; + +pub const Updater = struct { + alloc: std.mem.Allocator, + state_path: []const u8, + exe_path: []const u8, + current_version: []const u8, + platform: []const u8, + agent_id: []const u8, + /// Server-side ring override, if the server sent one. + ring_override: ?Ring = null, + key: ?minisign.PublicKey, + status: State = .idle, + status_version: [32]u8 = @splat(0), + status_version_len: usize = 0, + reason: []const u8 = "", + + pub fn init(alloc: std.mem.Allocator, state_path: []const u8, exe_path: []const u8, current_version: []const u8, platform: []const u8, agent_id: []const u8) Updater { + const key = update_key.get() catch null; + return .{ + .alloc = alloc, + .state_path = state_path, + .exe_path = exe_path, + .current_version = current_version, + .platform = platform, + .agent_id = agent_id, + .key = key, + .status = if (key == null) .disabled_no_release_key else .idle, + }; + } + + pub fn ring(self: *const Updater) Ring { + return self.ring_override orelse ringForBucket(bucket(self.agent_id)); + } + + pub fn health(self: *const Updater) HealthState { + return .{ + .state = self.status, + .version = if (self.status_version_len > 0) self.status_version[0..self.status_version_len] else null, + .ring = @tagName(self.ring()), + .bucket = bucket(self.agent_id), + .reason = if (self.reason.len > 0) self.reason else null, + }; + } + + fn setStatus(self: *Updater, s: State, version: []const u8, why: []const u8) void { + self.status = s; + self.reason = why; + const n = @min(version.len, self.status_version.len); + @memcpy(self.status_version[0..n], version[0..n]); + self.status_version_len = n; + } + + /// Call once at start. Returns `.restart_now` after a rollback swap. + pub fn startCheck(self: *Updater, now: i64) !Outcome { + var parsed = try load(self.alloc, self.state_path); + defer parsed.deinit(); + var p = parsed.value; + switch (onStart(p, self.current_version, now)) { + .none => { + if (p.state == .rolled_back) self.setStatus(.rolled_back, p.refused_version, "health check failed"); + if (self.key == null) self.status = .disabled_no_release_key; + return .nothing; + }, + .health_check => { + p.state = .health_check; + p.attempts += 1; + try save(self.alloc, self.state_path, p); + self.setStatus(.health_check, p.version, ""); + return .nothing; + }, + .rollback => return self.doRollback(p, "the new version did not pass its health check"), + } + } + + /// Feed heartbeat results while in the health window. + pub fn onHeartbeat(self: *Updater, ok: bool, now: i64) !Outcome { + if (self.status != .health_check) return .nothing; + var parsed = try load(self.alloc, self.state_path); + defer parsed.deinit(); + var p = parsed.value; + if (ok and p.state == .health_check) { + p.state = .committed; + p.attempts = 0; + try save(self.alloc, self.state_path, p); + self.setStatus(.committed, p.version, ""); + return .nothing; + } + return switch (onTick(p, ok, now)) { + .rollback => self.doRollback(p, "no good heartbeat inside the health window"), + else => .nothing, + }; + } + + fn doRollback(self: *Updater, p_in: Persisted, why: []const u8) !Outcome { + var p = p_in; + const paths = try Paths.init(self.alloc, self.exe_path); + defer paths.deinit(self.alloc); + rollback(paths) catch |err| { + p.state = .failed; + p.reason = "rollback failed: no previous binary"; + save(self.alloc, self.state_path, p) catch {}; + self.setStatus(.failed, p.version, p.reason); + return err; + }; + p.state = .rolled_back; + p.refused_version = p.version; + p.reason = why; + try save(self.alloc, self.state_path, p); + self.setStatus(.rolled_back, p.version, why); + return .restart_now; + } + + /// One update check. Returns `.restart_now` once a new binary is in + /// place; the caller then stops so the service manager restarts it. + pub fn check(self: *Updater, fetcher: Fetcher) !Outcome { + if (self.key == null) { + self.status = .disabled_no_release_key; + return .nothing; + } + if (self.status == .health_check) return .nothing; + const offered = (try fetcher.release(fetcher.ctx, self.alloc, self.platform)) orelse { + if (self.status != .rolled_back and self.status != .committed) self.setStatus(.idle, "", ""); + return .nothing; + }; + defer self.alloc.free(offered); + const Offer = struct { manifest: []const u8, signature: []const u8, download_url: []const u8 }; + const offer = std.json.parseFromSlice(Offer, self.alloc, offered, .{ .ignore_unknown_fields = true }) catch { + self.setStatus(.refused, "", "release reply is not valid"); + return .nothing; + }; + defer offer.deinit(); + return self.apply(fetcher, offer.value.manifest, offer.value.signature, offer.value.download_url); + } + + /// Verify, decide, download, stage and swap. Exposed for tests. + pub fn apply(self: *Updater, fetcher: Fetcher, manifest: []const u8, signature: []const u8, url: []const u8) !Outcome { + var m = verifyManifest(self.alloc, self.key, manifest, signature) catch |err| { + self.setStatus(.refused, "", @errorName(err)); + return .nothing; + }; + defer m.deinit(); + var prev = try load(self.alloc, self.state_path); + defer prev.deinit(); + const decision = decide(m.value, .{ + .current_version = self.current_version, + .platform = self.platform, + .agent_ring = self.ring(), + .refused_version = if (prev.value.refused_version.len > 0) prev.value.refused_version else null, + }); + switch (decision) { + .update => {}, + .up_to_date, .not_in_ring => { + if (self.status != .rolled_back and self.status != .committed) self.setStatus(.idle, "", ""); + return .nothing; + }, + else => { + self.setStatus(.refused, m.value.version, @tagName(decision)); + return .nothing; + }, + } + if (!isHttps(url)) { + self.setStatus(.refused, m.value.version, "download url is not https"); + return .nothing; + } + self.setStatus(.downloading, m.value.version, ""); + const bytes = fetcher.download(fetcher.ctx, self.alloc, url, m.value.size) catch |err| { + self.setStatus(.failed, m.value.version, @errorName(err)); + return .nothing; + }; + defer self.alloc.free(bytes); + verifyPayload(m.value, bytes) catch |err| { + self.setStatus(.refused, m.value.version, @errorName(err)); + return .nothing; + }; + const paths = try Paths.init(self.alloc, self.exe_path); + defer paths.deinit(self.alloc); + try stage(paths, bytes); + self.setStatus(.staged, m.value.version, ""); + try swap(paths); + try save(self.alloc, self.state_path, .{ + .state = .restarting, + .version = m.value.version, + .previous_version = self.current_version, + .sha256 = m.value.sha256, + .deadline = iox.timestamp() + health_window_seconds, + .attempts = 0, + }); + // Keep the signed manifest so tamper checks can compare the binary. + saveRelease(self.alloc, self.state_path, manifest, signature) catch {}; + self.setStatus(.restarting, m.value.version, ""); + return .restart_now; + } +}; + +fn isHttps(url: []const u8) bool { + return std.ascii.startsWithIgnoreCase(url, "https://"); +} + +/// `.release.json` + `.minisig`: the manifest the running binary was +/// installed from. +pub fn saveRelease(alloc: std.mem.Allocator, state_path: []const u8, manifest: []const u8, signature: []const u8) !void { + const io = iox.current(); + const m = try alloc.print("{s}.release.json", .{state_path}); + defer alloc.free(m); + const s = try alloc.print("{s}.release.json.minisig", .{state_path}); + defer alloc.free(s); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = m, .data = manifest }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = s, .data = signature }); +} + +/// SHA-256 the running binary should have, from the saved manifest, when +/// its signature still verifies and it names `version`. +pub fn expectedBinaryHash(alloc: std.mem.Allocator, key: ?minisign.PublicKey, state_path: []const u8, version: []const u8) ?[32]u8 { + const io = iox.current(); + const m_path = alloc.print("{s}.release.json", .{state_path}) catch return null; + defer alloc.free(m_path); + const s_path = alloc.print("{s}.release.json.minisig", .{state_path}) catch return null; + defer alloc.free(s_path); + const manifest = std.Io.Dir.cwd().readFileAlloc(io, m_path, alloc, .limited(16 * 1024)) catch return null; + defer alloc.free(manifest); + const sig = std.Io.Dir.cwd().readFileAlloc(io, s_path, alloc, .limited(4096)) catch return null; + defer alloc.free(sig); + var parsed = verifyManifest(alloc, key, manifest, sig) catch return null; + defer parsed.deinit(); + if (!std.mem.eql(u8, parsed.value.version, version)) return null; + var out: [32]u8 = undefined; + _ = std.fmt.hexToBytes(&out, parsed.value.sha256) catch return null; + return out; +} + +/// Agent platform name used by releases (`windows-x64`, `linux-arm64`...). +pub fn platformName() []const u8 { + const os = switch (builtin.target.os.tag) { + .windows => "windows", + .macos => "macos", + else => "linux", + }; + const arch = if (builtin.target.cpu.arch == .aarch64) "arm64" else "x64"; + return os ++ "-" ++ arch; +} + +// --------------------------------------------------------------------------- +// Debug subcommand: `--update-selftest ` (CI). Builds a fake install +// under , signs a manifest with a key made for the run, and runs the +// good, bad signature, bad hash, downgrade and rollback paths through the +// real file operations (including renaming a file the way the running exe +// is renamed). No network and no service restart. + +pub fn isDebugCommand(arg: []const u8) bool { + return std.mem.eql(u8, arg, "--update-selftest"); +} + +pub fn debugCommand(alloc: std.mem.Allocator, args: []const []const u8) u8 { + if (args.len != 2) { + std.debug.print("usage: tawny-agent --update-selftest \n", .{}); + return 2; + } + const results = runScenarios(alloc, args[1]) catch |err| { + std.debug.print("UPDATE\tresult=failed\terror={s}\n", .{@errorName(err)}); + return 1; + }; + std.debug.print("UPDATE\tgood={s}\tbad_signature={s}\tbad_hash={s}\tdowngrade={s}\trollback={s}\tresult=ok\n", .{ + results.good, results.bad_sig, results.bad_hash, results.downgrade, results.rollback, + }); + std.debug.print("UPDATE\trelease_key={s}\n", .{if (update_key.isPlaceholder()) "placeholder (updates disabled)" else "set"}); + return 0; +} + +const Scenarios = struct { + good: []const u8, + bad_sig: []const u8, + bad_hash: []const u8, + downgrade: []const u8, + rollback: []const u8, +}; + +const FakeServer = struct { + payload: []const u8, + fn download(ctx: *anyopaque, alloc: std.mem.Allocator, _: []const u8, max: u64) anyerror![]u8 { + const self: *FakeServer = @ptrCast(@alignCast(ctx)); + if (self.payload.len > max) return error.TooBig; + return alloc.dupe(u8, self.payload); + } + fn release(_: *anyopaque, _: std.mem.Allocator, _: []const u8) anyerror!?[]u8 { + return null; + } + fn fetcher(self: *FakeServer) Fetcher { + return .{ .ctx = self, .release = release, .download = download }; + } +}; + +fn manifestFor(alloc: std.mem.Allocator, version: []const u8, bytes: []const u8, rollback_flag: bool) ![]u8 { + var d: [32]u8 = undefined; + Sha256.hash(bytes, &d, .{}); + return std.fmt.allocPrint(alloc, + \\{{"version":"{s}","platform":"{s}","sha256":"{x}","size":{d},"min_from_version":"0.0.1","ring":"100","rollback":{}}} + , .{ version, platformName(), d, bytes.len, rollback_flag }); +} + +fn readAll(alloc: std.mem.Allocator, path: []const u8) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(iox.current(), path, alloc, .limited(1024 * 1024)); +} + +fn runScenarios(alloc: std.mem.Allocator, dir: []const u8) !Scenarios { + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir); + const exe_name = if (builtin.target.os.tag == .windows) "tawny-agent.exe" else "tawny-agent"; + const exe = try std.fs.path.join(alloc, &.{ dir, exe_name }); + defer alloc.free(exe); + const state = try std.fs.path.join(alloc, &.{ dir, "state.toml" }); + defer alloc.free(state); + // Start clean. + for ([_][]const u8{ ".update.json", ".release.json", ".release.json.minisig" }) |suffix| { + const p = try alloc.print("{s}{s}", .{ state, suffix }); + defer alloc.free(p); + cwd.deleteFile(io, p) catch {}; + } + try cwd.writeFile(io, .{ .sub_path = exe, .data = "old agent 0.1.0" }); + + const signer = minisign.TestSigner.generate(io); + const pub_text = try signer.publicKeyText(alloc); + defer alloc.free(pub_text); + const key = try minisign.parsePublicKey(pub_text); + + const new_bytes = "new agent 0.2.0"; + var server = FakeServer{ .payload = new_bytes }; + var u = Updater.init(alloc, state, exe, "0.1.0", platformName(), "00000000-0000-0000-0000-000000000042"); + u.key = key; + u.status = .idle; + + // Bad signature: signed by another key. + const other = minisign.TestSigner.generate(io); + const good_manifest = try manifestFor(alloc, "0.2.0", new_bytes, false); + defer alloc.free(good_manifest); + const forged = try other.sign(alloc, good_manifest, "tawny release", .prehashed); + defer alloc.free(forged); + _ = try u.apply(server.fetcher(), good_manifest, forged, "https://example.invalid/a"); + if (u.status != .refused) return error.BadSignatureAccepted; + const bad_sig = "refused"; + + // Bad hash: signed manifest, wrong bytes on the wire. + const sig = try signer.sign(alloc, good_manifest, "tawny release", .prehashed); + defer alloc.free(sig); + server.payload = "new agent 0.2.X"; + _ = try u.apply(server.fetcher(), good_manifest, sig, "https://example.invalid/a"); + if (u.status != .refused) return error.BadHashAccepted; + if (!std.mem.eql(u8, try readOnce(alloc, exe), "old agent 0.1.0")) return error.BinaryChanged; + const bad_hash = "refused"; + + // Downgrade: correctly signed, lower version, not a rollback. + const down = try manifestFor(alloc, "0.0.9", new_bytes, false); + defer alloc.free(down); + const down_sig = try signer.sign(alloc, down, "tawny release", .prehashed); + defer alloc.free(down_sig); + server.payload = new_bytes; + _ = try u.apply(server.fetcher(), down, down_sig, "https://example.invalid/a"); + if (u.status != .refused) return error.DowngradeAccepted; + const downgrade = "refused"; + + // Good update: staged, swapped, old binary kept as .previous. + if (try u.apply(server.fetcher(), good_manifest, sig, "https://example.invalid/a") != .restart_now) return error.GoodUpdateNotApplied; + if (!std.mem.eql(u8, try readOnce(alloc, exe), new_bytes)) return error.SwapFailed; + const paths = try Paths.init(alloc, exe); + defer paths.deinit(alloc); + if (!std.mem.eql(u8, try readOnce(alloc, paths.previous), "old agent 0.1.0")) return error.PreviousMissing; + const good = "swapped"; + + // The new binary starts; no good heartbeat before the deadline: roll back. + var nu = Updater.init(alloc, state, exe, "0.2.0", platformName(), "00000000-0000-0000-0000-000000000042"); + nu.key = key; + const t0 = iox.timestamp(); + if (try nu.startCheck(t0) != .nothing or nu.status != .health_check) return error.HealthWindowNotOpened; + if (try nu.onHeartbeat(false, t0 + health_window_seconds + 1) != .restart_now) return error.NoRollback; + if (!std.mem.eql(u8, try readOnce(alloc, exe), "old agent 0.1.0")) return error.RollbackDidNotRestore; + // The old binary refuses the version it rolled back from. + var ou = Updater.init(alloc, state, exe, "0.1.0", platformName(), "00000000-0000-0000-0000-000000000042"); + ou.key = key; + _ = try ou.startCheck(t0 + 400); + if (ou.status != .rolled_back) return error.RollbackNotReported; + _ = try ou.apply(server.fetcher(), good_manifest, sig, "https://example.invalid/a"); + if (ou.status != .refused) return error.RefusedVersionRetried; + const rolled = "restored"; + + return .{ .good = good, .bad_sig = bad_sig, .bad_hash = bad_hash, .downgrade = downgrade, .rollback = rolled }; +} + +/// Small helper for the scenarios: read a file into a static buffer. +var read_buf: [256]u8 = undefined; +fn readOnce(alloc: std.mem.Allocator, path: []const u8) ![]const u8 { + const data = try readAll(alloc, path); + defer alloc.free(data); + const n = @min(data.len, read_buf.len); + @memcpy(read_buf[0..n], data[0..n]); + return read_buf[0..n]; +} + +// --------------------------------------------------------------------------- +// Tests (pure logic on every OS, plus the file scenarios in a temp dir) + +const testing = std.testing; + +test "bucket is stable, in range, and matches the server vector" { + // Same vector as server/src/routes/agent_releases.zig. + try testing.expectEqual(bucket("00000000-0000-0000-0000-000000000042"), bucket("00000000-0000-0000-0000-000000000042")); + try testing.expectEqual(bucket("ABCDEF00-0000-0000-0000-000000000000"), bucket("abcdef00-0000-0000-0000-000000000000")); + try testing.expectEqual(@as(u8, 19), bucket("00000000-0000-0000-0000-000000000001")); + try testing.expectEqual(@as(u8, 16), bucket("00000000-0000-0000-0000-000000000042")); + var seen: [100]bool = @splat(false); + var buf: [36]u8 = undefined; + var i: u32 = 0; + while (i < 2000) : (i += 1) { + const id = try std.fmt.bufPrint(&buf, "00000000-0000-0000-0000-{d:0>12}", .{i}); + const b = bucket(id); + try testing.expect(b < 100); + seen[b] = true; + } + var covered: usize = 0; + for (seen) |s| covered += @intFromBool(s); + try testing.expect(covered > 95); +} + +test "ring order gates who is offered a release" { + try testing.expectEqual(Ring.@"10", ringForBucket(9)); + try testing.expectEqual(Ring.@"50", ringForBucket(10)); + try testing.expectEqual(Ring.@"100", ringForBucket(99)); + try testing.expect(ringAllows(.canary, .canary)); + try testing.expect(!ringAllows(.canary, .internal)); + try testing.expect(ringAllows(.@"50", .@"10")); + try testing.expect(!ringAllows(.@"50", .@"100")); + try testing.expect(ringAllows(.@"100", .@"100")); +} + +test "decide: upgrade, same, downgrade, rollback, platform, min_from, ring" { + const sha: []const u8 = &(@as([64]u8, @splat('a'))); + const base: Manifest = .{ .version = "0.2.0", .platform = "linux-x64", .sha256 = sha, .size = 10, .min_from_version = "0.1.0", .ring = "100" }; + const ctx: Context = .{ .current_version = "0.1.0", .platform = "linux-x64", .agent_ring = .@"100" }; + try testing.expectEqual(Decision.update, decide(base, ctx)); + var m = base; + m.version = "0.1.0"; + try testing.expectEqual(Decision.up_to_date, decide(m, ctx)); + m.version = "0.0.9"; + try testing.expectEqual(Decision.downgrade_refused, decide(m, ctx)); + m.rollback = true; + try testing.expectEqual(Decision.update, decide(m, ctx)); + m.version = "0.3.0"; + try testing.expectEqual(Decision.up_to_date, decide(m, ctx)); + m = base; + m.platform = "windows-x64"; + try testing.expectEqual(Decision.wrong_platform, decide(m, ctx)); + m = base; + m.min_from_version = "0.1.5"; + try testing.expectEqual(Decision.below_min_from, decide(m, ctx)); + m = base; + m.ring = "canary"; + try testing.expectEqual(Decision.not_in_ring, decide(m, ctx)); + m.ring = "bogus"; + try testing.expectEqual(Decision.bad_manifest, decide(m, ctx)); + var c2 = ctx; + c2.refused_version = "0.2.0"; + try testing.expectEqual(Decision.refused_version, decide(base, c2)); +} + +test "health window: commit on heartbeat, roll back on deadline or repeated starts" { + const p: Persisted = .{ .state = .restarting, .version = "0.2.0", .deadline = 1000, .attempts = 0 }; + try testing.expectEqual(StartAction.health_check, onStart(p, "0.2.0", 10)); + try testing.expectEqual(StartAction.none, onStart(p, "0.1.0", 10)); + try testing.expectEqual(StartAction.rollback, onStart(p, "0.2.0", 1001)); + var many = p; + many.attempts = 2; + try testing.expectEqual(StartAction.rollback, onStart(many, "0.2.0", 10)); + var hc = p; + hc.state = .health_check; + try testing.expectEqual(StartAction.none, onTick(hc, true, 10)); + try testing.expectEqual(StartAction.health_check, onTick(hc, false, 10)); + try testing.expectEqual(StartAction.rollback, onTick(hc, false, 1001)); +} + +test "placeholder key disables updates" { + var u = Updater.init(testing.allocator, "x", "y", "0.1.0", "linux-x64", "00000000-0000-0000-0000-000000000001"); + try testing.expectEqual(State.disabled_no_release_key, u.status); + var server = FakeServer{ .payload = "" }; + try testing.expectEqual(Outcome.nothing, try u.check(server.fetcher())); + try testing.expectEqual(State.disabled_no_release_key, u.health().state); +} + +test "good update, bad signature, bad hash, downgrade refused, failed health check rolls back" { + const a = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + defer a.free(dir); + const r = try runScenarios(a, dir); + try testing.expectEqualStrings("swapped", r.good); + try testing.expectEqualStrings("restored", r.rollback); +} + +test "a committed manifest gives the expected binary hash" { + const a = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const state = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path, "state.toml" }); + defer a.free(state); + const signer = minisign.TestSigner.generate(testing.io); + const pub_text = try signer.publicKeyText(a); + defer a.free(pub_text); + const key = try minisign.parsePublicKey(pub_text); + const manifest = try manifestFor(a, "0.2.0", "bytes", false); + defer a.free(manifest); + const sig = try signer.sign(a, manifest, "c", .prehashed); + defer a.free(sig); + try saveRelease(a, state, manifest, sig); + var want: [32]u8 = undefined; + Sha256.hash("bytes", &want, .{}); + try testing.expectEqualSlices(u8, &want, &(expectedBinaryHash(a, key, state, "0.2.0").?)); + try testing.expect(expectedBinaryHash(a, key, state, "0.3.0") == null); + try testing.expect(expectedBinaryHash(a, null, state, "0.2.0") == null); +} From 775259e271dafb28be5a54af98fadb59dc6d38f2 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:12 +1100 Subject: [PATCH 5/8] feat(agent): clean shutdown marker, tamper checks, health and service DACL - lifecycle: stop reasons from the SCM handler and signals; on a clean stop the agent flushes, sends a shutdown heartbeat and writes .clean. A start without it sends agent_tamper unexpected_stop. - tamper.zig: binary hash (against the signed manifest after an update), config and identity file changes outside the agent, Sysmon service stopped, Defender Operational 5007 exclusions covering Tawny paths. - agent_health carries key_protection, sensors and update state. - Run loop checks for signed updates every 6 hours (off while the release key is the placeholder) and exits non-zero after a swap so the service manager starts the new binary. - install.ps1 sets a service DACL so only SYSTEM and Administrators can stop, reconfigure or delete TawnyAgent. Co-Authored-By: Claude Opus 5.5 --- agent/install/install.ps1 | 13 + agent/src/collectors/windows_events.zig | 31 +- agent/src/lifecycle.zig | 108 +++++- agent/src/main.zig | 211 +++++++++++- agent/src/platform/windows/scm.zig | 75 ++++ agent/src/platform/windows/service.zig | 4 +- agent/src/schema_check.zig | 1 + agent/src/tamper.zig | 439 ++++++++++++++++++++++++ agent/src/transport/http.zig | 73 ++++ 9 files changed, 939 insertions(+), 16 deletions(-) create mode 100644 agent/src/platform/windows/scm.zig create mode 100644 agent/src/tamper.zig diff --git a/agent/install/install.ps1 b/agent/install/install.ps1 index 683636d..e43280f 100644 --- a/agent/install/install.ps1 +++ b/agent/install/install.ps1 @@ -6,6 +6,12 @@ $script:TawnySysmonDownloadUrl = "https://download.sysinternals.com/files/Sysmon $script:TawnySysmonConfigUrl = "https://github.com/olafhartong/sysmon-modular/releases/download/configs-a45dedb13a43/sysmonconfig-with-filedelete.xml" $script:TawnySysmonConfigSha256 = "a7832f4423aae16e39342e08f3a2962291eafb7972eb9dfb070009781fde50d9" $script:TawnySysmonChannel = "Microsoft-Windows-Sysmon/Operational" +# Service security descriptor (#58). SYSTEM (SY) and Administrators (BA) get +# full control. Interactive (IU), service (SU) and authenticated (AU) users +# may only query config and status, enumerate dependents, interrogate and read +# the DACL (CC LC SW LO CR RC): no start (RP), stop (WP), pause (DT), change +# config (DC) or delete (SD). The SACL audits failed changes by anyone. +$script:TawnyServiceSddl = "D:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;CCLCSWLOCRRC;;;AU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)" function Get-TawnySysmonStatus { [CmdletBinding()] @@ -414,6 +420,13 @@ fim_paths = [] & sc.exe sidtype $ServiceName unrestricted | Out-Null & sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/15000/restart/60000 | Out-Null & sc.exe failureflag $ServiceName 1 | Out-Null + # Service DACL (#58): only SYSTEM and Administrators may stop, + # pause, reconfigure or delete the service. Interactive users, + # service accounts and authenticated users can still query it. + & sc.exe sdset $ServiceName $script:TawnyServiceSddl | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "Failed to restrict the service DACL for $ServiceName." + } $serviceRegistryPath = "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName" New-ItemProperty -Path $serviceRegistryPath ` -Name Environment ` diff --git a/agent/src/collectors/windows_events.zig b/agent/src/collectors/windows_events.zig index 6e88da0..4945b28 100644 --- a/agent/src/collectors/windows_events.zig +++ b/agent/src/collectors/windows_events.zig @@ -13,6 +13,7 @@ const entity = @import("../entity.zig"); const schema_check = @import("../schema_check.zig"); const iox = @import("../io_compat.zig"); const eventlog = if (builtin.target.os.tag == .windows) @import("../platform/windows/eventlog.zig") else struct {}; +const tamper = @import("../tamper.zig"); const Jw = std.json.Stringify; @@ -35,7 +36,7 @@ const max_registry_data_bytes: usize = 1024; // --------------------------------------------------------------------------- // Channels -pub const Source = enum { sysmon, security, system, powershell }; +pub const Source = enum { sysmon, security, system, powershell, defender }; pub const Channel = struct { source: Source, @@ -65,6 +66,13 @@ pub const channels = [_]Channel{ .path = "Microsoft-Windows-PowerShell/Operational", .event_filter = "EventID=4104", }, + // Defender configuration changes (#58). Only 5007 entries that add an + // exclusion covering a Tawny path become events (agent_tamper). + .{ + .source = .defender, + .path = "Microsoft-Windows-Windows Defender/Operational", + .event_filter = "EventID=5007", + }, }; /// XPath query for one channel. `since_ms` bounds the query to recent events @@ -244,7 +252,7 @@ pub fn mapEventWith(alloc: std.mem.Allocator, ev: *const evtxml.Event, table: ?* 7045 => "service_create", else => return null, }, - .powershell => return null, + .powershell, .defender => return null, }; var out: std.Io.Writer.Allocating = .init(alloc); @@ -277,7 +285,7 @@ pub fn mapEventWith(alloc: std.mem.Allocator, ev: *const evtxml.Event, table: ?* else => unreachable, }, .system => try mapSystem7045(alloc, &jw, ev), - .powershell => unreachable, + .powershell, .defender => unreachable, } try jw.endObject(); return .{ .event_type = event_type, .payload = try out.toOwnedSlice() }; @@ -1326,6 +1334,23 @@ pub const Processor = struct { self.counters.emitted += out.items.len - before; return; } + if (source == .defender) { + // 5007: configuration changed. Only a new exclusion that covers a + // Tawny path is reported, as agent_tamper. + const payload = (try tamper.defenderExclusionPayload(self.allocator, ev.get("Old Value"), ev.get("New Value"))) orelse { + self.counters.dropped_unmapped += 1; + return; + }; + errdefer self.allocator.free(payload); + try out.append(.{ + .event_type = "agent_tamper", + .occurred_at = parseSystemTime(ev.time_created) orelse now, + .client_event_id = recordEventId(ev.channel, ev.record_id, ev.time_created), + .payload = payload, + }); + self.counters.emitted += 1; + return; + } if (source == .security and ev.event_id == 4688 and self.sysmon_active) { self.counters.skipped_4688_with_sysmon += 1; return; diff --git a/agent/src/lifecycle.zig b/agent/src/lifecycle.zig index 1a322a6..9def3f6 100644 --- a/agent/src/lifecycle.zig +++ b/agent/src/lifecycle.zig @@ -1,11 +1,38 @@ //! Process-wide shutdown flag shared by the run loop, the Windows service -//! control handler and POSIX signal handlers. +//! control handler and POSIX signal handlers, plus the clean shutdown marker. +//! +//! Clean shutdown marker (#58): when the run loop stops because the service +//! manager or a signal asked it to, the agent writes `.clean` and sends +//! a final heartbeat with `shutdown: true`. On the next start the agent reads +//! and removes the marker. If it is missing (crash, kill -9, `taskkill /f`, +//! power loss, or someone stopping the process outside the service manager) +//! the agent sends an `agent_tamper` event with check `unexpected_stop`. const std = @import("std"); const builtin = @import("builtin"); +const iox = @import("io_compat.zig"); var stop_flag: std.atomic.Value(bool) = .init(false); +/// Why the stop was requested, for the shutdown notice. +var stop_reason: std.atomic.Value(u8) = .init(@backingInt(StopReason.none)); + +pub const StopReason = enum(u8) { + none, + service_stop, + system_shutdown, + signal, + update_restart, + + pub fn text(self: StopReason) []const u8 { + return @tagName(self); + } +}; pub fn requestStop() void { + requestStopFor(.signal); +} + +pub fn requestStopFor(why: StopReason) void { + _ = stop_reason.cmpxchgStrong(@backingInt(StopReason.none), @backingInt(why), .acq_rel, .acquire); stop_flag.store(true, .release); } @@ -13,8 +40,12 @@ pub fn shouldStop() bool { return stop_flag.load(.acquire); } +pub fn reason() StopReason { + return @fromBackingInt(@intCast(stop_reason.load(.acquire))); +} + /// Install SIGTERM/SIGINT handlers that request a clean shutdown. The handler -/// only performs an atomic store, which is async-signal-safe. +/// only performs atomic stores, which are async-signal-safe. pub fn installPosixSignalHandlers() void { if (builtin.target.os.tag == .windows) return; const act: std.posix.Sigaction = .{ @@ -27,14 +58,79 @@ pub fn installPosixSignalHandlers() void { } fn handleSignal(_: std.posix.SIG) callconv(.c) void { - requestStop(); + requestStopFor(.signal); } -test "stop flag round-trips" { +// --------------------------------------------------------------------------- +// Clean shutdown marker + +pub fn markerPath(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { + return alloc.print("{s}.clean", .{state_path}); +} + +pub const StartKind = enum { + /// First run on this host (no state yet): nothing to compare. + first_run, + /// The last run wrote the marker. + clean, + /// The last run did not write the marker. + unexpected, +}; + +/// Read and remove the marker. `enrolled_before` is false on the very first +/// start, when no marker can exist yet. +pub fn consumeMarker(alloc: std.mem.Allocator, state_path: []const u8, enrolled_before: bool) StartKind { + const path = markerPath(alloc, state_path) catch return if (enrolled_before) .unexpected else .first_run; + defer alloc.free(path); + const io = iox.current(); + const cwd = std.Io.Dir.cwd(); + const present = blk: { + const f = cwd.openFile(io, path, .{}) catch break :blk false; + f.close(io); + break :blk true; + }; + if (present) cwd.deleteFile(io, path) catch {}; + if (present) return .clean; + return if (enrolled_before) .unexpected else .first_run; +} + +/// Write the marker with the stop reason and time. Best effort. +pub fn writeMarker(alloc: std.mem.Allocator, state_path: []const u8, why: StopReason) void { + const path = markerPath(alloc, state_path) catch return; + defer alloc.free(path); + var buf: [96]u8 = undefined; + const body = std.fmt.bufPrint(&buf, "reason={s}\nat={d}\n", .{ why.text(), iox.timestamp() }) catch return; + std.Io.Dir.cwd().writeFile(iox.current(), .{ .sub_path = path, .data = body }) catch |err| { + std.debug.print("clean shutdown marker not written: {s}\n", .{@errorName(err)}); + }; +} + +test "stop flag round-trips and keeps the first reason" { const before = shouldStop(); - defer stop_flag.store(before, .release); + defer { + stop_flag.store(before, .release); + stop_reason.store(@backingInt(StopReason.none), .release); + } stop_flag.store(false, .release); + stop_reason.store(@backingInt(StopReason.none), .release); try std.testing.expect(!shouldStop()); - requestStop(); + requestStopFor(.service_stop); + requestStopFor(.signal); try std.testing.expect(shouldStop()); + try std.testing.expectEqual(StopReason.service_stop, reason()); +} + +test "clean shutdown marker: written, consumed once, missing means unexpected" { + const a = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const state = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path, "state.toml" }); + defer a.free(state); + + try std.testing.expectEqual(StartKind.first_run, consumeMarker(a, state, false)); + try std.testing.expectEqual(StartKind.unexpected, consumeMarker(a, state, true)); + writeMarker(a, state, .service_stop); + try std.testing.expectEqual(StartKind.clean, consumeMarker(a, state, true)); + // Consumed: a crash after this start shows as unexpected next time. + try std.testing.expectEqual(StartKind.unexpected, consumeMarker(a, state, true)); } diff --git a/agent/src/main.zig b/agent/src/main.zig index 2a7daf1..8f6d59b 100644 --- a/agent/src/main.zig +++ b/agent/src/main.zig @@ -24,6 +24,8 @@ const yara_scanner = @import("yara_scanner.zig"); const entity = @import("entity.zig"); const iox = @import("io_compat.zig"); const lifecycle = @import("lifecycle.zig"); +const tamper = @import("tamper.zig"); +const updater = @import("updater.zig"); const windows_service = if (builtin.target.os.tag == .windows) @import("platform/windows/service.zig") else struct {}; const AGENT_VERSION = "0.1.0"; @@ -39,6 +41,16 @@ 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 @import("keystore_debug.zig").isDebugCommand(args[1])) { + const code = @import("keystore_debug.zig").run(alloc, args[1..]); + if (code != 0) std.process.exit(code); + return; + } + if (args.len >= 2 and updater.isDebugCommand(args[1])) { + const code = updater.debugCommand(alloc, args[1..]); + if (code != 0) std.process.exit(code); + return; + } if (args.len >= 2 and @import("response_debug.zig").isDebugCommand(args[1])) { const code = @import("response_debug.zig").run(alloc, args[1..]); if (code != 0) std.process.exit(code); @@ -73,6 +85,11 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { }; defer cfg.deinit(); + // Was the agent enrolled before this start? Only then can a missing clean + // shutdown marker mean anything. + const enrolled_before = cfg.agent_id != null; + const start_kind = lifecycle.consumeMarker(alloc, cfg.state_path, enrolled_before); + if (cfg.agent_id == null) { std.debug.print("not enrolled; running enrollment...\n", .{}); try enrollment.run(alloc, &cfg, AGENT_VERSION); @@ -206,11 +223,46 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { std.debug.print("system collector failed: {s}\n", .{@errorName(err)}); } + // Tamper checks (#58). The last run's missing marker is reported first. + if (start_kind == .unexpected) { + if (tamper.payload(alloc, .unexpected_stop, "The agent started without the clean shutdown marker from its last run.", .{})) |p| { + defer alloc.free(p); + queueEvent(&buf, "agent_tamper", p); + } else |_| {} + } + var tamper_mon = tamper.Monitor{ .alloc = alloc }; + defer tamper_mon.deinit(); + watchTamperFiles(alloc, &tamper_mon, &cfg, device_key_path); + var tamper_timer = try iox.Timer.start(); + + // Signed self-update (#58). Off while update_key.zig holds the + // placeholder; health then says disabled_no_release_key. + const exe_path = std.process.executablePathAlloc(iox.current(), alloc) catch try alloc.dupeSentinel(u8, "", 0); + defer alloc.free(exe_path); + var upd = updater.Updater.init(alloc, cfg.state_path, exe_path, AGENT_VERSION, updater.platformName(), cfg.agent_id orelse ""); + if (upd.startCheck(iox.timestamp())) |o| { + if (o == .restart_now) { + std.debug.print("update: rolled back to the previous binary; restarting\n", .{}); + lifecycle.requestStopFor(.update_restart); + } + } else |err| std.debug.print("update state unreadable: {s}\n", .{@errorName(err)}); + if (updater.expectedBinaryHash(alloc, upd.key, cfg.state_path, AGENT_VERSION)) |h| tamper_mon.expectBinary(h); + var update_timer = try iox.Timer.start(); + var first_update_check = true; + 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); - if (healthPayload(alloc, uptime, buf.totalLen(), buf.next_sequence, &boot_id)) |payload| { + 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), + .update = upd.health(), + })) |payload| { defer alloc.free(payload); queueEvent(&buf, "agent_health", payload); } else |_| {} @@ -221,10 +273,14 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { })) |heartbeat_result| { var heartbeat = heartbeat_result; defer heartbeat.deinit(alloc); + if (upd.onHeartbeat(true, iox.timestamp())) |_| {} else |err| { + std.debug.print("update commit failed: {s}\n", .{@errorName(err)}); + } if (heartbeat.rotated_jwt) |rotated| { persistRotatedJwt(alloc, &cfg, &http, rotated) catch |err| { std.debug.print("jwt rotation persist failed: {s}\n", .{@errorName(err)}); }; + tamper_mon.acceptOwnWrite(cfg.state_path); } if (heartbeat.yara_pack_version > yara.pack_version and yara.public_key != null) { refreshYaraPack(alloc, &http, &yara); @@ -234,6 +290,7 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { if (action_pub == null) { if (heartbeat.action_public_key) |k| { action_key.pin(alloc, cfg.state_path, k) catch {}; + acceptOwnKeyWrite(alloc, &tamper_mon, cfg.state_path, ".actionkey"); if (action_key.load(alloc, cfg.state_path)) |pinned| { if (action_pub_text) |old| alloc.free(old); action_pub_text = pinned; @@ -267,9 +324,25 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { enforceIsolationDeadline(alloc, &cfg); } else |err| { std.debug.print("heartbeat failed: {s}\n", .{@errorName(err)}); + if (upd.onHeartbeat(false, iox.timestamp())) |o| { + if (o == .restart_now) lifecycle.requestStopFor(.update_restart); + } else |_| {} } } + if (lifecycle.shouldStop()) break; + if (upd.key != null and (first_update_check or update_timer.read() / std.time.ns_per_s >= update_interval_seconds)) { + first_update_check = false; + update_timer.reset(); + var fetch_ctx = UpdateFetch{ .http = &http, .ring = @tagName(upd.ring()) }; + if (upd.check(fetch_ctx.fetcher())) |o| { + if (o == .restart_now) { + std.debug.print("update: new binary in place; restarting through the service manager\n", .{}); + lifecycle.requestStopFor(.update_restart); + } + } else |err| std.debug.print("update check failed: {s}\n", .{@errorName(err)}); + } + if (lifecycle.shouldStop()) break; if (process_timer.read() / std.time.ns_per_s >= cfg.process_interval_seconds) { process_timer.reset(); @@ -332,6 +405,7 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { if (process_events_timer.read() / std.time.ns_per_s >= cfg.process_events_interval_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); } else |err| { std.debug.print("process_events collector failed: {s}\n", .{@errorName(err)}); @@ -433,6 +507,16 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { } } + if (lifecycle.shouldStop()) break; + if (tamper_timer.read() / std.time.ns_per_s >= tamper_interval_seconds) { + tamper_timer.reset(); + if (tamper_mon.check()) |found| { + emitBatch(&buf, "agent_tamper", found, alloc); + } else |err| { + std.debug.print("tamper check failed: {s}\n", .{@errorName(err)}); + } + } + if (lifecycle.shouldStop()) break; const retry_ready = http.backoff_seconds == 0 or flush_retry_timer.read() / std.time.ns_per_s >= http.backoff_seconds; @@ -449,6 +533,78 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { iox.sleep(1 * std.time.ns_per_s); } std.debug.print("tawny-agent stopping\n", .{}); + // Clean shutdown (#58): flush what we can, tell the server, then leave the + // marker so the next start does not report an unexpected stop. + const why = lifecycle.reason(); + if (buf.len() > 0) http.flushEvents(&buf) catch {}; + const uptime_end: i64 = @intCast(iox.timestamp() - start_time); + http.sendShutdownNotice(AGENT_VERSION, uptime_end, buf.totalLen(), why.text()) catch |err| { + std.debug.print("shutdown notice not sent: {s}\n", .{@errorName(err)}); + }; + lifecycle.writeMarker(alloc, cfg.state_path, why); + // After an update swap or rollback, exit non-zero so the service manager + // starts the binary now in place (SCM failure actions, systemd + // Restart=on-failure, launchd KeepAlive). + if (why == .update_restart) return error.UpdateRestart; +} + +/// How often the agent asks for a signed release. +const update_interval_seconds: u64 = 6 * 3600; + +const UpdateFetch = struct { + http: *transport.Client, + ring: []const u8, + + fn release(ctx: *anyopaque, _: std.mem.Allocator, platform: []const u8) anyerror!?[]u8 { + const self: *UpdateFetch = @ptrCast(@alignCast(ctx)); + return self.http.updateCheck(platform, self.ring); + } + fn download(ctx: *anyopaque, _: std.mem.Allocator, url: []const u8, max: u64) anyerror![]u8 { + const self: *UpdateFetch = @ptrCast(@alignCast(ctx)); + return self.http.download(url, max); + } + fn fetcher(self: *UpdateFetch) updater.Fetcher { + return .{ .ctx = self, .release = release, .download = download }; + } +}; + +/// How often the tamper monitor runs. The binary is hashed every fifth run. +const tamper_interval_seconds: u64 = 60; + +/// Last time the launch tracker reported a new process (0: none yet). +var process_tracker_last_event: i64 = 0; + +fn watchTamperFiles(alloc: std.mem.Allocator, mon: *tamper.Monitor, cfg: *const config_mod.Config, device_key_path: []const u8) void { + if (std.process.executablePathAlloc(iox.current(), alloc)) |exe| { + defer alloc.free(exe); + mon.watch(.binary, exe) catch {}; + } else |_| {} + mon.watch(.config, cfg.config_path) catch {}; + mon.watch(.identity, cfg.state_path) catch {}; + mon.watch(.identity, device_key_path) catch {}; + const action_key_path = alloc.print("{s}.actionkey", .{cfg.state_path}) catch return; + defer alloc.free(action_key_path); + mon.watch(.identity, action_key_path) catch {}; +} + +fn acceptOwnKeyWrite(alloc: std.mem.Allocator, mon: *tamper.Monitor, state_path: []const u8, suffix: []const u8) void { + const path = alloc.print("{s}{s}", .{ state_path, suffix }) catch return; + defer alloc.free(path); + mon.acceptOwnWrite(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; + 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), + }}; } /// Quarantine directory. `%ProgramData%\Tawny\Quarantine` on Windows, @@ -597,6 +753,13 @@ test "main module loads" { _ = @import("platform/windows/wfp.zig"); _ = @import("platform/windows/process_control.zig"); _ = @import("response_debug.zig"); + _ = tamper; + _ = @import("minisign.zig"); + _ = @import("update_key.zig"); + _ = updater; + _ = @import("platform/windows/scm.zig"); + _ = @import("platform/windows/dpapi.zig"); + _ = @import("keystore_debug.zig"); // Pure macOS parsers have no syscalls, so their tests run on every host. _ = @import("platform/macos/parse.zig"); // Windows event log parsing and mapping are pure too. @@ -701,19 +864,55 @@ fn emitBatch( /// `agent_health` data (schemas/events/agent_health.v1.json). fn healthPayload(alloc: std.mem.Allocator, uptime: i64, depth: usize, next_sequence: u64, boot_id: []const u8) ![]u8 { + return healthPayloadFull(alloc, .{ .uptime = uptime, .depth = depth, .next_sequence = next_sequence, .boot_id = boot_id }); +} + +pub const SensorEntry = struct { + name: []const u8, + status: []const u8, + last_event_age_seconds: ?i64 = null, +}; + +pub const HealthInput = struct { + uptime: i64, + depth: usize, + next_sequence: u64, + boot_id: []const u8, + key_protection: ?[]const u8 = null, + sensors: [1]SensorEntry = .{.{ .name = "process_events", .status = "unknown" }}, + update: ?updater.HealthState = null, +}; + +fn healthPayloadFull(alloc: std.mem.Allocator, in: HealthInput) ![]u8 { return std.json.Stringify.valueAlloc(alloc, .{ .sensor_version = AGENT_VERSION, - .buffer_depth = depth, - .uptime_seconds = @max(uptime, 0), - .next_sequence = next_sequence, - .boot_id = boot_id, - }, .{}); + .buffer_depth = in.depth, + .uptime_seconds = @max(in.uptime, 0), + .next_sequence = in.next_sequence, + .boot_id = in.boot_id, + .key_protection = in.key_protection, + .sensors = &in.sensors, + .update = in.update, + }, .{ .emit_null_optional_fields = false }); } test "agent_health payload matches its schema" { const p = try healthPayload(std.testing.allocator, 5, 2, 9, entity.nil_uuid); defer std.testing.allocator.free(p); try @import("schema_check.zig").expectValid(std.testing.allocator, "agent_health", p); + const full = try healthPayloadFull(std.testing.allocator, .{ + .uptime = 5, + .depth = 2, + .next_sequence = 9, + .boot_id = entity.nil_uuid, + .key_protection = "dpapi", + .sensors = .{.{ .name = "process_events", .status = "running", .last_event_age_seconds = 3 }}, + .update = .{ .state = .idle, .ring = "50", .bucket = 42 }, + }); + defer std.testing.allocator.free(full); + try @import("schema_check.zig").expectValid(std.testing.allocator, "agent_health", full); + try std.testing.expect(std.mem.indexOf(u8, full, "\"key_protection\":\"dpapi\"") != null); + try std.testing.expect(std.mem.indexOf(u8, full, "\"state\":\"idle\"") != null); } fn queueEvent(buf: *buffer.Buffer, event_type: []const u8, payload: []const u8) void { diff --git a/agent/src/platform/windows/scm.zig b/agent/src/platform/windows/scm.zig new file mode 100644 index 0000000..919ac9d --- /dev/null +++ b/agent/src/platform/windows/scm.zig @@ -0,0 +1,75 @@ +//! Service Control Manager queries for tamper checks (#58). Constants and +//! signatures checked against windows-rs `Win32/winsvc/mod.rs`; values are +//! pinned by a test that runs on every OS. +const std = @import("std"); +const builtin = @import("builtin"); + +const WINAPI: std.lang.CallingConvention = .winapi; +const SC_HANDLE = *opaque {}; + +pub const SC_MANAGER_CONNECT: u32 = 1; +pub const SERVICE_QUERY_STATUS: u32 = 4; +pub const SERVICE_STOPPED: u32 = 1; +pub const SERVICE_RUNNING: u32 = 4; +pub const ERROR_SERVICE_DOES_NOT_EXIST: u32 = 1060; + +const SERVICE_STATUS = extern struct { + dwServiceType: u32, + dwCurrentState: u32, + dwControlsAccepted: u32, + dwWin32ExitCode: u32, + dwServiceSpecificExitCode: u32, + dwCheckPoint: u32, + dwWaitHint: u32, +}; + +const impl = if (builtin.target.os.tag == .windows) struct { + extern "advapi32" fn OpenSCManagerW(machine: ?[*:0]const u16, database: ?[*:0]const u16, access: u32) callconv(WINAPI) ?SC_HANDLE; + extern "advapi32" fn OpenServiceW(scm: SC_HANDLE, name: [*:0]const u16, access: u32) callconv(WINAPI) ?SC_HANDLE; + extern "advapi32" fn QueryServiceStatus(service: SC_HANDLE, status: *SERVICE_STATUS) callconv(WINAPI) i32; + extern "advapi32" fn CloseServiceHandle(handle: SC_HANDLE) callconv(WINAPI) i32; + extern "kernel32" fn GetLastError() callconv(WINAPI) u32; +} else struct {}; + +pub const ServiceState = enum { not_installed, stopped, running, other, unknown }; + +/// Current state of a service by name. `unknown` when the SCM can't be read. +pub fn serviceState(comptime name: []const u8) ServiceState { + if (builtin.target.os.tag != .windows) return .unknown; + const name_w = std.unicode.utf8ToUtf16LeStringLiteral(name); + const scm = impl.OpenSCManagerW(null, null, SC_MANAGER_CONNECT) orelse return .unknown; + defer _ = impl.CloseServiceHandle(scm); + const svc = impl.OpenServiceW(scm, name_w, SERVICE_QUERY_STATUS) orelse { + return if (impl.GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) .not_installed else .unknown; + }; + defer _ = impl.CloseServiceHandle(svc); + var st: SERVICE_STATUS = std.mem.zeroes(SERVICE_STATUS); + if (impl.QueryServiceStatus(svc, &st) == 0) return .unknown; + return fromCurrentState(st.dwCurrentState); +} + +pub fn fromCurrentState(state: u32) ServiceState { + return switch (state) { + SERVICE_RUNNING => .running, + SERVICE_STOPPED => .stopped, + else => .other, + }; +} + +/// Sysmon installs as `Sysmon64` on 64-bit Windows and `Sysmon` otherwise. +pub fn sysmonState() ServiceState { + const a = serviceState("Sysmon64"); + if (a != .not_installed) return a; + return serviceState("Sysmon"); +} + +test "winsvc constants match windows-rs" { + try std.testing.expectEqual(@as(u32, 1), SC_MANAGER_CONNECT); + try std.testing.expectEqual(@as(u32, 4), SERVICE_QUERY_STATUS); + try std.testing.expectEqual(@as(u32, 1), SERVICE_STOPPED); + try std.testing.expectEqual(@as(u32, 4), SERVICE_RUNNING); + try std.testing.expectEqual(@as(u32, 1060), ERROR_SERVICE_DOES_NOT_EXIST); + try std.testing.expectEqual(@as(usize, 28), @sizeOf(SERVICE_STATUS)); + try std.testing.expectEqual(ServiceState.running, fromCurrentState(4)); + try std.testing.expectEqual(ServiceState.other, fromCurrentState(3)); +} diff --git a/agent/src/platform/windows/service.zig b/agent/src/platform/windows/service.zig index faf42a3..3b9f0b4 100644 --- a/agent/src/platform/windows/service.zig +++ b/agent/src/platform/windows/service.zig @@ -116,7 +116,9 @@ fn serviceMain(_: u32, _: ?[*]?[*:0]u16) callconv(WINAPI) void { fn controlHandler(control: u32, _: u32, _: ?*anyopaque, _: ?*anyopaque) callconv(WINAPI) u32 { switch (control) { SERVICE_CONTROL_STOP, SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_PRESHUTDOWN => { - lifecycle.requestStop(); + // The run loop writes the clean shutdown marker and sends the + // shutdown notice once it sees the flag (#58). + lifecycle.requestStopFor(if (control == SERVICE_CONTROL_STOP) .service_stop else .system_shutdown); reportStatus(SERVICE_STOP_PENDING, NO_ERROR, 0, stop_wait_hint_ms); return NO_ERROR; }, diff --git a/agent/src/schema_check.zig b/agent/src/schema_check.zig index edadf01..bf87bb2 100644 --- a/agent/src/schema_check.zig +++ b/agent/src/schema_check.zig @@ -207,6 +207,7 @@ pub const schema_types = [_][]const u8{ "process_start", "process_exit", "network_connect", "dns_query", "file_create", "registry_set", "user_logon", "service_create", "powershell_script_block", "agent_health", "sensor_health", + "agent_tamper", }; test "golden payloads match their schemas" { diff --git a/agent/src/tamper.zig b/agent/src/tamper.zig new file mode 100644 index 0000000..0c6ac46 --- /dev/null +++ b/agent/src/tamper.zig @@ -0,0 +1,439 @@ +//! Tamper checks (#58, target-edr §10 "Tamper detection"). Each finding is an +//! `agent_tamper` event (schemas/events/agent_tamper.v1.json): +//! +//! - `unexpected_stop`: the last run ended without the clean shutdown marker +//! (lifecycle.zig). +//! - `binary_changed`: the agent executable's SHA-256 differs from the +//! manifest the updater committed (`.release.json`), or, without +//! one, from the hash taken when this process started. +//! - `config_changed`, `identity_changed`: config.toml, state.toml, the device +//! key or the pinned action key changed (hash and mtime) without the agent +//! writing it. The agent calls `Monitor.acceptOwnWrite` after its own writes. +//! - `sysmon_stopped` (Windows): the Sysmon service was running and is not. +//! - `defender_exclusion` (Windows): Defender Operational 5007 shows a new +//! path or process exclusion covering a Tawny path. Mapped from the event +//! log by collectors/windows_events.zig through `defenderExclusionPayload`. +//! +//! No anti-debug or rootkit behaviour: these are detections, not defences. + +const std = @import("std"); +const builtin = @import("builtin"); +const iox = @import("io_compat.zig"); +const scm = @import("platform/windows/scm.zig"); + +const Sha256 = std.crypto.hash.sha2.Sha256; + +pub const Check = enum { + unexpected_stop, + binary_changed, + config_changed, + identity_changed, + sysmon_stopped, + defender_exclusion, +}; + +/// `agent_tamper` payload. Caller frees. +pub fn payload(alloc: std.mem.Allocator, check: Check, detail: []const u8, extra: Extra) ![]u8 { + return std.json.Stringify.valueAlloc(alloc, .{ + .check = @tagName(check), + .detail = detail, + .path = extra.path, + .expected_sha256 = extra.expected_sha256, + .actual_sha256 = extra.actual_sha256, + .service = extra.service, + .exclusion = extra.exclusion, + }, .{ .emit_null_optional_fields = false }); +} + +pub const Extra = struct { + path: ?[]const u8 = null, + expected_sha256: ?[]const u8 = null, + actual_sha256: ?[]const u8 = null, + service: ?[]const u8 = null, + exclusion: ?[]const u8 = null, +}; + +// --------------------------------------------------------------------------- +// Defender 5007 + +/// Paths and names that, when excluded from Defender, blind it to Tawny or +/// let something hide beside it. Compared case-insensitively. +const tawny_paths = [_][]const u8{ + "C:\\ProgramData\\Tawny", + "C:\\Program Files\\Tawny", +}; +const tawny_process = "tawny-agent.exe"; + +/// Defender 5007 `New Value` looks like +/// `HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths\C:\ProgramData\Tawny = 0x0`. +/// Returns the excluded value and its kind when the change adds a path or +/// process exclusion, else null. +pub const Exclusion = struct { kind: enum { path, process }, value: []const u8 }; + +pub fn parseExclusion(new_value: []const u8) ?Exclusion { + const markers = [_]struct { m: []const u8, k: @FieldType(Exclusion, "kind") }{ + .{ .m = "\\Exclusions\\Paths\\", .k = .path }, + .{ .m = "\\Exclusions\\Processes\\", .k = .process }, + }; + for (markers) |mk| { + const at = std.ascii.findIgnoreCase(new_value, mk.m) orelse continue; + var rest = new_value[at + mk.m.len ..]; + if (std.mem.lastIndexOf(u8, rest, " = ")) |eq| rest = rest[0..eq]; + rest = std.mem.trim(u8, rest, " \t\""); + if (rest.len == 0) return null; + return .{ .kind = mk.k, .value = rest }; + } + return null; +} + +/// True when excluding `value` from scanning covers a Tawny path: the value +/// is a Tawny path, sits under one, or is a parent of one (for example `C:\`). +pub fn coversTawny(ex: Exclusion) bool { + switch (ex.kind) { + .process => { + const base = std.fs.path.basenameWindows(ex.value); + return std.ascii.eqlIgnoreCase(base, tawny_process); + }, + .path => { + const v = std.mem.trimEnd(u8, ex.value, "\\/"); + if (v.len == 0) return false; + for (tawny_paths) |p| { + if (isPrefixPath(v, p) or isPrefixPath(p, v)) return true; + } + // Environment-variable forms Defender keeps unexpanded. + const env_forms = [_][]const u8{ "%ProgramData%\\Tawny", "%ProgramFiles%\\Tawny", "%ProgramData%", "%ProgramFiles%" }; + for (env_forms) |p| if (isPrefixPath(p, v) or isPrefixPath(v, p)) return true; + return false; + }, + } +} + +/// `parent` equals `child` or is a directory above it (case-insensitive, +/// either slash). +fn isPrefixPath(parent: []const u8, child: []const u8) bool { + const p = std.mem.trimEnd(u8, parent, "\\/"); + if (child.len < p.len) return false; + for (p, child[0..p.len]) |a, b| { + const na = if (a == '/') '\\' else std.ascii.toLower(a); + const nb = if (b == '/') '\\' else std.ascii.toLower(b); + if (na != nb) return false; + } + return child.len == p.len or child[p.len] == '\\' or child[p.len] == '/' or (p.len > 0 and p[p.len - 1] == ':'); +} + +/// Payload for a 5007 event, or null when it is not a new exclusion covering +/// Tawny. An exclusion that was already there (same old and new value) is +/// ignored. +pub fn defenderExclusionPayload(alloc: std.mem.Allocator, old_value: ?[]const u8, new_value: ?[]const u8) !?[]u8 { + const nv = new_value orelse return null; + const ex = parseExclusion(nv) orelse return null; + if (old_value) |ov| if (parseExclusion(ov)) |old_ex| { + if (old_ex.kind == ex.kind and std.ascii.eqlIgnoreCase(old_ex.value, ex.value)) return null; + }; + if (!coversTawny(ex)) return null; + const detail = try std.fmt.allocPrint(alloc, "Defender {s} exclusion added that covers Tawny: {s}", .{ @tagName(ex.kind), ex.value }); + defer alloc.free(detail); + return try payload(alloc, .defender_exclusion, detail, .{ .exclusion = ex.value }); +} + +// --------------------------------------------------------------------------- +// File baselines + +pub const FileKind = enum { binary, config, identity }; + +pub const Fingerprint = struct { + present: bool, + sha256: [32]u8 = @splat(0), + mtime_ns: i96 = 0, + size: u64 = 0, + + pub fn eql(a: Fingerprint, b: Fingerprint) bool { + if (a.present != b.present) return false; + if (!a.present) return true; + return std.mem.eql(u8, &a.sha256, &b.sha256); + } +}; + +/// Hash a file (at most `max_bytes`). Missing files are `present = false`. +pub fn fingerprint(path: []const u8, max_bytes: u64) !Fingerprint { + const io = iox.current(); + const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch |err| switch (err) { + error.FileNotFound => return .{ .present = false }, + else => return err, + }; + defer file.close(io); + const st = try file.stat(io); + if (st.size > max_bytes) return error.FileTooBig; + var h = Sha256.init(.{}); + var buf: [64 * 1024]u8 = undefined; + var off: u64 = 0; + while (true) { + const n = try file.readPositionalAll(io, &buf, off); + if (n == 0) break; + h.update(buf[0..n]); + off += n; + if (n < buf.len) break; + } + return .{ .present = true, .sha256 = h.finalResult(), .mtime_ns = st.mtime.toNanoseconds(), .size = st.size }; +} + +pub const Watched = struct { + kind: FileKind, + path: []u8, + base: Fingerprint, + /// The binary is compared with the committed release hash, not the start. + expected_sha256: ?[32]u8 = null, + /// Already reported for the current contents: report once per change. + reported: bool = false, +}; + +pub const SysmonTracker = struct { + was_running: bool = false, + reported: bool = false, + + /// Feed the current state. Returns true once when Sysmon goes from + /// running to anything else. Coming back clears the report. + pub fn observe(self: *SysmonTracker, state: scm.ServiceState) bool { + switch (state) { + .running => { + self.was_running = true; + self.reported = false; + return false; + }, + .unknown => return false, + .stopped, .other, .not_installed => { + if (!self.was_running or self.reported) return false; + self.reported = true; + return true; + }, + } + } +}; + +const max_binary_bytes: u64 = 256 * 1024 * 1024; +const max_small_bytes: u64 = 1024 * 1024; + +pub const Monitor = struct { + alloc: std.mem.Allocator, + files: std.ArrayList(Watched) = .empty, + sysmon: SysmonTracker = .{}, + checks: u32 = 0, + + pub fn deinit(self: *Monitor) void { + for (self.files.items) |f| self.alloc.free(f.path); + self.files.deinit(self.alloc); + } + + /// Start watching `path`, baseline taken now. Unreadable files are + /// skipped with a log line. + pub fn watch(self: *Monitor, kind: FileKind, path: []const u8) !void { + const fp = fingerprint(path, if (kind == .binary) max_binary_bytes else max_small_bytes) catch |err| { + std.debug.print("tamper: cannot baseline {s}: {s}\n", .{ path, @errorName(err) }); + return; + }; + const owned = try self.alloc.dupe(u8, path); + errdefer self.alloc.free(owned); + try self.files.append(self.alloc, .{ .kind = kind, .path = owned, .base = fp }); + } + + /// Pin the binary to the hash from a committed, signature-checked + /// release manifest. + pub fn expectBinary(self: *Monitor, sha256: [32]u8) void { + for (self.files.items) |*f| if (f.kind == .binary) { + f.expected_sha256 = sha256; + }; + } + + /// The agent changed `path` itself (JWT rotation, key pinning): take a + /// new baseline so it isn't reported. + pub fn acceptOwnWrite(self: *Monitor, path: []const u8) void { + for (self.files.items) |*f| if (std.mem.eql(u8, f.path, path)) { + f.base = fingerprint(f.path, max_small_bytes) catch f.base; + f.reported = false; + }; + } + + /// Run every check. Returns `agent_tamper` payloads; caller frees each + /// and the slice. The binary is hashed every 5th call. + pub fn check(self: *Monitor) ![][]u8 { + var out: std.ArrayList([]u8) = .empty; + errdefer { + for (out.items) |p| self.alloc.free(p); + out.deinit(self.alloc); + } + self.checks +%= 1; + for (self.files.items) |*f| { + if (f.kind == .binary and self.checks % 5 != 1) continue; + const now = fingerprint(f.path, if (f.kind == .binary) max_binary_bytes else max_small_bytes) catch continue; + if (try self.compare(f, now)) |p| try out.append(self.alloc, p); + } + if (builtin.target.os.tag == .windows) { + if (self.sysmon.observe(scm.sysmonState())) { + try out.append(self.alloc, try payload(self.alloc, .sysmon_stopped, "The Sysmon service was running and has stopped.", .{ .service = "Sysmon" })); + } + } + return out.toOwnedSlice(self.alloc); + } + + fn compare(self: *Monitor, f: *Watched, now: Fingerprint) !?[]u8 { + var exp_hex: [64]u8 = undefined; + var act_hex: [64]u8 = undefined; + if (f.kind == .binary) { + const want = f.expected_sha256 orelse f.base.sha256; + if (now.present and std.mem.eql(u8, &want, &now.sha256)) { + f.reported = false; + return null; + } + if (f.reported) return null; + f.reported = true; + _ = std.fmt.bufPrint(&exp_hex, "{x}", .{want}) catch unreachable; + _ = std.fmt.bufPrint(&act_hex, "{x}", .{now.sha256}) catch unreachable; + const why = if (!now.present) "The agent binary is missing." else if (f.expected_sha256 != null) "The agent binary does not match the signed release manifest." else "The agent binary changed while the agent was running."; + return try payload(self.alloc, .binary_changed, why, .{ .path = f.path, .expected_sha256 = &exp_hex, .actual_sha256 = if (now.present) &act_hex else null }); + } + if (Fingerprint.eql(f.base, now)) return null; + // Report once, then take the new contents as the baseline so a + // second edit is reported again. + f.base = now; + const check_kind: Check = if (f.kind == .config) .config_changed else .identity_changed; + const why = if (!now.present) + (if (f.kind == .config) "The agent config file was removed outside the agent." else "An agent identity file was removed outside the agent.") + else + (if (f.kind == .config) "The agent config file changed outside the agent." else "An agent identity file changed outside the agent."); + _ = std.fmt.bufPrint(&act_hex, "{x}", .{now.sha256}) catch unreachable; + return try payload(self.alloc, check_kind, why, .{ .path = f.path, .actual_sha256 = if (now.present) &act_hex else null }); + } +}; + +// --------------------------------------------------------------------------- +// Tests + +const testing = std.testing; +const schema_check = @import("schema_check.zig"); + +test "Defender 5007 exclusions that cover Tawny are reported, others are not" { + const a = testing.allocator; + const cases = [_]struct { new: []const u8, hit: bool }{ + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\C:\\ProgramData\\Tawny = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\c:\\programdata\\tawny\\state = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\C:\\ = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\C:\\ProgramData = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Processes\\C:\\Program Files\\Tawny\\tawny-agent.exe = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\%ProgramData%\\Tawny = 0x0", .hit = true }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\C:\\ProgramDataX = 0x0", .hit = false }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\D:\\builds = 0x0", .hit = false }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Extensions\\.log = 0x0", .hit = false }, + .{ .new = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Real-Time Protection\\DisableRealtimeMonitoring = 0x1", .hit = false }, + }; + for (cases) |c| { + const got = try defenderExclusionPayload(a, null, c.new); + defer if (got) |g| a.free(g); + if ((got != null) != c.hit) { + std.debug.print("case {s}: want hit={}\n", .{ c.new, c.hit }); + return error.TestUnexpectedResult; + } + if (got) |g| try schema_check.expectValid(a, "agent_tamper", g); + } + // Unchanged value (Defender rewrites on policy refresh): not news. + const same = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\C:\\ProgramData\\Tawny = 0x0"; + try testing.expect((try defenderExclusionPayload(a, same, same)) == null); +} + +test "config and identity changes are reported once per change, own writes are not" { + const a = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + defer a.free(dir); + const cfg = try std.fs.path.join(a, &.{ dir, "config.toml" }); + defer a.free(cfg); + const key = try std.fs.path.join(a, &.{ dir, "state.toml.devicekey" }); + defer a.free(key); + const io = iox.current(); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = cfg, .data = "url = \"https://a\"\n" }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = key, .data = "0123456789abcdef0123456789abcdef" }); + + var m = Monitor{ .alloc = a }; + defer m.deinit(); + try m.watch(.config, cfg); + try m.watch(.identity, key); + + const quiet = try m.check(); + defer a.free(quiet); + try testing.expectEqual(@as(usize, 0), quiet.len); + + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = cfg, .data = "url = \"https://evil\"\n" }); + try std.Io.Dir.cwd().deleteFile(io, key); + const found = try m.check(); + defer { + for (found) |p| a.free(p); + a.free(found); + } + try testing.expectEqual(@as(usize, 2), found.len); + try testing.expect(std.mem.indexOf(u8, found[0], "\"config_changed\"") != null); + try testing.expect(std.mem.indexOf(u8, found[1], "\"identity_changed\"") != null); + for (found) |p| try schema_check.expectValid(a, "agent_tamper", p); + + const again = try m.check(); + defer a.free(again); + try testing.expectEqual(@as(usize, 0), again.len); + + // The agent rewrites its own file and says so: nothing reported. + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = cfg, .data = "url = \"https://b\"\n" }); + m.acceptOwnWrite(cfg); + const own = try m.check(); + defer a.free(own); + try testing.expectEqual(@as(usize, 0), own.len); +} + +test "binary hash is checked against the committed manifest hash" { + const a = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const bin = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path, "tawny-agent" }); + defer a.free(bin); + const io = iox.current(); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = bin, .data = "release bytes" }); + var m = Monitor{ .alloc = a }; + defer m.deinit(); + try m.watch(.binary, bin); + const ok = try m.check(); + defer a.free(ok); + try testing.expectEqual(@as(usize, 0), ok.len); + + // The manifest says something else: reported once. + var want: [32]u8 = undefined; + Sha256.hash("signed release bytes", &want, .{}); + m.expectBinary(want); + m.checks = 0; + const bad = try m.check(); + defer { + for (bad) |p| a.free(p); + a.free(bad); + } + try testing.expectEqual(@as(usize, 1), bad.len); + try testing.expect(std.mem.indexOf(u8, bad[0], "signed release manifest") != null); + try schema_check.expectValid(a, "agent_tamper", bad[0]); + m.checks = 0; + const once = try m.check(); + defer a.free(once); + try testing.expectEqual(@as(usize, 0), once.len); +} + +test "Sysmon stop is reported once after it was seen running" { + var t: SysmonTracker = .{}; + try testing.expect(!t.observe(.not_installed)); + try testing.expect(!t.observe(.running)); + try testing.expect(!t.observe(.unknown)); + try testing.expect(t.observe(.stopped)); + try testing.expect(!t.observe(.stopped)); + try testing.expect(!t.observe(.running)); + try testing.expect(t.observe(.not_installed)); +} + +test "unexpected stop payload matches its schema" { + const a = testing.allocator; + const p = try payload(a, .unexpected_stop, "The agent started without the clean shutdown marker from its last run.", .{}); + defer a.free(p); + try schema_check.expectValid(a, "agent_tamper", p); +} diff --git a/agent/src/transport/http.zig b/agent/src/transport/http.zig index d71d09a..bf528e5 100644 --- a/agent/src/transport/http.zig +++ b/agent/src/transport/http.zig @@ -10,6 +10,16 @@ pub const HeartbeatPayload = struct { buffer_depth: usize, }; +/// Clean shutdown notice (#58): a final heartbeat. The server then skips +/// `Agent silent` when the agent goes offline. +pub const ShutdownPayload = struct { + agent_version: []const u8, + uptime_seconds: i64, + buffer_depth: usize, + shutdown: bool = true, + shutdown_reason: []const u8, +}; + pub const HeartbeatResult = struct { rotated_jwt: ?[]u8 = null, /// Latest signed YARA rule pack version for this tenant (0: none). @@ -183,6 +193,54 @@ pub const Client = struct { return result; } + /// Send the clean shutdown notice as a final heartbeat. One attempt, no + /// retry: a stopping service has a short wait hint. + pub fn sendShutdownNotice(self: *Client, agent_version: []const u8, uptime: i64, depth: usize, reason: []const u8) !void { + const body = try std.json.Stringify.valueAlloc(self.allocator, ShutdownPayload{ + .agent_version = agent_version, + .uptime_seconds = @max(uptime, 0), + .buffer_depth = depth, + .shutdown_reason = reason, + }, .{}); + defer self.allocator.free(body); + const response = try self.post("/api/agents/heartbeat", body); + self.allocator.free(response); + } + + /// Signed release offered to this agent (#58): POST + /// /api/agent/update-check. Returns the reply body, or null on 204. + pub fn updateCheck(self: *Client, platform: []const u8, ring: []const u8) !?[]u8 { + const body = try std.json.Stringify.valueAlloc(self.allocator, .{ .platform = platform, .ring = ring }, .{}); + defer self.allocator.free(body); + const reply = try self.post("/api/agent/update-check", body); + if (reply.len == 0) { + self.allocator.free(reply); + return null; + } + return reply; + } + + /// GET a release binary over HTTPS, at most `max` bytes. Redirects are + /// followed (GitHub release assets redirect to object storage); the + /// bytes are checked against the signed manifest by the caller. + pub fn download(self: *Client, url: []const u8, max: u64) ![]u8 { + if (!std.ascii.startsWithIgnoreCase(url, "https://")) return error.InsecureDownloadUrl; + var client = std.http.Client{ .allocator = self.allocator, .io = iox.current() }; + defer client.deinit(); + var out: std.Io.Writer.Allocating = .init(self.allocator); + errdefer out.deinit(); + const result = try client.fetch(.{ + .method = .GET, + .location = .{ .url = url }, + .response_writer = &out.writer, + .redirect_behavior = .init(5), + .keep_alive = false, + }); + if (@backingInt(result.status) != 200) return error.DownloadFailed; + if (out.written().len > max) return error.DownloadTooLarge; + return out.toOwnedSlice(); + } + /// Fetch the tenant's signed YARA rule pack. The caller verifies it /// (`rule_pack.verify`) before using it. pub fn fetchYaraPack(self: *Client) ![]u8 { @@ -544,6 +602,21 @@ test "heartbeat body escapes agent version" { ); } +test "shutdown notice body carries the flag and reason" { + const alloc = std.testing.allocator; + const body = try std.json.Stringify.valueAlloc(alloc, ShutdownPayload{ + .agent_version = "0.1.0", + .uptime_seconds = 5, + .buffer_depth = 0, + .shutdown_reason = "service_stop", + }, .{}); + defer alloc.free(body); + try std.testing.expectEqualStrings( + "{\"agent_version\":\"0.1.0\",\"uptime_seconds\":5,\"buffer_depth\":0,\"shutdown\":true,\"shutdown_reason\":\"service_stop\"}", + body, + ); +} + test "v2 batch body and canonical string" { const alloc = std.testing.allocator; const id = [_]u8{ 0, 0, 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 0xe1 }; From 6ec090e2286615b22ec0681209cb80385fa6124f Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:20 +1100 Subject: [PATCH 6/8] ci: prove update paths on every OS, DPAPI keystore and service DACL on Windows Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 55 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54a9526..6bc2922 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -368,6 +368,61 @@ jobs: if ((Select-Events $third "powershell_script_block" $m2).Count -eq 0) { throw "event after restart was lost: $m2" } if ((Select-Events $third "powershell_script_block" $m1).Count -ne 0) { throw "restart replayed $m1" } Write-Host "event log telemetry and bookmarks OK" + # Signed self-update (#58): a key made for the run signs manifests, and + # the real file operations run good, bad signature, bad hash, downgrade + # and failed-health-check rollback in a temp install. On Windows this + # includes renaming a file the way the running exe is renamed. + - name: prove signed update paths (good, bad signature, bad hash, downgrade, rollback) + timeout-minutes: 2 + run: | + set -euo pipefail + bin="zig-out/bin/tawny-agent${{ matrix.binary_ext }}" + out="$("$bin" --update-selftest "$RUNNER_TEMP/tawny-update-selftest" 2>&1)" + printf '%s\n' "$out" + printf '%s\n' "$out" | grep -F "result=ok" + printf '%s\n' "$out" | grep -F "release_key=placeholder (updates disabled)" + # DPAPI keystore (#58): round trip, plaintext seed migrated and removed, + # no plaintext in the protected file. The hosted runner has no TPM, so + # key_protection is expected to be dpapi. Then the service DACL from + # install.ps1 is applied to a throwaway service and read back. + - name: prove Windows DPAPI keystore and service DACL + if: matrix.name == 'windows-x64' + shell: pwsh + timeout-minutes: 5 + run: | + $ErrorActionPreference = "Stop" + $PSNativeCommandUseErrorActionPreference = $false + $agent = Join-Path $PWD "zig-out\bin\tawny-agent.exe" + $dir = Join-Path $env:RUNNER_TEMP "tawny-keystore-selftest" + Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue + $out = & $agent --keystore-selftest $dir 2>&1 | Out-String + Write-Host $out + if ($LASTEXITCODE -ne 0) { throw "keystore selftest exit $LASTEXITCODE" } + foreach ($want in @("backend=windows_dpapi", "round_trip=ok", "plaintext_removed=true", "result=ok")) { + if (-not $out.Contains($want)) { throw "keystore selftest output lacks $want" } + } + if (-not ($out -match "key_protection=(dpapi|tpm)")) { throw "no key_protection in output" } + if (Test-Path -LiteralPath (Join-Path $dir "state.toml.devicekey")) { throw "plaintext seed left behind" } + + # Service DACL: same SDDL as install.ps1, on a stopped dummy service. + $match = Select-String -Path (Join-Path $PWD "install\install.ps1") -Pattern '^\$script:TawnyServiceSddl = "(.+)"$' + if (-not $match) { throw "TawnyServiceSddl not found in install.ps1" } + $sddl = $match.Matches[0].Groups[1].Value + $svc = "TawnyCiAclProbe" + & sc.exe delete $svc 2>&1 | Out-Null + & sc.exe create $svc binPath= "`"$agent`"" start= demand | Out-Host + if ($LASTEXITCODE -ne 0) { throw "sc create exit $LASTEXITCODE" } + try { + & sc.exe sdset $svc $sddl | Out-Host + if ($LASTEXITCODE -ne 0) { throw "sc sdset exit $LASTEXITCODE" } + $got = (& sc.exe sdshow $svc | Out-String).Trim() + Write-Host "sdshow: $got" + if ($got -match "\(A;;[A-Z]*(RP|WP|SD|DC)[A-Z]*;;;(IU|SU|AU)\)") { throw "non-admin principals can still start, stop, change or delete the service" } + if (-not ($got -match "\(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA\)")) { throw "Administrators lost full control" } + Write-Host "service DACL OK" + } finally { + & sc.exe delete $svc | Out-Null + } - name: test installer upgrade and recovery paths if: matrix.name == 'linux-x64' run: bash install/test-install.sh From 120fc16fee4eb45bc83838bb7cd2b82e8d656064 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:20 +1100 Subject: [PATCH 7/8] ci(release): Authenticode, notarisation and minisign steps that skip without secrets sign-windows, notarize-macos and release-manifests each gate on a job-level env flag set from their secrets, so releases still publish unsigned binaries when none are configured. The minisign key is read only from the protected release-signing environment. docs/code-signing.md lists the Windows and macOS options to choose from, without prices. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 206 +++++++++++++++++++++++++++++++++- docs/code-signing.md | 117 +++++++++++++++++++ 2 files changed, 322 insertions(+), 1 deletion(-) create mode 100644 docs/code-signing.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d97d1f9..95f23a8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -66,6 +66,204 @@ jobs: path: agent/zig-out/bin/tawny-agent-* if-no-files-found: error + # Code signing (#58, docs/code-signing.md). Each step below runs only when + # its secrets exist, so a release without certificates still publishes the + # unsigned binaries. Secrets can't be read in `if:`, so a job-level env flag + # carries "are they set". Signing changes the bytes, so the .sha256 sidecar + # is rewritten and the artifact replaced; the release job attests the final + # files. + sign-windows: + name: sign Windows agent (Authenticode) + needs: [build-agent] + runs-on: windows-latest + permissions: + contents: read + env: + HAS_WINDOWS_SIGNING: ${{ secrets.WINDOWS_PFX_BASE64 != '' && secrets.WINDOWS_PFX_PASSWORD != '' }} + WINDOWS_TIMESTAMP_URL: ${{ vars.WINDOWS_TIMESTAMP_URL || 'http://timestamp.digicert.com' }} + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: agent-windows-x64 + path: dist + - name: skip note + if: env.HAS_WINDOWS_SIGNING != 'true' + shell: pwsh + run: Write-Host "WINDOWS_PFX_BASE64 / WINDOWS_PFX_PASSWORD not set; publishing the Windows agent unsigned." + - name: sign with signtool + if: env.HAS_WINDOWS_SIGNING == 'true' + shell: pwsh + env: + WINDOWS_PFX_BASE64: ${{ secrets.WINDOWS_PFX_BASE64 }} + WINDOWS_PFX_PASSWORD: ${{ secrets.WINDOWS_PFX_PASSWORD }} + run: | + $ErrorActionPreference = "Stop" + $signtool = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin" -Recurse -Filter signtool.exe | + Where-Object { $_.FullName -match "\\x64\\" } | Sort-Object FullName -Descending | Select-Object -First 1 + if (-not $signtool) { throw "signtool.exe not found on the runner" } + $pfx = Join-Path $env:RUNNER_TEMP "tawny-signing.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_PFX_BASE64)) + try { + Get-ChildItem dist -Filter "tawny-agent-*.exe" | ForEach-Object { + & $signtool.FullName sign /fd sha256 /tr $env:WINDOWS_TIMESTAMP_URL /td sha256 /f $pfx /p $env:WINDOWS_PFX_PASSWORD $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool sign failed for $($_.Name)" } + & $signtool.FullName verify /pa /v $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool verify failed for $($_.Name)" } + $stem = $_.BaseName + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower() + # Same " " shape as sha256sum, LF only. + [IO.File]::WriteAllText((Join-Path dist "$stem.sha256"), "$hash $($_.Name)`n") + } + } finally { + Remove-Item -LiteralPath $pfx -Force -ErrorAction SilentlyContinue + } + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: env.HAS_WINDOWS_SIGNING == 'true' + with: + name: agent-windows-x64 + path: dist/tawny-agent-* + overwrite: true + if-no-files-found: error + + notarize-macos: + name: sign and notarise macOS agents + needs: [build-agent] + runs-on: macos-latest + permissions: + contents: read + strategy: + matrix: + name: [macos-arm64, macos-x64] + env: + HAS_APPLE_SIGNING: ${{ secrets.APPLE_DEVELOPER_ID_P12_BASE64 != '' && secrets.APPLE_DEVELOPER_ID_P12_PASSWORD != '' && secrets.APPLE_DEVELOPER_ID_IDENTITY != '' }} + HAS_APPLE_NOTARY: ${{ secrets.APPLE_NOTARY_APPLE_ID != '' && secrets.APPLE_NOTARY_TEAM_ID != '' && secrets.APPLE_NOTARY_PASSWORD != '' }} + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: agent-${{ matrix.name }} + path: dist + - name: skip note + if: env.HAS_APPLE_SIGNING != 'true' + run: echo "Apple Developer ID secrets not set; publishing the macOS agent unsigned (ad-hoc signed by the linker)." + - name: codesign with Developer ID + if: env.HAS_APPLE_SIGNING == 'true' + env: + P12_BASE64: ${{ secrets.APPLE_DEVELOPER_ID_P12_BASE64 }} + P12_PASSWORD: ${{ secrets.APPLE_DEVELOPER_ID_P12_PASSWORD }} + IDENTITY: ${{ secrets.APPLE_DEVELOPER_ID_IDENTITY }} + run: | + set -euo pipefail + keychain="$RUNNER_TEMP/tawny-signing.keychain-db" + kc_pass="$(openssl rand -hex 24)" + p12="$RUNNER_TEMP/tawny-signing.p12" + printf '%s' "$P12_BASE64" | base64 --decode > "$p12" + security create-keychain -p "$kc_pass" "$keychain" + security set-keychain-settings -lut 3600 "$keychain" + security unlock-keychain -p "$kc_pass" "$keychain" + security import "$p12" -k "$keychain" -P "$P12_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple: -s -k "$kc_pass" "$keychain" >/dev/null + security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"') + rm -f "$p12" + for bin in dist/tawny-agent-*-${{ matrix.name }}; do + codesign --force --options runtime --timestamp --keychain "$keychain" --sign "$IDENTITY" "$bin" + codesign --verify --strict --verbose=2 "$bin" + done + - name: notarise with notarytool + if: env.HAS_APPLE_SIGNING == 'true' && env.HAS_APPLE_NOTARY == 'true' + env: + APPLE_ID: ${{ secrets.APPLE_NOTARY_APPLE_ID }} + TEAM_ID: ${{ secrets.APPLE_NOTARY_TEAM_ID }} + NOTARY_PASSWORD: ${{ secrets.APPLE_NOTARY_PASSWORD }} + run: | + set -euo pipefail + # A bare Mach-O can't be stapled; Gatekeeper checks the ticket + # online. The zip is only the upload container. + for bin in dist/tawny-agent-*-${{ matrix.name }}; do + zip="$RUNNER_TEMP/$(basename "$bin").zip" + ditto -c -k --keepParent "$bin" "$zip" + xcrun notarytool submit "$zip" --apple-id "$APPLE_ID" --team-id "$TEAM_ID" --password "$NOTARY_PASSWORD" --wait + done + - name: rehash signed binaries + if: env.HAS_APPLE_SIGNING == 'true' + working-directory: dist + run: | + set -euo pipefail + for bin in tawny-agent-*-${{ matrix.name }}; do + case "$bin" in *.sha256) continue ;; esac + shasum -a 256 "$bin" > "${bin}.sha256" + done + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: env.HAS_APPLE_SIGNING == 'true' + with: + name: agent-${{ matrix.name }} + path: dist/tawny-agent-* + overwrite: true + if-no-files-found: error + + # Signed update manifests (#58, target-edr §10 "Updates"). The minisign + # secret key lives only in the protected `release-signing` environment + # (required reviewers), never in repository secrets. Without it no manifest + # is published and agents never self-update; they also refuse to while the + # compiled-in key in agent/src/update_key.zig is the placeholder. + release-manifests: + name: sign update manifests (minisign) + needs: [sign-windows, notarize-macos] + runs-on: ubuntu-latest + environment: release-signing + permissions: + contents: read + env: + HAS_MINISIGN: ${{ secrets.MINISIGN_SECRET_KEY != '' }} + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + pattern: agent-* + path: dist + merge-multiple: true + - name: write manifests + run: | + set -euo pipefail + mkdir -p manifests + VERSION="${GITHUB_REF_NAME#v}" + echo "manifests for $VERSION" > manifests/status.txt + cd dist + for bin in tawny-agent-*; do + case "$bin" in *.sha256) continue ;; esac + stem="${bin%.exe}" + platform="${stem#tawny-agent-${VERSION}-}" + sha="$(sha256sum "$bin" | awk '{print $1}')" + size="$(stat -c %s "$bin")" + printf '{"version":"%s","platform":"%s","sha256":"%s","size":%s,"min_from_version":"0.1.0","ring":"canary","rollback":false}' \ + "$VERSION" "$platform" "$sha" "$size" > "../manifests/${stem}.manifest.json" + done + - name: skip note + if: env.HAS_MINISIGN != 'true' + run: | + echo "MINISIGN_SECRET_KEY is not set in the release-signing environment; no update manifests are published." + rm -f manifests/*.manifest.json + - name: sign manifests + if: env.HAS_MINISIGN == 'true' + env: + MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }} + MINISIGN_PASSWORD: ${{ secrets.MINISIGN_PASSWORD }} + run: | + set -euo pipefail + sudo apt-get update -qq && sudo apt-get install -y -qq minisign + key="$RUNNER_TEMP/tawny-release.key" + umask 077 + printf '%s\n' "$MINISIGN_SECRET_KEY" > "$key" + trap 'rm -f "$key"' EXIT + for m in manifests/*.manifest.json; do + # A key made with `minisign -G -W` has no password; otherwise the + # password is read from stdin. + printf '%s\n' "${MINISIGN_PASSWORD:-}" | minisign -S -s "$key" -m "$m" -x "$m.minisig" -t "tawny release $GITHUB_REF_NAME $(basename "$m")" + done + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: release-manifests + path: manifests + if-no-files-found: error + build-server-image: name: publish tawny-server image runs-on: ubuntu-latest @@ -102,7 +300,7 @@ jobs: release: name: publish release - needs: [build-agent, build-server-image] + needs: [build-agent, sign-windows, notarize-macos, release-manifests, build-server-image] runs-on: ubuntu-latest permissions: contents: write @@ -117,6 +315,10 @@ jobs: pattern: agent-* path: dist merge-multiple: true + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: release-manifests + path: manifests - name: verify artifacts and create release manifest run: | set -euo pipefail @@ -124,6 +326,8 @@ jobs: for checksum in *.sha256; do sha256sum -c "$checksum" done + # Signed update manifests, when the release key is configured. + find ../manifests -maxdepth 1 -name '*.manifest.json*' -exec cp {} . \; install -m 0755 ../agent/install/install.sh ./install.sh install -m 0644 ../agent/install/install.ps1 ./install.ps1 find . -maxdepth 1 -type f ! -name SHA256SUMS -print0 \ diff --git a/docs/code-signing.md b/docs/code-signing.md new file mode 100644 index 0000000..f641415 --- /dev/null +++ b/docs/code-signing.md @@ -0,0 +1,117 @@ +# Code signing + +Status: prepared, not active. No certificate has been bought and no signing +key exists. Justin needs to choose the options below. This page lists them, +what each needs, and how the release workflow uses them. + +Code signing and the update manifest do different jobs: + +- **Authenticode and Apple notarisation** tell Windows SmartScreen and macOS + Gatekeeper who published the binary, so people installing Tawny by hand see + no warning. They cost money and need a vendor's identity checks. +- **The minisign release key** is the trust root for self-update (target-edr + §10). Agents install only a binary named by a manifest signed with that + key. It is free, and it stays the trust root whatever is chosen below. + +## What the release workflow does + +`.github/workflows/release.yml` has three signing jobs. Each one checks for +its secrets through a job-level env flag (secrets can't be used directly in +`if:`) and skips with a log line when they are missing, so a tagged release +still publishes unsigned binaries, `.sha256` sidecars and attestations. + +| Job | Runs when these secrets are set | What it does | +| --- | --- | --- | +| `sign-windows` | `WINDOWS_PFX_BASE64`, `WINDOWS_PFX_PASSWORD` (optional variable `WINDOWS_TIMESTAMP_URL`) | `signtool sign /fd sha256 /tr /td sha256`, then `signtool verify /pa`, rewrites the `.sha256` sidecar, replaces the artifact | +| `notarize-macos` | `APPLE_DEVELOPER_ID_P12_BASE64`, `APPLE_DEVELOPER_ID_P12_PASSWORD`, `APPLE_DEVELOPER_ID_IDENTITY`; notarising also needs `APPLE_NOTARY_APPLE_ID`, `APPLE_NOTARY_TEAM_ID`, `APPLE_NOTARY_PASSWORD` | `codesign --options runtime --timestamp` into a throwaway keychain, `xcrun notarytool submit --wait`, rewrites the `.sha256` sidecars | +| `release-manifests` | `MINISIGN_SECRET_KEY` (and `MINISIGN_PASSWORD` if the key has one) in the protected `release-signing` environment | Writes `{version, platform, sha256, size, min_from_version, ring, rollback}` per binary and signs it with `minisign -S` | + +The `release` job then attests and publishes everything, including the +signed binaries' final hashes. + +The `sign-windows` job takes a PFX file. That fits a certificate whose key +can be exported, which public CAs no longer issue for code signing (see +below). With a hardware token or a cloud signing service the step changes to +that vendor's tool or GitHub Action; the gating stays the same. Change it +once the option is chosen. + +A bare Mach-O binary can't be stapled, so macOS checks the notarisation +ticket online on first run. That is normal for command-line tools. + +## Windows options + +Check current pricing and eligibility on each vendor's own pages before +choosing. Prices and rules change, and none are quoted here. + +1. **OV code-signing certificate from a public CA** (for example DigiCert, + Sectigo, GlobalSign, SSL.com). Since the CA/Browser Forum code-signing + rules changed in 2023, the private key must be generated and kept on a + hardware token or in a cloud HSM, so it can't sit in a GitHub secret as a + PFX. Options are a USB token (signing then needs a machine with the token + attached, or a self-hosted runner), or the CA's cloud signing service + (for example DigiCert KeyLocker, SSL.com eSigner), which has a CLI or + GitHub Action. SmartScreen reputation builds up over time with OV. + Pages to check: each CA's "code signing certificate" pricing page and its + cloud signing product page. +2. **EV code-signing certificate.** Same key rules as OV, more identity + checks, historically faster SmartScreen reputation. Check whether that + still holds; Microsoft has changed how EV is treated. Pages to check: the + same CA pages, EV variant. +3. **Microsoft Azure Artifact Signing** (formerly Trusted Signing). A monthly + subscription where Microsoft holds the key and signs through an Azure + account; there is an official GitHub Action. It has eligibility rules for + organisations and individuals, and its availability by country has changed + since launch. Check that an Australian business (or individual) can enrol + today. Pages to check: "Artifact Signing" (or "Trusted Signing") on + learn.microsoft.com, its pricing page on azure.microsoft.com, and the + Azure account needed for it. Using it creates an Azure resource, which is + Justin's call. + +Things to weigh: whether signing must run on GitHub-hosted runners (rules out +a USB token unless there is a self-hosted runner), who verifies the +business identity, and renewal. + +## macOS option + +**Apple Developer Program** membership gives a Developer ID Application +certificate and access to the notary service. Membership is a yearly fee in +local currency. Check the current Australian price on Apple's "Apple +Developer Program" enrolment page and "Membership details" page. Enrolling +as an organisation needs a D-U-N-S number; enrolling as an individual puts +Justin's name on the signature. + +After enrolment: + +1. Create a Developer ID Application certificate, export it as `.p12`, and + store it base64-encoded in `APPLE_DEVELOPER_ID_P12_BASE64` with its + password in `APPLE_DEVELOPER_ID_P12_PASSWORD`. +2. Set `APPLE_DEVELOPER_ID_IDENTITY` to the certificate name, for example + `Developer ID Application: ()`. +3. Create an app-specific password for the Apple ID and set + `APPLE_NOTARY_APPLE_ID`, `APPLE_NOTARY_TEAM_ID` and + `APPLE_NOTARY_PASSWORD`. A notary API key is an alternative; the step + would change to `--key`, `--key-id`, `--issuer`. + +A signed agent also stops the installers' upgrade path from having to export +Keychain items first, because a Developer ID build keeps the same code +identity across versions. + +## Release minisign key (free, needed for self-update) + +Self-update is off until this exists. The agent compiles in a placeholder +public key and refuses every update while it is there. + +1. On a machine you trust, offline if possible: `minisign -G -p tawny-release.pub -s tawny-release.key`. + Use a password. Keep the secret key and its password out of the + repository, chat and shared drives. +2. Put the second line of `tawny-release.pub` into `agent/src/update_key.zig` + as `public_key`, replacing the placeholder, and update the test there. +3. Create the GitHub environment `release-signing` with required reviewers + (Settings, Environments). Add `MINISIGN_SECRET_KEY` (the whole secret key + file) and `MINISIGN_PASSWORD` there, not as repository secrets. +4. Tag a release. The manifests are published beside the binaries and new + releases start in the `canary` ring. + +If the secret key leaks: create a new key, ship a release whose +`update_key.zig` holds the new public key through the installers (not +self-update), and remove the old secret from the environment. From ecd4929d310de3c1da343c3cdfe430014313e963 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 04:55:20 +1100 Subject: [PATCH 8/8] docs: agent hardening, key protection, update rings, no-mTLS decision Closes #58 Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 68 ++++++++++++++++++++++++- docs/architecture/target-edr.md | 38 ++++++++++++++ docs/production-agent-hardening.md | 80 ++++++++++++++++++++++++++++++ docs/threat-model.md | 19 ++++++- 4 files changed, 202 insertions(+), 3 deletions(-) diff --git a/docs/api.md b/docs/api.md index f023706..516daa6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -78,6 +78,70 @@ If the JWT is close to expiry (within the rotation window, 15 minutes by default The response also has `yara_pack_version`, the version of the tenant's YARA rule pack (0 when there are no YARA rules). An agent with a lower version fetches the pack. +**Clean shutdown notice (#58).** As the agent stops for the service manager +or a signal it sends one more heartbeat with `"shutdown": true` and +`"shutdown_reason"` (`service_stop`, `system_shutdown`, `signal` or +`update_restart`, at most 64 characters). The server records +`clean_shutdown_at`, audits `agent.clean_shutdown`, and replies `{"actions":[]}` +with no rotated token. The next normal heartbeat clears the notice. An agent +that goes `offline` (15 minutes) without the notice raises an `Agent silent` +alert, which its next heartbeat closes (status `resolved`). Revoked agents +never raise it. + +**Server-raised alerts.** `Agent silent`, `Sensor silent` and `Agent tamper` +alerts hang off one disabled rule per tenant (external ids +`tawny-system:agent-silent`, `tawny-system:sensor-silent`, +`tawny-system:agent-tamper`) and go to the usual sinks. `Agent silent` and +`Sensor silent` from the periodic job are anchored on a server-written event +of type `agent_silent` or `sensor_silent` with confidence `server_observed`. + +- `agent_tamper` (schemas/events/agent_tamper.v1.json): one alert per event. + `check` is `unexpected_stop`, `binary_changed`, `config_changed`, + `identity_changed`, `sysmon_stopped` or `defender_exclusion`. +- `sensor_health` (per Windows channel) and `agent_health.sensors` + (`[{name, status, last_event_age_seconds}]`) update per-sensor status. A + sensor that was running and then reports stopped, failed, missing or + access denied raises `Sensor silent`. For the continuous sensors (Sysmon and + Security) the agent's own 15 minute `silent` state does too, and so does the + server when `agent_health` shows no event for 15 minutes while the agent is + still online. Delivering again closes the alert. +- `agent_health` also carries `key_protection` (`keychain`, `dpapi`, `tpm` or + `file`) and `update` (`{state, version, ring, bucket, reason}`), stored on + the agent row as `key_protection`, `update_state` and `update_version`. + +### POST `/api/agent/update-check` + +Auth: Agent JWT. Body `{"platform": "windows-x64"}` (a `ring` field from the +agent is ignored). The server picks the agent's ring: the `agents.update_ring` +override when set, else the bucket, `sha256(lower-case agent id)` first four +bytes big-endian mod 100, with buckets 0 to 9 in ring `10`, 10 to 49 in `50` +and the rest in `100`. `canary` and `internal` are only reached by override. + +Response `200` when the latest release for the platform carries a signed +manifest and is open to the agent's ring (ring order canary, internal, 10, +50, 100; a release open to ring R is offered to R and every earlier ring): + +```json +{ "manifest": "{\"version\":\"0.2.0\",...}", "signature": "untrusted comment: ...", "download_url": "https://...", "agent_ring": "50" } +``` + +`204` when nothing signed is offered. The server passes the manifest bytes on +and never trusts them; the agent verifies the minisign signature with its +compiled-in release key. The agent refuses every update while that key is the +placeholder (`update.state` = `disabled_no_release_key`). + +Manifest: `{version, platform, sha256, size, min_from_version, ring, rollback}`, +signed as a file by `minisign -S` (prehashed `ED`; the legacy `Ed` form is +also accepted). The release job publishes `.manifest.json` and +`.manifest.json.minisig` beside each binary; the release sync stores them in +`agent_releases.manifest` and `manifest_signature`. + +**Rings and promotion.** The release sync inserts new releases in ring +`canary`. Every hour the server moves a latest release to the next ring when +it has been in its ring for the soak period (24 hours) and no more than 5% of +agents that reported that version are `rolled_back` or `failed`. Releases +synced before #58 start in `100`. + ### POST `/api/agent/yara-rules` Auth: Agent JWT. Body `{}`. Returns the tenant's enabled YARA rules as one signed pack: @@ -280,7 +344,9 @@ Auth: web user (Admin). Revokes. Auth: session cookie or `twny_` API token. Anonymous and agent JWT requests are 401. Returns the current `is_latest` row for that platform -(`version`, `platform`, `download_url`, `sha256`, `released_at`). Unknown +(`version`, `platform`, `download_url`, `sha256`, `released_at`, `ring`). +Optional `ring=canary|internal|10|50|100` returns the release only when it is +already open to that ring (else 404); any other value is 400. Unknown platform is 404 `No release is published for that platform.` A missing `platform` query is 400 `platform is required.` Enrolled agents still receive `latest_agent_version`, `download_url`, and `sha256` on heartbeat. diff --git a/docs/architecture/target-edr.md b/docs/architecture/target-edr.md index 186e379..ba4af30 100644 --- a/docs/architecture/target-edr.md +++ b/docs/architecture/target-edr.md @@ -654,6 +654,15 @@ permits for now. Linux nftables isolation lands in #59. 4. Ingest checks `cv` (fixes current gap). Pinned server action key and release key delivered at enrollment. + **Status (#58, Nov 2026):** Windows keeps the JWT and device seed in DPAPI + machine scope (fixed entropy, SYSTEM and Administrators ACL), wrapped by a + TPM key in the Microsoft Platform Crypto Provider when one is usable, and + migrates plaintext copies away. Linux stays on a root-only 0600 file; + tpm2-tss is not done. `agent_health.key_protection` reports which. The + release key is compiled in (`agent/src/update_key.zig`) rather than sent at + enrolment, and is a placeholder until the owner creates it. No mTLS: see + docs/threat-model.md. + ### Tamper detection (`AGENT_TAMPER`) Service stop not initiated by SCM shutdown/upgrade (recorded on next start @@ -664,6 +673,14 @@ added for Tawny paths. Server-side: heartbeat gap > N min with no shutdown notice → `AGENT_SILENT` detection. Install ACLs and service DACL restrict stop/delete to SYSTEM/Admins. No anti-debug or rootkit behaviour. +**Status (#58, Nov 2026):** done except the ETW checks (no ETW sessions yet; +Sysmon service state stands in) and Windows directory change notifications +(the agent polls hashes every 60 seconds instead). The clean shutdown marker, +`agent_tamper` checks and `Agent silent` alert (offline at 15 minutes without +a notice, closed by the next heartbeat, never for revoked agents) are in +`agent/src/lifecycle.zig`, `agent/src/tamper.zig` and +`server/src/jobs/agent_alerts.zig`. `install.ps1` sets the service DACL. + ### Updates - Release manifest `{version, platform, sha256, size, min_from_version, @@ -680,6 +697,17 @@ stop/delete to SYSTEM/Admins. No anti-debug or rootkit behaviour. - Authenticode-sign Windows binaries and notarise macOS when certificates are available; the manifest signature is the trust root regardless. +**Status (#58, Nov 2026):** built and tested, off by default. Minisign +manifests (`ED` prehashed and legacy `Ed`), downgrade refusal, signed +rollback, stage, swap with `.previous`, restart through the service manager, +a 5 minute health window and rollback are in `agent/src/updater.zig`, with a +CI self-test on every OS. Rings and gated promotion (24 hour soak, under 5% +rolled back or failed) are in `server/src/jobs/releases.zig` and +`routes/agent_releases.zig`. The compiled-in release key is a placeholder, so +agents refuse every update until the owner provides one. Release signing +steps (signtool, notarytool, minisign) skip cleanly without their secrets; +options are in docs/code-signing.md. + ### Health (`AGENT_HEALTH`, every heartbeat) version, uptime, last event ts, queue depth per priority, spool bytes, events @@ -688,6 +716,13 @@ status (running/degraded/stopped + last event age), isolation state, update state. Server computes `healthy|degraded|silent|tampered`; agents list sorts unhealthy first; silent > 15 min raises a detection. +**Status (#58, Nov 2026):** `agent_health` now carries `key_protection`, +`sensors` (name, status, last event age) and `update` (state, version, ring, +bucket). Windows channels keep their own `sensor_health`. The server alerts +`Sensor silent` when a sensor that was running stops, fails, or (Sysmon and +Security) delivers nothing for 15 minutes. CPU, RSS, disk, per-priority +queues and the `healthy|degraded|silent|tampered` verdict are not done. + ## 11. False-positive management Exceptions table generalises `SuppressionRules`: match on hash, signer, @@ -786,3 +821,6 @@ with current packages, agent on Zig 0.17.0, Windows service runs as prevention is limited to post-launch kill/quarantine and WFP blocking. 4. **Code-signing certificates** (Authenticode, Apple Developer ID) — needed for production trust and SmartScreen; procurement is outside the repo. + **Status (#58, Nov 2026):** release steps are ready and skip without + secrets. Options and what to check are in docs/code-signing.md; waiting + on the owner's choice. diff --git a/docs/production-agent-hardening.md b/docs/production-agent-hardening.md index 9409358..48875d1 100644 --- a/docs/production-agent-hardening.md +++ b/docs/production-agent-hardening.md @@ -27,6 +27,82 @@ not a normal install option. Keep a copy of each approved binary, `SHA256SUMS`, release tag, attestation verification output, and deployment approval in the SOC change record. +### Code signing and signed update manifests + +Authenticode (Windows) and Developer ID with notarisation (macOS) steps are in +`.github/workflows/release.yml` and run only when their secrets exist, so +releases still publish without them. The options and what they need are in +[code-signing.md](code-signing.md). Until certificates exist, Windows +SmartScreen and macOS Gatekeeper warn on first run, and the SHA-256 plus +attestation checks above are the release trust. + +Self-update trusts neither of those. It trusts only a minisign signature on a +release manifest, checked with the public key compiled into the agent +(`agent/src/update_key.zig`). **That key is a placeholder today, so the agent +refuses every update** and reports `update.state` = +`disabled_no_release_key` in `agent_health`. Installs and upgrades go through +the installers as before. To turn self-update on: + +1. The project owner creates the key offline (`minisign -G`), keeps the + secret key off any shared machine, and commits only the second line of + `minisign.pub` into `update_key.zig` in place of the placeholder. +2. The owner creates a GitHub environment named `release-signing` with + required reviewers and puts the secret key in `MINISIGN_SECRET_KEY` (and + `MINISIGN_PASSWORD` if it has one). Repository secrets are not used. +3. The next tagged release publishes `*.manifest.json` and `.minisig` beside + each binary. New releases start in the `canary` ring and widen one ring a + day while rollbacks stay under 5% (docs/api.md, update-check). + +## Agent self-protection + +- **Clean shutdown marker.** On a service stop, system shutdown or SIGTERM, + the agent flushes, sends a final heartbeat with `shutdown: true` and writes + `.clean`. A start without that file sends `agent_tamper` + `unexpected_stop`. The server raises `Agent silent` when an agent goes + offline without the notice. +- **Tamper checks** (`agent/src/tamper.zig`, every 60 seconds): the agent + binary's SHA-256 (against the signed manifest after a self-update, else the + hash at start; hashed every fifth run), `config.toml`, `state.toml`, the + device key and the pinned action key changing outside the agent, the Sysmon + service stopping (Windows), and Defender Operational 5007 entries adding a + path or process exclusion that covers `C:\ProgramData\Tawny`, + `C:\Program Files\Tawny` or `tawny-agent.exe`. Each sends `agent_tamper` + and the server raises `Agent tamper`. These are detections only. There is + no anti-debug or rootkit behaviour. +- **Service DACL (Windows).** `install.ps1` runs `sc.exe sdset` so only + SYSTEM and Administrators can stop, pause, reconfigure or delete + `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. + +## Key protection + +`agent_health.key_protection` reports how the agent JWT and device seed are +held: + +| Value | Where | Notes | +| --- | --- | --- | +| `keychain` | macOS System keychain (LaunchDaemon) or login keychain | Unchanged from before #58 | +| `tpm` | Windows: DPAPI blob wrapped by a non-exportable 2048-bit RSA key `TawnyAgentWrap` in the Microsoft Platform Crypto Provider (RSA-OAEP SHA-256) | Copying the files to another machine is useless without that TPM | +| `dpapi` | Windows: DPAPI machine scope, fixed entropy, `%ProgramData%\Tawny\state\.dpapi`, ACL SYSTEM and Administrators only | Used when no TPM is usable, or with `TAWNY_KEYSTORE_TPM=off` | +| `file` | Linux: `state.toml` and `state.toml.devicekey`, mode 0600, in the root-owned 0750 state directory; any OS with `TAWNY_KEYSTORE=file` | tpm2-tss sealing on Linux is not done yet | + +On the first start after an upgrade to #58, a Windows agent moves a plaintext +JWT and device seed into DPAPI, reads them back, and only then scrubs and +deletes the plaintext files. If any step fails the plaintext stays and the +agent logs why. An administrator on the host can still decrypt DPAPI machine +secrets; the ACL and the TPM wrap raise the bar for everyone else and for +offline copies. + +Check on a host: + +```powershell +icacls "$env:ProgramData\Tawny\state\device-seed.dpapi" # SYSTEM and Administrators only +Test-Path "$env:ProgramData\Tawny\state\state.toml.devicekey" # False after migration +& "$env:ProgramFiles\Tawny\tawny-agent.exe" --keystore-selftest "$env:TEMP\tawny-ks" # prints key_protection +``` + ## Linux and EC2 Prerequisites: root, `curl`, Python 3, GitHub CLI, systemd, and outbound HTTPS to @@ -353,6 +429,10 @@ criteria and SOC ownership for heartbeat and upgrade alerts. ## Known residual risk +Self-update is built but off until the release key exists (see above). +Authenticode and notarisation need certificates the project does not have +yet. Linux keeps its secrets in a 0600 file without TPM sealing. + Response actions do not yet have durable lease, execution journal, or explicit agent acknowledgement semantics. Backend can mark an action `Dispatched` before host execution; agent crash or network loss can therefore leave outcome unknown. diff --git a/docs/threat-model.md b/docs/threat-model.md index dd55f8c..a67bd06 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -26,7 +26,7 @@ Honest threat model for Tawny as a self-hosted EDR. Not a substitute for a forma | Threat | Mitigation | Residual / future | | --- | --- | --- | | Enrollment token theft | Single-use, hashed at rest, short TTL | Bind to expected host / CIDR | -| Agent JWT theft from disk | Short-lived JWT (minutes), `jti`, `cv` credential version, admin revoke bumps version | Platform keystores (DPAPI/Keychain/TPM), device-bound keys | +| Agent JWT theft from disk | Short-lived JWT (minutes), `jti`, `cv` credential version, admin revoke bumps version. macOS Keychain; Windows DPAPI machine scope with fixed entropy and a SYSTEM/Administrators ACL, TPM-wrapped through the Platform Crypto Provider when present (#58) | Linux keeps a root-only 0600 file; tpm2-tss sealing not done. An administrator on the host can still read DPAPI secrets | | Stolen JWT after revoke | Every agent endpoint (JWT validation hook) rejects revoked agents and credential-version mismatch, and audits the rejection | Global denylist of `jti` | | Stolen session cookie | HttpOnly, Secure, SameSite=Lax; idle 8h and absolute 7d; logout deletes the row | XSS that can read a non-HttpOnly token is out of this cookie's reach; CSRF still applies | | Cross-site session use | `X-CSRF-Token` required on state-changing session requests. API tokens and agent JWTs are exempt | A stolen cookie plus a stolen CSRF secret is a full session | @@ -42,8 +42,23 @@ Honest threat model for Tawny as a self-hosted EDR. Not a substitute for a forma | XSS in dashboard | Static pages must escape telemetry and operator text on insert | Trusted Types | | OpenAPI probe in production | tawny-server does not publish an OpenAPI document | — | | Reverse-proxy misconfig | Document HTTPS termination; public URL HTTPS checks in production | Trusted proxy / forwarded headers validation | -| Supply-chain agent release | Published SHA-256 | Sigstore / Authenticode / notarisation | +| Supply-chain agent release | Published SHA-256 and build attestations. Self-update only installs a binary named by a minisign-signed manifest (`ED`, BLAKE2b prehashed) checked against the release key compiled into the agent, then checks size and SHA-256, refuses downgrades except a signed `rollback`, and rolls back after a failed health window (#58) | Authenticode and notarisation steps exist but need certificates (docs/code-signing.md). The release key is a placeholder until the owner creates it, so self-update is off | | Insider DB access | Audit log of security-sensitive actions | Column encryption, append-only audit sink | +| Agent stopped or killed to blind the host | Clean shutdown marker plus a final `shutdown` heartbeat on service stop and SIGTERM. A start without the marker sends `agent_tamper` `unexpected_stop`. An agent that goes offline without the notice raises `Agent silent` (closed by its next heartbeat; revoked agents never alert). Installer service DACL lets only SYSTEM and Administrators stop or delete the service (#58) | An administrator can still stop the service and delete the marker first; the server still sees the missing heartbeat | +| Sensor silenced (Sysmon stopped, channel cleared, Defender exclusion) | `sensor_health` and `agent_health.sensors` feed per-sensor status. A sensor that was running and stops, fails, or (Sysmon, Security) delivers nothing for 15 minutes raises `Sensor silent`. Tamper checks report the Sysmon service stopping, Defender 5007 exclusions covering Tawny paths, the binary hash changing, and config or identity files changing outside the agent | User-mode only; an attacker with kernel access can hide these. No anti-debug or rootkit behaviour by design | + +## Decision: no mutual TLS for now (#58) + +Agents authenticate with short-lived JWT bearer tokens over server-side TLS. +Mutual TLS was considered and left out for this release. The risks it would +cover are already covered: every event batch is signed with the agent's +Ed25519 device key and verified by the server, every response action is +signed by the server action key and verified by the agent, and the agent's +secrets are held in the OS keystore (Keychain, DPAPI with optional TPM wrap). +mTLS would add certificate issuance, rotation and revocation, and would break +TLS-terminating proxies such as Caddy in front of the server, for little +gain over those. Revisit if agents ever need to talk to the server through an +untrusted proxy that could replay bearer tokens. ## Explicit coverage (required scenarios)