Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
1ef364e
fix(shields,state): preserve gateway access under shields-up + tolera…
laitingsheng May 24, 2026
15d095f
refactor(shields,state): drop issue refs from comments + rename test …
laitingsheng May 24, 2026
31ce569
fix(shields): create agents/<id>/sessions on lock + tighten audit-fin…
laitingsheng May 24, 2026
8608886
fix(shields): drop symlinked parents in runtime-subpath restore + fix…
laitingsheng May 24, 2026
1262ddf
fix(shields): replay restore helper under sh + drop NC tag from updat…
laitingsheng May 24, 2026
4bcb560
fix(shields): refuse symlinked state-dir/workspace roots in shields-u…
laitingsheng May 24, 2026
b95913a
fix(shields): fail shields-up when a state-dir root is a symlink
laitingsheng May 24, 2026
f099b8b
fix(shields): preflight all state-dir/workspace roots before mutating…
laitingsheng May 24, 2026
bd70291
Merge branch 'main' into fix/shields-up-lockdown-runtime-perms
laitingsheng May 25, 2026
c55ed51
revert: drop pre-backup audit-find tolerance from this PR
laitingsheng May 25, 2026
5b19451
Merge branch 'main' into fix/shields-up-lockdown-runtime-perms
laitingsheng May 25, 2026
41a8bb3
Merge branch 'main' into fix/shields-up-lockdown-runtime-perms
cv May 26, 2026
9574166
Merge branch 'main' into fix/shields-up-lockdown-runtime-perms
cv May 30, 2026
ad984e9
Merge branch 'main' into fix/shields-up-lockdown-runtime-perms
cv May 30, 2026
8085cd1
fix(shields): verify state-dir lock, expand high-risk set, mock privi…
laitingsheng May 31, 2026
9a6a635
refactor(shields): extract state-dir lock, fail-closed preflight, str…
laitingsheng May 31, 2026
4df0f53
Merge remote-tracking branch 'origin/main' into fix/shields-up-lockdo…
laitingsheng May 31, 2026
6d8233d
fix(shields): hoist preflight, exit 0 on empty roots, verify+surface …
laitingsheng May 31, 2026
d2d24d7
fix(shields): surface unlock state-dir issues, split doc exemption wo…
laitingsheng May 31, 2026
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
92 changes: 81 additions & 11 deletions src/lib/shields/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,11 +337,20 @@ function isShieldsState(value: unknown): value is ShieldsState {
// ---------------------------------------------------------------------------
// NC-2227-05: State directories locked by shields-up.
//
// During shields-up, these must be locked (root:root 755) so the sandbox
// user cannot create new entries or modify existing ones. This covers both
// executable state (skills, hooks, cron jobs, extensions, plugins, agent
// definitions) and writable agent state entry points such as workspace and
// memory, so a stale symlink bridge cannot bypass the lockdown.
// During shields-up, these must be locked so the sandbox user cannot create
// new entries or modify existing ones. This covers both executable state
// (skills, hooks, cron jobs, extensions, plugins, agent definitions) and
// writable agent state entry points such as workspace and memory, so a stale
// symlink bridge cannot bypass the lockdown.
//
// Lock ownership is `root:sandbox` (not `root:root`): the OpenClaw gateway
// runs as `gateway`, which is a member of the sandbox group via
// `Dockerfile.base`. Owning these dirs as `root:sandbox` preserves the
// sandbox group's `r-x` access to descendant files (after `chmod -R go-w`),
// so plugin discovery can still scan `extensions/<plugin>/` while the
// sandbox user is denied write through the stripped group/other write
// bits. The top-level config dir is still owned by `root:root`
// (lockAgentConfig) — only the high-risk state subtrees switch.
//
// The list is a superset: directories that don't exist in a given agent's
// config dir are silently skipped.
Expand All @@ -363,10 +372,18 @@ const HIGH_RISK_STATE_DIRS = [
"telegram",
];

// Runtime-data subpaths the agent must keep writing to under shields-up.
// Each entry is a shell glob relative to the agent config dir; after the
// main lock loop the matching directories are restored to
// `sandbox:sandbox 2770` so they remain writable inside an otherwise-locked
// tree.
const WRITABLE_RUNTIME_SUBPATHS = ["agents/*/sessions"];

function applyStateDirLockMode(
sandboxName: string,
configDir: string,
owner: string,
isLocking: boolean,
): void {
// Locking (shields-up) strips group + world write. Unlocking (shields-down)
// restores the same group-readable/writable + o-rwx mutable-default contract
Expand All @@ -376,7 +393,6 @@ function applyStateDirLockMode(
// The unlock variant uses `g+rwX,o-rwx` because a prior lock can strip group
// access from descendants. Without re-adding group read/write explicitly,
// shields-down would leave nested files readable/writable only by owner.
const isLocking = owner === "root:root";
const recursiveMode = isLocking ? "go-w" : "g+rwX,o-rwx";
const dirMode = isLocking ? "755" : "2770";

Expand Down Expand Up @@ -443,6 +459,54 @@ done
} catch {
// Best effort; verification below catches the primary config lock.
}

if (isLocking) {
restoreWritableRuntimeSubpaths(sandboxName, configDir);
}
}

function restoreWritableRuntimeSubpaths(
sandboxName: string,
configDir: string,
): void {
try {
privilegedSandboxExec(sandboxName, [
"sh",
"-c",
`
set -u
config_dir="$1"
shift
for pattern in "$@"; do
case "$pattern" in
*/*) prefix="\${pattern%/*}"; leaf="\${pattern##*/}" ;;
*) prefix=""; leaf="$pattern" ;;
esac
if [ -n "$prefix" ]; then
set -- "$config_dir"/$prefix
else
set -- "$config_dir"
fi
for parent in "$@"; do
case "$parent" in
*"*"*) continue ;;
esac
[ -d "$parent" ] || continue
target="$parent/$leaf"
mkdir -p "$target" 2>/dev/null || continue
chown -R sandbox:sandbox "$target" 2>/dev/null || true
chmod 2770 "$target" 2>/dev/null || true
chmod -R g+rwX,o-rwx "$target" 2>/dev/null || true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
done
done
`,
"sh",
configDir,
...WRITABLE_RUNTIME_SUBPATHS,
]);
} catch {
// Best effort; sandbox can recreate sessions/ in shields-down if missing.
}
}

function legacyDataDirFor(configDir: string): string {
Expand Down Expand Up @@ -550,7 +614,12 @@ function unlockAgentConfig(
// NC-2227-05: Restore sandbox ownership on locked state directories.
// Use chown -R to restore the full tree (files within may have been
// locked to root:root by a prior shields-up).
applyStateDirLockMode(sandboxName, target.configDir, "sandbox:sandbox");
applyStateDirLockMode(
sandboxName,
target.configDir,
"sandbox:sandbox",
false,
);

if (errors.length > 0) {
console.error(
Expand Down Expand Up @@ -682,10 +751,11 @@ function lockAgentConfig(
}
}

// NC-2227-05: Lock state directories. Root-own the directory and set 755 so
// the sandbox user can read/execute but cannot create new entries or modify
// existing ones.
applyStateDirLockMode(sandboxName, target.configDir, "root:root");
// NC-2227-05: Lock state directories. Owned by `root:sandbox` so the
// gateway (in sandbox group) can still read plugin/agent code while the
// sandbox user is denied write through `chmod -R go-w`. See
// HIGH_RISK_STATE_DIRS doc above. Top-level configDir stays root:root.
applyStateDirLockMode(sandboxName, target.configDir, "root:sandbox", true);

// OpenClaw's mutable-default config root is setgid (#2681). Clear setgid
// after descendant locking so shields-up verifies the root config dir as
Expand Down
12 changes: 10 additions & 2 deletions src/lib/state/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1105,12 +1105,20 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions =
// empty for non-symlinks but always present, so the field count is
// stable. Tab separator assumes state-dir paths don't contain tabs,
// matching the wider convention in this file.
// Per-dir `find` invocations are joined with `;` (not `&&`) and each
// is tolerant of its own exit code via `|| true`. The base image bakes
// a few state subdirs as root-owned (e.g. `extensions/<plugin>`,
// `agents/<id>`) and `find` walking those from the sandbox-user SSH
// session exits 1 on permission denied. The audit's real signal is
// stdout (the printf-emitted symlink/hardlink/special-file rows);
// letting one perm-denied subdir abort the whole chain blocks legitimate
// rebuilds.
const auditCmd = existingDirs
.map(
(d) =>
`find ${shellQuote(`${dir}/${d}`)} \\( -type l -o \\( -type f -a -links +1 \\) -o \\( ! -type f -a ! -type d \\) \\) -printf "%y\\t%p\\t%l\\n" 2>/dev/null`,
`{ find ${shellQuote(`${dir}/${d}`)} \\( -type l -o \\( -type f -a -links +1 \\) -o \\( ! -type f -a ! -type d \\) \\) -printf "%y\\t%p\\t%l\\n" 2>/dev/null || true; }`,
)
.join(" && ");
.join("; ");
_log(`Pre-backup audit: checking for symlinks, hard links, and special files`);
const auditResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), auditCmd], {
encoding: "utf-8",
Expand Down
2 changes: 1 addition & 1 deletion test/repro-2681-group-writable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ process.stdout.write(JSON.stringify(calls));
command[0] === "sh" &&
command[1] === "-c" &&
command.includes("/sandbox/.openclaw") &&
command.includes("root:root") &&
command.includes("root:sandbox") &&
command.includes("go-w") &&
command.includes("755"),
);
Expand Down
143 changes: 143 additions & 0 deletions test/shields-up-runtime-perms.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { describe, expect, it } from "vitest";

function runLockAgentConfigProbe(): string[][] {
const probe = spawnSync(
process.execPath,
[
"-e",
String.raw`
const Module = require("node:module");
const originalLoad = Module._load;
const calls = [];
Module._load = function patchedLoad(request, parent, isMain) {
if (request === "../adapters/docker/exec") {
return {
dockerExecFileSync(args) {
const separator = args.indexOf("--");
const command = separator >= 0 ? args.slice(separator + 1) : args;
calls.push(command);
if (command[0] === "stat" && command[1] === "-c") {
return command.at(-1) === "/sandbox/.openclaw"
? "755 root:root\n"
: "444 root:root\n";
}
if (command[0] === "lsattr") {
return "----i----------------- " + command.at(-1) + "\n";
}
return "";
},
};
}
return originalLoad.call(this, request, parent, isMain);
};
const { lockAgentConfig } = require("./dist/lib/shields/index.js");
lockAgentConfig("sandbox-pod", {
agentName: "openclaw",
configPath: "/sandbox/.openclaw/openclaw.json",
configDir: "/sandbox/.openclaw",
sensitiveFiles: ["/sandbox/.openclaw/.config-hash"],
});
process.stdout.write(JSON.stringify(calls));
`,
],
{ encoding: "utf-8", timeout: 5000 },
);
expect(probe.status).toBe(0);
return JSON.parse(probe.stdout) as string[][];
}

describe("shields-up state-dir lock preserves sandbox-group access + runtime sessions writable", () => {
it("locks each high-risk state dir to root:sandbox so the gateway keeps r-x via the sandbox group", () => {
const commands = runLockAgentConfigProbe();

const stateDirChowns = commands.filter(
(command) =>
command[0] === "chown" &&
command[1] === "-R" &&
typeof command[3] === "string" &&
command[3].startsWith("/sandbox/.openclaw/"),
);

expect(stateDirChowns.length).toBeGreaterThan(0);
for (const command of stateDirChowns) {
expect(command[2]).toBe("root:sandbox");
}
expect(stateDirChowns.map((command) => command[3])).toContain(
"/sandbox/.openclaw/extensions",
);
expect(stateDirChowns.map((command) => command[3])).toContain(
"/sandbox/.openclaw/agents",
);
});

it("keeps the top-level config dir owned by root:root (lock contract unchanged)", () => {
const commands = runLockAgentConfigProbe();
expect(commands).toContainEqual([
"chown",
"root:root",
"/sandbox/.openclaw",
]);
expect(commands).toContainEqual([
"chown",
"root:root",
"/sandbox/.openclaw/openclaw.json",
]);
});

it("restores agents/*/sessions to sandbox:sandbox 2770 after the main lock loop", () => {
const commands = runLockAgentConfigProbe();
const restoreShell = commands.find(
(command) =>
command[0] === "sh" &&
command[1] === "-c" &&
command.includes("/sandbox/.openclaw") &&
command.includes("agents/*/sessions") &&
typeof command[2] === "string" &&
command[2].includes("chown -R sandbox:sandbox") &&
command[2].includes("chmod 2770"),
);
expect(restoreShell).toBeDefined();
});

// Behavioral check against a real filesystem fixture: the restore script
// must mkdir `agents/<id>/sessions` even when the leaf does not yet exist
// (fresh sandbox, never-run TUI). The pre-fix script's case-`*` guard
// skipped the literal pattern when the glob matched nothing, leaving
// `sessions/` uncreated and the post-lockdown TUI mkdir blocked.
it("creates agents/<id>/sessions under a fresh agent dir that has no sessions yet", () => {
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-runtime-"));
const configDir = path.join(fixture, ".openclaw");
const agentDir = path.join(configDir, "agents", "main");
fs.mkdirSync(agentDir, { recursive: true });

const restoreShell = runLockAgentConfigProbe().find(
(command) =>
command[0] === "sh" &&
command[1] === "-c" &&
command.includes("agents/*/sessions"),
);
if (!restoreShell) {
throw new Error("restore-writable-runtime-subpaths shell command not found");
}
const script = restoreShell[2];
const patterns = restoreShell.slice(4);

const result = spawnSync(
"bash",
["-c", `${script}\n`, "sh", configDir, ...patterns],
{ encoding: "utf-8", timeout: 5000 },
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);
expect(result.status).toBe(0);
expect(fs.existsSync(path.join(agentDir, "sessions"))).toBe(true);
expect(fs.statSync(path.join(agentDir, "sessions")).isDirectory()).toBe(true);

fs.rmSync(fixture, { recursive: true, force: true });
});
});
Loading
Loading