fix(security): trust resolved skill-bin paths in allowlist auto-allow

This commit is contained in:
Peter Steinberger
2026-02-24 03:12:22 +00:00
parent 204d9fb404
commit ffd63b7a2c
7 changed files with 243 additions and 32 deletions

View File

@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { saveExecApprovals } from "../infra/exec-approvals.js";
import type { ExecHostResponse } from "../infra/exec-host.js";
import { handleSystemRunInvoke, formatSystemRunAllowlistMissMessage } from "./invoke-system-run.js";
@@ -49,7 +50,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
sessionKey: "agent:main:main",
},
skillBins: {
current: async () => new Set<string>(),
current: async () => [],
},
execHostEnforced: false,
execHostFallbackAllowed: true,
@@ -187,7 +188,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
sessionKey: "agent:main:main",
},
skillBins: {
current: async () => new Set<string>(),
current: async () => [],
},
execHostEnforced: false,
execHostFallbackAllowed: true,
@@ -226,6 +227,85 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
}
});
it("denies ./skill-bin even when autoAllowSkills trust entry exists", async () => {
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-skill-path-spoof-"));
const previousOpenClawHome = process.env.OPENCLAW_HOME;
const skillBinPath = path.join(tempHome, "skill-bin");
fs.writeFileSync(skillBinPath, "#!/bin/sh\necho should-not-run\n", { mode: 0o755 });
fs.chmodSync(skillBinPath, 0o755);
process.env.OPENCLAW_HOME = tempHome;
saveExecApprovals({
version: 1,
defaults: {
security: "allowlist",
ask: "on-miss",
askFallback: "deny",
autoAllowSkills: true,
},
agents: {},
});
const runCommand = vi.fn(async () => ({
success: true,
stdout: "local-ok",
stderr: "",
timedOut: false,
truncated: false,
exitCode: 0,
error: null,
}));
const sendInvokeResult = vi.fn(async () => {});
const sendNodeEvent = vi.fn(async () => {});
try {
await handleSystemRunInvoke({
client: {} as never,
params: {
command: ["./skill-bin", "--help"],
cwd: tempHome,
sessionKey: "agent:main:main",
},
skillBins: {
current: async () => [{ name: "skill-bin", resolvedPath: skillBinPath }],
},
execHostEnforced: false,
execHostFallbackAllowed: true,
resolveExecSecurity: () => "allowlist",
resolveExecAsk: () => "on-miss",
isCmdExeInvocation: () => false,
sanitizeEnv: () => undefined,
runCommand,
runViaMacAppExecHost: vi.fn(async () => null),
sendNodeEvent,
buildExecEventPayload: (payload) => payload,
sendInvokeResult,
sendExecFinishedEvent: vi.fn(async () => {}),
preferMacAppExecHost: false,
});
} finally {
if (previousOpenClawHome === undefined) {
delete process.env.OPENCLAW_HOME;
} else {
process.env.OPENCLAW_HOME = previousOpenClawHome;
}
fs.rmSync(tempHome, { recursive: true, force: true });
}
expect(runCommand).not.toHaveBeenCalled();
expect(sendNodeEvent).toHaveBeenCalledWith(
expect.anything(),
"exec.denied",
expect.objectContaining({ reason: "approval-required" }),
);
expect(sendInvokeResult).toHaveBeenCalledWith(
expect.objectContaining({
ok: false,
error: expect.objectContaining({
message: "SYSTEM_RUN_DENIED: approval required",
}),
}),
);
});
it("denies env -S shell payloads in allowlist mode", async () => {
const { runCommand, sendInvokeResult } = await runSystemInvoke({
preferMacAppExecHost: false,

View File

@@ -14,6 +14,7 @@ import {
type ExecAsk,
type ExecCommandSegment,
type ExecSecurity,
type SkillBinTrustEntry,
} from "../infra/exec-approvals.js";
import type { ExecHostRequest, ExecHostResponse, ExecHostRunResult } from "../infra/exec-host.js";
import { resolveExecSafeBinRuntimePolicy } from "../infra/exec-safe-bin-runtime-policy.js";
@@ -145,7 +146,7 @@ function evaluateSystemRunAllowlist(params: {
trustedSafeBinDirs: ReturnType<typeof resolveExecSafeBinRuntimePolicy>["trustedSafeBinDirs"];
cwd: string | undefined;
env: Record<string, string> | undefined;
skillBins: Set<string>;
skillBins: SkillBinTrustEntry[];
autoAllowSkills: boolean;
}): SystemRunAllowlistAnalysis {
if (params.shellCommand) {
@@ -310,7 +311,7 @@ export async function handleSystemRunInvoke(opts: HandleSystemRunInvokeOptions):
global: cfg.tools?.exec,
local: agentExec,
});
const bins = autoAllowSkills ? await opts.skillBins.current() : new Set<string>();
const bins = autoAllowSkills ? await opts.skillBins.current() : [];
let { analysisOk, allowlistMatches, allowlistSatisfied, segments } = evaluateSystemRunAllowlist({
shellCommand,
argv,

View File

@@ -1,3 +1,5 @@
import type { SkillBinTrustEntry } from "../infra/exec-approvals.js";
export type SystemRunParams = {
command: string[];
rawCommand?: string | null;
@@ -35,5 +37,5 @@ export type ExecEventPayload = {
};
export type SkillBinsProvider = {
current(force?: boolean): Promise<Set<string>>;
current(force?: boolean): Promise<SkillBinTrustEntry[]>;
};

View File

@@ -1,7 +1,10 @@
import fs from "node:fs";
import path from "node:path";
import { resolveBrowserConfig } from "../browser/config.js";
import { loadConfig } from "../config/config.js";
import { GatewayClient } from "../gateway/client.js";
import { loadOrCreateDeviceIdentity } from "../infra/device-identity.js";
import type { SkillBinTrustEntry } from "../infra/exec-approvals.js";
import { getMachineDisplayName } from "../infra/machine-name.js";
import { ensureOpenClawCliOnPath } from "../infra/path-env.js";
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
@@ -27,17 +30,83 @@ type NodeHostRunOptions = {
const DEFAULT_NODE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
function isExecutableFile(filePath: string): boolean {
try {
const stat = fs.statSync(filePath);
if (!stat.isFile()) {
return false;
}
if (process.platform !== "win32") {
fs.accessSync(filePath, fs.constants.X_OK);
}
return true;
} catch {
return false;
}
}
function resolveExecutablePathFromEnv(bin: string, pathEnv: string): string | null {
if (bin.includes("/") || bin.includes("\\")) {
return null;
}
const hasExtension = process.platform === "win32" && path.extname(bin).length > 0;
const extensions =
process.platform === "win32"
? hasExtension
? [""]
: (process.env.PATHEXT ?? process.env.PathExt ?? ".EXE;.CMD;.BAT;.COM")
.split(";")
.map((ext) => ext.toLowerCase())
: [""];
for (const dir of pathEnv.split(path.delimiter).filter(Boolean)) {
for (const ext of extensions) {
const candidate = path.join(dir, bin + ext);
if (isExecutableFile(candidate)) {
return candidate;
}
}
}
return null;
}
function resolveSkillBinTrustEntries(bins: string[], pathEnv: string): SkillBinTrustEntry[] {
const trustEntries: SkillBinTrustEntry[] = [];
const seen = new Set<string>();
for (const bin of bins) {
const name = bin.trim();
if (!name) {
continue;
}
const resolvedPath = resolveExecutablePathFromEnv(name, pathEnv);
if (!resolvedPath) {
continue;
}
const key = `${name}\u0000${resolvedPath}`;
if (seen.has(key)) {
continue;
}
seen.add(key);
trustEntries.push({ name, resolvedPath });
}
return trustEntries.toSorted(
(left, right) =>
left.name.localeCompare(right.name) || left.resolvedPath.localeCompare(right.resolvedPath),
);
}
class SkillBinsCache implements SkillBinsProvider {
private bins = new Set<string>();
private bins: SkillBinTrustEntry[] = [];
private lastRefresh = 0;
private readonly ttlMs = 90_000;
private readonly fetch: () => Promise<string[]>;
private readonly pathEnv: string;
constructor(fetch: () => Promise<string[]>) {
constructor(fetch: () => Promise<string[]>, pathEnv: string) {
this.fetch = fetch;
this.pathEnv = pathEnv;
}
async current(force = false): Promise<Set<string>> {
async current(force = false): Promise<SkillBinTrustEntry[]> {
if (force || Date.now() - this.lastRefresh > this.ttlMs) {
await this.refresh();
}
@@ -47,11 +116,11 @@ class SkillBinsCache implements SkillBinsProvider {
private async refresh() {
try {
const bins = await this.fetch();
this.bins = new Set(bins);
this.bins = resolveSkillBinTrustEntries(bins, this.pathEnv);
this.lastRefresh = Date.now();
} catch {
if (!this.lastRefresh) {
this.bins = new Set();
this.bins = [];
}
}
}
@@ -155,7 +224,7 @@ export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
const res = await client.request<{ bins: Array<unknown> }>("skills.bins", {});
const bins = Array.isArray(res?.bins) ? res.bins.map((bin) => String(bin)) : [];
return bins;
});
}, pathEnv);
client.start();
await new Promise(() => {});