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
117 changes: 110 additions & 7 deletions src/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,23 @@ import * as os from "node:os";
import * as path from "node:path";
import { AGENTSHIELD_VERSION } from "./version.js";

export interface PeerCredentials {
uid?: number;
gid?: number;
pid?: number;
}

export interface DaemonConfig {
socketPath?: string;
authSecret?: string;
tokenFilePath?: string;
maxRingBufferEntries?: number;
/** Restrict IPC connections to these POSIX UIDs (defaults to [process.getuid()] on POSIX) */
allowedUids?: number[];
/** Optional custom peer credential resolver (SO_PEERCRED / LOCAL_PEERCRED hook for OS & testing) */
peerCredentialResolver?: (socket: net.Socket) => PeerCredentials | null;
/** Enforce strict peer credential verification on every IPC connection (default: true when resolver or POSIX UID policy active) */
requirePeerCredentials?: boolean;
}

export interface OtelMetricRecord {
Expand Down Expand Up @@ -78,12 +90,24 @@ export class AgentShieldDaemon {
private activeLocks: Map<string, DaemonLockHandle> = new Map();
private otelRingBuffer: OtelMetricRecord[] = [];
private maxRingBufferEntries: number;
private clientSessions: Map<net.Socket, { authenticated: boolean; id: string }> = new Map();
private allowedUids: number[];
private peerCredentialResolver?: (socket: net.Socket) => PeerCredentials | null;
private requirePeerCredentials: boolean;
private activePolicyOverrides: Record<string, unknown> = {};
private clientSessions: Map<
net.Socket,
{ authenticated: boolean; id: string; peer?: PeerCredentials | null }
> = new Map();

constructor(config: DaemonConfig = {}) {
this.socketPath = config.socketPath || getDefaultSocketPath();
this.authSecret = config.authSecret || crypto.randomBytes(32).toString("hex");
this.maxRingBufferEntries = config.maxRingBufferEntries || 2000;
const currentUid = typeof process.getuid === "function" ? process.getuid() : undefined;
this.allowedUids = config.allowedUids ?? (currentUid !== undefined ? [currentUid] : []);
this.peerCredentialResolver = config.peerCredentialResolver;
this.requirePeerCredentials =
config.requirePeerCredentials ?? Boolean(config.peerCredentialResolver);

const defaultTokenDir = path.join(os.homedir(), ".agentshield");
this.tokenFilePath = config.tokenFilePath || path.join(defaultTokenDir, "daemon.token");
Expand Down Expand Up @@ -162,7 +186,11 @@ export class AgentShieldDaemon {
this.clientSessions.clear();

await new Promise<void>((resolve) => {
this.server?.close(() => resolve());
const timer = setTimeout(() => resolve(), 250);
this.server?.close(() => {
clearTimeout(timer);
resolve();
});
});
this.server = null;

Expand Down Expand Up @@ -192,9 +220,61 @@ export class AgentShieldDaemon {
return [...this.otelRingBuffer];
}

private verifyPeerCredentials(socket: net.Socket): {
allowed: boolean;
peer: PeerCredentials | null;
reason?: string;
} {
if (!this.peerCredentialResolver) {
return {
allowed: !this.requirePeerCredentials,
peer: null,
reason: this.requirePeerCredentials ? "Missing peer credential resolver" : undefined,
};
}
const peer = this.peerCredentialResolver(socket);
if (!peer) {
return {
allowed: false,
peer: null,
reason: "EACCES: Unable to verify IPC peer credentials (SO_PEERCRED)",
};
}
if (
this.allowedUids.length > 0 &&
(peer.uid === undefined || !this.allowedUids.includes(peer.uid))
) {
return {
allowed: false,
peer,
reason: `EACCES: Unauthorized IPC peer UID ${peer.uid ?? "unknown"} rejected (allowed: ${this.allowedUids.join(",")})`,
};
}
return { allowed: true, peer };
}

private timingSafeTokenMatch(supplied: string): boolean {
const a = Buffer.from(supplied, "utf8");
const b = Buffer.from(this.authSecret, "utf8");
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}

private handleConnection(socket: net.Socket): void {
const peerCheck = this.verifyPeerCredentials(socket);
if (!peerCheck.allowed) {
socket.on("error", () => {});
this.sendResponse(socket, {
ok: false,
code: "EACCES",
error: peerCheck.reason || "EACCES: Peer credential verification failed",
});
socket.end(() => socket.destroy());
return;
}

const sessionId = crypto.randomUUID().slice(0, 8);
this.clientSessions.set(socket, { authenticated: false, id: sessionId });
this.clientSessions.set(socket, { authenticated: false, id: sessionId, peer: peerCheck.peer });

let buffer = "";

Expand Down Expand Up @@ -243,13 +323,24 @@ export class AgentShieldDaemon {
return;
}

// 2. AUTH handshake
// 2. AUTH handshake (timing-safe token verification)
if (action === "AUTH") {
if (msg.token && msg.token === this.authSecret) {
if (typeof msg.token === "string" && this.timingSafeTokenMatch(msg.token)) {
session.authenticated = true;
this.sendResponse(socket, { id, ok: true, message: "Authenticated successfully" });
this.sendResponse(socket, {
id,
ok: true,
message: "Authenticated successfully",
peerUid: session.peer?.uid,
peerPid: session.peer?.pid,
});
} else {
this.sendResponse(socket, { id, ok: false, error: "Invalid authentication token" });
this.sendResponse(socket, {
id,
ok: false,
code: "EACCES",
error: "EACCES: Invalid authentication token",
});
}
return;
}
Expand All @@ -259,11 +350,23 @@ export class AgentShieldDaemon {
this.sendResponse(socket, {
id,
ok: false,
code: "EACCES",
error: "Unauthorized: AUTH handshake required before command execution",
});
return;
}

// 2b. POLICY_SET (requires authenticated, peer-verified session)
if (action === "POLICY_SET") {
if (msg.policy && typeof msg.policy === "object") {
this.activePolicyOverrides = { ...this.activePolicyOverrides, ...msg.policy };
this.sendResponse(socket, { id, ok: true, policy: this.activePolicyOverrides });
} else {
this.sendResponse(socket, { id, ok: false, error: "Missing policy object" });
}
return;
}

// 3. LOCK_ACQUIRE
if (action === "LOCK_ACQUIRE") {
const { resourceKey, ownerId, leaseTtlMs } = msg;
Expand Down
133 changes: 133 additions & 0 deletions tests/phase7-daemon-ipc-peer-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import assert from "node:assert/strict";
import * as net from "node:net";
import * as os from "node:os";
import * as path from "node:path";
import test from "node:test";
import { AgentShieldDaemon } from "../src/daemon.js";

function makeTempSocketPath(tag: string): string {
const id = `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
return process.platform === "win32"
? `\\\\.\\pipe\\agentshield-p7-${tag}-${id}`
: path.join(os.tmpdir(), `agentshield-p7-${tag}-${id}.sock`);
}

function sendRawLine(socketPath: string, payload?: string): Promise<string> {
return new Promise((resolve, reject) => {
const client = net.createConnection(socketPath);
let data = "";
const timer = setTimeout(() => {
client.destroy();
resolve(data);
}, 1500);

client.on("connect", () => {
if (payload && !client.destroyed && client.writable) {
client.write(`${payload}\n`, () => {});
}
});
client.on("data", (chunk) => {
data += chunk.toString("utf8");
if (data.includes("\n")) {
clearTimeout(timer);
client.destroy();
resolve(data.trim());
}
});
client.on("end", () => {
clearTimeout(timer);
resolve(data.trim());
});
client.on("error", (err) => {
clearTimeout(timer);
if (data.trim()) resolve(data.trim());
else reject(err);
});
});
}

test("Phase 7 (SEC-07): agentshieldd rejects untrusted peer UID via SO_PEERCRED guard with EACCES", async () => {
const socketPath = makeTempSocketPath("reject");
const daemon = new AgentShieldDaemon({
socketPath,
authSecret: "super-secret-daemon-token-32bytes",
allowedUids: [1000],
requirePeerCredentials: true,
peerCredentialResolver: () => ({ uid: 65534, gid: 65534, pid: 9999 }), // untrusted nobody UID
});

await daemon.start();
try {
const rawResp = await sendRawLine(
socketPath,
JSON.stringify({ id: "1", action: "POLICY_SET", policy: { blockEnvReads: false } }),
);
const parsed = JSON.parse(rawResp);
assert.equal(parsed.ok, false);
assert.equal(parsed.code, "EACCES");
assert.match(parsed.error, /Unauthorized IPC peer UID 65534/i);
} finally {
await daemon.stop();
}
});

test("Phase 7 (SEC-07): agentshieldd rejects unauthenticated POLICY_SET and allows verified same-UID + token", async () => {
const socketPath = makeTempSocketPath("allow");
const secret = "verified-peer-token-0123456789abcdef";
const daemon = new AgentShieldDaemon({
socketPath,
authSecret: secret,
allowedUids: [1000],
requirePeerCredentials: true,
peerCredentialResolver: () => ({ uid: 1000, gid: 1000, pid: process.pid }),
});

await daemon.start();
try {
// 1. Unauthenticated POLICY_SET must fail with EACCES
const unauthRaw = await sendRawLine(
socketPath,
JSON.stringify({ id: "unauth-1", action: "POLICY_SET", policy: { strict: false } }),
);
const unauth = JSON.parse(unauthRaw);
assert.equal(unauth.ok, false);
assert.equal(unauth.code, "EACCES");

// 2. Authenticated same-UID peer succeeds
const authResp = await new Promise<string>((resolve, reject) => {
const client = net.createConnection(socketPath);
let buf = "";
let step = 0;
client.on("connect", () => {
client.write(`${JSON.stringify({ id: "a1", action: "AUTH", token: secret })}\n`);
});
client.on("data", (chunk) => {
buf += chunk.toString("utf8");
const lines = buf.split("\n");
buf = lines.pop() || "";
for (const line of lines) {
if (!line.trim()) continue;
if (step === 0) {
step = 1;
const authJson = JSON.parse(line);
assert.equal(authJson.ok, true);
assert.equal(authJson.peerUid, 1000);
client.write(
`${JSON.stringify({ id: "p1", action: "POLICY_SET", policy: { strict: true } })}\n`,
);
} else {
client.end();
resolve(line);
}
}
});
client.on("error", reject);
});

const policyJson = JSON.parse(authResp);
assert.equal(policyJson.ok, true);
assert.equal(policyJson.policy.strict, true);
} finally {
await daemon.stop();
}
});
Loading