Skip to content

Commit 2044167

Browse files
fix: prevent sqlite commands from opening live state (#123816)
* fix: prevent sqlite commands from opening live state * fix: preserve early exec control rejection * fix: guard sqlite shell reopen commands
1 parent 4613eed commit 2044167

4 files changed

Lines changed: 419 additions & 19 deletions

File tree

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { detectUnsafeExecControlShellCommand } from "../infra/exec-control-command-guard.js";
5+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
6+
import { withEnvAsync } from "../test-utils/env.js";
7+
import { withTempDir } from "../test-utils/temp-dir.js";
8+
import { createExecTool } from "./bash-tools.exec-run.js";
9+
10+
vi.mock("./bash-tools.exec-host-gateway.js", () => ({
11+
processGatewayAllowlist: async () => ({ allowWithoutEnforcedCommand: true }),
12+
}));
13+
14+
vi.mock("./bash-tools.exec-host-node.js", () => ({
15+
executeNodeHostCommand: async () => {
16+
throw new Error("node host execution is not used by live state SQLite guard tests");
17+
},
18+
}));
19+
20+
vi.mock("../utils/delivery-context.shared.js", () => ({
21+
normalizeDeliveryContext: (value: unknown) => value,
22+
}));
23+
24+
const describeNonWin = process.platform === "win32" ? describe.skip : describe;
25+
const quote = (value: string) => JSON.stringify(value);
26+
27+
afterEach(() => {
28+
closeOpenClawStateDatabaseForTest();
29+
vi.restoreAllMocks();
30+
});
31+
32+
describeNonWin("exec live OpenClaw state SQLite guard", () => {
33+
it("detects direct and carrier-wrapped SQLite targets under the active state directory", async () => {
34+
await withTempDir("openclaw-exec-live-sqlite-", async (root) => {
35+
const stateDir = path.join(root, "state with spaces");
36+
const databasePath = path.join(stateDir, "state", "openclaw.sqlite");
37+
await fs.mkdir(path.dirname(databasePath), { recursive: true });
38+
await fs.writeFile(databasePath, "fixture");
39+
40+
const context = { stateDir, workdir: root };
41+
await expect(
42+
detectUnsafeExecControlShellCommand(`sqlite3 --json ${quote(databasePath)}`, context),
43+
).resolves.toBe("live-state-sqlite");
44+
await expect(
45+
detectUnsafeExecControlShellCommand(
46+
`sudo -u openclaw env sqlite3 -header -column ${quote(databasePath)}`,
47+
context,
48+
),
49+
).resolves.toBe("live-state-sqlite");
50+
await expect(
51+
detectUnsafeExecControlShellCommand(
52+
'sqlite3 -cmd ".timeout 1000" "$OPENCLAW_STATE_DIR/state/openclaw.sqlite"',
53+
context,
54+
),
55+
).resolves.toBe("live-state-sqlite");
56+
await expect(
57+
detectUnsafeExecControlShellCommand(
58+
`sqlite3 :memory: ${quote(`.open ${quote(databasePath)}`)}`,
59+
context,
60+
),
61+
).resolves.toBe("live-state-sqlite");
62+
await expect(
63+
detectUnsafeExecControlShellCommand(
64+
`sqlite3 :memory: ${quote(`.op ${quote(databasePath)}`)}`,
65+
context,
66+
),
67+
).resolves.toBe("live-state-sqlite");
68+
await expect(
69+
detectUnsafeExecControlShellCommand(
70+
`sqlite3 -cmd ${quote(`.open --readonly ${quote(databasePath)}`)} :memory:`,
71+
context,
72+
),
73+
).resolves.toBe("live-state-sqlite");
74+
});
75+
});
76+
77+
it("detects relative and symlink-aliased live state targets", async () => {
78+
await withTempDir("openclaw-exec-live-sqlite-alias-", async (root) => {
79+
const stateDir = path.join(root, "state");
80+
const databasePath = path.join(stateDir, "agents", "main", "state.sqlite");
81+
const aliasDir = path.join(root, "state-alias");
82+
await fs.mkdir(path.dirname(databasePath), { recursive: true });
83+
await fs.writeFile(databasePath, "fixture");
84+
await fs.symlink(stateDir, aliasDir);
85+
86+
const context = { stateDir, workdir: root };
87+
await expect(
88+
detectUnsafeExecControlShellCommand("sqlite3 state/agents/main/state.sqlite", context),
89+
).resolves.toBe("live-state-sqlite");
90+
await expect(
91+
detectUnsafeExecControlShellCommand(
92+
`sqlite3 --readonly ${quote(path.join(aliasDir, "agents", "main", "state.sqlite"))}`,
93+
context,
94+
),
95+
).resolves.toBe("live-state-sqlite");
96+
});
97+
});
98+
99+
it("allows SQLite inspection of a private copy outside the active state directory", async () => {
100+
await withTempDir("openclaw-exec-copied-sqlite-", async (root) => {
101+
const stateDir = path.join(root, "state");
102+
const copiedDatabasePath = path.join(root, "snapshot", "openclaw.sqlite");
103+
await fs.mkdir(path.dirname(copiedDatabasePath), { recursive: true });
104+
await fs.writeFile(copiedDatabasePath, "fixture");
105+
106+
await expect(
107+
detectUnsafeExecControlShellCommand(`sqlite3 ${quote(copiedDatabasePath)}`, {
108+
stateDir,
109+
workdir: root,
110+
}),
111+
).resolves.toBeNull();
112+
await expect(
113+
detectUnsafeExecControlShellCommand(
114+
`sqlite3 :memory: ${quote(`.open ${quote(copiedDatabasePath)}`)}`,
115+
{ stateDir, workdir: root },
116+
),
117+
).resolves.toBeNull();
118+
await expect(
119+
detectUnsafeExecControlShellCommand(
120+
`sqlite3 -cmd ${quote(`.open --readonly ${quote(copiedDatabasePath)}`)} :memory:`,
121+
{ stateDir, workdir: root },
122+
),
123+
).resolves.toBeNull();
124+
await expect(
125+
detectUnsafeExecControlShellCommand(`cat ${quote(path.join(stateDir, "state.sqlite"))}`, {
126+
stateDir,
127+
workdir: root,
128+
}),
129+
).resolves.toBeNull();
130+
});
131+
});
132+
133+
it("rejects the live target before the external SQLite process starts", async () => {
134+
await withTempDir("openclaw-exec-live-sqlite-spawn-", async (root) => {
135+
const stateDir = path.join(root, "state");
136+
const databasePath = path.join(stateDir, "agents", "main", "state.sqlite");
137+
const markerPath = path.join(root, "sqlite-spawned");
138+
const sqlitePath = path.join(root, "sqlite3");
139+
await fs.mkdir(path.dirname(databasePath), { recursive: true });
140+
await fs.writeFile(sqlitePath, `#!/bin/sh\nprintf spawned > ${quote(markerPath)}\n`, {
141+
mode: 0o755,
142+
});
143+
144+
await withEnvAsync(
145+
{
146+
HOME: root,
147+
USERPROFILE: root,
148+
OPENCLAW_HOME: root,
149+
OPENCLAW_STATE_DIR: stateDir,
150+
},
151+
async () => {
152+
const tool = createExecTool({
153+
host: "gateway",
154+
security: "full",
155+
ask: "on-miss",
156+
allowBackground: false,
157+
});
158+
await expect(
159+
tool.execute("call-live-sqlite", {
160+
command: `${quote(sqlitePath)} :memory: ${quote(`.open ${quote(databasePath)}`)}`,
161+
workdir: root,
162+
}),
163+
).rejects.toThrow(
164+
/external sqlite3 cannot open databases under the active OpenClaw state directory/,
165+
);
166+
},
167+
);
168+
169+
await expect(fs.stat(markerPath)).rejects.toMatchObject({ code: "ENOENT" });
170+
});
171+
});
172+
});

‎src/agents/bash-tools.exec-run.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Exec tool policy, host dispatch, and process lifecycle pipeline.
33
*/
44
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
5+
import { resolveStateDir } from "../config/paths.js";
56
import { createAbortError } from "../infra/abort-signal.js";
67
import {
78
type ExecHost,
@@ -13,7 +14,10 @@ import {
1314
resolveExecApprovalsFromFile,
1415
resolveExecModePolicy,
1516
} from "../infra/exec-approvals.js";
16-
import { rejectUnsafeExecControlShellCommand } from "../infra/exec-control-command-guard.js";
17+
import {
18+
rejectUnsafeExecControlShellCommand,
19+
rejectUnsafeExecLiveStateSqliteShellCommand,
20+
} from "../infra/exec-control-command-guard.js";
1721
import { resolveExecSafeBinRuntimePolicy } from "../infra/exec-safe-bin-runtime-policy.js";
1822
import { logInfo } from "../logger.js";
1923
import { parseAgentSessionKey, resolveAgentIdFromSessionKey } from "../routing/session-key.js";
@@ -388,6 +392,12 @@ export function createExecTool(
388392
} else {
389393
workdir = workdirResolution.remoteCwd;
390394
}
395+
if (host === "gateway" && workdir) {
396+
await rejectUnsafeExecLiveStateSqliteShellCommand(params.command, {
397+
stateDir: resolveStateDir(),
398+
workdir,
399+
});
400+
}
391401
let run: ExecProcessHandle;
392402
let backgroundTask: BackgroundExecTaskHandle | null = null;
393403
let settledOutcome: ExecProcessOutcome | null = null;

‎src/infra/command-analysis/risks.ts‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,38 +44,50 @@ function isCommandCarrierExecutable(executable: string, options?: { includeExec?
4444
);
4545
}
4646

47-
/** Builds candidate command payload strings from nested carriers and shell wrappers. */
48-
export function buildCommandPayloadCandidates(
47+
/** Builds candidate command argv arrays from nested carriers and shell wrappers. */
48+
export function buildCommandPayloadArgvCandidates(
4949
argv: string[],
5050
seenArgv = new Set<string>(),
51-
): string[] {
51+
): string[][] {
5252
const key = commandArgvKey(argv);
5353
if (seenArgv.has(key)) {
54-
return argv.length > 0 ? [argv.join(" ")] : [];
54+
return argv.length > 0 ? [argv] : [];
5555
}
5656
seenArgv.add(key);
5757
const assignmentStrippedArgv = stripLeadingEnvAssignments(argv);
5858
const carriedArgv = resolveCarrierCommandArgv(assignmentStrippedArgv, 0, {
5959
includeExec: true,
6060
});
6161
const executableArgv = carriedArgv ?? assignmentStrippedArgv;
62-
const carriedCandidates = carriedArgv ? buildCommandPayloadCandidates(carriedArgv, seenArgv) : [];
62+
const carriedCandidates = carriedArgv
63+
? buildCommandPayloadArgvCandidates(carriedArgv, seenArgv)
64+
: [];
6365
const shellWrapperPayload = extractShellWrapperInlineCommand(executableArgv);
6466
const shellWrapperCandidates = shellWrapperPayload
6567
? (() => {
6668
const innerArgv = splitShellArgs(shellWrapperPayload);
6769
return innerArgv
68-
? buildCommandPayloadCandidates(innerArgv, seenArgv)
69-
: [shellWrapperPayload];
70+
? buildCommandPayloadArgvCandidates(innerArgv, seenArgv)
71+
: [[shellWrapperPayload]];
7072
})()
7173
: [];
72-
return uniqueCommandPayloadCandidates([
73-
...(executableArgv.length > 0 ? [executableArgv.join(" ")] : []),
74+
return uniqueCommandPayloadArgvCandidates([
75+
...(executableArgv.length > 0 ? [executableArgv] : []),
7476
...carriedCandidates,
7577
...shellWrapperCandidates,
7678
]);
7779
}
7880

81+
/** Builds candidate command payload strings from nested carriers and shell wrappers. */
82+
export function buildCommandPayloadCandidates(
83+
argv: string[],
84+
seenArgv = new Set<string>(),
85+
): string[] {
86+
return uniqueStrings(
87+
buildCommandPayloadArgvCandidates(argv, seenArgv).map((candidate) => candidate.join(" ")),
88+
);
89+
}
90+
7991
function stripLeadingEnvAssignments(argv: string[]): string[] {
8092
let index = 0;
8193
while (index < argv.length && isEnvAssignmentToken(argv[index] ?? "")) {
@@ -84,8 +96,19 @@ function stripLeadingEnvAssignments(argv: string[]): string[] {
8496
return index > 0 ? argv.slice(index) : argv;
8597
}
8698

87-
function uniqueCommandPayloadCandidates(candidates: string[]): string[] {
88-
return uniqueStrings(candidates.filter((candidate) => candidate.trim().length > 0));
99+
function uniqueCommandPayloadArgvCandidates(candidates: string[][]): string[][] {
100+
const seen = new Set<string>();
101+
return candidates.filter((candidate) => {
102+
if (candidate.length === 0) {
103+
return false;
104+
}
105+
const key = commandArgvKey(candidate);
106+
if (seen.has(key)) {
107+
return false;
108+
}
109+
seen.add(key);
110+
return true;
111+
});
89112
}
90113

91114
type ShellPositionalCarrierPlan = { kind: "all" } | { kind: "indexes"; indexes: number[] };

0 commit comments

Comments
 (0)