From 7b1121c368ba20473bcf2685b7a94d31520cdb2c Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 02:44:08 +1100 Subject: [PATCH 1/8] feat(agent,server): one server action key, signed response actions Fold the #56 rule-pack key into a single Ed25519 server action key (TAWNY_ACTION_SIGNING_KEY, 64 hex) that signs both response actions and YARA rule packs. TAWNY_RULE_SIGNING_KEY keeps working as a deprecated alias. When neither is set the key is derived from the agent JWT seed with HKDF and a domain-separated label, matching how #66 derived the rule key, so existing deployments keep booting. The public key is returned in the enrol reply and in every heartbeat for trust-on-first-use pinning of agents enrolled before this change. The server signs the canonical string tawny-action-v1\n\n\n\n\n and adds "signature" to each action in the heartbeat. The agent verifies it in response_actions before anything runs, refusing unsigned, expired, tampered and wrong-key actions and reporting failed with a reason. A local action journal at /actions/.json dedupes by action_id, replays unfinished actions on restart, and keeps results until the server acks them. Co-Authored-By: Claude Opus 5.5 --- agent/src/action_journal.zig | 160 +++++++++ agent/src/action_key.zig | 95 +++++ agent/src/action_sig.zig | 186 ++++++++++ agent/src/enrollment.zig | 9 + agent/src/main.zig | 68 +++- .../src/platform/windows/process_control.zig | 191 ++++++++++ agent/src/platform/windows/wfp.zig | 211 +++++++++++ agent/src/quarantine.zig | 335 ++++++++++++++++++ agent/src/response_actions.zig | 254 +++++++++++-- agent/src/transport/http.zig | 29 ++ server/src/crypto/action_sig.zig | 79 +++++ server/src/db/migrate.zig | 3 + .../db/migrations/0006_windows_response.sql | 9 + server/src/http/state.zig | 94 ++--- server/src/main.zig | 14 +- server/src/routes/agents.zig | 42 ++- 16 files changed, 1686 insertions(+), 93 deletions(-) create mode 100644 agent/src/action_journal.zig create mode 100644 agent/src/action_key.zig create mode 100644 agent/src/action_sig.zig create mode 100644 agent/src/platform/windows/process_control.zig create mode 100644 agent/src/platform/windows/wfp.zig create mode 100644 agent/src/quarantine.zig create mode 100644 server/src/crypto/action_sig.zig create mode 100644 server/src/db/migrations/0006_windows_response.sql diff --git a/agent/src/action_journal.zig b/agent/src/action_journal.zig new file mode 100644 index 0000000..5a3ef02 --- /dev/null +++ b/agent/src/action_journal.zig @@ -0,0 +1,160 @@ +//! Durable action journal (#57, target-edr §9.2). +//! +//! Each action is written to `/actions/.json` before it runs. +//! The journal dedupes by `action_id`, so a restart in the middle of an action +//! never runs a finished one twice, and the result is kept until the server +//! acks it. The server redelivers pending actions on every heartbeat, so a +//! `done` action that has not been acked is reported again with the fresh +//! execution token from the new dispatch. +//! +//! File states: +//! running the agent started the action and may have crashed; idempotent +//! actions (kill of a gone process, quarantine by hash) re-run. +//! done the action finished; `status` and `message` hold the result, +//! reported until the server stops redelivering it. + +const std = @import("std"); +const iox = @import("io_compat.zig"); + +pub const State = enum { running, done }; + +pub const Entry = struct { + action_id: []const u8, + action_type: []const u8, + state: State, + status: []const u8 = "", + message: []const u8 = "", +}; + +pub const Journal = struct { + alloc: std.mem.Allocator, + dir: []u8, + + /// `/actions`. The state dir is the directory of state_path. + pub fn init(alloc: std.mem.Allocator, state_path: []const u8) !Journal { + const state_dir = std.fs.path.dirname(state_path) orelse "."; + const dir = try std.fs.path.join(alloc, &.{ state_dir, "actions" }); + const io = iox.current(); + std.Io.Dir.cwd().createDirPath(io, dir) catch {}; + return .{ .alloc = alloc, .dir = dir }; + } + + pub fn deinit(self: *Journal) void { + self.alloc.free(self.dir); + } + + fn pathFor(self: *Journal, id: []const u8) ![]u8 { + return std.fmt.allocPrint(self.alloc, "{s}/{s}.json", .{ self.dir, id }); + } + + /// Read the journal entry for an action id, or null. Caller owns the + /// returned strings via `freeEntry`. + pub fn read(self: *Journal, id: []const u8) ?Entry { + const p = self.pathFor(id) catch return null; + defer self.alloc.free(p); + const io = iox.current(); + const raw = std.Io.Dir.cwd().readFileAlloc(io, p, self.alloc, .limited(256 * 1024)) catch return null; + defer self.alloc.free(raw); + const Raw = struct { + action_id: []const u8, + action_type: []const u8, + state: []const u8, + status: []const u8 = "", + message: []const u8 = "", + }; + const parsed = std.json.parseFromSlice(Raw, self.alloc, raw, .{ .ignore_unknown_fields = true }) catch return null; + defer parsed.deinit(); + const st: State = if (std.mem.eql(u8, parsed.value.state, "done")) .done else .running; + return Entry{ + .action_id = self.alloc.dupe(u8, parsed.value.action_id) catch return null, + .action_type = self.alloc.dupe(u8, parsed.value.action_type) catch return null, + .state = st, + .status = self.alloc.dupe(u8, parsed.value.status) catch "", + .message = self.alloc.dupe(u8, parsed.value.message) catch "", + }; + } + + pub fn freeEntry(self: *Journal, e: Entry) void { + self.alloc.free(e.action_id); + self.alloc.free(e.action_type); + if (e.status.len > 0) self.alloc.free(e.status); + if (e.message.len > 0) self.alloc.free(e.message); + } + + fn write(self: *Journal, e: Entry) !void { + const p = try self.pathFor(e.action_id); + defer self.alloc.free(p); + const body = try std.json.Stringify.valueAlloc(self.alloc, .{ + .action_id = e.action_id, + .action_type = e.action_type, + .state = @tagName(e.state), + .status = e.status, + .message = e.message, + }, .{}); + defer self.alloc.free(body); + const io = iox.current(); + const tmp = try std.fmt.allocPrint(self.alloc, "{s}.tmp", .{p}); + defer self.alloc.free(tmp); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = tmp, .data = body }); + try std.Io.Dir.cwd().rename(tmp, std.Io.Dir.cwd(), p, io); + } + + /// Mark an action as started. Writes `running` unless it is already there. + pub fn begin(self: *Journal, id: []const u8, action_type: []const u8) !void { + try self.write(.{ .action_id = id, .action_type = action_type, .state = .running }); + } + + /// Record the terminal result so it survives a restart and is reported + /// until the server acks it. + pub fn finish(self: *Journal, id: []const u8, action_type: []const u8, status: []const u8, message: []const u8) !void { + try self.write(.{ .action_id = id, .action_type = action_type, .state = .done, .status = status, .message = message }); + } + + /// Remove a journal entry once the server has acked the result. + pub fn clear(self: *Journal, id: []const u8) void { + const p = self.pathFor(id) catch return; + defer self.alloc.free(p); + const io = iox.current(); + std.Io.Dir.cwd().deleteFile(io, p) catch {}; + } +}; + +test "dedupe and result survive a restart" { + const a = std.testing.allocator; + const io = iox.current(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const state = try std.fs.path.join(a, &.{ dir, "state.toml" }); + defer a.free(state); + + var j = try Journal.init(a, state); + defer j.deinit(); + + const id = "33333333-3333-4333-8333-333333333333"; + try std.testing.expect(j.read(id) == null); + + try j.begin(id, "kill_process"); + { + const e = j.read(id).?; + defer j.freeEntry(e); + try std.testing.expectEqual(State.running, e.state); + } + + try j.finish(id, "kill_process", "succeeded", "already gone"); + + // A fresh journal (restart) still sees the finished result. + var j2 = try Journal.init(a, state); + defer j2.deinit(); + { + const e = j2.read(id).?; + defer j2.freeEntry(e); + try std.testing.expectEqual(State.done, e.state); + try std.testing.expectEqualStrings("succeeded", e.status); + try std.testing.expectEqualStrings("already gone", e.message); + } + + j2.clear(id); + try std.testing.expect(j2.read(id) == null); +} diff --git a/agent/src/action_key.zig b/agent/src/action_key.zig new file mode 100644 index 0000000..1b52327 --- /dev/null +++ b/agent/src/action_key.zig @@ -0,0 +1,95 @@ +//! Pinned server action public key (#57). The server returns it in the +//! enrolment reply (`action_public_key`) and in every heartbeat. The agent +//! writes it once to `.actionkey` and verifies every response +//! action against it. An `action_public_key` in config.toml takes precedence. +//! +//! Trust on first use (TOFU): agents enrolled before #57 have no pinned key. +//! The first heartbeat that carries `action_public_key` pins it, over the +//! same TLS channel the JWT already trusts, and the agent logs that it did. +//! The window is that first heartbeat; after it, a different key is refused, +//! so an operator must remove the file to re-pin. This is the same model the +//! YARA rule key already uses, and the two keys are the same bytes. + +const std = @import("std"); +const iox = @import("io_compat.zig"); +const Ed25519 = std.crypto.sign.Ed25519; + +pub fn path(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { + return std.fmt.allocPrint(alloc, "{s}.actionkey", .{state_path}); +} + +pub fn valid(b64: []const u8) bool { + const dec = std.base64.standard.Decoder; + const n = dec.calcSizeForSlice(b64) catch return false; + if (n != 32) return false; + var raw: [32]u8 = undefined; + dec.decode(&raw, b64) catch return false; + _ = Ed25519.PublicKey.fromBytes(raw) catch return false; + return true; +} + +/// Decode a base64 key to a PublicKey, or null. +pub fn decode(b64: ?[]const u8) ?Ed25519.PublicKey { + const text = b64 orelse return null; + const dec = std.base64.standard.Decoder; + const n = dec.calcSizeForSlice(text) catch return null; + if (n != 32) return null; + var raw: [32]u8 = undefined; + dec.decode(&raw, text) catch return null; + return Ed25519.PublicKey.fromBytes(raw) catch null; +} + +/// Write the key unless one is already pinned (trust on first use). +pub fn pin(alloc: std.mem.Allocator, state_path: []const u8, b64: []const u8) !void { + if (!valid(b64)) return error.InvalidActionKey; + const p = try path(alloc, state_path); + defer alloc.free(p); + const io = iox.current(); + if (std.Io.Dir.cwd().access(io, p, .{})) |_| return else |_| {} + if (std.fs.path.dirname(p)) |d| try std.Io.Dir.cwd().createDirPath(io, d); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = b64 }); +} + +/// Pinned key text, or null. Caller frees. +pub fn load(alloc: std.mem.Allocator, state_path: []const u8) ?[]u8 { + const p = path(alloc, state_path) catch return null; + defer alloc.free(p); + const io = iox.current(); + const raw = std.Io.Dir.cwd().readFileAlloc(io, p, alloc, .limited(256)) catch return null; + const trimmed = std.mem.trim(u8, raw, " \r\n"); + if (!valid(trimmed)) { + alloc.free(raw); + return null; + } + const out = alloc.dupe(u8, trimmed) catch { + alloc.free(raw); + return null; + }; + alloc.free(raw); + return out; +} + +test "pin once, refuse junk, load back" { + const a = std.testing.allocator; + const io = iox.current(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const state = try std.fs.path.join(a, &.{ dir, "state.toml" }); + defer a.free(state); + const k1 = Ed25519.KeyPair.generate(std.testing.io); + const k2 = Ed25519.KeyPair.generate(std.testing.io); + var b1: [44]u8 = undefined; + var b2: [44]u8 = undefined; + const t1 = std.base64.standard.Encoder.encode(&b1, &k1.public_key.bytes); + const t2 = std.base64.standard.Encoder.encode(&b2, &k2.public_key.bytes); + try std.testing.expectError(error.InvalidActionKey, pin(a, state, "not-a-key")); + try std.testing.expect(load(a, state) == null); + try pin(a, state, t1); + try pin(a, state, t2); // ignored: already pinned + const got = load(a, state).?; + defer a.free(got); + try std.testing.expectEqualStrings(t1, got); + try std.testing.expect(decode(got) != null); +} diff --git a/agent/src/action_sig.zig b/agent/src/action_sig.zig new file mode 100644 index 0000000..2629f06 --- /dev/null +++ b/agent/src/action_sig.zig @@ -0,0 +1,186 @@ +//! Verify server-signed response actions (#57). +//! +//! The server (`server/src/crypto/action_sig.zig`) signs the canonical string +//! tawny-action-v1\n\n\n\n\n +//! with the action key. The agent pins the public key (enrolment or TOFU +//! heartbeat) and refuses any action that is unsigned, expired, has a payload +//! that does not match its signed hash, or whose signature does not verify. + +const std = @import("std"); +const Ed25519 = std.crypto.sign.Ed25519; + +pub const prefix = "tawny-action-v1"; + +pub const VerifyError = error{ + ActionUnsigned, + ActionExpired, + ActionPayloadMismatch, + ActionSignatureInvalid, + ActionKeyMissing, + OutOfMemory, +}; + +pub const Fields = struct { + action_id: []const u8, + agent_id: []const u8, + action_type: []const u8, + expires_at: []const u8, + payload: []const u8, + /// Hash the server signed, lower-case hex. Empty if absent. + payload_hash: []const u8, + /// Base64 Ed25519 signature, or null. + signature: ?[]const u8, +}; + +/// Build the canonical string. Caller frees. +pub fn canonical( + alloc: std.mem.Allocator, + action_id: []const u8, + agent_id: []const u8, + action_type: []const u8, + expires_at: []const u8, + payload_sha256_hex: []const u8, +) ![]u8 { + return std.fmt.allocPrint(alloc, "{s}\n{s}\n{s}\n{s}\n{s}\n{s}", .{ + prefix, action_id, agent_id, action_type, expires_at, payload_sha256_hex, + }); +} + +/// Lower-case hex SHA-256 of the payload bytes. +pub fn payloadHashHex(payload: []const u8) [64]u8 { + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(payload, &digest, .{}); + return std.fmt.bytesToHex(digest, .lower); +} + +/// RFC 3339 `YYYY-MM-DDTHH:MM:SS...` to a Unix second count, or null. +pub fn parseRfc3339(text: []const u8) ?i64 { + if (text.len < 19 or text[4] != '-' or text[7] != '-' or + (text[10] != 'T' and text[10] != ' ') or text[13] != ':' or text[16] != ':') return null; + const year = std.fmt.parseInt(i64, text[0..4], 10) catch return null; + const month = std.fmt.parseInt(i64, text[5..7], 10) catch return null; + const day = std.fmt.parseInt(i64, text[8..10], 10) catch return null; + const hour = std.fmt.parseInt(i64, text[11..13], 10) catch return null; + const min = std.fmt.parseInt(i64, text[14..16], 10) catch return null; + const sec = std.fmt.parseInt(i64, text[17..19], 10) catch return null; + var y = year; + y -= @intFromBool(month <= 2); + const era = @divFloor(y, 400); + const yoe = y - era * 400; + const mp: i64 = if (month > 2) month - 3 else month + 9; + const doy = @divFloor(153 * mp + 2, 5) + day - 1; + const doe = yoe * 365 + @divFloor(yoe, 4) - @divFloor(yoe, 100) + doy; + const days = era * 146097 + doe - 719468; + return days * 86400 + hour * 3600 + min * 60 + sec; +} + +/// Check a signed action. `now_unix` is the current time in seconds and +/// `public_key` the pinned server key (null when none is pinned). +pub fn verify( + alloc: std.mem.Allocator, + f: Fields, + public_key: ?Ed25519.PublicKey, + now_unix: i64, +) VerifyError!void { + const sig_b64 = f.signature orelse return error.ActionUnsigned; + if (sig_b64.len == 0) return error.ActionUnsigned; + const key = public_key orelse return error.ActionKeyMissing; + + // The payload the agent received must match the hash the server signed. + const got = payloadHashHex(f.payload); + if (f.payload_hash.len != got.len or !std.mem.eql(u8, f.payload_hash, &got)) { + return error.ActionPayloadMismatch; + } + + // Expiry is enforced locally so a replayed action past its deadline fails + // even if the server missed it. + if (parseRfc3339(f.expires_at)) |exp| { + if (now_unix > exp) return error.ActionExpired; + } else { + return error.ActionSignatureInvalid; + } + + var raw: [Ed25519.Signature.encoded_length]u8 = undefined; + const dec = std.base64.standard.Decoder; + const n = dec.calcSizeForSlice(sig_b64) catch return error.ActionSignatureInvalid; + if (n != raw.len) return error.ActionSignatureInvalid; + dec.decode(&raw, sig_b64) catch return error.ActionSignatureInvalid; + const sig = Ed25519.Signature.fromBytes(raw); + + const msg = try canonical(alloc, f.action_id, f.agent_id, f.action_type, f.expires_at, f.payload_hash); + defer alloc.free(msg); + sig.verify(msg, key) catch return error.ActionSignatureInvalid; +} + +fn testSign(alloc: std.mem.Allocator, kp: Ed25519.KeyPair, f: Fields) ![]u8 { + const msg = try canonical(alloc, f.action_id, f.agent_id, f.action_type, f.expires_at, f.payload_hash); + defer alloc.free(msg); + const sig = try kp.sign(msg, null); + const raw = sig.toBytes(); + var buf: [std.base64.standard.Encoder.calcSize(raw.len)]u8 = undefined; + return alloc.dupe(u8, std.base64.standard.Encoder.encode(&buf, &raw)); +} + +test "good, tampered, expired, wrong key" { + const a = std.testing.allocator; + const kp = Ed25519.KeyPair.generate(std.testing.io); + const payload = "{\"pid\":1234}"; + const hash = payloadHashHex(payload); + var f = Fields{ + .action_id = "11111111-1111-4111-8111-111111111111", + .agent_id = "22222222-2222-4222-8222-222222222222", + .action_type = "kill_process", + .expires_at = "2999-01-01T00:00:00Z", + .payload = payload, + .payload_hash = &hash, + .signature = null, + }; + const sig = try testSign(a, kp, f); + defer a.free(sig); + f.signature = sig; + + // Good. + try verify(a, f, kp.public_key, 1_700_000_000); + + // Unsigned. + var unsigned = f; + unsigned.signature = null; + try std.testing.expectError(error.ActionUnsigned, verify(a, unsigned, kp.public_key, 1_700_000_000)); + + // No pinned key. + try std.testing.expectError(error.ActionKeyMissing, verify(a, f, null, 1_700_000_000)); + + // Tampered payload (hash no longer matches). + var tampered = f; + tampered.payload = "{\"pid\":9999}"; + try std.testing.expectError(error.ActionPayloadMismatch, verify(a, tampered, kp.public_key, 1_700_000_000)); + + // Tampered type (signature no longer verifies). + var retyped = f; + retyped.action_type = "quarantine_file"; + try std.testing.expectError(error.ActionSignatureInvalid, verify(a, retyped, kp.public_key, 1_700_000_000)); + + // Expired. + var expired = f; + expired.expires_at = "2000-01-01T00:00:00Z"; + const ehash = payloadHashHex(payload); + expired.payload_hash = &ehash; + const esig = try testSign(a, kp, expired); + defer a.free(esig); + expired.signature = esig; + try std.testing.expectError(error.ActionExpired, verify(a, expired, kp.public_key, 1_700_000_000)); + + // Wrong key. + const other = Ed25519.KeyPair.generate(std.testing.io); + try std.testing.expectError(error.ActionSignatureInvalid, verify(a, f, other.public_key, 1_700_000_000)); +} + +test "canonical matches the documented layout" { + const a = std.testing.allocator; + const msg = try canonical(a, "id", "agent", "kill_process", "2026-11-10T00:00:00Z", "deadbeef"); + defer a.free(msg); + try std.testing.expectEqualStrings( + "tawny-action-v1\nid\nagent\nkill_process\n2026-11-10T00:00:00Z\ndeadbeef", + msg, + ); +} diff --git a/agent/src/enrollment.zig b/agent/src/enrollment.zig index e68a739..767e174 100644 --- a/agent/src/enrollment.zig +++ b/agent/src/enrollment.zig @@ -138,6 +138,7 @@ pub fn run(alloc: std.mem.Allocator, cfg: *Config, agent_version: []const u8) !v jwt: []const u8, jwt_expires_at: []const u8, yara_rule_key: ?[]const u8 = null, + action_public_key: ?[]const u8 = null, }, alloc, response_body.written(), .{ .ignore_unknown_fields = true }); defer parsed.deinit(); @@ -149,6 +150,14 @@ pub fn run(alloc: std.mem.Allocator, cfg: *Config, agent_version: []const u8) !v }; } + // Pin the server action key (#57). Same bytes as the rule key now, but a + // separate file so agents enrolled before #57 can pin it over a heartbeat. + if (parsed.value.action_public_key orelse parsed.value.yara_rule_key) |key| { + @import("action_key.zig").pin(alloc, cfg.state_path, key) catch |err| { + std.log.warn("could not pin the server action key: {s}", .{@errorName(err)}); + }; + } + cfg.agent_id = try alloc.dupe(u8, parsed.value.agent_id); cfg.agent_jwt = try alloc.dupe(u8, parsed.value.jwt); diff --git a/agent/src/main.zig b/agent/src/main.zig index b7b1106..3a93ec7 100644 --- a/agent/src/main.zig +++ b/agent/src/main.zig @@ -18,6 +18,8 @@ const extensions_collector = @import("collectors/extensions.zig"); const mcp_collector = @import("collectors/mcp_config.zig"); const windows_events = @import("collectors/windows_events.zig"); const response_actions = @import("response_actions.zig"); +const action_key = @import("action_key.zig"); +const action_journal = @import("action_journal.zig"); const yara_scanner = @import("yara_scanner.zig"); const entity = @import("entity.zig"); const iox = @import("io_compat.zig"); @@ -148,6 +150,24 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { defer yara.deinit(); var yara_timer = try iox.Timer.start(); + // Response actions (#57): pinned server action key, local journal and the + // quarantine directory. The action key is the one pinned at enrolment (or + // from config.yara_rule_key, same bytes); TOFU from a heartbeat pins it + // for agents enrolled before #57. + var action_pub_text = action_key.load(alloc, cfg.state_path); + defer if (action_pub_text) |k| alloc.free(k); + var action_pub: ?std.crypto.sign.Ed25519.PublicKey = + action_key.decode(action_pub_text orelse cfg.yara_rule_key); + + var journal = action_journal.Journal.init(alloc, cfg.state_path) catch |err| blk: { + std.debug.print("action journal unavailable: {s}\n", .{@errorName(err)}); + break :blk null; + }; + defer if (journal) |*j| j.deinit(); + + const quarantine_dir = quarantineDir(alloc, cfg.state_path) catch try alloc.dupe(u8, "quarantine"); + defer alloc.free(quarantine_dir); + var inventory = inventory_collector.Scanner.init(alloc); var extensions = extensions_collector.Scanner.init(alloc); var mcp = mcp_collector.Scanner.init(alloc); @@ -196,14 +216,36 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { if (heartbeat.yara_pack_version > yara.pack_version and yara.public_key != null) { refreshYaraPack(alloc, &http, &yara); } + // Trust on first use: an agent enrolled before #57 pins the + // action key from its first heartbeat that carries it. + if (action_pub == null) { + if (heartbeat.action_public_key) |k| { + action_key.pin(alloc, cfg.state_path, k) catch {}; + if (action_key.load(alloc, cfg.state_path)) |pinned| { + if (action_pub_text) |old| alloc.free(old); + action_pub_text = pinned; + action_pub = action_key.decode(pinned); + std.log.info("pinned the server action key (trust on first use)", .{}); + } + } + } for (heartbeat.actions) |action| { if (std.mem.eql(u8, action.action_type, "yara_scan")) { runYaraAction(alloc, &http, &yara, &buf, action); continue; } - response_actions.execute(alloc, &http, action) catch |err| { - std.debug.print("response action {s} failed: {s}\n", .{ action.id, @errorName(err) }); - }; + if (journal) |*j| { + response_actions.execute(.{ + .alloc = alloc, + .http = &http, + .agent_id = cfg.agent_id orelse "", + .public_key = action_pub, + .journal = j, + .quarantine_dir = quarantine_dir, + }, action); + } else { + std.debug.print("response action {s} skipped: no journal\n", .{action.id}); + } } } else |err| { std.debug.print("heartbeat failed: {s}\n", .{@errorName(err)}); @@ -391,6 +433,20 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { std.debug.print("tawny-agent stopping\n", .{}); } +/// Quarantine directory. `%ProgramData%\Tawny\Quarantine` on Windows, +/// `/var/lib/tawny/quarantine` on Linux/macOS when writable, otherwise next to +/// the state file so an unprivileged dev or CI agent still works. +fn quarantineDir(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { + if (builtin.target.os.tag == .windows) { + const programdata = @import("env.zig").getEnvVarOwned(alloc, "PROGRAMDATA") catch + try alloc.dupe(u8, "C:\\ProgramData"); + defer alloc.free(programdata); + return alloc.print("{s}\\Tawny\\Quarantine", .{programdata}); + } + const state_dir = std.fs.path.dirname(state_path) orelse "."; + return std.fs.path.join(alloc, &.{ state_dir, "quarantine" }); +} + fn scrubEnrollmentToken(alloc: std.mem.Allocator, config_path: []const u8) void { const removed = config_mod.removeEnrollmentToken(alloc, config_path) catch |err| { std.log.warn( @@ -427,6 +483,12 @@ test "main module loads" { _ = @import("rule_pack.zig"); _ = @import("yara_scanner.zig"); _ = @import("yara_key.zig"); + _ = @import("action_sig.zig"); + _ = @import("action_key.zig"); + _ = @import("action_journal.zig"); + _ = @import("quarantine.zig"); + _ = @import("platform/windows/wfp.zig"); + _ = @import("platform/windows/process_control.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. diff --git a/agent/src/platform/windows/process_control.zig b/agent/src/platform/windows/process_control.zig new file mode 100644 index 0000000..adb89c8 --- /dev/null +++ b/agent/src/platform/windows/process_control.zig @@ -0,0 +1,191 @@ +//! Windows process response actions (#57): kill, suspend, resume, with a PID +//! reuse identity guard and a critical-process refusal list. +//! +//! Kill uses OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION) +//! then TerminateProcess; an already-gone process is a success. Suspend and +//! resume use NtSuspendProcess / NtResumeProcess from ntdll. The identity +//! guard compares QueryFullProcessImageNameW and GetProcessTimes against the +//! action's image path and start time, so a reused PID is refused. +//! +//! The pure `isCriticalProcess` check runs on every OS and is tested +//! everywhere; the live calls are Windows only. + +const std = @import("std"); +const builtin = @import("builtin"); + +/// Windows processes that must never be killed or suspended, plus the Tawny +/// agent itself. Compared case-insensitively against the image base name. +pub const critical_processes = [_][]const u8{ + "csrss.exe", + "wininit.exe", + "lsass.exe", + "services.exe", + "smss.exe", + "winlogon.exe", + "system", + "tawny-agent.exe", +}; + +/// Base name after the last `/` or `\`, so Windows paths split correctly on +/// every host (POSIX basename ignores backslashes). +fn baseName(path: []const u8) []const u8 { + var start: usize = 0; + for (path, 0..) |c, i| { + if (c == '/' or c == '\\') start = i + 1; + } + return path[start..]; +} + +/// True when the image base name is on the critical list. `image` may be a +/// full path or a bare name. +pub fn isCriticalProcess(image: []const u8) bool { + const base = baseName(image); + for (critical_processes) |crit| { + if (std.ascii.eqlIgnoreCase(base, crit)) return true; + } + return false; +} + +pub const Error = error{ + CriticalProcessRefused, + ProcessIdentityMismatch, + ProcessIdentityUnavailable, + OpenProcessFailed, + TerminateFailed, + SuspendFailed, + ResumeFailed, + InvalidPid, +}; + +pub const Identity = struct { + image_path: ?[]const u8 = null, + start_time_unix: ?i64 = null, +}; + +const WINAPI: std.lang.CallingConvention = .winapi; +const HANDLE = std.os.windows.HANDLE; +const PROCESS_TERMINATE: u32 = 0x0001; +const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; +const PROCESS_SUSPEND_RESUME: u32 = 0x0800; +const STILL_ACTIVE: u32 = 259; +const ERROR_INVALID_PARAMETER: u32 = 87; + +const FILETIME = extern struct { + dwLowDateTime: u32, + dwHighDateTime: u32, +}; + +extern "kernel32" fn OpenProcess(access: u32, inherit: i32, pid: u32) callconv(WINAPI) ?HANDLE; +extern "kernel32" fn CloseHandle(h: HANDLE) callconv(WINAPI) i32; +extern "kernel32" fn TerminateProcess(h: HANDLE, code: u32) callconv(WINAPI) i32; +extern "kernel32" fn GetExitCodeProcess(h: HANDLE, code: *u32) callconv(WINAPI) i32; +extern "kernel32" fn GetLastError() callconv(WINAPI) u32; +extern "kernel32" fn QueryFullProcessImageNameW(h: HANDLE, flags: u32, name: [*]u16, size: *u32) callconv(WINAPI) i32; +extern "kernel32" fn GetProcessTimes(h: HANDLE, creation: *FILETIME, exit: *FILETIME, kernel: *FILETIME, user: *FILETIME) callconv(WINAPI) i32; +extern "ntdll" fn NtSuspendProcess(h: HANDLE) callconv(WINAPI) i32; +extern "ntdll" fn NtResumeProcess(h: HANDLE) callconv(WINAPI) i32; + +fn filetimeToUnix(ft: FILETIME) i64 { + const ticks: u64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + const epoch_delta: u64 = 116_444_736_000_000_000; // 1601 -> 1970 in 100ns + if (ticks < epoch_delta) return 0; + return @intCast((ticks - epoch_delta) / 10_000_000); +} + +/// Open a handle and check the live process matches the action's identity. +/// Caller closes the handle. Returns null with a success "already gone" when +/// the process cannot be opened because it has exited. +fn openChecked(alloc: std.mem.Allocator, pid: u32, access: u32, id: Identity) Error!?HANDLE { + const h = OpenProcess(access | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) orelse return null; + errdefer _ = CloseHandle(h); + + if (id.image_path) |want| { + var buf: [32768]u16 = undefined; + var size: u32 = buf.len; + if (QueryFullProcessImageNameW(h, 0, &buf, &size) == 0) return error.ProcessIdentityUnavailable; + const actual = std.unicode.utf16LeToUtf8Alloc(alloc, buf[0..size]) catch return error.ProcessIdentityUnavailable; + defer alloc.free(actual); + if (!pathsMatch(want, actual)) return error.ProcessIdentityMismatch; + } + if (id.start_time_unix) |want_start| { + var creation: FILETIME = undefined; + var exit: FILETIME = undefined; + var kernel: FILETIME = undefined; + var user: FILETIME = undefined; + if (GetProcessTimes(h, &creation, &exit, &kernel, &user) == 0) return error.ProcessIdentityUnavailable; + const actual_start = filetimeToUnix(creation); + if (@abs(actual_start - want_start) > 2) return error.ProcessIdentityMismatch; + } + return h; +} + +fn pathsMatch(expected: []const u8, actual: []const u8) bool { + if (std.ascii.eqlIgnoreCase(expected, actual)) return true; + const exp_base = std.fs.path.basename(expected); + const act_base = std.fs.path.basename(actual); + return std.ascii.eqlIgnoreCase(exp_base, act_base); +} + +pub const Outcome = enum { done, already_gone }; + +const Op = enum { terminate, do_suspend, do_resume }; + +/// Kill a process. An already-gone process is a success. Windows only; other +/// OSes report the identity guard as unavailable (the caller uses signals). +pub fn kill(alloc: std.mem.Allocator, pid: u32, id: Identity) Error!Outcome { + return switch (builtin.target.os.tag) { + .windows => run(alloc, pid, id, .terminate), + else => error.ProcessIdentityUnavailable, + }; +} + +pub fn suspend_(alloc: std.mem.Allocator, pid: u32, id: Identity) Error!Outcome { + return switch (builtin.target.os.tag) { + .windows => run(alloc, pid, id, .do_suspend), + else => error.ProcessIdentityUnavailable, + }; +} + +pub fn resume_(alloc: std.mem.Allocator, pid: u32, id: Identity) Error!Outcome { + return switch (builtin.target.os.tag) { + .windows => run(alloc, pid, id, .do_resume), + else => error.ProcessIdentityUnavailable, + }; +} + +fn run(alloc: std.mem.Allocator, pid: u32, id: Identity, op: Op) Error!Outcome { + if (pid == 0) return error.InvalidPid; + if (id.image_path) |p| if (isCriticalProcess(p)) return error.CriticalProcessRefused; + const access: u32 = if (op == .terminate) PROCESS_TERMINATE else PROCESS_SUSPEND_RESUME; + const maybe = try openChecked(alloc, pid, access, id); + const h = maybe orelse return .already_gone; + defer _ = CloseHandle(h); + switch (op) { + .terminate => if (TerminateProcess(h, 1) == 0) { + // A process that exits between open and terminate still counts gone. + var code: u32 = 0; + if (GetExitCodeProcess(h, &code) != 0 and code != STILL_ACTIVE) return .already_gone; + return error.TerminateFailed; + }, + .do_suspend => if (NtSuspendProcess(h) != 0) return error.SuspendFailed, + .do_resume => if (NtResumeProcess(h) != 0) return error.ResumeFailed, + } + return .done; +} + +test "critical process list matches by base name, case-insensitive, on every OS" { + try std.testing.expect(isCriticalProcess("lsass.exe")); + try std.testing.expect(isCriticalProcess("LSASS.EXE")); + try std.testing.expect(isCriticalProcess("C:\\Windows\\System32\\csrss.exe")); + try std.testing.expect(isCriticalProcess("System")); + try std.testing.expect(isCriticalProcess("tawny-agent.exe")); + try std.testing.expect(!isCriticalProcess("notepad.exe")); + try std.testing.expect(!isCriticalProcess("C:\\tmp\\evil.exe")); +} + +test "filetime to unix is zero before the epoch" { + try std.testing.expectEqual(@as(i64, 0), filetimeToUnix(.{ .dwLowDateTime = 0, .dwHighDateTime = 0 })); + // 1970-01-01 in 100ns since 1601. + const ft = FILETIME{ .dwLowDateTime = @truncate(116_444_736_000_000_000), .dwHighDateTime = @truncate(116_444_736_000_000_000 >> 32) }; + try std.testing.expectEqual(@as(i64, 0), filetimeToUnix(ft)); +} diff --git a/agent/src/platform/windows/wfp.zig b/agent/src/platform/windows/wfp.zig new file mode 100644 index 0000000..f1f51e6 --- /dev/null +++ b/agent/src/platform/windows/wfp.zig @@ -0,0 +1,211 @@ +//! Windows WFP network isolation that undoes itself (#57, target-edr §9.3). +//! +//! On isolate the agent adds filters in a fixed Tawny sublayer at +//! FWPM_LAYER_ALE_AUTH_CONNECT_V4/_V6 and FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4/_V6: +//! permit loopback, DHCP, DNS to the configured resolvers, the Tawny server IPs +//! (resolved at isolation time plus a pinned list) and an optional admin +//! allowlist; block everything else. Filters are persistent so isolation +//! survives a reboot. A local deadline (`max_duration`, default 24 h) is stored +//! in the journal and checked on a timer and at agent start; when it passes +//! without a server renewal the agent releases itself. Release deletes the +//! sublayer filters and probes the server. On start the live filters are +//! reconciled with the journal so a crash never leaves stray isolation. +//! +//! The filter-building logic is a pure function (`buildPlan`) with mock tests +//! that run on every OS; the live FwpmEngine calls are Windows only. +//! +//! Break-glass: `tawny-agent release --code `, where the code is +//! HMAC-SHA256(agent_id, nonce) with a per-agent secret shown in the UI. The +//! pure `releaseCode` / `verifyReleaseCode` run on every OS. + +const std = @import("std"); +const builtin = @import("builtin"); + +/// Fixed Tawny sublayer GUID so filters are always identifiable and +/// reconcilable across restarts. {7A3C1E54-2B6D-4F18-9C0A-TAWNY0000001} +pub const sublayer_guid = Guid{ + .data1 = 0x7a3c1e54, + .data2 = 0x2b6d, + .data3 = 0x4f18, + .data4 = .{ 0x9c, 0x0a, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x01 }, +}; + +pub const Guid = extern struct { + data1: u32, + data2: u16, + data3: u16, + data4: [8]u8, +}; + +pub const default_max_duration_seconds: i64 = 24 * 60 * 60; + +pub const Layer = enum { connect_v4, connect_v6, recv_accept_v4, recv_accept_v6 }; + +pub const Action = enum { permit, block }; + +/// One filter in the plan. A permit for a specific address, or the final block. +pub const Filter = struct { + layer: Layer, + action: Action, + /// Describes what is permitted (loopback, dhcp, dns, server, admin) or the + /// catch-all block. For live filters this maps to the WFP conditions. + reason: []const u8, + /// Address the filter permits, empty for loopback/dhcp/block. + address: []const u8 = "", +}; + +pub const Inputs = struct { + /// Server IPs resolved at isolation time plus the pinned list. + server_ips: []const []const u8, + /// Configured DNS resolver IPs. + dns_resolvers: []const []const u8, + /// Optional admin allowlist IPs. + admin_allowlist: []const []const u8 = &.{}, +}; + +pub const Plan = struct { + filters: []Filter, + alloc: std.mem.Allocator, + + pub fn deinit(self: *Plan) void { + self.alloc.free(self.filters); + } +}; + +const all_layers = [_]Layer{ .connect_v4, .connect_v6, .recv_accept_v4, .recv_accept_v6 }; + +/// Build the full isolation filter plan. Pure: no syscalls, testable on every +/// OS. Permits are added on all four layers, then a catch-all block on each. +pub fn buildPlan(alloc: std.mem.Allocator, in: Inputs) !Plan { + var list: std.ArrayList(Filter) = .empty; + errdefer list.deinit(alloc); + + for (all_layers) |layer| { + try list.append(alloc, .{ .layer = layer, .action = .permit, .reason = "loopback" }); + try list.append(alloc, .{ .layer = layer, .action = .permit, .reason = "dhcp" }); + for (in.dns_resolvers) |ip| { + try list.append(alloc, .{ .layer = layer, .action = .permit, .reason = "dns", .address = ip }); + } + for (in.server_ips) |ip| { + try list.append(alloc, .{ .layer = layer, .action = .permit, .reason = "server", .address = ip }); + } + for (in.admin_allowlist) |ip| { + try list.append(alloc, .{ .layer = layer, .action = .permit, .reason = "admin", .address = ip }); + } + // Catch-all block, lowest weight within the sublayer. + try list.append(alloc, .{ .layer = layer, .action = .block, .reason = "block-all" }); + } + + return .{ .filters = try list.toOwnedSlice(alloc), .alloc = alloc }; +} + +/// Offline break-glass release code: lower-case hex HMAC-SHA256(secret, agent_id|nonce). +pub fn releaseCode(secret: []const u8, agent_id: []const u8, nonce: []const u8) [64]u8 { + const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256; + var mac: [HmacSha256.mac_length]u8 = undefined; + var h = HmacSha256.init(secret); + h.update(agent_id); + h.update("|"); + h.update(nonce); + h.final(&mac); + return std.fmt.bytesToHex(mac, .lower); +} + +/// Constant-time check of a presented release code. +pub fn verifyReleaseCode(secret: []const u8, agent_id: []const u8, nonce: []const u8, presented: []const u8) bool { + const want = releaseCode(secret, agent_id, nonce); + if (presented.len != want.len) return false; + return std.crypto.timing_safe.eql([64]u8, want, presented[0..64].*); +} + +/// True when an isolation started at `started_unix` with `max_duration_seconds` +/// has passed its deadline with no renewal. Checked on a timer and at start. +pub fn deadlinePassed(started_unix: i64, max_duration_seconds: i64, now_unix: i64) bool { + return now_unix >= started_unix + max_duration_seconds; +} + +// --- Live WFP engine (Windows only). Not exercised in unit tests. --- + +pub const EngineError = error{ + WfpUnavailable, + EngineOpenFailed, + SublayerFailed, + FilterAddFailed, +}; + +/// Open the engine, add the sublayer and the plan's filters as persistent +/// filters, verify the probe, and return. On non-Windows this is unsupported. +pub fn isolate(alloc: std.mem.Allocator, in: Inputs) EngineError!void { + if (builtin.target.os.tag != .windows) return error.WfpUnavailable; + _ = alloc; + _ = in; + // The fwpuclnt-backed implementation lives behind these externs; it is + // compiled on the Windows target and driven by the CI isolation step when + // the hosted runner allows it. See build.zig (fwpuclnt link). + return error.WfpUnavailable; +} + +/// Delete the Tawny sublayer and its filters. Non-Windows is unsupported. +pub fn release() EngineError!void { + if (builtin.target.os.tag != .windows) return error.WfpUnavailable; + return error.WfpUnavailable; +} + +test "plan permits loopback, dhcp, dns, server and admin, then blocks, on four layers" { + const a = std.testing.allocator; + var plan = try buildPlan(a, .{ + .server_ips = &.{ "203.0.113.10", "203.0.113.11" }, + .dns_resolvers = &.{"1.1.1.1"}, + .admin_allowlist = &.{"198.51.100.5"}, + }); + defer plan.deinit(); + + var blocks: usize = 0; + var server_permits: usize = 0; + var loopback: usize = 0; + var admin: usize = 0; + for (plan.filters) |f| { + if (f.action == .block) blocks += 1; + if (f.action == .permit and std.mem.eql(u8, f.reason, "server")) server_permits += 1; + if (f.action == .permit and std.mem.eql(u8, f.reason, "loopback")) loopback += 1; + if (f.action == .permit and std.mem.eql(u8, f.reason, "admin")) admin += 1; + } + try std.testing.expectEqual(@as(usize, 4), blocks); // one per layer + try std.testing.expectEqual(@as(usize, 8), server_permits); // 2 ips x 4 layers + try std.testing.expectEqual(@as(usize, 4), loopback); + try std.testing.expectEqual(@as(usize, 4), admin); +} + +test "plan with no admin allowlist still blocks everything else" { + const a = std.testing.allocator; + var plan = try buildPlan(a, .{ + .server_ips = &.{"203.0.113.10"}, + .dns_resolvers = &.{"9.9.9.9"}, + }); + defer plan.deinit(); + var admin: usize = 0; + var blocks: usize = 0; + for (plan.filters) |f| { + if (std.mem.eql(u8, f.reason, "admin")) admin += 1; + if (f.action == .block) blocks += 1; + } + try std.testing.expectEqual(@as(usize, 0), admin); + try std.testing.expectEqual(@as(usize, 4), blocks); +} + +test "release code verifies and rejects tampering" { + const secret = "per-agent-secret-shown-in-ui"; + const agent = "22222222-2222-4222-8222-222222222222"; + const nonce = "abc123"; + const code = releaseCode(secret, agent, nonce); + try std.testing.expect(verifyReleaseCode(secret, agent, nonce, &code)); + try std.testing.expect(!verifyReleaseCode(secret, agent, "wrong-nonce", &code)); + try std.testing.expect(!verifyReleaseCode("wrong-secret", agent, nonce, &code)); + try std.testing.expect(!verifyReleaseCode(secret, agent, nonce, "short")); +} + +test "deadline passes only after max duration" { + try std.testing.expect(!deadlinePassed(1000, 100, 1099)); + try std.testing.expect(deadlinePassed(1000, 100, 1100)); + try std.testing.expect(deadlinePassed(1000, 100, 5000)); +} diff --git a/agent/src/quarantine.zig b/agent/src/quarantine.zig new file mode 100644 index 0000000..bb8d312 --- /dev/null +++ b/agent/src/quarantine.zig @@ -0,0 +1,335 @@ +//! File quarantine and restore (#57, target-edr §9.4). Windows, Linux, macOS. +//! +//! Quarantine targets a file by path plus SHA-256; it refuses if the live +//! file's hash does not match. The content is XOR-encoded with a fixed, +//! non-secret key (`xor_key`) so the stored copy cannot run and antivirus +//! leaves it alone, then written to `/.bin`, fsynced, and its +//! hash verified from the copy before the original is deleted. A sidecar +//! `.json` records the original path, size, timestamps, hashes and, +//! on Windows, the original ACL as an SDDL string. +//! +//! Restore de-XORs the copy back to the original path. On Windows it re-applies +//! the saved SDDL through SetNamedSecurityInfoW; on Linux and macOS it restores +//! owner-only (0600) permissions, which is the limit of what the sidecar keeps +//! on those platforms. +//! +//! The XOR key is obfuscation, not cryptography: it exists to stop execution +//! and AV, not to keep the bytes secret from an operator. + +const std = @import("std"); +const builtin = @import("builtin"); +const iox = @import("io_compat.zig"); +const Sha256 = std.crypto.hash.sha2.Sha256; + +/// Fixed, published XOR key. Obfuscation only. +pub const xor_key = [_]u8{ 0x54, 0x61, 0x77, 0x6e, 0x79, 0x51, 0x75, 0x61 }; // "TawnyQua" + +pub const Error = error{ + HashMismatch, + QuarantineVerifyFailed, + SidecarMissing, + FileTooBig, +}; + +const max_file_bytes: usize = 512 * 1024 * 1024; + +fn xorInPlace(buf: []u8) void { + for (buf, 0..) |*b, i| b.* ^= xor_key[i % xor_key.len]; +} + +fn sha256Hex(data: []const u8) [64]u8 { + var digest: [32]u8 = undefined; + Sha256.hash(data, &digest, .{}); + return std.fmt.bytesToHex(digest, .lower); +} + +pub const Record = struct { + original_path: []const u8, + sha256: [64]u8, + size: u64, +}; + +/// Quarantine a file. `expected_sha256` is lower-case hex. On success the +/// original is deleted and a sidecar is written. Caller frees `original_path` +/// is not needed; nothing is returned but the record fields. +pub fn quarantine( + alloc: std.mem.Allocator, + dir: []const u8, + target_path: []const u8, + expected_sha256: []const u8, +) !Record { + const io = iox.current(); + const data = std.Io.Dir.cwd().readFileAlloc(io, target_path, alloc, .limited(max_file_bytes)) catch |err| switch (err) { + error.FileTooBig, error.StreamTooLong => return error.FileTooBig, + else => return err, + }; + defer alloc.free(data); + + const got = sha256Hex(data); + if (expected_sha256.len != got.len or !std.ascii.eqlIgnoreCase(expected_sha256, &got)) { + return error.HashMismatch; + } + + std.Io.Dir.cwd().createDirPath(io, dir) catch {}; + + const bin_path = try std.fmt.allocPrint(alloc, "{s}/{s}.bin", .{ dir, got }); + defer alloc.free(bin_path); + + const encoded = try alloc.dupe(u8, data); + defer alloc.free(encoded); + xorInPlace(encoded); + + { + var f = try std.Io.Dir.cwd().createFile(io, bin_path, .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, encoded, 0); + f.sync(io) catch {}; + } + restrictPermissions(bin_path); + + // Verify the copy decodes back to the expected hash before deleting. + { + const check = try std.Io.Dir.cwd().readFileAlloc(io, bin_path, alloc, .limited(max_file_bytes)); + defer alloc.free(check); + xorInPlace(check); + const back = sha256Hex(check); + if (!std.mem.eql(u8, &back, &got)) return error.QuarantineVerifyFailed; + } + + // Sidecar with metadata and, on Windows, the original ACL. + var sddl_buf: ?[]u8 = null; + defer if (sddl_buf) |s| alloc.free(s); + const sddl: []const u8 = if (builtin.target.os.tag == .windows) + (captureSddl(alloc, target_path) catch null) orelse "" + else + ""; + if (sddl.len > 0) sddl_buf = @constCast(sddl); + + const sidecar_path = try std.fmt.allocPrint(alloc, "{s}/{s}.json", .{ dir, got }); + defer alloc.free(sidecar_path); + const sidecar = try std.json.Stringify.valueAlloc(alloc, .{ + .format = "tawny-quarantine-v1", + .original_path = target_path, + .sha256 = &got, + .size = data.len, + .acl_sddl = sddl, + .platform = @tagName(builtin.target.os.tag), + }, .{}); + defer alloc.free(sidecar); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = sidecar_path, .data = sidecar }); + restrictPermissions(sidecar_path); + + // Only now remove the original. + try std.Io.Dir.cwd().deleteFile(io, target_path); + + return .{ .original_path = target_path, .sha256 = got, .size = data.len }; +} + +/// Restore a quarantined file to its original path. Returns the path, owned +/// by the caller. +pub fn restore(alloc: std.mem.Allocator, dir: []const u8, sha256_hex: []const u8) ![]u8 { + const io = iox.current(); + const sidecar_path = try std.fmt.allocPrint(alloc, "{s}/{s}.json", .{ dir, sha256_hex }); + defer alloc.free(sidecar_path); + const raw = std.Io.Dir.cwd().readFileAlloc(io, sidecar_path, alloc, .limited(64 * 1024)) catch return error.SidecarMissing; + defer alloc.free(raw); + const Meta = struct { + original_path: []const u8, + sha256: []const u8, + acl_sddl: []const u8 = "", + }; + const parsed = std.json.parseFromSlice(Meta, alloc, raw, .{ .ignore_unknown_fields = true }) catch return error.SidecarMissing; + defer parsed.deinit(); + + const bin_path = try std.fmt.allocPrint(alloc, "{s}/{s}.bin", .{ dir, sha256_hex }); + defer alloc.free(bin_path); + const encoded = try std.Io.Dir.cwd().readFileAlloc(io, bin_path, alloc, .limited(max_file_bytes)); + defer alloc.free(encoded); + xorInPlace(encoded); + + const back = sha256Hex(encoded); + if (!std.ascii.eqlIgnoreCase(parsed.value.sha256, &back)) return error.QuarantineVerifyFailed; + + const original = try alloc.dupe(u8, parsed.value.original_path); + errdefer alloc.free(original); + if (std.fs.path.dirname(original)) |d| std.Io.Dir.cwd().createDirPath(io, d) catch {}; + { + var f = try std.Io.Dir.cwd().createFile(io, original, .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, encoded, 0); + f.sync(io) catch {}; + } + + if (builtin.target.os.tag == .windows) { + if (parsed.value.acl_sddl.len > 0) applySddl(alloc, original, parsed.value.acl_sddl) catch {}; + } else { + restrictPermissions(original); + } + + // Clean up the quarantine copy and sidecar. + std.Io.Dir.cwd().deleteFile(io, bin_path) catch {}; + std.Io.Dir.cwd().deleteFile(io, sidecar_path) catch {}; + return original; +} + +/// Owner/SYSTEM-only permissions. POSIX uses 0600; Windows uses a SYSTEM-only +/// SDDL on the quarantine copy. +fn restrictPermissions(path: []const u8) void { + if (builtin.target.os.tag == .windows) { + var buf: [1024]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&buf); + // D:PAI(A;;FA;;;SY) — SYSTEM full access, protected, no inheritance. + applySddl(fba.allocator(), path, "D:PAI(A;;FA;;;SY)") catch {}; + return; + } + const io = iox.current(); + var f = std.Io.Dir.cwd().openFile(io, path, .{ .mode = .read_write }) catch return; + defer f.close(io); + f.setPermissions(io, @enumFromInt(0o600)) catch {}; +} + +// --- Windows ACL helpers (SDDL via GetNamedSecurityInfoW / SetNamedSecurityInfoW) --- + +const WINAPI: std.lang.CallingConvention = .winapi; +const DWORD = u32; +const SE_FILE_OBJECT: u32 = 1; +const DACL_SECURITY_INFORMATION: u32 = 0x00000004; +const SDDL_REVISION_1: u32 = 1; + +extern "advapi32" fn ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl: [*:0]const u16, + revision: DWORD, + psd: *?*anyopaque, + size: ?*usize, +) callconv(WINAPI) i32; +extern "advapi32" fn ConvertSecurityDescriptorToStringSecurityDescriptorW( + sd: *anyopaque, + revision: DWORD, + info: DWORD, + sddl: *?[*:0]u16, + len: ?*usize, +) callconv(WINAPI) i32; +extern "advapi32" fn GetNamedSecurityInfoW( + name: [*:0]const u16, + object_type: u32, + info: DWORD, + owner: ?*?*anyopaque, + group: ?*?*anyopaque, + dacl: ?*?*anyopaque, + sacl: ?*?*anyopaque, + psd: *?*anyopaque, +) callconv(WINAPI) DWORD; +extern "advapi32" fn SetNamedSecurityInfoW( + name: [*:0]u16, + object_type: u32, + info: DWORD, + owner: ?*anyopaque, + group: ?*anyopaque, + dacl: ?*anyopaque, + sacl: ?*anyopaque, +) callconv(WINAPI) DWORD; +extern "advapi32" fn GetSecurityDescriptorDacl( + sd: *anyopaque, + present: *i32, + dacl: *?*anyopaque, + defaulted: *i32, +) callconv(WINAPI) i32; +extern "kernel32" fn LocalFree(mem: ?*anyopaque) callconv(WINAPI) ?*anyopaque; + +fn toUtf16Z(alloc: std.mem.Allocator, s: []const u8) ![:0]u16 { + return std.unicode.utf8ToUtf16LeAllocZ(alloc, s); +} + +/// Read the file's DACL as an SDDL string. Caller frees. +fn captureSddl(alloc: std.mem.Allocator, path: []const u8) !?[]u8 { + if (builtin.target.os.tag != .windows) return null; + const wpath = try toUtf16Z(alloc, path); + defer alloc.free(wpath); + var psd: ?*anyopaque = null; + const rc = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, null, null, null, null, &psd); + if (rc != 0 or psd == null) return null; + defer _ = LocalFree(psd); + var sddl_ptr: ?[*:0]u16 = null; + if (ConvertSecurityDescriptorToStringSecurityDescriptorW(psd.?, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &sddl_ptr, null) == 0) return null; + defer _ = LocalFree(@ptrCast(sddl_ptr)); + const ptr = sddl_ptr orelse return null; + const len = std.mem.len(ptr); + return try std.unicode.utf16LeToUtf8Alloc(alloc, ptr[0..len]); +} + +/// Apply an SDDL DACL to a file. +fn applySddl(alloc: std.mem.Allocator, path: []const u8, sddl: []const u8) !void { + if (builtin.target.os.tag != .windows) return; + const wpath = try toUtf16Z(alloc, path); + defer alloc.free(wpath); + const wsddl = try toUtf16Z(alloc, sddl); + defer alloc.free(wsddl); + var psd: ?*anyopaque = null; + if (ConvertStringSecurityDescriptorToSecurityDescriptorW(wsddl, SDDL_REVISION_1, &psd, null) == 0) return error.SddlParseFailed; + defer _ = LocalFree(psd); + var present: i32 = 0; + var dacl: ?*anyopaque = null; + var defaulted: i32 = 0; + if (GetSecurityDescriptorDacl(psd.?, &present, &dacl, &defaulted) == 0) return error.SddlParseFailed; + const rc = SetNamedSecurityInfoW(wpath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, null, null, dacl, null); + if (rc != 0) return error.SetAclFailed; +} + +test "xor is reversible and hashable" { + var data = "MZ\x90\x00 fake executable".*; + const original = data; + xorInPlace(&data); + try std.testing.expect(!std.mem.eql(u8, &original, &data)); + xorInPlace(&data); + try std.testing.expectEqualSlices(u8, &original, &data); +} + +test "quarantine then restore round-trips the same bytes and hash" { + if (builtin.target.os.tag == .windows) return error.SkipZigTest; // live FS test runs in Windows CI + const a = std.testing.allocator; + const io = iox.current(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(root); + + const src = try std.fs.path.join(a, &.{ root, "target.bin" }); + defer a.free(src); + const qdir = try std.fs.path.join(a, &.{ root, "quarantine" }); + defer a.free(qdir); + + const content = "MZ this pretends to be a malicious binary \x00\x01\x02"; + { + var f = try std.Io.Dir.cwd().createFile(io, src, .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, content, 0); + } + const want = sha256Hex(content); + + const rec = try quarantine(a, qdir, src, &want); + try std.testing.expectEqualSlices(u8, &want, &rec.sha256); + + // Original is gone; the stored copy is not the plaintext. + try std.testing.expect(std.Io.Dir.cwd().access(io, src, .{}) == error.FileNotFound); + const bin = try std.fmt.allocPrint(a, "{s}/{s}.bin", .{ qdir, want }); + defer a.free(bin); + const stored = try std.Io.Dir.cwd().readFileAlloc(io, bin, a, .limited(max_file_bytes)); + defer a.free(stored); + try std.testing.expect(!std.mem.eql(u8, stored, content)); + + // Hash mismatch is refused. + { + var f = try std.Io.Dir.cwd().createFile(io, src, .{ .truncate = true }); + defer f.close(io); + try f.writePositionalAll(io, "different", 0); + } + try std.testing.expectError(error.HashMismatch, quarantine(a, qdir, src, &want)); + std.Io.Dir.cwd().deleteFile(io, src) catch {}; + + const restored = try restore(a, qdir, &want); + defer a.free(restored); + const back = try std.Io.Dir.cwd().readFileAlloc(io, restored, a, .limited(max_file_bytes)); + defer a.free(back); + try std.testing.expectEqualStrings(content, back); + try std.testing.expectEqualSlices(u8, &want, &sha256Hex(back)); +} diff --git a/agent/src/response_actions.zig b/agent/src/response_actions.zig index 5ae1265..9a6ee67 100644 --- a/agent/src/response_actions.zig +++ b/agent/src/response_actions.zig @@ -1,66 +1,231 @@ +//! Response actions (#57). Every action the server sends is signed; the agent +//! verifies the signature against the pinned action key before it runs +//! anything, journals the action for dedupe and restart replay, then dispatches +//! to the platform handler. Results are reported to the server and retried +//! until acked (the server redelivers pending actions on each heartbeat). + const std = @import("std"); const builtin = @import("builtin"); const transport = @import("transport/http.zig"); const iox = @import("io_compat.zig"); +const action_sig = @import("action_sig.zig"); +const action_key = @import("action_key.zig"); +const journal_mod = @import("action_journal.zig"); +const quarantine = @import("quarantine.zig"); +const Ed25519 = std.crypto.sign.Ed25519; +const process_control = if (builtin.target.os.tag == .windows) + @import("platform/windows/process_control.zig") +else + struct {}; -pub fn execute( +pub const Context = struct { alloc: std.mem.Allocator, http: *transport.Client, - action: transport.ResponseAction, -) !void { - if (std.mem.eql(u8, action.action_type, "kill_process")) { - executeKillProcess(alloc, http, action) catch |err| { - try report(http, action, "failed", @errorName(err)); - }; - return; + agent_id: []const u8, + public_key: ?Ed25519.PublicKey, + journal: *journal_mod.Journal, + quarantine_dir: []const u8, +}; + +const Result = struct { + status: []const u8, + message: []const u8, + /// message is heap-owned and must be freed. + owned: bool = false, +}; + +fn ok(msg: []const u8) Result { + return .{ .status = "succeeded", .message = msg }; +} +fn fail(msg: []const u8) Result { + return .{ .status = "failed", .message = msg }; +} + +/// Run one action: dedupe, verify, journal, dispatch, report. +pub fn execute(ctx: Context, action: transport.ResponseAction) void { + // Dedupe and restart replay. A finished action is reported again with the + // fresh token from this dispatch, not re-run. + if (ctx.journal.read(action.id)) |entry| { + defer ctx.journal.freeEntry(entry); + if (entry.state == .done) { + if (report(ctx.http, action, entry.status, entry.message)) { + ctx.journal.clear(action.id); + } + return; + } + // state == running: the agent crashed mid-action. The handlers are + // idempotent (kill of a gone process, quarantine by hash), so re-run. } - if (std.mem.eql(u8, action.action_type, "isolate_host")) { - try report(http, action, "failed", "isolate_host is not implemented by this agent build"); + // Verify the server signature before doing anything. + const fields = action_sig.Fields{ + .action_id = action.id, + .agent_id = ctx.agent_id, + .action_type = action.action_type, + .expires_at = action.expires_at, + .payload = action.payload, + .payload_hash = action.payload_hash, + .signature = action.signature, + }; + action_sig.verify(ctx.alloc, fields, ctx.public_key, iox.timestamp()) catch |err| { + const reason = switch (err) { + error.ActionUnsigned => "action has no server signature", + error.ActionExpired => "action expired before execution", + error.ActionPayloadMismatch => "action payload does not match its signed hash", + error.ActionSignatureInvalid => "action signature did not verify", + error.ActionKeyMissing => "no pinned server action key", + error.OutOfMemory => "out of memory verifying action", + }; + _ = report(ctx.http, action, "failed", reason); return; + }; + + ctx.journal.begin(action.id, action.action_type) catch {}; + + const result = dispatch(ctx, action); + defer if (result.owned) ctx.alloc.free(result.message); + + ctx.journal.finish(action.id, action.action_type, result.status, result.message) catch {}; + if (report(ctx.http, action, result.status, result.message)) { + ctx.journal.clear(action.id); } +} - try report(http, action, "failed", "unknown response action"); +fn dispatch(ctx: Context, action: transport.ResponseAction) Result { + const t = action.action_type; + if (std.mem.eql(u8, t, "kill_process")) return processAction(ctx, action, .kill); + if (std.mem.eql(u8, t, "suspend_process")) return processAction(ctx, action, .do_suspend); + if (std.mem.eql(u8, t, "resume_process")) return processAction(ctx, action, .do_resume); + if (std.mem.eql(u8, t, "quarantine_file")) return quarantineAction(ctx, action); + if (std.mem.eql(u8, t, "restore_file")) return restoreAction(ctx, action); + if (std.mem.eql(u8, t, "isolate_host") or std.mem.eql(u8, t, "isolate")) + return fail(isolate_unsupported_message); + if (std.mem.eql(u8, t, "release")) + return fail("release is not supported on this agent build"); + return fail("unknown response action"); } -fn executeKillProcess( - alloc: std.mem.Allocator, - http: *transport.Client, - action: transport.ResponseAction, -) !void { - const parsed = try std.json.parseFromSlice(struct { - pid: i32, - image_path: ?[]const u8 = null, - start_time_unix: ?i64 = null, - image_hash: ?[]const u8 = null, - command_line: ?[]const u8 = null, - }, alloc, action.payload, .{ .ignore_unknown_fields = true }); - defer parsed.deinit(); +/// The message the Linux e2e agent returns for isolate_host until #59 adds +/// nftables isolation. Contract tests assert on this exact string. +pub const isolate_unsupported_message = "isolate_host is not supported on linux yet (nftables isolation lands in #59)"; + +const ProcessOp = enum { kill, do_suspend, do_resume }; - if (parsed.value.pid <= 0) return error.InvalidPid; +const ProcessPayload = struct { + pid: i32, + image_path: ?[]const u8 = null, + start_time_unix: ?i64 = null, + image_hash: ?[]const u8 = null, + command_line: ?[]const u8 = null, +}; + +fn processAction(ctx: Context, action: transport.ResponseAction, op: ProcessOp) Result { + const parsed = std.json.parseFromSlice(ProcessPayload, ctx.alloc, action.payload, .{ .ignore_unknown_fields = true }) catch + return fail("invalid process action payload"); + defer parsed.deinit(); + const p = parsed.value; + if (p.pid <= 0) return fail("process action needs a positive pid"); - if (parsed.value.image_path != null or parsed.value.start_time_unix != null) { - try assertProcessIdentity(alloc, parsed.value.pid, parsed.value.image_path, parsed.value.start_time_unix); + if (builtin.target.os.tag == .windows) { + const id = process_control.Identity{ .image_path = p.image_path, .start_time_unix = p.start_time_unix }; + const outcome = switch (op) { + .kill => process_control.kill(ctx.alloc, @intCast(p.pid), id), + .do_suspend => process_control.suspend_(ctx.alloc, @intCast(p.pid), id), + .do_resume => process_control.resume_(ctx.alloc, @intCast(p.pid), id), + } catch |err| return fail(processErrorReason(err)); + return switch (outcome) { + .already_gone => ok("process already gone"), + .done => switch (op) { + .kill => ok("process terminated"), + .do_suspend => ok("process suspended"), + .do_resume => ok("process resumed"), + }, + }; } - switch (builtin.target.os.tag) { - .windows => return error.UnsupportedPlatform, - else => try std.posix.kill(parsed.value.pid, std.posix.SIG.TERM), + // POSIX: identity guard is Linux /proc backed; macOS fails closed when + // identity is requested. + if (p.image_path != null or p.start_time_unix != null) { + assertProcessIdentity(ctx.alloc, p.pid, p.image_path, p.start_time_unix) catch |err| + return fail(@errorName(err)); } + const sig = switch (op) { + .kill => std.posix.SIG.TERM, + .do_suspend => std.posix.SIG.STOP, + .do_resume => std.posix.SIG.CONT, + }; + std.posix.kill(p.pid, sig) catch |err| switch (err) { + error.ProcessNotFound => return ok("process already gone"), + else => return fail(@errorName(err)), + }; + return switch (op) { + .kill => ok("process termination signal sent"), + .do_suspend => ok("process suspended"), + .do_resume => ok("process resumed"), + }; +} + +fn processErrorReason(err: anyerror) []const u8 { + return switch (err) { + error.CriticalProcessRefused => "refused: target is a critical system process", + error.ProcessIdentityMismatch => "refused: process identity no longer matches (possible PID reuse)", + error.ProcessIdentityUnavailable => "could not confirm process identity", + error.InvalidPid => "process action needs a positive pid", + else => @errorName(err), + }; +} - try report(http, action, "succeeded", "process termination signal sent"); +const FilePayload = struct { + path: ?[]const u8 = null, + sha256: ?[]const u8 = null, +}; + +fn quarantineAction(ctx: Context, action: transport.ResponseAction) Result { + const parsed = std.json.parseFromSlice(FilePayload, ctx.alloc, action.payload, .{ .ignore_unknown_fields = true }) catch + return fail("invalid quarantine payload"); + defer parsed.deinit(); + const path = parsed.value.path orelse return fail("quarantine_file needs a path"); + const sha = parsed.value.sha256 orelse return fail("quarantine_file needs a sha256"); + const rec = quarantine.quarantine(ctx.alloc, ctx.quarantine_dir, path, sha) catch |err| return switch (err) { + error.HashMismatch => fail("refused: file hash does not match the action"), + error.FileTooBig => fail("file too large to quarantine"), + error.QuarantineVerifyFailed => fail("quarantine copy failed verification"), + else => fail(@errorName(err)), + }; + const msg = std.fmt.allocPrint(ctx.alloc, "quarantined {s} ({d} bytes)", .{ rec.sha256[0..16], rec.size }) catch + return ok("quarantined"); + return .{ .status = "succeeded", .message = msg, .owned = true }; +} + +fn restoreAction(ctx: Context, action: transport.ResponseAction) Result { + const parsed = std.json.parseFromSlice(FilePayload, ctx.alloc, action.payload, .{ .ignore_unknown_fields = true }) catch + return fail("invalid restore payload"); + defer parsed.deinit(); + const sha = parsed.value.sha256 orelse return fail("restore_file needs a sha256"); + const original = quarantine.restore(ctx.alloc, ctx.quarantine_dir, sha) catch |err| return switch (err) { + error.SidecarMissing => fail("no quarantined file for that sha256"), + error.QuarantineVerifyFailed => fail("quarantine copy failed verification"), + else => fail(@errorName(err)), + }; + defer ctx.alloc.free(original); + const msg = std.fmt.allocPrint(ctx.alloc, "restored to {s}", .{original}) catch return ok("restored"); + return .{ .status = "succeeded", .message = msg, .owned = true }; } -/// Refuse kill when optional identity fields no longer match the live process (PID reuse). +/// Refuse kill/suspend/resume when optional identity fields no longer match +/// the live process (PID reuse). Windows delegates to the process_control +/// identity check so it no longer fails closed; POSIX uses /proc on Linux. fn assertProcessIdentity( alloc: std.mem.Allocator, pid: i32, expected_path: ?[]const u8, expected_start: ?i64, ) !void { + if (builtin.target.os.tag == .windows) { + // process_control re-checks inside its open; nothing to do here. + return; + } if (builtin.target.os.tag != .linux) { - // Path/start identity checks are Linux /proc-backed for now. - // When identity was requested on other platforms, fail closed. if (expected_path != null or expected_start != null) return error.ProcessIdentityUnavailable; return; } @@ -88,7 +253,6 @@ fn readLinuxProcessImagePath(alloc: std.mem.Allocator, pid: i32) ![]u8 { var path_buf: [64]u8 = undefined; const link_path = try std.fmt.bufPrint(&path_buf, "/proc/{d}/exe", .{pid}); var target_buf: [std.fs.max_path_bytes]u8 = undefined; - // Zig 0.16+: use Io.Dir.readLinkAbsolute (std.posix.readlink is not available). const n = std.Io.Dir.readLinkAbsolute(iox.current(), link_path, &target_buf) catch return error.ProcessIdentityMismatch; return try alloc.dupe(u8, target_buf[0..n]); @@ -136,6 +300,22 @@ fn readBtime() !i64 { return error.ProcessIdentityMismatch; } -fn report(http: *transport.Client, action: transport.ResponseAction, status: []const u8, message: []const u8) !void { - try http.reportActionResult(action.id, action.execution_token, status, message); +/// Report a result. Returns true when the server acked it (so the journal +/// entry can be cleared). A failed report leaves the entry for the next +/// heartbeat to retry. +fn report(http: *transport.Client, action: transport.ResponseAction, status: []const u8, message: []const u8) bool { + http.reportActionResult(action.id, action.execution_token, status, message) catch |err| { + std.debug.print("response action {s} result report failed: {s}\n", .{ action.id, @errorName(err) }); + return false; + }; + return true; +} + +test "pure helpers compile on every OS" { + _ = action_sig; + _ = action_key; + _ = journal_mod; + _ = quarantine; + try std.testing.expect(pathsMatch("/usr/bin/evil", "evil")); + try std.testing.expect(!pathsMatch("/usr/bin/a", "/usr/bin/b")); } diff --git a/agent/src/transport/http.zig b/agent/src/transport/http.zig index 26d3937..d71d09a 100644 --- a/agent/src/transport/http.zig +++ b/agent/src/transport/http.zig @@ -16,13 +16,21 @@ pub const HeartbeatResult = struct { yara_pack_version: u64 = 0, actions: []ResponseAction = &.{}, + /// Server action public key for trust-on-first-use pinning (#57). Base64 + /// Ed25519. Present on heartbeats so agents enrolled before #57 pin it. + action_public_key: ?[]u8 = null, + pub fn deinit(self: *HeartbeatResult, alloc: std.mem.Allocator) void { if (self.rotated_jwt) |jwt| alloc.free(jwt); + if (self.action_public_key) |k| alloc.free(k); for (self.actions) |action| { alloc.free(action.id); alloc.free(action.action_type); alloc.free(action.payload); alloc.free(action.execution_token); + alloc.free(action.expires_at); + alloc.free(action.payload_hash); + if (action.signature) |s| alloc.free(s); } if (self.actions.len > 0) alloc.free(self.actions); } @@ -33,6 +41,13 @@ pub const ResponseAction = struct { action_type: []u8, payload: []u8, execution_token: []u8, + /// RFC 3339 deadline the server signed (empty if the server omitted it). + expires_at: []u8 = &.{}, + /// Lower-case hex SHA-256 of the payload the server signed. + payload_hash: []u8 = &.{}, + /// Base64 Ed25519 signature over the canonical action string. Null when + /// the server sent no signature (refused by the agent). + signature: ?[]u8 = null, }; pub const Client = struct { @@ -105,10 +120,14 @@ pub const Client = struct { action_type: []const u8, payload: std.json.Value, execution_token: []const u8, + expires_at: ?[]const u8 = null, + payload_hash: ?[]const u8 = null, + signature: ?[]const u8 = null, }; const Parsed = struct { rotated_jwt: ?[]const u8 = null, yara_pack_version: u64 = 0, + action_public_key: ?[]const u8 = null, actions: []const ParsedAction = &.{}, }; const parsed = std.json.parseFromSlice(Parsed, self.allocator, response, .{ @@ -117,9 +136,13 @@ pub const Client = struct { defer parsed.deinit(); var result = HeartbeatResult{ .yara_pack_version = parsed.value.yara_pack_version }; + errdefer result.deinit(self.allocator); if (parsed.value.rotated_jwt) |jwt| { result.rotated_jwt = try self.allocator.dupe(u8, jwt); } + if (parsed.value.action_public_key) |k| { + result.action_public_key = try self.allocator.dupe(u8, k); + } if (parsed.value.actions.len > 0) { var actions = std.array_list.Managed(ResponseAction).init(self.allocator); errdefer { @@ -128,6 +151,9 @@ pub const Client = struct { self.allocator.free(action.action_type); self.allocator.free(action.payload); self.allocator.free(action.execution_token); + self.allocator.free(action.expires_at); + self.allocator.free(action.payload_hash); + if (action.signature) |s| self.allocator.free(s); } actions.deinit(); } @@ -147,6 +173,9 @@ pub const Client = struct { .action_type = try self.allocator.dupe(u8, action.action_type), .payload = try payload.toOwnedSlice(), .execution_token = try self.allocator.dupe(u8, action.execution_token), + .expires_at = try self.allocator.dupe(u8, action.expires_at orelse ""), + .payload_hash = try self.allocator.dupe(u8, action.payload_hash orelse ""), + .signature = if (action.signature) |s| try self.allocator.dupe(u8, s) else null, }); } result.actions = try actions.toOwnedSlice(); diff --git a/server/src/crypto/action_sig.zig b/server/src/crypto/action_sig.zig new file mode 100644 index 0000000..6fdec4d --- /dev/null +++ b/server/src/crypto/action_sig.zig @@ -0,0 +1,79 @@ +//! Server action signatures (#57). +//! +//! The server signs every response action with the action key +//! (`state.actionKey`, an Ed25519 key separate from the JWT key). The agent +//! pins the public key at enrolment (or from the heartbeat, trust on first +//! use) and refuses any action that is unsigned, expired, tampered with, or +//! signed by another key. +//! +//! Canonical string, one field per line, no trailing newline: +//! tawny-action-v1 +//! +//! +//! +//! +//! +//! +//! `expires_at` is the RFC 3339 string the heartbeat sends. The payload hash +//! is the lower-case hex SHA-256 of the exact payload bytes delivered to the +//! agent. The agent rebuilds this string from the action it received and +//! verifies the Ed25519 signature before it runs anything. + +const std = @import("std"); +const Ed25519 = std.crypto.sign.Ed25519; + +pub const prefix = "tawny-action-v1"; + +/// Build the canonical string. Caller frees. +pub fn canonical( + alloc: std.mem.Allocator, + action_id: []const u8, + agent_id: []const u8, + action_type: []const u8, + expires_at: []const u8, + payload_sha256_hex: []const u8, +) ![]u8 { + return std.fmt.allocPrint(alloc, "{s}\n{s}\n{s}\n{s}\n{s}\n{s}", .{ + prefix, action_id, agent_id, action_type, expires_at, payload_sha256_hex, + }); +} + +/// Sign the canonical string, returning the base64 signature. Caller frees. +pub fn sign( + alloc: std.mem.Allocator, + kp: Ed25519.KeyPair, + action_id: []const u8, + agent_id: []const u8, + action_type: []const u8, + expires_at: []const u8, + payload_sha256_hex: []const u8, +) ![]u8 { + const msg = try canonical(alloc, action_id, agent_id, action_type, expires_at, payload_sha256_hex); + defer alloc.free(msg); + const sig = try kp.sign(msg, null); + const raw = sig.toBytes(); + var buf: [std.base64.standard.Encoder.calcSize(raw.len)]u8 = undefined; + const b64 = std.base64.standard.Encoder.encode(&buf, &raw); + return alloc.dupe(u8, b64); +} + +test "sign then verify round-trips, tamper fails" { + const a = std.testing.allocator; + const kp = Ed25519.KeyPair.generate(std.testing.io); + const sig_b64 = try sign(a, kp, "id-1", "agent-1", "kill_process", "2026-11-10T00:00:00Z", "abc123"); + defer a.free(sig_b64); + + const msg = try canonical(a, "id-1", "agent-1", "kill_process", "2026-11-10T00:00:00Z", "abc123"); + defer a.free(msg); + var raw: [Ed25519.Signature.encoded_length]u8 = undefined; + try std.base64.standard.Decoder.decode(&raw, sig_b64); + const sig = Ed25519.Signature.fromBytes(raw); + try sig.verify(msg, kp.public_key); + + const bad = try canonical(a, "id-1", "agent-1", "suspend_process", "2026-11-10T00:00:00Z", "abc123"); + defer a.free(bad); + try std.testing.expectError(error.SignatureVerificationFailed, sig.verify(bad, kp.public_key)); + + const other = Ed25519.KeyPair.generate(std.testing.io); + try std.testing.expectError(error.SignatureVerificationFailed, sig.verify(msg, other.public_key)); +} diff --git a/server/src/db/migrate.zig b/server/src/db/migrate.zig index 29588c4..6bba630 100644 --- a/server/src/db/migrate.zig +++ b/server/src/db/migrate.zig @@ -11,6 +11,8 @@ const process_entities_sql = @embedFile("migrations/0004_process_entities.sql"); const process_entities_version = "0004_process_entities"; 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"; pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try conn.execSimple( @@ -28,6 +30,7 @@ pub fn apply(allocator: std.mem.Allocator, conn: *pg.Conn) !void { try applyScript(allocator, conn, ai_reasoning_version, ai_reasoning_sql, true); 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 conn.execSimple("GRANT EXECUTE ON FUNCTION tawny_purge_expired(timestamptz) TO tawny_jobs"); try ensurePartitions(conn); } diff --git a/server/src/db/migrations/0006_windows_response.sql b/server/src/db/migrations/0006_windows_response.sql new file mode 100644 index 0000000..e1ab875 --- /dev/null +++ b/server/src/db/migrations/0006_windows_response.sql @@ -0,0 +1,9 @@ +-- Windows response (#57): new signed action types the agent can run. +ALTER TABLE response_actions DROP CONSTRAINT IF EXISTS response_actions_action_type_check; +ALTER TABLE response_actions ADD CONSTRAINT response_actions_action_type_check + CHECK (action_type IN ( + 'kill_process', 'suspend_process', 'resume_process', + 'quarantine_file', 'restore_file', + 'isolate_host', 'release_host', 'release', + 'yara_scan' + )); diff --git a/server/src/http/state.zig b/server/src/http/state.zig index e9e3763..47d7d3c 100644 --- a/server/src/http/state.zig +++ b/server/src/http/state.zig @@ -7,12 +7,11 @@ pub var peer_ip: []const u8 = "127.0.0.1"; pub var agent_kp: ?Ed25519.KeyPair = null; -/// Signs YARA rule packs for agents (#56). Set at startup from -/// TAWNY_RULE_SIGNING_KEY like the JWT seed. Kept apart from `agent_kp` -/// so a leaked JWT key can't sign rules. Issue #57 adds a server action key; -/// that change can fold this key into it, keeping `rulePackKey` as the one -/// accessor. -pub var rule_kp: ?Ed25519.KeyPair = null; +/// Server action key (#57). One Ed25519 key signs response actions and YARA +/// rule packs (#56). Set at startup from TAWNY_ACTION_SIGNING_KEY (or the +/// deprecated TAWNY_RULE_SIGNING_KEY). Kept apart from `agent_kp` so a leaked +/// JWT key can't sign commands or rules. +pub var action_kp: ?Ed25519.KeyPair = null; const RateBucket = struct { window_start: i64, @@ -70,47 +69,56 @@ pub fn configureAgentKey(io: std.Io, seed_text: ?[]const u8, dev: bool) !SeedSou return chosen.source; } -pub const RuleKeyError = error{RuleSigningKeyMalformed}; +pub const ActionKeyError = error{ActionSigningKeyMalformed}; -/// Rule-pack signing seed. TAWNY_RULE_SIGNING_KEY (64 hex characters) wins. -/// When it is unset the seed is derived from the agent JWT seed with -/// HKDF-SHA256 and a label of its own, so a deployment that only sets -/// TAWNY_AGENT_JWT_SEED keeps the same rule key across restarts, and the two -/// Ed25519 keys still differ. A malformed value is refused, never ignored. -pub fn ruleSeed(rule_text: ?[]const u8, jwt_seed: [32]u8) RuleKeyError!struct { seed: [32]u8, derived: bool } { - const text = rule_text orelse ""; - if (text.len == 0) { +pub const ActionKeySource = enum { configured, legacy_rule_alias, derived }; + +/// Action signing seed. TAWNY_ACTION_SIGNING_KEY (64 hex characters) wins, +/// then the deprecated TAWNY_RULE_SIGNING_KEY. When neither is set the seed +/// is derived from the agent JWT seed with HKDF-SHA256 and its own label, so +/// a deployment that only sets TAWNY_AGENT_JWT_SEED keeps the same action key +/// across restarts and the two Ed25519 keys still differ. A malformed value +/// is refused, never ignored. +pub fn actionSeed(action_text: ?[]const u8, legacy_rule_text: ?[]const u8, jwt_seed: [32]u8) ActionKeyError!struct { seed: [32]u8, source: ActionKeySource } { + const a = action_text orelse ""; + const r = legacy_rule_text orelse ""; + const text, const source: ActionKeySource = if (a.len > 0) .{ a, .configured } else if (r.len > 0) .{ r, .legacy_rule_alias } else .{ "", .derived }; + var seed: [32]u8 = undefined; + if (source == .derived) { const Hkdf = std.crypto.kdf.hkdf.HkdfSha256; - const prk = Hkdf.extract("tawny-rule-pack-v1", &jwt_seed); - var seed: [32]u8 = undefined; - Hkdf.expand(&seed, "tawny rule pack signing key", prk); - return .{ .seed = seed, .derived = true }; + const prk = Hkdf.extract("tawny-action-key-v1", &jwt_seed); + Hkdf.expand(&seed, "tawny server action signing key", prk); + return .{ .seed = seed, .source = .derived }; } - var seed: [32]u8 = undefined; - if (text.len != 64) return error.RuleSigningKeyMalformed; - _ = std.fmt.hexToBytes(&seed, text) catch return error.RuleSigningKeyMalformed; - return .{ .seed = seed, .derived = false }; + if (text.len != 64) return error.ActionSigningKeyMalformed; + _ = std.fmt.hexToBytes(&seed, text) catch return error.ActionSigningKeyMalformed; + return .{ .seed = seed, .source = source }; } /// Call after `configureAgentKey`. -pub fn configureRuleKey(rule_text: ?[]const u8) !bool { +pub fn configureActionKey(action_text: ?[]const u8, legacy_rule_text: ?[]const u8) !ActionKeySource { const jwt = agent_kp orelse return error.AgentKeyNotConfigured; var jwt_seed = jwt.secret_key.seed(); defer std.crypto.secureZero(u8, &jwt_seed); - var chosen = try ruleSeed(rule_text, jwt_seed); + var chosen = try actionSeed(action_text, legacy_rule_text, jwt_seed); defer std.crypto.secureZero(u8, &chosen.seed); - rule_kp = try Ed25519.KeyPair.generateDeterministic(chosen.seed); - return chosen.derived; + action_kp = try Ed25519.KeyPair.generateDeterministic(chosen.seed); + return chosen.source; } -/// Rule-pack signing key. Tests and one-off commands get a random key. -pub fn rulePackKey(io: std.Io) !Ed25519.KeyPair { - if (rule_kp) |kp| return kp; +/// The server action key. Tests and one-off commands get a random key. +pub fn actionKey(io: std.Io) !Ed25519.KeyPair { + if (action_kp) |kp| return kp; var seed: [32]u8 = undefined; io.random(&seed); defer std.crypto.secureZero(u8, &seed); - rule_kp = try Ed25519.KeyPair.generateDeterministic(seed); - return rule_kp.?; + action_kp = try Ed25519.KeyPair.generateDeterministic(seed); + return action_kp.?; +} + +/// YARA rule packs are signed with the action key. +pub fn rulePackKey(io: std.Io) !Ed25519.KeyPair { + return actionKey(io); } /// Set from TAWNY_REQUIRE_SIGNED_BATCHES at startup. On unless set to 0, false or off. @@ -229,22 +237,26 @@ test "principal and agent-events partitions do not collapse" { try std.testing.expect(!tooMany(io, "test-search", user_a, 1)); } -test "rule signing key: configured, derived, or refused" { +test "action signing key: configured, legacy alias, derived, or refused" { const jwt: [32]u8 = @splat(7); - try std.testing.expectError(error.RuleSigningKeyMalformed, ruleSeed("abc", jwt)); - try std.testing.expectError(error.RuleSigningKeyMalformed, ruleSeed("zz00000000000000000000000000000000000000000000000000000000000000", jwt)); - const a = try ruleSeed(null, jwt); - const b = try ruleSeed("", jwt); - try std.testing.expect(a.derived and b.derived); + try std.testing.expectError(error.ActionSigningKeyMalformed, actionSeed("abc", null, jwt)); + try std.testing.expectError(error.ActionSigningKeyMalformed, actionSeed(null, "abc", jwt)); + try std.testing.expectError(error.ActionSigningKeyMalformed, actionSeed("zz00000000000000000000000000000000000000000000000000000000000000", null, jwt)); + const a = try actionSeed(null, null, jwt); + const b = try actionSeed("", "", jwt); + try std.testing.expect(a.source == .derived and b.source == .derived); try std.testing.expectEqualSlices(u8, &a.seed, &b.seed); // Derived seed is not the JWT seed itself. try std.testing.expect(!std.mem.eql(u8, &a.seed, &jwt)); const other_jwt: [32]u8 = @splat(8); - const c = try ruleSeed(null, other_jwt); + const c = try actionSeed(null, null, other_jwt); try std.testing.expect(!std.mem.eql(u8, &a.seed, &c.seed)); - const set = try ruleSeed("00000000000000000000000000000000000000000000000000000000000000ff", jwt); - try std.testing.expect(!set.derived); + const set = try actionSeed("00000000000000000000000000000000000000000000000000000000000000ff", "00000000000000000000000000000000000000000000000000000000000000ee", jwt); + try std.testing.expectEqual(ActionKeySource.configured, set.source); try std.testing.expectEqual(@as(u8, 0xff), set.seed[31]); + const legacy = try actionSeed(null, "00000000000000000000000000000000000000000000000000000000000000ee", jwt); + try std.testing.expectEqual(ActionKeySource.legacy_rule_alias, legacy.source); + try std.testing.expectEqual(@as(u8, 0xee), legacy.seed[31]); } test "agent seed refuses missing and malformed values outside dev mode" { diff --git a/server/src/main.zig b/server/src/main.zig index 7a73531..73ff430 100644 --- a/server/src/main.zig +++ b/server/src/main.zig @@ -67,12 +67,17 @@ pub fn main(init: std.process.Init) !void { if (seed_source == .dev_random) { std.debug.print("tawny-server: TAWNY_DEV is on and TAWNY_AGENT_JWT_SEED is unusable. Using a random agent JWT seed; agents must re-enrol after a restart.\n", .{}); } - const rule_derived = state.configureRuleKey(init.environ_map.get("TAWNY_RULE_SIGNING_KEY")) catch |err| { - if (err == error.RuleSigningKeyMalformed) std.debug.print("tawny-server: TAWNY_RULE_SIGNING_KEY must be exactly 64 hex characters.\n", .{}); + const action_source = state.configureActionKey( + init.environ_map.get("TAWNY_ACTION_SIGNING_KEY"), + init.environ_map.get("TAWNY_RULE_SIGNING_KEY"), + ) catch |err| { + if (err == error.ActionSigningKeyMalformed) std.debug.print("tawny-server: TAWNY_ACTION_SIGNING_KEY (or TAWNY_RULE_SIGNING_KEY) must be exactly 64 hex characters.\n", .{}); return err; }; - if (rule_derived) { - std.debug.print("tawny-server: TAWNY_RULE_SIGNING_KEY is not set. YARA rule packs are signed with a key derived from the agent JWT seed.\n", .{}); + switch (action_source) { + .configured => {}, + .legacy_rule_alias => std.debug.print("tawny-server: TAWNY_RULE_SIGNING_KEY is deprecated. Rename it to TAWNY_ACTION_SIGNING_KEY; it now signs response actions and YARA rule packs.\n", .{}), + .derived => std.debug.print("tawny-server: TAWNY_ACTION_SIGNING_KEY is not set. Response actions and YARA rule packs are signed with a key derived from the agent JWT seed.\n", .{}), } state.require_signed_batches = state.flagOn(init.environ_map.get("TAWNY_REQUIRE_SIGNED_BATCHES"), true); if (!state.require_signed_batches) { @@ -435,6 +440,7 @@ fn readyBody(allocator: std.mem.Allocator, conn: *pg.Conn) Ready { comptime { _ = @import("crypto/jwt.zig"); _ = @import("crypto/batch_sig.zig"); + _ = @import("crypto/action_sig.zig"); _ = @import("crypto/secret_box.zig"); _ = @import("crypto/sigv4.zig"); _ = @import("crypto/passwords.zig"); diff --git a/server/src/routes/agents.zig b/server/src/routes/agents.zig index 44787a4..8974a27 100644 --- a/server/src/routes/agents.zig +++ b/server/src/routes/agents.zig @@ -5,6 +5,7 @@ const auth = @import("../http/auth.zig"); const audit = @import("../http/audit.zig"); const state = @import("../http/state.zig"); const batch_sig = @import("../crypto/batch_sig.zig"); +const action_sig = @import("../crypto/action_sig.zig"); const detect = @import("../jobs/detect.zig"); const ingest_v2 = @import("../ingest/v2.zig"); const ingest_entity = @import("../ingest/entity.zig"); @@ -170,13 +171,15 @@ pub fn enroll( defer allocator.free(jwt_j); const exp_j = try util.escapeJson(allocator, exp_s); defer allocator.free(exp_j); - // The agent pins this key and refuses YARA rule packs signed by any other. - const rule_kp = try state.rulePackKey(io); + // One action key signs response actions and YARA rule packs (#57). The + // agent pins this public key and refuses anything signed by another key. + // `yara_rule_key` is the same bytes, kept for agents enrolled before #57. + const act_kp = try state.actionKey(io); var rk_buf: [44]u8 = undefined; - const rule_key = std.base64.standard.Encoder.encode(&rk_buf, &rule_kp.public_key.bytes); + const action_key = std.base64.standard.Encoder.encode(&rk_buf, &act_kp.public_key.bytes); const json = try std.fmt.allocPrint(allocator, - \\{{"agent_id":{s},"jwt":{s},"jwt_expires_at":{s},"yara_rule_key":"{s}","config":{{"heartbeat_interval_seconds":60}}}} - , .{ aid_j, jwt_j, exp_j, rule_key }); + \\{{"agent_id":{s},"jwt":{s},"jwt_expires_at":{s},"action_public_key":"{s}","yara_rule_key":"{s}","config":{{"heartbeat_interval_seconds":60}}}} + , .{ aid_j, jwt_j, exp_j, action_key, action_key }); defer allocator.free(json); try util.respondJson(request, .ok, json); } @@ -455,10 +458,23 @@ pub fn heartbeat( const ph_j = try util.escapeJson(allocator, ph.?); defer allocator.free(ph_j); const payload = row.cols[2] orelse "{}"; + // Sign the action so the agent can refuse anything the server did not + // authorise. The signed string pins the id, agent, type, deadline and + // the hash of the payload the agent receives. + const sig_b64 = try action_sig.sign( + allocator, + try state.actionKey(io), + row.cols[0].?, + agent.agent_id, + row.cols[1] orelse "", + exp_at.?, + ph.?, + ); + defer allocator.free(sig_b64); { - const __tmp = try std.fmt.allocPrint(allocator, - "{{\"id\":{s},\"action_type\":{s},\"payload\":{s},\"execution_token\":{s},\"expires_at\":{s},\"payload_hash\":{s}}}", - .{ id_j, at_j, payload, tok_j, exp_j, ph_j }, + const __tmp = try std.fmt.allocPrint(allocator, + "{{\"id\":{s},\"action_type\":{s},\"payload\":{s},\"execution_token\":{s},\"expires_at\":{s},\"payload_hash\":{s},\"signature\":\"{s}\"}}", + .{ id_j, at_j, payload, tok_j, exp_j, ph_j, sig_b64 }, ); defer allocator.free(__tmp); try actions_json.appendSlice(allocator, __tmp); @@ -517,6 +533,16 @@ pub fn heartbeat( defer allocator.free(__tmp); try out.appendSlice(allocator, __tmp); } + { + // Carry the action public key so agents enrolled before #57 pin it on + // their next heartbeat (trust on first use). + const act_kp = try state.actionKey(io); + var kb: [44]u8 = undefined; + const kb64 = std.base64.standard.Encoder.encode(&kb, &act_kp.public_key.bytes); + const __tmp = try std.fmt.allocPrint(allocator, "\"action_public_key\":\"{s}\",", .{kb64}); + defer allocator.free(__tmp); + try out.appendSlice(allocator, __tmp); + } if (rotated) |r| { const rj = try util.escapeJson(allocator, r); defer allocator.free(rj); From d5688234513ac21554fcc6dd7282590d1e4c6e78 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 02:50:10 +1100 Subject: [PATCH 2/8] feat: Windows process control, quarantine, WFP plan, server action types Agent: - platform/windows/process_control.zig: kill (already-gone is success), suspend and resume via NtSuspendProcess/NtResumeProcess, an identity guard (image path plus start time) so Windows no longer fails closed, and a critical-process refusal list tested on every OS. - quarantine.zig: encode the file with a fixed XOR key so it cannot run, hash and verify the copy, delete the original, write a sidecar, and restore. Windows keeps the ACL as SDDL; POSIX restores owner-only permissions. Round-trips on Linux and macOS. - platform/windows/wfp.zig: a pure filter-building plan with a fixed sublayer GUID, an auto-release deadline check, and the break-glass release code (HMAC of agent id and nonce), all tested on every OS. The live FwpmEngine calls are stubs behind the Windows target for now. - response_actions dispatches kill, suspend, resume, quarantine, restore, and reports isolate_host as not supported on this build. Server: - migration 0006 adds suspend_process, resume_process, quarantine_file, restore_file and release action types. - the SPA agent page lists recent actions and lets an admin create one. - a contract test verifies the action signature with openssl; the Linux e2e now expects the new isolate_host message. Co-Authored-By: Claude Opus 5.5 --- ci/agent_e2e.py | 2 +- contract-tests/suite.py | 68 +++++++++++++++++++++++++ server/src/routes/agents.zig | 42 ++++++++++----- server/ui/assets/app.a1de0f605695.js | 76 ++++++++++++++++++++++++++++ 4 files changed, 175 insertions(+), 13 deletions(-) diff --git a/ci/agent_e2e.py b/ci/agent_e2e.py index 3d3af85..f537fcb 100644 --- a/ci/agent_e2e.py +++ b/ci/agent_e2e.py @@ -20,7 +20,7 @@ EMAIL = os.environ.get("TAWNY_CONTRACT_EMAIL", "admin@tawny.local") PASSWORD = os.environ.get("TAWNY_CONTRACT_PASSWORD", "contract-password") AGENT_BIN = os.environ.get("TAWNY_AGENT_BIN", "") -NOT_IMPLEMENTED = "isolate_host is not implemented by this agent build" +NOT_IMPLEMENTED = "isolate_host is not supported on linux yet" def call(method: str, path: str, body: object | None, cookie: str, csrf: str) -> tuple[int, str]: diff --git a/contract-tests/suite.py b/contract-tests/suite.py index 60166d9..d12fb27 100644 --- a/contract-tests/suite.py +++ b/contract-tests/suite.py @@ -280,6 +280,7 @@ def enroll_host( "agent_id": agent_id, "jwt": parsed["jwt"], "yara_rule_key": parsed.get("yara_rule_key"), + "action_public_key": parsed.get("action_public_key"), "hostname": hostname, "config": parsed["config"], "summary": summary, @@ -1375,6 +1376,73 @@ def test_response_action_dispatch_and_result(self) -> None: self.assertIsNotNone(fetched.get("completed_at")) self.assertIn("process terminated", got_raw) + def test_response_action_is_signed(self) -> None: + # The server signs every dispatched action with the action key. The + # agent verifies this before running anything. Check the signature with + # openssl against the public key, and that tampering breaks it. + agent = windows_agent() + self.assertEqual(agent.get("action_public_key"), agent.get("yara_rule_key")) + pid = 40000 + secrets.randbelow(10000) + created, action, created_raw = call( + "POST", + f"/api/agents/{agent['agent_id']}/actions", + {"action_type": "kill_process", "payload": {"pid": pid}}, + ) + self.assertIn(created, (200, 201), created_raw[:800]) + hb_code, hb, hb_raw = call( + "POST", + "/api/agents/heartbeat", + {"agent_version": "0.1.1", "uptime_seconds": 7, "buffer_depth": 0}, + auth="agent", + bearer=agent["jwt"], + ) + self.assertEqual(hb_code, 200, hb_raw[:800]) + assert isinstance(hb, dict) + self.assertEqual(hb.get("action_public_key"), agent.get("action_public_key")) + match = next( + ( + row + for row in hb.get("actions", []) + if isinstance(row, dict) and row.get("id") == action["id"] + ), + None, + ) + self.assertIsNotNone(match, hb_raw[:800]) + assert isinstance(match, dict) + self.assertTrue(match.get("signature")) + self.assertTrue(match.get("payload_hash")) + canonical = ( + "tawny-action-v1\n" + f"{match['id']}\n{agent['agent_id']}\n{match['action_type']}\n" + f"{match['expires_at']}\n{match['payload_hash']}" + ).encode() + import tempfile + + raw_pub = base64.b64decode(agent["action_public_key"]) + der = bytes.fromhex("302a300506032b6570032100") + raw_pub + with tempfile.TemporaryDirectory(prefix="tawny-ct-action-") as tmp: + pub = os.path.join(tmp, "pub.der") + msg = os.path.join(tmp, "msg") + sig = os.path.join(tmp, "sig") + with open(pub, "wb") as h: + h.write(der) + with open(msg, "wb") as h: + h.write(canonical) + with open(sig, "wb") as h: + h.write(base64.b64decode(match["signature"])) + ok = subprocess.run( + ["openssl", "pkeyutl", "-verify", "-pubin", "-keyform", "DER", "-inkey", pub, "-rawin", "-in", msg, "-sigfile", sig], + capture_output=True, + ) + self.assertEqual(ok.returncode, 0, ok.stdout + ok.stderr) + with open(msg, "wb") as h: + h.write(canonical.replace(b"kill_process", b"quarantine_file")) + bad = subprocess.run( + ["openssl", "pkeyutl", "-verify", "-pubin", "-keyform", "DER", "-inkey", pub, "-rawin", "-in", msg, "-sigfile", sig], + capture_output=True, + ) + self.assertNotEqual(bad.returncode, 0) + def test_other_agent_cannot_complete_action(self) -> None: owner = enroll_host("own", "windows", "11", "x64") other = enroll_host("oth", "linux", "6.1", "x64") diff --git a/server/src/routes/agents.zig b/server/src/routes/agents.zig index 8974a27..ae2980c 100644 --- a/server/src/routes/agents.zig +++ b/server/src/routes/agents.zig @@ -428,13 +428,15 @@ pub fn heartbeat( exp_owned = try allocator.dupe(u8, util.formatRfc3339(&tbuf, now + 15 * 60)); exp_at = exp_owned; } - var ph = row.cols[4]; - var ph_owned: ?[]u8 = null; - defer if (ph_owned) |p| allocator.free(p); - if (ph == null) { - ph_owned = try util.sha256Hex(allocator, row.cols[2] orelse "{}"); - ph = ph_owned; - } + // Reserialize the payload to the compact form the agent reconstructs + // (parse then stringify), so the signed payload_hash matches the bytes + // the agent recomputes from the payload field it receives. + const payload_raw = row.cols[2] orelse "{}"; + const payload_compact = reserializePayload(allocator, payload_raw) catch try allocator.dupe(u8, payload_raw); + defer allocator.free(payload_compact); + const ph_owned = try util.sha256Hex(allocator, payload_compact); + const ph: []const u8 = ph_owned; + defer allocator.free(ph_owned); try conn.execNoRows( \\UPDATE response_actions SET status = 'dispatched', dispatched_at = $2::timestamptz, \\ execution_token_hash = $3, expires_at = COALESCE(expires_at, $4::timestamptz), @@ -445,7 +447,7 @@ pub fn heartbeat( .{ .text = now_s }, .{ .text = exec_hash }, .{ .text = exp_at.? }, - .{ .text = ph.? }, + .{ .text = ph }, }); const id_j = try util.escapeJson(allocator, row.cols[0].?); defer allocator.free(id_j); @@ -455,9 +457,8 @@ pub fn heartbeat( defer allocator.free(tok_j); const exp_j = try util.escapeJson(allocator, exp_at.?); defer allocator.free(exp_j); - const ph_j = try util.escapeJson(allocator, ph.?); + const ph_j = try util.escapeJson(allocator, ph); defer allocator.free(ph_j); - const payload = row.cols[2] orelse "{}"; // Sign the action so the agent can refuse anything the server did not // authorise. The signed string pins the id, agent, type, deadline and // the hash of the payload the agent receives. @@ -468,13 +469,13 @@ pub fn heartbeat( agent.agent_id, row.cols[1] orelse "", exp_at.?, - ph.?, + ph, ); defer allocator.free(sig_b64); { const __tmp = try std.fmt.allocPrint(allocator, "{{\"id\":{s},\"action_type\":{s},\"payload\":{s},\"execution_token\":{s},\"expires_at\":{s},\"payload_hash\":{s},\"signature\":\"{s}\"}}", - .{ id_j, at_j, payload, tok_j, exp_j, ph_j, sig_b64 }, + .{ id_j, at_j, payload_compact, tok_j, exp_j, ph_j, sig_b64 }, ); defer allocator.free(__tmp); try actions_json.appendSlice(allocator, __tmp); @@ -1018,6 +1019,23 @@ pub fn createAction( try util.respondJson(request, .created, json); } +/// Parse then compact-serialize a JSON payload, matching the bytes the agent +/// reconstructs from the payload field. Caller frees. +fn reserializePayload(allocator: std.mem.Allocator, raw: []const u8) ![]u8 { + var parsed = try std.json.parseFromSlice(std.json.Value, allocator, raw, .{}); + defer parsed.deinit(); + return std.json.Stringify.valueAlloc(allocator, parsed.value, .{}); +} + +test "reserializePayload produces compact JSON the agent can match" { + const a = std.testing.allocator; + const out = try reserializePayload(a, "{\"pid\": 1234, \"image_path\": \"/bin/x\"}"); + defer a.free(out); + // No spaces after the structural characters. + try std.testing.expect(std.mem.indexOf(u8, out, ": ") == null); + try std.testing.expect(std.mem.indexOf(u8, out, "1234") != null); +} + fn idempotencyConflict(msg: []const u8) bool { return std.mem.indexOf(u8, msg, "duplicate key") != null and std.mem.indexOf(u8, msg, "idempotency_key") != null; } diff --git a/server/ui/assets/app.a1de0f605695.js b/server/ui/assets/app.a1de0f605695.js index 954a6cf..a77e909 100644 --- a/server/ui/assets/app.a1de0f605695.js +++ b/server/ui/assets/app.a1de0f605695.js @@ -166,6 +166,7 @@ view.main.appendChild(el("p", (res.body.hostname || id) + " · " + (res.body.status || ""), "muted")); }); renderProcessTree(view, id); + renderActions(view, id); var live = el("div", null, "card"); live.appendChild(el("p", "Live events", "muted")); var list = el("div"); @@ -190,6 +191,81 @@ }; } + // Response actions. Lists recent actions and, for admins, lets one create + // a signed action. The server signs each action; the agent verifies it. + var ACTION_TYPES = [ + "kill_process", + "suspend_process", + "resume_process", + "quarantine_file", + "restore_file", + "isolate_host", + "release", + ]; + + function renderActions(view, id) { + var card = el("div", null, "card"); + card.appendChild(el("p", "Response actions", "muted")); + var listing = el("div"); + card.appendChild(listing); + + function reload() { + api("GET", "/api/agents/" + id + "/actions").then(function (res) { + listing.textContent = ""; + var rows = (res.status === 200 && Array.isArray(res.body)) ? res.body : []; + if (!rows.length) { + listing.appendChild(el("p", "No actions yet.", "muted")); + return; + } + listing.appendChild(table( + ["Type", "Status", "Requested"], + rows.map(function (a) { + return [a.action_type || "", a.status || "", a.requested_at || ""]; + }) + )); + }); + } + + if (isAdmin()) { + var form = el("div"); + var select = document.createElement("select"); + ACTION_TYPES.forEach(function (t) { + var opt = document.createElement("option"); + opt.value = t; + opt.textContent = t; + select.appendChild(opt); + }); + var payload = textInput(""); + payload.placeholder = '{"pid":1234} or {"path":"...","sha256":"..."}'; + var run = el("button", "Create"); + run.addEventListener("click", function () { + var body = {}; + var raw = (payload.value || "").trim(); + if (raw.length) { + try { body = JSON.parse(raw); } catch (e) { + alert("Payload must be valid JSON."); + return; + } + } + api("POST", "/api/agents/" + id + "/actions", { + action_type: select.value, + payload: body, + }).then(function (res) { + if (res.status !== 201) return alert("Action failed: HTTP " + res.status); + payload.value = ""; + reload(); + }); + }); + form.appendChild(select); + form.appendChild(payload); + form.appendChild(run); + card.appendChild(form); + } + + view.main.appendChild(card); + reload(); + } + // Process tree from GET /api/agents/{id}/process-tree. Picking a process // shows its ancestors (oldest first), the process, and its descendants, // indented by depth. From de9e0a4b71e06737afa8ae459919890082caeb1d Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 02:57:34 +1100 Subject: [PATCH 3/8] feat: Windows response CI, debug subcommands, docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add agent debug subcommands (--kill-pid, --suspend-pid, --resume-pid, --quarantine, --restore) that drive the response actions from CI without a server, following the --eventlog-dump pattern. A new Windows CI step starts ping, kills it by PID and start time and checks it is gone, suspends and resumes a child, refuses lsass, and quarantines then restores a temp file comparing hashes. Document the action signing scheme and the new action types in docs/api.md, TAWNY_ACTION_SIGNING_KEY and the trust-on-first-use window in docs/production.md, the §9 status and the merged key in docs/architecture/target-edr.md, and the signed-action and PID-reuse rows in docs/threat-model.md. Closes #57 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 61 ++++++++++++++++++++++ agent/src/main.zig | 6 +++ agent/src/response_debug.zig | 91 +++++++++++++++++++++++++++++++++ docs/api.md | 41 ++++++++++++--- docs/architecture/target-edr.md | 18 +++++-- docs/production.md | 3 +- docs/threat-model.md | 5 +- 7 files changed, 211 insertions(+), 14 deletions(-) create mode 100644 agent/src/response_debug.zig diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bca359b..fb764d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -191,6 +191,67 @@ jobs: # Proves the wevtapi path on the hosted runner without Sysmon: Security # 4688 (process creation auditing) and PowerShell 4104 (script block # logging) are switched on, activity is generated, and the agent's + # Drives the Windows response actions with the agent's debug subcommands: + # kill a process by PID and start time, suspend and resume a child, and + # quarantine then restore a file comparing hashes. No server involved. + - name: prove Windows response actions (kill, suspend, resume, quarantine) + if: matrix.name == 'windows-x64' + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = "Stop" + $agent = Join-Path $PWD "zig-out\bin\tawny-agent.exe" + + # Kill by PID plus start time. Start a long-running ping we own. + $ping = Start-Process -FilePath "ping.exe" -ArgumentList @("-t", "127.0.0.1") -PassThru + Start-Sleep -Seconds 1 + $start = [int][double]::Parse((Get-Date $ping.StartTime.ToUniversalTime() -UFormat %s)) + $image = (Get-Process -Id $ping.Id).Path + & $agent --kill-pid $ping.Id $image $start | Out-Host + if ($LASTEXITCODE -ne 0) { throw "kill-pid exit $LASTEXITCODE" } + Start-Sleep -Seconds 1 + if (Get-Process -Id $ping.Id -ErrorAction SilentlyContinue) { throw "ping $($ping.Id) still running after kill" } + Write-Host "kill by pid and start time OK" + + # Killing an already-gone pid is a success. + & $agent --kill-pid $ping.Id | Out-Host + if ($LASTEXITCODE -ne 0) { throw "already-gone kill should succeed" } + + # Suspend and resume a child, then clean it up. + $child = Start-Process -FilePath "ping.exe" -ArgumentList @("-t", "127.0.0.1") -PassThru + Start-Sleep -Seconds 1 + & $agent --suspend-pid $child.Id | Out-Host + if ($LASTEXITCODE -ne 0) { throw "suspend exit $LASTEXITCODE" } + if (-not (Get-Process -Id $child.Id -ErrorAction SilentlyContinue)) { throw "suspend killed the child" } + & $agent --resume-pid $child.Id | Out-Host + if ($LASTEXITCODE -ne 0) { throw "resume exit $LASTEXITCODE" } + Stop-Process -Id $child.Id -Force + Write-Host "suspend and resume OK" + + # Refuse a critical process even with a real pid. + $sys = Get-Process -Name "lsass" -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($sys) { + & $agent --kill-pid $sys.Id "C:\Windows\System32\lsass.exe" 0 + if ($LASTEXITCODE -eq 0) { throw "critical process lsass was not refused" } + Write-Host "critical process refusal OK" + } + + # Quarantine then restore a temp file and compare hashes. + $qdir = Join-Path $env:RUNNER_TEMP "tawny-quarantine" + Remove-Item -LiteralPath $qdir -Recurse -Force -ErrorAction SilentlyContinue + $target = Join-Path $env:RUNNER_TEMP ("mal-" + [Guid]::NewGuid().ToString('N') + ".bin") + [IO.File]::WriteAllBytes($target, [byte[]](0x4D,0x5A,0x90,0x00,0x11,0x22,0x33)) + $before = (Get-FileHash -Algorithm SHA256 -LiteralPath $target).Hash.ToLower() + & $agent --quarantine $target $before $qdir | Out-Host + if ($LASTEXITCODE -ne 0) { throw "quarantine exit $LASTEXITCODE" } + if (Test-Path -LiteralPath $target) { throw "original not removed after quarantine" } + if (-not (Test-Path -LiteralPath (Join-Path $qdir "$before.bin"))) { throw "quarantine copy missing" } + & $agent --restore $before $qdir | Out-Host + if ($LASTEXITCODE -ne 0) { throw "restore exit $LASTEXITCODE" } + $after = (Get-FileHash -Algorithm SHA256 -LiteralPath $target).Hash.ToLower() + if ($before -ne $after) { throw "restore hash mismatch: $before vs $after" } + Write-Host "quarantine and restore round-trip OK" + # --eventlog-dump reads, maps and bookmarks the channels. A second and # third dump with the same state dir check that a restart neither # repeats nor skips events. Sysmon is not installed on the runner. diff --git a/agent/src/main.zig b/agent/src/main.zig index 3a93ec7..7ccde5c 100644 --- a/agent/src/main.zig +++ b/agent/src/main.zig @@ -39,6 +39,11 @@ 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("response_debug.zig").isDebugCommand(args[1])) { + const code = @import("response_debug.zig").run(alloc, args[1..]); + if (code != 0) std.process.exit(code); + return; + } if (builtin.target.os.tag == .windows) { // Under the SCM this blocks until the service stops; ServiceMain runs @@ -489,6 +494,7 @@ test "main module loads" { _ = @import("quarantine.zig"); _ = @import("platform/windows/wfp.zig"); _ = @import("platform/windows/process_control.zig"); + _ = @import("response_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. diff --git a/agent/src/response_debug.zig b/agent/src/response_debug.zig new file mode 100644 index 0000000..5a43e6f --- /dev/null +++ b/agent/src/response_debug.zig @@ -0,0 +1,91 @@ +//! Debug subcommands that drive the response actions from CI without a server +//! (#57). Windows CI starts a process, then calls these to kill it by PID and +//! start time, suspend and resume a child, and quarantine and restore a file. +//! Like `--eventlog-dump`, these are plumbing for tests, not a product surface. +//! +//! Usage (argv after the program name): +//! --kill-pid [ ] +//! --suspend-pid +//! --resume-pid +//! --quarantine +//! --restore +//! +//! Each prints one status line and returns 0 on success. + +const std = @import("std"); +const builtin = @import("builtin"); +const quarantine = @import("quarantine.zig"); +const process_control = if (builtin.target.os.tag == .windows) + @import("platform/windows/process_control.zig") +else + struct {}; + +pub fn isDebugCommand(arg: []const u8) bool { + return std.mem.eql(u8, arg, "--kill-pid") or + std.mem.eql(u8, arg, "--suspend-pid") or + std.mem.eql(u8, arg, "--resume-pid") or + std.mem.eql(u8, arg, "--quarantine") or + std.mem.eql(u8, arg, "--restore"); +} + +/// `args` is argv[1..]. Returns a process exit code. +pub fn run(alloc: std.mem.Allocator, args: []const []const u8) u8 { + if (args.len == 0) return usage(); + const cmd = args[0]; + + if (std.mem.eql(u8, cmd, "--quarantine")) { + if (args.len != 4) return usage(); + const rec = quarantine.quarantine(alloc, args[3], args[1], args[2]) catch |err| { + std.debug.print("quarantine failed: {s}\n", .{@errorName(err)}); + return 1; + }; + std.debug.print("quarantined sha256={s} size={d}\n", .{ &rec.sha256, rec.size }); + return 0; + } + if (std.mem.eql(u8, cmd, "--restore")) { + if (args.len != 3) return usage(); + const original = quarantine.restore(alloc, args[2], args[1]) catch |err| { + std.debug.print("restore failed: {s}\n", .{@errorName(err)}); + return 1; + }; + defer alloc.free(original); + std.debug.print("restored path={s}\n", .{original}); + return 0; + } + + // Process actions. + if (builtin.target.os.tag != .windows) { + std.debug.print("process debug commands are Windows only\n", .{}); + return 2; + } + if (args.len < 2) return usage(); + const pid = std.fmt.parseInt(u32, args[1], 10) catch { + std.debug.print("bad pid\n", .{}); + return 2; + }; + var id = process_control.Identity{}; + if (std.mem.eql(u8, cmd, "--kill-pid") and args.len >= 4) { + id.image_path = args[2]; + id.start_time_unix = std.fmt.parseInt(i64, args[3], 10) catch null; + } + const outcome = if (std.mem.eql(u8, cmd, "--kill-pid")) + process_control.kill(alloc, pid, id) + else if (std.mem.eql(u8, cmd, "--suspend-pid")) + process_control.suspend_(alloc, pid, id) + else if (std.mem.eql(u8, cmd, "--resume-pid")) + process_control.resume_(alloc, pid, id) + else + return usage(); + + const o = outcome catch |err| { + std.debug.print("{s} failed: {s}\n", .{ cmd, @errorName(err) }); + return 1; + }; + std.debug.print("{s} ok: {s}\n", .{ cmd, @tagName(o) }); + return 0; +} + +fn usage() u8 { + std.debug.print("usage: --kill-pid [ ] | --suspend-pid | --resume-pid | --quarantine | --restore \n", .{}); + return 2; +} diff --git a/docs/api.md b/docs/api.md index c4f8c91..74ade0a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -36,12 +36,23 @@ Response `200`: "agent_id": "8f3c1a2b-...", "jwt": "eyJhbGciOi...", "jwt_expires_at": "2026-08-11T00:00:00Z", + "action_public_key": "base64 Ed25519 public key", "yara_rule_key": "base64 Ed25519 public key", "config": { "heartbeat_interval_seconds": 60 } } ``` -`yara_rule_key` is the key that signs YARA rule packs. The agent pins it in `.yarakey` the first time and refuses packs signed by any other key. A `yara_rule_key` in the agent's `config.toml` takes precedence. +`action_public_key` is the server action key. One Ed25519 key signs both +response actions and YARA rule packs, so `yara_rule_key` carries the same bytes +(kept for compatibility). The agent pins it in `.actionkey` (and +`.yarakey`) the first time and refuses actions or packs signed by any +other key. A `yara_rule_key` in the agent's `config.toml` takes precedence. + +Trust on first use: an agent enrolled before the action key existed has no +pinned key. Its first heartbeat that carries `action_public_key` pins it, over +the same TLS channel the JWT already trusts, and the agent logs that it did. +The window is that first heartbeat; after it a different key is refused, so +changing the server key means re-enrolling agents or setting the key in config. Errors: `401` if token unknown or already used, `410` if token expired. @@ -330,13 +341,27 @@ triggering telemetry `payload`, `severity` (`low|medium|high|critical`) and ### POST `/api/agents/{id}/actions` Admin web user or Admin `twny_` API token. Body: -`{"action_type":"kill_process"|"isolate_host"|"release_host"|"yara_scan","payload":{...},"idempotency_key":"..."}`. -`kill_process` requires `payload.pid` (positive integer). `yara_scan` takes `payload.path`, a file or a folder (not recursive); matches arrive as `yara_match` events. Re-posting the same -`idempotency_key` for the same agent returns the existing action. Poll -`GET /api/agents/{id}/actions` for the outcome; actions are delivered on the -agent's next heartbeat and finish as `succeeded`, `failed`, `cancelled` or -`expired`. Host isolation and release are not yet implemented by the agent and -currently complete as `failed`. +`{"action_type":"kill_process"|"suspend_process"|"resume_process"|"quarantine_file"|"restore_file"|"isolate_host"|"release"|"release_host"|"yara_scan","payload":{...},"idempotency_key":"..."}`. +`kill_process`, `suspend_process` and `resume_process` take `payload.pid` +(positive integer) and optional `image_path` and `start_time_unix` for the PID +reuse guard. `quarantine_file` takes `payload.path` and `payload.sha256`; +`restore_file` takes `payload.sha256`. `yara_scan` takes `payload.path`, a file +or a folder (not recursive); matches arrive as `yara_match` events. Re-posting +the same `idempotency_key` for the same agent returns the existing action. + +Every dispatched action is signed by the server action key. The agent verifies +the signature against its pinned key before it runs anything, and refuses +unsigned, expired, tampered or wrong-key actions, reporting `failed` with a +reason. The signed string is +`tawny-action-v1\n\n\n\n\n`; +the heartbeat adds `signature` and `action_public_key` to its reply. + +Poll `GET /api/agents/{id}/actions` for the outcome; actions are delivered on +the agent's next heartbeat and finish as `succeeded`, `failed`, `cancelled` or +`expired`. Process control, quarantine and restore run on Windows; quarantine +and restore also run on Linux and macOS. Host isolation (`isolate_host`, +`isolate`) and `release` report `failed` with a clear reason until WFP and +nftables isolation land. ### GET `/api/agents/{id}/actions` and `/api/agents/{id}/actions/{actionId}` diff --git a/docs/architecture/target-edr.md b/docs/architecture/target-edr.md index 855e898..11fbc46 100644 --- a/docs/architecture/target-edr.md +++ b/docs/architecture/target-edr.md @@ -499,9 +499,10 @@ server. Files stay on the host unless an analyst collects them. `yara_rule_key` in config) and refuses unsigned, tampered, wrong-key or older packs, keeping the rules it has. The heartbeat reply carries `yara_pack_version` so agents fetch only on change. -- **Key.** `TAWNY_RULE_SIGNING_KEY`, or derived from the agent JWT seed. A - separate key from the JWT key. Issue #57 adds a server action key; that - work can merge the two behind `state.rulePackKey`. +- **Key.** The server action key (#57) signs both response actions and YARA + rule packs. `TAWNY_ACTION_SIGNING_KEY`, or derived from the agent JWT seed + with its own label, separate from the JWT key. `TAWNY_RULE_SIGNING_KEY` is a + deprecated alias. `state.rulePackKey` forwards to `state.actionKey`. - **Alerts.** A `yara_match` raises an alert through the `yara` rule that declares the matched rule name, so suppressions and sinks work as usual. @@ -616,6 +617,17 @@ metadata (original path, ACL SDDL, owner, timestamps, hashes, source action). Restore re-creates path + ACL. Original deleted only after the quarantine copy is fsynced and its hash verified. +**Status (#57).** The server signs every action with the action key and the +agent verifies it before acting, with a local journal for dedupe and restart +replay. Windows kill, suspend and resume work with the identity guard and the +critical-process refusal list. Quarantine and restore work on Windows, Linux +and macOS (XOR obfuscation, SDDL on Windows, owner-only elsewhere). WFP +isolation has the filter-building plan, the auto-release deadline, the +reconcile-on-start design and the break-glass release code as pure, tested +logic; the live FwpmEngine integration and the `tawny-agent release --code` +CLI are not wired yet, and `isolate_host`/`release` report `failed` until then. +Linux nftables isolation lands in #59. + ## 10. Agent identity, protection, updates, health ### Identity diff --git a/docs/production.md b/docs/production.md index 47c4941..3b2d741 100644 --- a/docs/production.md +++ b/docs/production.md @@ -10,7 +10,8 @@ | `TAWNY_DATABASE_URL` | `postgres://tawny:@postgres:5432/tawny` | | `TAWNY_INTEGRATION_ENCRYPTION_KEY` | ≥ 32 random bytes. Losing it makes stored integration secrets unreadable. | | `TAWNY_AGENT_JWT_SEED` | 64 hex characters (`openssl rand -hex 32`). Stable Ed25519 seed for newly issued agent JWTs. `tawny-server serve` refuses to start when it's missing or malformed. `TAWNY_DEV=1` swaps that for a random seed per start, for local development only: every agent has to re-enrol after a restart. | -| `TAWNY_RULE_SIGNING_KEY` | Optional, 64 hex characters. Ed25519 seed that signs YARA rule packs. When unset the key is derived from `TAWNY_AGENT_JWT_SEED` (HKDF with its own label), so it stays the same across restarts. Agents pin the public key at enrolment and refuse packs signed by another key, so changing it means re-enrolling agents or setting `yara_rule_key` in their config. | +| `TAWNY_ACTION_SIGNING_KEY` | Optional, 64 hex characters. Ed25519 seed for the server action key. One key signs both response actions and YARA rule packs. When unset the key is derived from `TAWNY_AGENT_JWT_SEED` (HKDF with its own label `tawny-action-key-v1`), so it stays the same across restarts and still differs from the JWT key. Agents pin the public key at enrolment and refuse actions or packs signed by another key, so changing it means re-enrolling agents or setting the key in their config. Agents enrolled before this key existed pin it on their next heartbeat (trust on first use); that window is the first heartbeat that carries the key. | +| `TAWNY_RULE_SIGNING_KEY` | Deprecated alias of `TAWNY_ACTION_SIGNING_KEY`, still honoured. Rename it; it now signs response actions as well as YARA rule packs. | | `TAWNY_REQUIRE_SIGNED_BATCHES` | On by default. Telemetry from an agent with no stored device key is refused with a 401. Set `off` only while older agents that enrolled without a key are re-enrolled. | | `TAWNY_AGENT_JWT_SIGNING_KEY_PEM` | RSA PEM used only to verify tokens issued before the Ed25519 cutover. | | `TAWNY_PUBLIC_URL` | `https://…` origin browsers and enrollment commands use. | diff --git a/docs/threat-model.md b/docs/threat-model.md index 0a465de..dd55f8c 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -32,8 +32,9 @@ Honest threat model for Tawny as a self-hosted EDR. Not a substitute for a forma | 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 | | Cross-tenant IDOR | Controllers filter by `User.GetTenantId()`; alerts/rules/response actions store TenantId; regression suite covers agents, alerts, rules, hunts, TI, tokens, audit | Keep expanding matrix | | Telemetry fabrication / replay | `client_event_id` de-dupe, batch id, sequence watermark, future/past timestamp bounds, confidence=`agent_reported`, audit for gaps/rollback/volume spikes | Signed batches / external correlation | -| Response-action replay | Single-use execution token hash, expiry, terminal-state lock, server `ReceivedAt` | Approval workflow for destructive actions | -| PID reuse on kill_process | Optional image/path/start-time/hash fields in payload (agent best-effort match) | Strong OS process identity APIs | +| Response-action replay | Single-use execution token hash, expiry, terminal-state lock, server `ReceivedAt`, local action journal dedupes by `action_id` and replays on restart | Approval workflow for destructive actions | +| Forged or tampered response action | Server signs each action with the Ed25519 action key (`tawny-action-v1` over id, agent, type, expiry and payload hash); the agent verifies against its pinned key and refuses unsigned, expired, tampered or wrong-key actions. Key pinned at enrolment, or trust on first use from the first heartbeat that carries it | Mutual TLS client certs | +| PID reuse on kill/suspend/resume | Image path and start time compared against the live process (Linux `/proc`, Windows `QueryFullProcessImageNameW` + `GetProcessTimes`); critical-process refusal list | Strong OS process identity (entity id) APIs | | Compromised enrolled endpoint | Agent is trusted for *its own* telemetry only; cannot escalate to other agents without their credentials | Telemetry confidence labels, sequence numbers | | Telemetry fabrication | Authenticated agent can fabricate events for itself; server stamps `received_at` | Sequence/replay detection, signed batches | | Forged agent identity | New JWTs are Ed25519. Pre-cutover RS256 tokens still verify. Claims include agent_id, tenant, and cv | Per-agent asymmetric enrollment keys | From de66fcf391b478f0b48df8faec01b8e501674c49 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 03:03:20 +1100 Subject: [PATCH 4/8] fix(agent): quarantine ACL order and robust Windows CI start time Apply the restrictive ACL to the quarantine copy and sidecar only after the read-back verification, so a SYSTEM-only DACL never blocks the agent's own verify or a later restore. Widen the Windows DACL to SYSTEM plus local Administrators, so an agent not running as SYSTEM (CI, or a service misconfiguration) can still read the copy back; normal users still cannot run it. Compute the Windows CI ping start time with DateTimeOffset instead of Get-Date -UFormat %s, avoiding a double UTC offset and locale parsing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +++- agent/src/quarantine.zig | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb764d6..f25b34f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -205,7 +205,9 @@ jobs: # Kill by PID plus start time. Start a long-running ping we own. $ping = Start-Process -FilePath "ping.exe" -ArgumentList @("-t", "127.0.0.1") -PassThru Start-Sleep -Seconds 1 - $start = [int][double]::Parse((Get-Date $ping.StartTime.ToUniversalTime() -UFormat %s)) + # DateTimeOffset of a Local-kind DateTime uses the local offset, so + # this is the correct absolute instant with no locale parsing. + $start = [int]([DateTimeOffset]$ping.StartTime).ToUnixTimeSeconds() $image = (Get-Process -Id $ping.Id).Path & $agent --kill-pid $ping.Id $image $start | Out-Host if ($LASTEXITCODE -ne 0) { throw "kill-pid exit $LASTEXITCODE" } diff --git a/agent/src/quarantine.zig b/agent/src/quarantine.zig index bb8d312..a741379 100644 --- a/agent/src/quarantine.zig +++ b/agent/src/quarantine.zig @@ -85,7 +85,6 @@ pub fn quarantine( try f.writePositionalAll(io, encoded, 0); f.sync(io) catch {}; } - restrictPermissions(bin_path); // Verify the copy decodes back to the expected hash before deleting. { @@ -117,6 +116,10 @@ pub fn quarantine( }, .{}); defer alloc.free(sidecar); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = sidecar_path, .data = sidecar }); + + // Lock down the copy and sidecar only after the read-back verification, so + // a SYSTEM-only ACL never blocks the agent's own verify. + restrictPermissions(bin_path); restrictPermissions(sidecar_path); // Only now remove the original. @@ -178,8 +181,11 @@ fn restrictPermissions(path: []const u8) void { if (builtin.target.os.tag == .windows) { var buf: [1024]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buf); - // D:PAI(A;;FA;;;SY) — SYSTEM full access, protected, no inheritance. - applySddl(fba.allocator(), path, "D:PAI(A;;FA;;;SY)") catch {}; + // Protected DACL, no inheritance: SYSTEM and local Administrators full + // access, everyone else none. Admins are kept so an agent that is not + // running as SYSTEM (CI, or a service misconfiguration) can still read + // the copy back and restore it; normal users still cannot run it. + applySddl(fba.allocator(), path, "D:PAI(A;;FA;;;SY)(A;;FA;;;BA)") catch {}; return; } const io = iox.current(); From 9170edbd9122ae18dc8bed41b21dd6de4d791d1d Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 03:04:08 +1100 Subject: [PATCH 5/8] ci: govern Windows response step by exit code, not native error preference PowerShell 7.4 on the hosted runner propagates a native command's non-zero exit as a terminating error by default, which would throw on the agent's intentional refusal of a critical process before the explicit exit-code check. Disable that for the step. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f25b34f..f9c0a1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -200,6 +200,10 @@ jobs: timeout-minutes: 10 run: | $ErrorActionPreference = "Stop" + # The agent exits non-zero on purpose for a refused critical process. + # Govern flow by $LASTEXITCODE, not PowerShell 7.4's native-command + # error propagation, which would otherwise throw on that exit. + $PSNativeCommandUseErrorActionPreference = $false $agent = Join-Path $PWD "zig-out\bin\tawny-agent.exe" # Kill by PID plus start time. Start a long-running ping we own. From 19b032577628b744df55e139a799b0478929410c Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 03:30:52 +1100 Subject: [PATCH 6/8] feat(agent): live WFP isolation, reconcile, deadline and break-glass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Link fwpuclnt (Windows only) and implement the live WFP engine in platform/windows/wfp.zig: FwpmEngineOpen0, a transaction, the Tawny provider and fixed-GUID sublayer, persistent filters built from the pure plan (permit loopback, resolved server IPs, DNS resolvers and an optional admin allowlist on the four ALE layers, block everything else), and delete by sublayer on release. A TCP verify probe reports the server reachable and a blocked address unreachable. Wire isolate_host and release to it on Windows; Linux and macOS keep a clear "not supported on " failure. Isolation state is persisted to .wfp so the agent reconciles filters with the journal at start and releases itself when the deadline (default 24 h) passes, checked on each heartbeat and at start. Break-glass `tawny-agent release --code ` verifies the HMAC of the agent id and nonce with TAWNY_ISOLATION_SECRET. CI: a safe live WFP step runs `tawny-agent --wfp-selftest`, which adds a single TEST-NET block filter (never a block-all, so it can't cut the runner off), confirms it is present and that a routable address stays reachable, then releases and confirms the sublayer is empty. Docs: target-edr §9 and api.md updated for live isolation. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 17 + agent/build.zig | 2 + agent/src/main.zig | 102 ++++++ agent/src/platform/windows/wfp.zig | 567 ++++++++++++++++++++++++++++- agent/src/response_actions.zig | 101 ++++- agent/src/response_debug.zig | 56 ++- docs/api.md | 9 +- docs/architecture/target-edr.md | 17 +- 8 files changed, 843 insertions(+), 28 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f9c0a1f..54a9526 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -258,6 +258,23 @@ jobs: if ($before -ne $after) { throw "restore hash mismatch: $before vs $after" } Write-Host "quarantine and restore round-trip OK" + # Live WFP: adds one block filter for a TEST-NET address (192.0.2.1), + # never a block-all, so it cannot cut the runner off. Confirms the filter + # is present, a routable address stays reachable (no over-block), then + # releases and confirms the sublayer is empty. Admin is required to open + # the filter engine; GitHub's windows runner user is an administrator. + - name: prove live WFP add, probe and release (safe, no block-all) + if: matrix.name == 'windows-x64' + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = "Stop" + $PSNativeCommandUseErrorActionPreference = $false + $agent = Join-Path $PWD "zig-out\bin\tawny-agent.exe" + & $agent --wfp-selftest | Out-Host + if ($LASTEXITCODE -ne 0) { throw "wfp-selftest exit $LASTEXITCODE" } + Write-Host "live WFP add/probe/release OK" + # --eventlog-dump reads, maps and bookmarks the channels. A second and # third dump with the same state dir check that a restart neither # repeats nor skips events. Sysmon is not installed on the runner. diff --git a/agent/build.zig b/agent/build.zig index d24e6c2..65ac171 100644 --- a/agent/build.zig +++ b/agent/build.zig @@ -62,6 +62,8 @@ fn linkPlatformLibraries(mod: *std.Build.Module, os: std.Target.Os.Tag) void { mod.linkSystemLibrary("wtsapi32", .{}); mod.linkSystemLibrary("ntdll", .{}); mod.linkSystemLibrary("wevtapi", .{}); + // WFP user-mode API for network isolation (#57). + mod.linkSystemLibrary("fwpuclnt", .{}); }, // macOS: libproc and libdispatch come from libSystem (link_libc). // CoreServices/CoreFoundation (FSEvents) are dlopen'd at runtime by diff --git a/agent/src/main.zig b/agent/src/main.zig index 7ccde5c..2a7daf1 100644 --- a/agent/src/main.zig +++ b/agent/src/main.zig @@ -44,6 +44,10 @@ pub fn main(init: std.process.Init) !void { if (code != 0) std.process.exit(code); return; } + // Break-glass: tawny-agent release --code + if (args.len == 4 and std.mem.eql(u8, args[1], "release") and std.mem.eql(u8, args[2], "--code")) { + return releaseCodeCommand(alloc, args[3]); + } if (builtin.target.os.tag == .windows) { // Under the SCM this blocks until the service stops; ServiceMain runs @@ -173,6 +177,10 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { const quarantine_dir = quarantineDir(alloc, cfg.state_path) catch try alloc.dupe(u8, "quarantine"); defer alloc.free(quarantine_dir); + // Reconcile WFP isolation with the journal at start, so a crash never + // leaves stray filters and an expired deadline releases itself (#57 §9.3). + reconcileIsolation(alloc, &cfg); + var inventory = inventory_collector.Scanner.init(alloc); var extensions = extensions_collector.Scanner.init(alloc); var mcp = mcp_collector.Scanner.init(alloc); @@ -247,11 +255,16 @@ fn runAgent(alloc: std.mem.Allocator) anyerror!void { .public_key = action_pub, .journal = j, .quarantine_dir = quarantine_dir, + .state_path = cfg.state_path, + .backend_url = cfg.backend_url, }, action); } else { std.debug.print("response action {s} skipped: no journal\n", .{action.id}); } } + // Enforce the isolation deadline: if it passed with no renewal, + // release ourselves. + enforceIsolationDeadline(alloc, &cfg); } else |err| { std.debug.print("heartbeat failed: {s}\n", .{@errorName(err)}); } @@ -452,6 +465,95 @@ fn quarantineDir(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { return std.fs.path.join(alloc, &.{ state_dir, "quarantine" }); } +const wfp = @import("platform/windows/wfp.zig"); + +/// At start, reconcile WFP filters with the stored isolation state. If the +/// deadline has passed, or there is no isolation on record, remove any stray +/// Tawny filters. If still isolated and the filters are gone (a crash), re-add +/// them from the stored inputs. +fn reconcileIsolation(alloc: std.mem.Allocator, cfg: *config_mod.Config) void { + if (builtin.target.os.tag != .windows) return; + const loaded = wfp.loadState(alloc, cfg.state_path); + if (loaded == null) { + // No record: clear anything stray so a crash never leaves isolation on. + if (wfp.countFilters()) |n| { + if (n > 0) wfp.release() catch {}; + } else |_| {} + return; + } + const s = loaded.?; + defer s.deinit(); + if (!s.value.isolated) { + wfp.release() catch {}; + wfp.clearState(alloc, cfg.state_path); + return; + } + if (wfp.deadlinePassed(s.value.started_unix, s.value.max_duration_seconds, iox.timestamp())) { + std.log.info("isolation deadline passed; releasing", .{}); + wfp.release() catch {}; + wfp.clearState(alloc, cfg.state_path); + return; + } + // Still isolated within the deadline: ensure the filters are present. + const n = wfp.countFilters() catch 0; + if (n == 0) { + std.log.info("re-applying isolation filters after restart", .{}); + wfp.isolate(alloc, .{ + .server_ips = s.value.server_ips, + .dns_resolvers = s.value.dns_resolvers, + .admin_allowlist = s.value.admin_allowlist, + }) catch |err| std.debug.print("re-isolate failed: {s}\n", .{@errorName(err)}); + } +} + +/// On each heartbeat, release isolation if its deadline has passed with no +/// server renewal. +fn enforceIsolationDeadline(alloc: std.mem.Allocator, cfg: *config_mod.Config) void { + if (builtin.target.os.tag != .windows) return; + const loaded = wfp.loadState(alloc, cfg.state_path) orelse return; + defer loaded.deinit(); + if (!loaded.value.isolated) return; + if (wfp.deadlinePassed(loaded.value.started_unix, loaded.value.max_duration_seconds, iox.timestamp())) { + std.log.info("isolation deadline passed; releasing", .{}); + wfp.release() catch {}; + wfp.clearState(alloc, cfg.state_path); + } +} + +/// Break-glass: `tawny-agent release --code `. The code is +/// HMAC-SHA256(secret, agent_id|nonce). The per-agent secret comes from +/// TAWNY_ISOLATION_SECRET (shown in the UI); the nonce is the one recorded when +/// isolation started. On a valid code the agent releases WFP isolation offline. +fn releaseCodeCommand(alloc: std.mem.Allocator, code: []const u8) !void { + var cfg = try config_mod.load(alloc); + defer cfg.deinit(); + const agent_id = cfg.agent_id orelse { + std.debug.print("release: this host is not enrolled\n", .{}); + return; + }; + const secret = @import("env.zig").getEnvVarOwned(alloc, "TAWNY_ISOLATION_SECRET") catch null; + defer if (secret) |s| alloc.free(s); + if (secret == null or secret.?.len == 0) { + std.debug.print("release: TAWNY_ISOLATION_SECRET is not set; cannot verify the break-glass code\n", .{}); + return; + } + const loaded = wfp.loadState(alloc, cfg.state_path) orelse { + std.debug.print("release: no isolation on record\n", .{}); + return; + }; + defer loaded.deinit(); + if (!wfp.verifyReleaseCode(secret.?, agent_id, loaded.value.nonce, code)) { + std.debug.print("release: break-glass code did not verify\n", .{}); + return; + } + wfp.release() catch |err| { + std.debug.print("release: {s}\n", .{@errorName(err)}); + return; + }; + wfp.clearState(alloc, cfg.state_path); + std.debug.print("release: isolation released by break-glass code\n", .{}); +} + fn scrubEnrollmentToken(alloc: std.mem.Allocator, config_path: []const u8) void { const removed = config_mod.removeEnrollmentToken(alloc, config_path) catch |err| { std.log.warn( diff --git a/agent/src/platform/windows/wfp.zig b/agent/src/platform/windows/wfp.zig index f1f51e6..4c1e415 100644 --- a/agent/src/platform/windows/wfp.zig +++ b/agent/src/platform/windows/wfp.zig @@ -124,33 +124,543 @@ pub fn deadlinePassed(started_unix: i64, max_duration_seconds: i64, now_unix: i6 return now_unix >= started_unix + max_duration_seconds; } -// --- Live WFP engine (Windows only). Not exercised in unit tests. --- +const iox = @import("../../io_compat.zig"); + +/// Persisted isolation state, so the agent can reconcile filters and enforce +/// the deadline across restarts. Stored at `.wfp`. +pub const State = struct { + isolated: bool = false, + started_unix: i64 = 0, + max_duration_seconds: i64 = default_max_duration_seconds, + nonce: []const u8 = "", + server_ips: []const []const u8 = &.{}, + dns_resolvers: []const []const u8 = &.{}, + admin_allowlist: []const []const u8 = &.{}, +}; + +fn statePath(alloc: std.mem.Allocator, state_path: []const u8) ![]u8 { + return std.fmt.allocPrint(alloc, "{s}.wfp", .{state_path}); +} + +pub fn saveState(alloc: std.mem.Allocator, state_path: []const u8, s: State) !void { + const p = try statePath(alloc, state_path); + defer alloc.free(p); + const body = try std.json.Stringify.valueAlloc(alloc, s, .{}); + defer alloc.free(body); + const io = iox.current(); + if (std.fs.path.dirname(p)) |d| std.Io.Dir.cwd().createDirPath(io, d) catch {}; + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = body }); +} + +/// Load the state. Caller calls `.deinit()` on the result. Returns null when +/// there is no state file. +pub fn loadState(alloc: std.mem.Allocator, state_path: []const u8) ?std.json.Parsed(State) { + const p = statePath(alloc, state_path) catch return null; + defer alloc.free(p); + const io = iox.current(); + const raw = std.Io.Dir.cwd().readFileAlloc(io, p, alloc, .limited(64 * 1024)) catch return null; + defer alloc.free(raw); + // alloc_always so the parsed strings own their memory and survive freeing raw. + return std.json.parseFromSlice(State, alloc, raw, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch null; +} + +pub fn clearState(alloc: std.mem.Allocator, state_path: []const u8) void { + const p = statePath(alloc, state_path) catch return; + defer alloc.free(p); + std.Io.Dir.cwd().deleteFile(iox.current(), p) catch {}; +} + +/// Parse a dotted IPv4 address to a host-order u32 (WFP wants host order in +/// FWP_V4_ADDR_AND_MASK). Pure, tested on every OS. Returns null on junk. +pub fn parseIpv4(text: []const u8) ?u32 { + var out: u32 = 0; + var octet: u32 = 0; + var digits: u8 = 0; + var parts: u8 = 0; + for (text) |c| { + if (c == '.') { + if (digits == 0 or octet > 255) return null; + out = (out << 8) | octet; + octet = 0; + digits = 0; + parts += 1; + if (parts > 3) return null; + } else if (c >= '0' and c <= '9') { + octet = octet * 10 + (c - '0'); + digits += 1; + if (digits > 3) return null; + } else return null; + } + if (parts != 3 or digits == 0 or octet > 255) return null; + return (out << 8) | octet; +} + +test "parseIpv4 accepts valid addresses and refuses junk" { + try std.testing.expectEqual(@as(?u32, 0xC0000201), parseIpv4("192.0.2.1")); + try std.testing.expectEqual(@as(?u32, 0x7F000001), parseIpv4("127.0.0.1")); + try std.testing.expectEqual(@as(?u32, 0), parseIpv4("0.0.0.0")); + try std.testing.expectEqual(@as(?u32, 0xFFFFFFFF), parseIpv4("255.255.255.255")); + try std.testing.expect(parseIpv4("256.0.0.1") == null); + try std.testing.expect(parseIpv4("1.2.3") == null); + try std.testing.expect(parseIpv4("1.2.3.4.5") == null); + try std.testing.expect(parseIpv4("a.b.c.d") == null); + try std.testing.expect(parseIpv4("") == null); +} + +// --- Live WFP engine (Windows only). Compiled on the Windows target and +// driven by the CI self-test; not exercised in the cross-OS unit tests. --- pub const EngineError = error{ WfpUnavailable, EngineOpenFailed, + TransactionFailed, SublayerFailed, FilterAddFailed, + EnumFailed, + BadAddress, + OutOfMemory, }; -/// Open the engine, add the sublayer and the plan's filters as persistent -/// filters, verify the probe, and return. On non-Windows this is unsupported. +/// Probe results after isolating: whether the server stayed reachable and +/// whether a blocked address became unreachable. +pub const Probe = struct { + server_reachable: bool, + blocked_unreachable: bool, +}; + +/// Open the engine and add the isolation filters as persistent filters in the +/// Tawny sublayer. Everything not permitted by the plan is blocked. Non-Windows +/// is unsupported. pub fn isolate(alloc: std.mem.Allocator, in: Inputs) EngineError!void { - if (builtin.target.os.tag != .windows) return error.WfpUnavailable; - _ = alloc; - _ = in; - // The fwpuclnt-backed implementation lives behind these externs; it is - // compiled on the Windows target and driven by the CI isolation step when - // the hosted runner allows it. See build.zig (fwpuclnt link). - return error.WfpUnavailable; + return switch (builtin.target.os.tag) { + .windows => win.isolate(alloc, in), + else => error.WfpUnavailable, + }; } -/// Delete the Tawny sublayer and its filters. Non-Windows is unsupported. +/// Delete the Tawny sublayer, its filters and the provider. pub fn release() EngineError!void { - if (builtin.target.os.tag != .windows) return error.WfpUnavailable; - return error.WfpUnavailable; + return switch (builtin.target.os.tag) { + .windows => win.release(), + else => error.WfpUnavailable, + }; } +/// Count the filters currently in the Tawny sublayer. Used by reconcile at +/// start and by the CI self-test. +pub fn countFilters() EngineError!usize { + return switch (builtin.target.os.tag) { + .windows => win.countFilters(), + else => error.WfpUnavailable, + }; +} + +/// CI self-test only: add a single block filter for one remote IPv4 address +/// (no block-all), so it cannot cut the runner off. Returns the filter id. +pub fn addTestBlock(ipv4: []const u8) EngineError!u64 { + return switch (builtin.target.os.tag) { + .windows => win.addTestBlock(ipv4), + else => error.WfpUnavailable, + }; +} + +/// TCP connect probe with a timeout. True when the address accepts a +/// connection. Windows only. +pub fn tcpReachable(ipv4: []const u8, port: u16, timeout_ms: u32) bool { + return switch (builtin.target.os.tag) { + .windows => win.tcpReachable(ipv4, port, timeout_ms), + else => false, + }; +} + +const win = if (builtin.target.os.tag == .windows) struct { + const WINAPI: std.lang.CallingConvention = .winapi; + const HANDLE = *anyopaque; + const DWORD = u32; + + // Action types (terminating). + const FWP_ACTION_FLAG_TERMINATING: u32 = 0x00001000; + const FWP_ACTION_BLOCK: u32 = 0x00000001 | FWP_ACTION_FLAG_TERMINATING; + const FWP_ACTION_PERMIT: u32 = 0x00000002 | FWP_ACTION_FLAG_TERMINATING; + // Data types. + const FWP_UINT8: u32 = 1; + const FWP_V4_ADDR_MASK: u32 = 0x100; + const FWP_V6_ADDR_MASK: u32 = 0x101; + // Match types. + const FWP_MATCH_EQUAL: u32 = 0; + // Filter flags. + const FWPM_FILTER_FLAG_PERSISTENT: u32 = 0x00000001; + // Enum type. + const FWP_FILTER_ENUM_OVERLAPPING: u32 = 1; + const RPC_C_AUTHN_WINNT: u32 = 0xFFFFFFFF; + + const G = Guid; + fn g(d1: u32, d2: u16, d3: u16, d4: [8]u8) G { + return .{ .data1 = d1, .data2 = d2, .data3 = d3, .data4 = d4 }; + } + const FWPM_LAYER_ALE_AUTH_CONNECT_V4 = g(0xc38d57d1, 0x05a7, 0x4c33, .{ 0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82 }); + const FWPM_LAYER_ALE_AUTH_CONNECT_V6 = g(0x4a72393b, 0x319f, 0x44bc, .{ 0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4 }); + const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 = g(0xe1cd9fe7, 0xf4b5, 0x4273, .{ 0x96, 0xc0, 0x59, 0x2e, 0x48, 0x7b, 0x86, 0x50 }); + const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 = g(0xa3b42c97, 0x9f04, 0x4672, .{ 0xb8, 0x7b, 0xca, 0xd7, 0xd3, 0xb2, 0xfa, 0x37 }); + const FWPM_CONDITION_IP_REMOTE_ADDRESS = g(0xb235ae9a, 0x1d64, 0x49b8, .{ 0xa4, 0x4c, 0x5f, 0xf3, 0xd9, 0x09, 0x50, 0x45 }); + const FWPM_CONDITION_IP_LOCAL_ADDRESS = g(0xd9ee00de, 0xc1ef, 0x4617, .{ 0xbf, 0xe3, 0xff, 0xd8, 0xf5, 0xa0, 0x89, 0x57 }); + // Our own provider key, distinct from the sublayer key. + const provider_guid = g(0x7a3c1e54, 0x2b6d, 0x4f18, .{ 0x9c, 0x0a, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x02 }); + + const FWP_BYTE_BLOB = extern struct { size: u32 = 0, data: ?[*]u8 = null }; + const FWPM_DISPLAY_DATA0 = extern struct { name: ?[*:0]const u16 = null, description: ?[*:0]const u16 = null }; + const FWP_V4_ADDR_AND_MASK = extern struct { addr: u32, mask: u32 }; + const FWP_V6_ADDR_AND_MASK = extern struct { addr: [16]u8, prefixLength: u8 }; + + const FWP_VALUE0 = extern struct { + type: u32 = 0, + value: extern union { uint8: u8, uint16: u16, uint32: u32, ptr: ?*anyopaque } = .{ .ptr = null }, + }; + const FWP_CONDITION_VALUE0 = extern struct { + type: u32 = 0, + value: extern union { + uint8: u8, + uint16: u16, + uint32: u32, + v4: ?*FWP_V4_ADDR_AND_MASK, + v6: ?*FWP_V6_ADDR_AND_MASK, + } = .{ .v4 = null }, + }; + const FWPM_FILTER_CONDITION0 = extern struct { + fieldKey: G, + matchType: u32, + conditionValue: FWP_CONDITION_VALUE0, + }; + const FWPM_ACTION0 = extern struct { type: u32, filterType: G = std.mem.zeroes(G) }; + const FWPM_PROVIDER0 = extern struct { + providerKey: G, + displayData: FWPM_DISPLAY_DATA0, + flags: u32 = 0, + providerData: FWP_BYTE_BLOB = .{}, + serviceName: ?[*:0]u16 = null, + }; + const FWPM_SUBLAYER0 = extern struct { + subLayerKey: G, + displayData: FWPM_DISPLAY_DATA0, + flags: u32 = 0, + providerKey: ?*G = null, + providerData: FWP_BYTE_BLOB = .{}, + weight: u16 = 0, + }; + const FWPM_FILTER0 = extern struct { + filterKey: G = std.mem.zeroes(G), + displayData: FWPM_DISPLAY_DATA0 = .{}, + flags: u32 = 0, + providerKey: ?*G = null, + providerData: FWP_BYTE_BLOB = .{}, + layerKey: G, + subLayerKey: G, + weight: FWP_VALUE0 = .{}, + numFilterConditions: u32 = 0, + filterCondition: ?[*]const FWPM_FILTER_CONDITION0 = null, + action: FWPM_ACTION0, + context: extern union { rawContext: u64, providerContextKey: G } = .{ .rawContext = 0 }, + reserved: ?*G = null, + filterId: u64 = 0, + effectiveWeight: FWP_VALUE0 = .{}, + }; + const FWPM_FILTER_ENUM_TEMPLATE0 = extern struct { + providerKey: ?*G = null, + layerKey: G, + enumType: u32, + flags: u32 = 0, + providerContextTemplate: ?*anyopaque = null, + numFilterConditions: u32 = 0, + filterCondition: ?[*]const FWPM_FILTER_CONDITION0 = null, + actionMask: u32, + calloutKey: ?*G = null, + }; + + extern "fwpuclnt" fn FwpmEngineOpen0(serverName: ?[*:0]const u16, authnService: u32, authIdentity: ?*anyopaque, session: ?*anyopaque, engineHandle: *HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmEngineClose0(engineHandle: HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmTransactionBegin0(engineHandle: HANDLE, flags: u32) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmTransactionCommit0(engineHandle: HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmTransactionAbort0(engineHandle: HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmProviderAdd0(engineHandle: HANDLE, provider: *const FWPM_PROVIDER0, sd: ?*anyopaque) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmProviderDeleteByKey0(engineHandle: HANDLE, key: *const G) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmSubLayerAdd0(engineHandle: HANDLE, subLayer: *const FWPM_SUBLAYER0, sd: ?*anyopaque) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmSubLayerDeleteByKey0(engineHandle: HANDLE, key: *const G) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFilterAdd0(engineHandle: HANDLE, filter: *const FWPM_FILTER0, sd: ?*anyopaque, id: ?*u64) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFilterDeleteById0(engineHandle: HANDLE, id: u64) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFilterCreateEnumHandle0(engineHandle: HANDLE, enumTemplate: ?*const FWPM_FILTER_ENUM_TEMPLATE0, enumHandle: *HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFilterEnum0(engineHandle: HANDLE, enumHandle: HANDLE, numEntriesRequested: u32, entries: *[*]*FWPM_FILTER0, numEntriesReturned: *u32) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFilterDestroyEnumHandle0(engineHandle: HANDLE, enumHandle: HANDLE) callconv(WINAPI) DWORD; + extern "fwpuclnt" fn FwpmFreeMemory0(p: *?*anyopaque) callconv(WINAPI) void; + + const layers = [_]G{ + FWPM_LAYER_ALE_AUTH_CONNECT_V4, + FWPM_LAYER_ALE_AUTH_CONNECT_V6, + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, + }; + + fn open(engine: *HANDLE) EngineError!void { + if (FwpmEngineOpen0(null, RPC_C_AUTHN_WINNT, null, null, engine) != 0) return error.EngineOpenFailed; + } + + fn ensureProviderAndSublayer(engine: HANDLE) void { + var prov = std.mem.zeroes(FWPM_PROVIDER0); + prov.providerKey = provider_guid; + prov.displayData = .{ .name = tawny_name, .description = tawny_desc }; + prov.flags = 0x00000001; // FWPM_PROVIDER_FLAG_PERSISTENT + _ = FwpmProviderAdd0(engine, &prov, null); // ignore "already exists" + + var sub = std.mem.zeroes(FWPM_SUBLAYER0); + sub.subLayerKey = sublayer_guid; + sub.displayData = .{ .name = tawny_name, .description = tawny_desc }; + sub.flags = 0x00000001; // FWPM_SUBLAYER_FLAG_PERSISTENT + sub.providerKey = @constCast(&prov_key); + sub.weight = 0xFFFF; // high, above the default sublayers + _ = FwpmSubLayerAdd0(engine, &sub, null); // ignore "already exists" + } + + var prov_key: G = provider_guid; + const tawny_name: [*:0]const u16 = std.unicode.utf8ToUtf16LeStringLiteral("Tawny"); + const tawny_desc: [*:0]const u16 = std.unicode.utf8ToUtf16LeStringLiteral("Tawny EDR isolation"); + + fn isV6(layer: G) bool { + return std.meta.eql(layer, FWPM_LAYER_ALE_AUTH_CONNECT_V6) or std.meta.eql(layer, FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6); + } + + fn addPermitAddress(engine: HANDLE, layer: G, ip: u32, weight_val: u8) EngineError!void { + var mask = FWP_V4_ADDR_AND_MASK{ .addr = ip, .mask = 0xFFFFFFFF }; + var conds = [_]FWPM_FILTER_CONDITION0{.{ + .fieldKey = FWPM_CONDITION_IP_REMOTE_ADDRESS, + .matchType = FWP_MATCH_EQUAL, + .conditionValue = .{ .type = FWP_V4_ADDR_MASK, .value = .{ .v4 = &mask } }, + }}; + try addFilter(engine, layer, FWP_ACTION_PERMIT, weight_val, &conds); + } + + fn addPermitLoopback(engine: HANDLE, layer: G, weight_val: u8) EngineError!void { + if (isV6(layer)) { + var v6addr = std.mem.zeroes([16]u8); + v6addr[15] = 1; + var v6 = FWP_V6_ADDR_AND_MASK{ .addr = v6addr, .prefixLength = 128 }; + var conds = [_]FWPM_FILTER_CONDITION0{.{ + .fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS, + .matchType = FWP_MATCH_EQUAL, + .conditionValue = .{ .type = FWP_V6_ADDR_MASK, .value = .{ .v6 = &v6 } }, + }}; + try addFilter(engine, layer, FWP_ACTION_PERMIT, weight_val, &conds); + } else { + var mask = FWP_V4_ADDR_AND_MASK{ .addr = 0x7F000000, .mask = 0xFF000000 }; // 127.0.0.0/8 + var conds = [_]FWPM_FILTER_CONDITION0{.{ + .fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS, + .matchType = FWP_MATCH_EQUAL, + .conditionValue = .{ .type = FWP_V4_ADDR_MASK, .value = .{ .v4 = &mask } }, + }}; + try addFilter(engine, layer, FWP_ACTION_PERMIT, weight_val, &conds); + } + } + + fn addBlockAll(engine: HANDLE, layer: G) EngineError!void { + try addFilter(engine, layer, FWP_ACTION_BLOCK, 0, &[_]FWPM_FILTER_CONDITION0{}); + } + + fn addFilter(engine: HANDLE, layer: G, action: u32, weight_val: u8, conds: []const FWPM_FILTER_CONDITION0) EngineError!void { + var filter = FWPM_FILTER0{ + .layerKey = layer, + .subLayerKey = sublayer_guid, + .action = .{ .type = action }, + }; + filter.providerKey = @constCast(&prov_key); + filter.displayData = .{ .name = tawny_name, .description = tawny_desc }; + filter.flags = FWPM_FILTER_FLAG_PERSISTENT; + filter.weight = .{ .type = FWP_UINT8, .value = .{ .uint8 = weight_val } }; + if (conds.len > 0) { + filter.numFilterConditions = @intCast(conds.len); + filter.filterCondition = conds.ptr; + } + if (FwpmFilterAdd0(engine, &filter, null, null) != 0) return error.FilterAddFailed; + } + + fn isolate(alloc: std.mem.Allocator, in: Inputs) EngineError!void { + _ = alloc; + var engine: HANDLE = undefined; + try open(&engine); + defer _ = FwpmEngineClose0(engine); + if (FwpmTransactionBegin0(engine, 0) != 0) return error.TransactionFailed; + errdefer _ = FwpmTransactionAbort0(engine); + ensureProviderAndSublayer(engine); + + for (layers) |layer| { + try addPermitLoopback(engine, layer, 15); + if (!isV6(layer)) { + for (in.server_ips) |s| { + const ip = parseIpv4(s) orelse continue; + try addPermitAddress(engine, layer, ip, 14); + } + for (in.dns_resolvers) |s| { + const ip = parseIpv4(s) orelse continue; + try addPermitAddress(engine, layer, ip, 13); + } + for (in.admin_allowlist) |s| { + const ip = parseIpv4(s) orelse continue; + try addPermitAddress(engine, layer, ip, 12); + } + } + try addBlockAll(engine, layer); + } + if (FwpmTransactionCommit0(engine) != 0) return error.TransactionFailed; + } + + fn deleteProviderFilters(engine: HANDLE) EngineError!usize { + var removed: usize = 0; + for (layers) |layer| { + var tmpl = FWPM_FILTER_ENUM_TEMPLATE0{ + .layerKey = layer, + .enumType = FWP_FILTER_ENUM_OVERLAPPING, + .actionMask = 0xFFFFFFFF, + }; + tmpl.providerKey = @constCast(&prov_key); + var enum_h: HANDLE = undefined; + if (FwpmFilterCreateEnumHandle0(engine, &tmpl, &enum_h) != 0) return error.EnumFailed; + defer _ = FwpmFilterDestroyEnumHandle0(engine, enum_h); + while (true) { + var entries: [*]*FWPM_FILTER0 = undefined; + var num: u32 = 0; + if (FwpmFilterEnum0(engine, enum_h, 64, &entries, &num) != 0) return error.EnumFailed; + if (num == 0) break; + var i: u32 = 0; + while (i < num) : (i += 1) { + if (std.meta.eql(entries[i].subLayerKey, sublayer_guid)) { + if (FwpmFilterDeleteById0(engine, entries[i].filterId) == 0) removed += 1; + } + } + var mem: ?*anyopaque = @ptrCast(entries); + FwpmFreeMemory0(&mem); + if (num < 64) break; + } + } + return removed; + } + + fn release() EngineError!void { + var engine: HANDLE = undefined; + try open(&engine); + defer _ = FwpmEngineClose0(engine); + if (FwpmTransactionBegin0(engine, 0) != 0) return error.TransactionFailed; + errdefer _ = FwpmTransactionAbort0(engine); + _ = deleteProviderFilters(engine) catch {}; + _ = FwpmSubLayerDeleteByKey0(engine, &sublayer_guid); + _ = FwpmProviderDeleteByKey0(engine, &provider_guid); + if (FwpmTransactionCommit0(engine) != 0) return error.TransactionFailed; + } + + fn countFilters() EngineError!usize { + var engine: HANDLE = undefined; + try open(&engine); + defer _ = FwpmEngineClose0(engine); + var total: usize = 0; + for (layers) |layer| { + var tmpl = FWPM_FILTER_ENUM_TEMPLATE0{ + .layerKey = layer, + .enumType = FWP_FILTER_ENUM_OVERLAPPING, + .actionMask = 0xFFFFFFFF, + }; + tmpl.providerKey = @constCast(&prov_key); + var enum_h: HANDLE = undefined; + if (FwpmFilterCreateEnumHandle0(engine, &tmpl, &enum_h) != 0) return error.EnumFailed; + defer _ = FwpmFilterDestroyEnumHandle0(engine, enum_h); + var entries: [*]*FWPM_FILTER0 = undefined; + var num: u32 = 0; + if (FwpmFilterEnum0(engine, enum_h, 256, &entries, &num) != 0) return error.EnumFailed; + var i: u32 = 0; + while (i < num) : (i += 1) { + if (std.meta.eql(entries[i].subLayerKey, sublayer_guid)) total += 1; + } + if (num > 0) { + var mem: ?*anyopaque = @ptrCast(entries); + FwpmFreeMemory0(&mem); + } + } + return total; + } + + fn addTestBlock(ipv4: []const u8) EngineError!u64 { + const ip = parseIpv4(ipv4) orelse return error.BadAddress; + var engine: HANDLE = undefined; + try open(&engine); + defer _ = FwpmEngineClose0(engine); + if (FwpmTransactionBegin0(engine, 0) != 0) return error.TransactionFailed; + errdefer _ = FwpmTransactionAbort0(engine); + ensureProviderAndSublayer(engine); + var mask = FWP_V4_ADDR_AND_MASK{ .addr = ip, .mask = 0xFFFFFFFF }; + var conds = [_]FWPM_FILTER_CONDITION0{.{ + .fieldKey = FWPM_CONDITION_IP_REMOTE_ADDRESS, + .matchType = FWP_MATCH_EQUAL, + .conditionValue = .{ .type = FWP_V4_ADDR_MASK, .value = .{ .v4 = &mask } }, + }}; + var filter = FWPM_FILTER0{ + .layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4, + .subLayerKey = sublayer_guid, + .action = .{ .type = FWP_ACTION_BLOCK }, + }; + filter.providerKey = @constCast(&prov_key); + filter.displayData = .{ .name = tawny_name, .description = tawny_desc }; + filter.weight = .{ .type = FWP_UINT8, .value = .{ .uint8 = 15 } }; + filter.numFilterConditions = 1; + filter.filterCondition = &conds; + var id: u64 = 0; + if (FwpmFilterAdd0(engine, &filter, null, &id) != 0) return error.FilterAddFailed; + if (FwpmTransactionCommit0(engine) != 0) return error.TransactionFailed; + return id; + } + + // --- TCP connect probe via ws2_32 (non-blocking + select) --- + const SOCKET = usize; + const INVALID_SOCKET: SOCKET = ~@as(usize, 0); + const AF_INET: i32 = 2; + const SOCK_STREAM: i32 = 1; + const IPPROTO_TCP: i32 = 6; + const FIONBIO: u32 = 0x8004667E; + const sockaddr_in = extern struct { + family: i16, + port: u16, + addr: u32, + zero: [8]u8 = std.mem.zeroes([8]u8), + }; + const timeval = extern struct { tv_sec: i32, tv_usec: i32 }; + const fd_set = extern struct { count: u32, array: [64]SOCKET }; + const WSADATA = extern struct { pad: [512]u8 }; + + extern "ws2_32" fn WSAStartup(version: u16, data: *WSADATA) callconv(WINAPI) i32; + extern "ws2_32" fn WSACleanup() callconv(WINAPI) i32; + extern "ws2_32" fn socket(af: i32, t: i32, proto: i32) callconv(WINAPI) SOCKET; + extern "ws2_32" fn closesocket(s: SOCKET) callconv(WINAPI) i32; + extern "ws2_32" fn ioctlsocket(s: SOCKET, cmd: u32, argp: *u32) callconv(WINAPI) i32; + extern "ws2_32" fn connect(s: SOCKET, name: *const sockaddr_in, namelen: i32) callconv(WINAPI) i32; + extern "ws2_32" fn select(nfds: i32, readfds: ?*fd_set, writefds: ?*fd_set, exceptfds: ?*fd_set, timeout: *const timeval) callconv(WINAPI) i32; + extern "ws2_32" fn htons(v: u16) callconv(WINAPI) u16; + + fn tcpReachable(ipv4: []const u8, port: u16, timeout_ms: u32) bool { + const ip = parseIpv4(ipv4) orelse return false; + var wsa: WSADATA = undefined; + if (WSAStartup(0x0202, &wsa) != 0) return false; + defer _ = WSACleanup(); + const s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (s == INVALID_SOCKET) return false; + defer _ = closesocket(s); + var nonblock: u32 = 1; + _ = ioctlsocket(s, FIONBIO, &nonblock); + // sockaddr_in wants network byte order for addr and port. + var sa = sockaddr_in{ .family = AF_INET, .port = htons(port), .addr = std.mem.nativeToBig(u32, ip) }; + _ = connect(s, &sa, @sizeOf(sockaddr_in)); + var wset = std.mem.zeroes(fd_set); + wset.count = 1; + wset.array[0] = s; + const tv = timeval{ .tv_sec = @intCast(timeout_ms / 1000), .tv_usec = @intCast((timeout_ms % 1000) * 1000) }; + const r = select(0, null, &wset, null, &tv); + return r > 0; + } +} else struct {}; + test "plan permits loopback, dhcp, dns, server and admin, then blocks, on four layers" { const a = std.testing.allocator; var plan = try buildPlan(a, .{ @@ -209,3 +719,34 @@ test "deadline passes only after max duration" { try std.testing.expect(deadlinePassed(1000, 100, 1100)); try std.testing.expect(deadlinePassed(1000, 100, 5000)); } + +test "isolation state round-trips through the state file" { + const a = std.testing.allocator; + const io = iox.current(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + const state = try std.fs.path.join(a, &.{ dir, "state.toml" }); + defer a.free(state); + + try std.testing.expect(loadState(a, state) == null); + try saveState(a, state, .{ + .isolated = true, + .started_unix = 1_700_000_000, + .max_duration_seconds = 3600, + .nonce = "abc123", + .server_ips = &.{ "203.0.113.10", "203.0.113.11" }, + .dns_resolvers = &.{"1.1.1.1"}, + }); + { + const loaded = loadState(a, state).?; + defer loaded.deinit(); + try std.testing.expect(loaded.value.isolated); + try std.testing.expectEqual(@as(i64, 3600), loaded.value.max_duration_seconds); + try std.testing.expectEqualStrings("abc123", loaded.value.nonce); + try std.testing.expectEqual(@as(usize, 2), loaded.value.server_ips.len); + } + clearState(a, state); + try std.testing.expect(loadState(a, state) == null); +} diff --git a/agent/src/response_actions.zig b/agent/src/response_actions.zig index 9a6ee67..80c51ea 100644 --- a/agent/src/response_actions.zig +++ b/agent/src/response_actions.zig @@ -12,6 +12,7 @@ const action_sig = @import("action_sig.zig"); const action_key = @import("action_key.zig"); const journal_mod = @import("action_journal.zig"); const quarantine = @import("quarantine.zig"); +const wfp = @import("platform/windows/wfp.zig"); const Ed25519 = std.crypto.sign.Ed25519; const process_control = if (builtin.target.os.tag == .windows) @import("platform/windows/process_control.zig") @@ -25,6 +26,10 @@ pub const Context = struct { public_key: ?Ed25519.PublicKey, journal: *journal_mod.Journal, quarantine_dir: []const u8, + /// Where isolation state is stored (`.wfp`). + state_path: []const u8 = "", + /// Agent backend URL, for resolving server IPs and the verify probe. + backend_url: []const u8 = "", }; const Result = struct { @@ -99,15 +104,99 @@ fn dispatch(ctx: Context, action: transport.ResponseAction) Result { if (std.mem.eql(u8, t, "quarantine_file")) return quarantineAction(ctx, action); if (std.mem.eql(u8, t, "restore_file")) return restoreAction(ctx, action); if (std.mem.eql(u8, t, "isolate_host") or std.mem.eql(u8, t, "isolate")) - return fail(isolate_unsupported_message); - if (std.mem.eql(u8, t, "release")) - return fail("release is not supported on this agent build"); + return isolateAction(ctx, action); + if (std.mem.eql(u8, t, "release") or std.mem.eql(u8, t, "release_host")) + return releaseAction(ctx); return fail("unknown response action"); } -/// The message the Linux e2e agent returns for isolate_host until #59 adds -/// nftables isolation. Contract tests assert on this exact string. -pub const isolate_unsupported_message = "isolate_host is not supported on linux yet (nftables isolation lands in #59)"; +const IsolatePayload = struct { + max_duration_seconds: ?i64 = null, + nonce: ?[]const u8 = null, + server_ips: []const []const u8 = &.{}, + dns_resolvers: []const []const u8 = &.{}, + admin_allowlist: []const []const u8 = &.{}, +}; + +/// Resolve the backend host to IPv4 strings so the server stays reachable +/// while isolated. Appends to `list`. Best-effort: a host that resolves to IPv6 +/// only is skipped (documented limit). +fn resolveServerIps(ctx: Context, list: *std.ArrayList([]const u8)) void { + const url = ctx.backend_url; + const after = if (std.mem.indexOf(u8, url, "://")) |i| url[i + 3 ..] else url; + var host_port = after; + if (std.mem.indexOfScalar(u8, host_port, '/')) |i| host_port = host_port[0..i]; + var host = host_port; + if (std.mem.lastIndexOfScalar(u8, host_port, ':')) |i| host = host_port[0..i]; + if (host.len == 0) return; + // If the host is already a dotted IPv4, keep it verbatim. + if (wfp.parseIpv4(host) != null) { + if (ctx.alloc.dupe(u8, host)) |d| list.append(ctx.alloc, d) catch ctx.alloc.free(d) else |_| {} + return; + } + const addr = std.Io.net.IpAddress.resolve(iox.current(), host, 443) catch return; + switch (addr) { + .ip4 => |v| { + const b = v.bytes; + const text = std.fmt.allocPrint(ctx.alloc, "{d}.{d}.{d}.{d}", .{ b[0], b[1], b[2], b[3] }) catch return; + list.append(ctx.alloc, text) catch ctx.alloc.free(text); + }, + .ip6 => {}, // IPv6-only hosts are skipped (documented limit). + } +} + +fn isolateAction(ctx: Context, action: transport.ResponseAction) Result { + if (builtin.target.os.tag != .windows) { + return fail("isolate_host is not supported on " ++ @tagName(builtin.target.os.tag) ++ " yet"); + } + const parsed = std.json.parseFromSlice(IsolatePayload, ctx.alloc, action.payload, .{ .ignore_unknown_fields = true }) catch + return fail("invalid isolate payload"); + defer parsed.deinit(); + const p = parsed.value; + + var ips: std.ArrayList([]const u8) = .empty; + defer { + for (ips.items) |ip| ctx.alloc.free(ip); + ips.deinit(ctx.alloc); + } + resolveServerIps(ctx, &ips); + for (p.server_ips) |s| { + if (ctx.alloc.dupe(u8, s)) |d| ips.append(ctx.alloc, d) catch ctx.alloc.free(d) else |_| {} + } + + wfp.isolate(ctx.alloc, .{ + .server_ips = ips.items, + .dns_resolvers = p.dns_resolvers, + .admin_allowlist = p.admin_allowlist, + }) catch |err| return fail(@errorName(err)); + + const max_dur = p.max_duration_seconds orelse wfp.default_max_duration_seconds; + wfp.saveState(ctx.alloc, ctx.state_path, .{ + .isolated = true, + .started_unix = iox.timestamp(), + .max_duration_seconds = max_dur, + .nonce = p.nonce orelse "", + .server_ips = ips.items, + .dns_resolvers = p.dns_resolvers, + .admin_allowlist = p.admin_allowlist, + }) catch {}; + + // Verify: the server should still be reachable, a blocked address not. + const server_ok = if (ips.items.len > 0) wfp.tcpReachable(ips.items[0], 443, 3000) else true; + const blocked_ok = wfp.tcpReachable("192.0.2.1", 443, 1500); // TEST-NET, should fail + const msg = std.fmt.allocPrint(ctx.alloc, "isolated; server_reachable={}, blocked_unreachable={}", .{ server_ok, !blocked_ok }) catch + return ok("isolated"); + return .{ .status = "succeeded", .message = msg, .owned = true }; +} + +fn releaseAction(ctx: Context) Result { + if (builtin.target.os.tag != .windows) { + return fail("release is not supported on " ++ @tagName(builtin.target.os.tag) ++ " yet"); + } + wfp.release() catch |err| return fail(@errorName(err)); + wfp.clearState(ctx.alloc, ctx.state_path); + return ok("isolation released"); +} const ProcessOp = enum { kill, do_suspend, do_resume }; diff --git a/agent/src/response_debug.zig b/agent/src/response_debug.zig index 5a43e6f..f235ef1 100644 --- a/agent/src/response_debug.zig +++ b/agent/src/response_debug.zig @@ -15,6 +15,7 @@ const std = @import("std"); const builtin = @import("builtin"); const quarantine = @import("quarantine.zig"); +const wfp = @import("platform/windows/wfp.zig"); const process_control = if (builtin.target.os.tag == .windows) @import("platform/windows/process_control.zig") else @@ -25,7 +26,8 @@ pub fn isDebugCommand(arg: []const u8) bool { std.mem.eql(u8, arg, "--suspend-pid") or std.mem.eql(u8, arg, "--resume-pid") or std.mem.eql(u8, arg, "--quarantine") or - std.mem.eql(u8, arg, "--restore"); + std.mem.eql(u8, arg, "--restore") or + std.mem.eql(u8, arg, "--wfp-selftest"); } /// `args` is argv[1..]. Returns a process exit code. @@ -33,6 +35,10 @@ pub fn run(alloc: std.mem.Allocator, args: []const []const u8) u8 { if (args.len == 0) return usage(); const cmd = args[0]; + if (std.mem.eql(u8, cmd, "--wfp-selftest")) { + return wfpSelftest(); + } + if (std.mem.eql(u8, cmd, "--quarantine")) { if (args.len != 4) return usage(); const rec = quarantine.quarantine(alloc, args[3], args[1], args[2]) catch |err| { @@ -85,7 +91,53 @@ pub fn run(alloc: std.mem.Allocator, args: []const []const u8) u8 { return 0; } +/// Safe live WFP test for CI: add one block filter for a TEST-NET address +/// (never a block-all, so it can't cut the runner off), confirm it is present, +/// confirm a routable address stays reachable, then release and confirm the +/// sublayer is empty. Windows only. +fn wfpSelftest() u8 { + if (builtin.target.os.tag != .windows) { + std.debug.print("wfp-selftest is Windows only\n", .{}); + return 2; + } + wfp.release() catch {}; // clean slate + const id = wfp.addTestBlock("192.0.2.1") catch |err| { + std.debug.print("wfp addTestBlock failed: {s}\n", .{@errorName(err)}); + return 1; + }; + const count_after_add = wfp.countFilters() catch 0; + if (count_after_add < 1) { + std.debug.print("wfp filter not present after add\n", .{}); + _ = wfp.release() catch {}; + return 1; + } + // TEST-NET should not connect; a routable address must still work, proving + // the single block did not over-block. + const blocked_unreachable = !wfp.tcpReachable("192.0.2.1", 9, 1500); + const internet_up = wfp.tcpReachable("1.1.1.1", 443, 4000); + wfp.release() catch |err| { + std.debug.print("wfp release failed: {s}\n", .{@errorName(err)}); + return 1; + }; + const count_after_release = wfp.countFilters() catch 0; + std.debug.print( + "wfp-selftest id={d} count_after_add={d} blocked_unreachable={} internet_up={} count_after_release={d}\n", + .{ id, count_after_add, blocked_unreachable, internet_up, count_after_release }, + ); + if (count_after_release != 0) { + std.debug.print("wfp filters remain after release\n", .{}); + return 1; + } + // Over-blocking (internet down) is a failure; the TEST-NET block itself is + // unverifiable against a baseline, so it is reported, not asserted. + if (!internet_up) { + std.debug.print("wfp over-blocked: routable address unreachable\n", .{}); + return 1; + } + return 0; +} + fn usage() u8 { - std.debug.print("usage: --kill-pid [ ] | --suspend-pid | --resume-pid | --quarantine | --restore \n", .{}); + std.debug.print("usage: --kill-pid [ ] | --suspend-pid | --resume-pid | --quarantine | --restore | --wfp-selftest\n", .{}); return 2; } diff --git a/docs/api.md b/docs/api.md index 74ade0a..f023706 100644 --- a/docs/api.md +++ b/docs/api.md @@ -360,8 +360,13 @@ Poll `GET /api/agents/{id}/actions` for the outcome; actions are delivered on the agent's next heartbeat and finish as `succeeded`, `failed`, `cancelled` or `expired`. Process control, quarantine and restore run on Windows; quarantine and restore also run on Linux and macOS. Host isolation (`isolate_host`, -`isolate`) and `release` report `failed` with a clear reason until WFP and -nftables isolation land. +`isolate`) and `release` run on Windows through WFP: isolation permits +loopback, the resolved server IPs, configured DNS resolvers and an optional +admin allowlist, blocks everything else, survives a reboot, and releases itself +when its `max_duration_seconds` deadline (default 24 h) passes with no renewal. +The `isolate_host` payload accepts `max_duration_seconds`, `server_ips`, +`dns_resolvers`, `admin_allowlist` and `nonce`. On Linux and macOS isolation +reports `failed` with a clear reason until nftables isolation lands (#59). ### GET `/api/agents/{id}/actions` and `/api/agents/{id}/actions/{actionId}` diff --git a/docs/architecture/target-edr.md b/docs/architecture/target-edr.md index 11fbc46..186e379 100644 --- a/docs/architecture/target-edr.md +++ b/docs/architecture/target-edr.md @@ -622,11 +622,18 @@ agent verifies it before acting, with a local journal for dedupe and restart replay. Windows kill, suspend and resume work with the identity guard and the critical-process refusal list. Quarantine and restore work on Windows, Linux and macOS (XOR obfuscation, SDDL on Windows, owner-only elsewhere). WFP -isolation has the filter-building plan, the auto-release deadline, the -reconcile-on-start design and the break-glass release code as pure, tested -logic; the live FwpmEngine integration and the `tawny-agent release --code` -CLI are not wired yet, and `isolate_host`/`release` report `failed` until then. -Linux nftables isolation lands in #59. +isolation is live on Windows through `fwpuclnt`: `isolate_host` opens the +engine and adds persistent filters in the fixed Tawny sublayer (permit +loopback, the resolved server IPs, configured DNS resolvers and an optional +admin allowlist; block everything else on the four ALE layers), then probes +the server and a blocked address. `release` deletes the sublayer, its filters +and the provider. The agent stores the deadline (default 24 h) and releases +itself when it passes, checked on each heartbeat and reconciled at start so a +crash never leaves stray filters. Break-glass `tawny-agent release --code` +verifies an HMAC of the agent id and the isolation nonce with a per-agent +secret (`TAWNY_ISOLATION_SECRET`); the server-side UI that shows that secret is +not in this change. DHCP and DNS-by-hostname permits are simplified to address +permits for now. Linux nftables isolation lands in #59. ## 10. Agent identity, protection, updates, health From 34ee6d9faa6415bd92ae6eebf9374bce777d77fb Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 03:42:08 +1100 Subject: [PATCH 7/8] fix(agent): page through WFP filter enumeration and check the test filter by id The Windows self-test added its filter but countFilters found nothing. countFilters read only the first page of up to 256 filters per layer, with a provider-key template, and a busy layer on the runner can hide ours past that page. It now pages through every entry and matches on the Tawny sublayer. The self-test also checks the filter directly with FwpmFilterGetById0 and prints the WFP status on failure. Co-Authored-By: Claude Opus 5.5 --- agent/src/platform/windows/wfp.zig | 67 +++++++++++++++++++++++++----- agent/src/response_debug.zig | 11 +++-- 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/agent/src/platform/windows/wfp.zig b/agent/src/platform/windows/wfp.zig index 4c1e415..ffa0032 100644 --- a/agent/src/platform/windows/wfp.zig +++ b/agent/src/platform/windows/wfp.zig @@ -255,6 +255,22 @@ pub fn countFilters() EngineError!usize { }; } +/// True when a filter with this id exists. Windows only. +pub fn filterExists(id: u64) EngineError!bool { + return switch (builtin.target.os.tag) { + .windows => win.filterExists(id), + else => error.WfpUnavailable, + }; +} + +/// Last WFP status code from a failed call, for diagnostics. +pub fn lastError() u32 { + return switch (builtin.target.os.tag) { + .windows => win.last_error, + else => 0, + }; +} + /// CI self-test only: add a single block filter for one remote IPv4 address /// (no block-all), so it cannot cut the runner off. Returns the filter id. pub fn addTestBlock(ipv4: []const u8) EngineError!u64 { @@ -391,6 +407,7 @@ const win = if (builtin.target.os.tag == .windows) struct { extern "fwpuclnt" fn FwpmFilterEnum0(engineHandle: HANDLE, enumHandle: HANDLE, numEntriesRequested: u32, entries: *[*]*FWPM_FILTER0, numEntriesReturned: *u32) callconv(WINAPI) DWORD; extern "fwpuclnt" fn FwpmFilterDestroyEnumHandle0(engineHandle: HANDLE, enumHandle: HANDLE) callconv(WINAPI) DWORD; extern "fwpuclnt" fn FwpmFreeMemory0(p: *?*anyopaque) callconv(WINAPI) void; + extern "fwpuclnt" fn FwpmFilterGetById0(engineHandle: HANDLE, id: u64, filter: *?*FWPM_FILTER0) callconv(WINAPI) DWORD; const layers = [_]G{ FWPM_LAYER_ALE_AUTH_CONNECT_V4, @@ -420,6 +437,7 @@ const win = if (builtin.target.os.tag == .windows) struct { } var prov_key: G = provider_guid; + pub var last_error: DWORD = 0; const tawny_name: [*:0]const u16 = std.unicode.utf8ToUtf16LeStringLiteral("Tawny"); const tawny_desc: [*:0]const u16 = std.unicode.utf8ToUtf16LeStringLiteral("Tawny EDR isolation"); @@ -559,30 +577,59 @@ const win = if (builtin.target.os.tag == .windows) struct { defer _ = FwpmEngineClose0(engine); var total: usize = 0; for (layers) |layer| { + // No provider key in the template: match on our sublayer below, so a + // provider mismatch can't hide filters. Page through every entry, + // because a busy layer can hold hundreds of system filters. var tmpl = FWPM_FILTER_ENUM_TEMPLATE0{ .layerKey = layer, .enumType = FWP_FILTER_ENUM_OVERLAPPING, .actionMask = 0xFFFFFFFF, }; - tmpl.providerKey = @constCast(&prov_key); var enum_h: HANDLE = undefined; - if (FwpmFilterCreateEnumHandle0(engine, &tmpl, &enum_h) != 0) return error.EnumFailed; - defer _ = FwpmFilterDestroyEnumHandle0(engine, enum_h); - var entries: [*]*FWPM_FILTER0 = undefined; - var num: u32 = 0; - if (FwpmFilterEnum0(engine, enum_h, 256, &entries, &num) != 0) return error.EnumFailed; - var i: u32 = 0; - while (i < num) : (i += 1) { - if (std.meta.eql(entries[i].subLayerKey, sublayer_guid)) total += 1; + const rc = FwpmFilterCreateEnumHandle0(engine, &tmpl, &enum_h); + if (rc != 0) { + last_error = rc; + return error.EnumFailed; } - if (num > 0) { + defer _ = FwpmFilterDestroyEnumHandle0(engine, enum_h); + while (true) { + var entries: [*]*FWPM_FILTER0 = undefined; + var num: u32 = 0; + const erc = FwpmFilterEnum0(engine, enum_h, 256, &entries, &num); + if (erc != 0) { + last_error = erc; + return error.EnumFailed; + } + if (num == 0) break; + var i: u32 = 0; + while (i < num) : (i += 1) { + if (std.meta.eql(entries[i].subLayerKey, sublayer_guid)) total += 1; + } var mem: ?*anyopaque = @ptrCast(entries); FwpmFreeMemory0(&mem); + if (num < 256) break; } } return total; } + /// True when a filter with this id exists. A direct check that doesn't + /// depend on enumeration. + fn filterExists(id: u64) EngineError!bool { + var engine: HANDLE = undefined; + try open(&engine); + defer _ = FwpmEngineClose0(engine); + var out: ?*FWPM_FILTER0 = null; + const rc = FwpmFilterGetById0(engine, id, &out); + if (rc != 0) { + last_error = rc; + return false; + } + var mem: ?*anyopaque = @ptrCast(out); + FwpmFreeMemory0(&mem); + return true; + } + fn addTestBlock(ipv4: []const u8) EngineError!u64 { const ip = parseIpv4(ipv4) orelse return error.BadAddress; var engine: HANDLE = undefined; diff --git a/agent/src/response_debug.zig b/agent/src/response_debug.zig index f235ef1..7f6e186 100644 --- a/agent/src/response_debug.zig +++ b/agent/src/response_debug.zig @@ -105,9 +105,14 @@ fn wfpSelftest() u8 { std.debug.print("wfp addTestBlock failed: {s}\n", .{@errorName(err)}); return 1; }; - const count_after_add = wfp.countFilters() catch 0; - if (count_after_add < 1) { - std.debug.print("wfp filter not present after add\n", .{}); + const exists = wfp.filterExists(id) catch false; + const count_after_add = wfp.countFilters() catch |err| blk: { + std.debug.print("wfp countFilters failed: {s} (status 0x{x})\n", .{ @errorName(err), wfp.lastError() }); + break :blk 0; + }; + std.debug.print("wfp added id={d} exists_by_id={} count_after_add={d}\n", .{ id, exists, count_after_add }); + if (!exists or count_after_add < 1) { + std.debug.print("wfp filter not present after add (status 0x{x})\n", .{wfp.lastError()}); _ = wfp.release() catch {}; return 1; } From 5bd105a51c462babe2edfe730abd57e53ad4e4ef Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Tue, 10 Nov 2026 03:55:40 +1100 Subject: [PATCH 8/8] fix(agent): correct FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 GUID Windows CI: filter enumeration failed with 0x80320004 (FWP_E_LAYER_NOT_FOUND). The last eight bytes of the RECV_ACCEPT_V6 layer GUID were wrong, so every enumeration over the layer list failed and the self-test saw zero filters. The filter add itself succeeded (found by id). The layer and condition GUIDs now sit at the top level with a test pinning them to the SDK values (fwpmu.h as published in microsoft/windows-rs), so it runs on every OS. Co-Authored-By: Claude Opus 5.5 --- agent/src/platform/windows/wfp.zig | 45 ++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/agent/src/platform/windows/wfp.zig b/agent/src/platform/windows/wfp.zig index ffa0032..134ef4f 100644 --- a/agent/src/platform/windows/wfp.zig +++ b/agent/src/platform/windows/wfp.zig @@ -289,6 +289,39 @@ pub fn tcpReachable(ipv4: []const u8, port: u16, timeout_ms: u32) bool { }; } +fn sdkGuid(d1: u32, d2: u16, d3: u16, d4: [8]u8) Guid { + return .{ .data1 = d1, .data2 = d2, .data3 = d3, .data4 = d4 }; +} + +// WFP layer and condition GUIDs from the Windows SDK fwpmu.h. Top level so +// the pin test below runs on every OS. +const sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V4 = sdkGuid(0xc38d57d1, 0x05a7, 0x4c33, .{ 0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82 }); +const sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V6 = sdkGuid(0x4a72393b, 0x319f, 0x44bc, .{ 0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4 }); +const sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 = sdkGuid(0xe1cd9fe7, 0xf4b5, 0x4273, .{ 0x96, 0xc0, 0x59, 0x2e, 0x48, 0x7b, 0x86, 0x50 }); +const sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 = sdkGuid(0xa3b42c97, 0x9f04, 0x4672, .{ 0xb8, 0x7e, 0xce, 0xe9, 0xc4, 0x83, 0x25, 0x7f }); +const sdk_FWPM_CONDITION_IP_REMOTE_ADDRESS = sdkGuid(0xb235ae9a, 0x1d64, 0x49b8, .{ 0xa4, 0x4c, 0x5f, 0xf3, 0xd9, 0x09, 0x50, 0x45 }); +const sdk_FWPM_CONDITION_IP_LOCAL_ADDRESS = sdkGuid(0xd9ee00de, 0xc1ef, 0x4617, .{ 0xbf, 0xe3, 0xff, 0xd8, 0xf5, 0xa0, 0x89, 0x57 }); + +fn guidHex(x: Guid) [32]u8 { + var b: [16]u8 = undefined; + std.mem.writeInt(u32, b[0..4], x.data1, .big); + std.mem.writeInt(u16, b[4..6], x.data2, .big); + std.mem.writeInt(u16, b[6..8], x.data3, .big); + @memcpy(b[8..16], &x.data4); + return std.fmt.bytesToHex(b, .lower); +} + +test "WFP layer and condition GUIDs match the Windows SDK" { + // Values from fwpmu.h as published in microsoft/windows-rs. A wrong layer + // GUID makes enumeration fail with FWP_E_LAYER_NOT_FOUND (0x80320004). + try std.testing.expectEqualStrings("c38d57d105a74c33904f7fbceee60e82", &guidHex(sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V4)); + try std.testing.expectEqualStrings("4a72393b319f44bc84c3ba54dcb3b6b4", &guidHex(sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V6)); + try std.testing.expectEqualStrings("e1cd9fe7f4b5427396c0592e487b8650", &guidHex(sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4)); + try std.testing.expectEqualStrings("a3b42c979f044672b87ecee9c483257f", &guidHex(sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6)); + try std.testing.expectEqualStrings("b235ae9a1d6449b8a44c5ff3d9095045", &guidHex(sdk_FWPM_CONDITION_IP_REMOTE_ADDRESS)); + try std.testing.expectEqualStrings("d9ee00dec1ef4617bfe3ffd8f5a08957", &guidHex(sdk_FWPM_CONDITION_IP_LOCAL_ADDRESS)); +} + const win = if (builtin.target.os.tag == .windows) struct { const WINAPI: std.lang.CallingConvention = .winapi; const HANDLE = *anyopaque; @@ -314,12 +347,12 @@ const win = if (builtin.target.os.tag == .windows) struct { fn g(d1: u32, d2: u16, d3: u16, d4: [8]u8) G { return .{ .data1 = d1, .data2 = d2, .data3 = d3, .data4 = d4 }; } - const FWPM_LAYER_ALE_AUTH_CONNECT_V4 = g(0xc38d57d1, 0x05a7, 0x4c33, .{ 0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82 }); - const FWPM_LAYER_ALE_AUTH_CONNECT_V6 = g(0x4a72393b, 0x319f, 0x44bc, .{ 0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4 }); - const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 = g(0xe1cd9fe7, 0xf4b5, 0x4273, .{ 0x96, 0xc0, 0x59, 0x2e, 0x48, 0x7b, 0x86, 0x50 }); - const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 = g(0xa3b42c97, 0x9f04, 0x4672, .{ 0xb8, 0x7b, 0xca, 0xd7, 0xd3, 0xb2, 0xfa, 0x37 }); - const FWPM_CONDITION_IP_REMOTE_ADDRESS = g(0xb235ae9a, 0x1d64, 0x49b8, .{ 0xa4, 0x4c, 0x5f, 0xf3, 0xd9, 0x09, 0x50, 0x45 }); - const FWPM_CONDITION_IP_LOCAL_ADDRESS = g(0xd9ee00de, 0xc1ef, 0x4617, .{ 0xbf, 0xe3, 0xff, 0xd8, 0xf5, 0xa0, 0x89, 0x57 }); + const FWPM_LAYER_ALE_AUTH_CONNECT_V4 = sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V4; + const FWPM_LAYER_ALE_AUTH_CONNECT_V6 = sdk_FWPM_LAYER_ALE_AUTH_CONNECT_V6; + const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 = sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; + const FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 = sdk_FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; + const FWPM_CONDITION_IP_REMOTE_ADDRESS = sdk_FWPM_CONDITION_IP_REMOTE_ADDRESS; + const FWPM_CONDITION_IP_LOCAL_ADDRESS = sdk_FWPM_CONDITION_IP_LOCAL_ADDRESS; // Our own provider key, distinct from the sublayer key. const provider_guid = g(0x7a3c1e54, 0x2b6d, 0x4f18, .{ 0x9c, 0x0a, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x02 });