Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,90 @@ 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"
# 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.
$ping = Start-Process -FilePath "ping.exe" -ArgumentList @("-t", "127.0.0.1") -PassThru
Start-Sleep -Seconds 1
# 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" }
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"

# 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.
Expand Down
2 changes: 2 additions & 0 deletions agent/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
160 changes: 160 additions & 0 deletions agent/src/action_journal.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! Durable action journal (#57, target-edr §9.2).
//!
//! Each action is written to `<state_dir>/actions/<id>.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,

/// `<state_dir>/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);
}
95 changes: 95 additions & 0 deletions agent/src/action_key.zig
Original file line number Diff line number Diff line change
@@ -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 `<state_path>.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);
}
Loading
Loading