refactor: unify boundary hardening for file reads

This commit is contained in:
Peter Steinberger
2026-02-26 13:04:33 +01:00
parent cf4853e2b8
commit eac86c2081
11 changed files with 455 additions and 56 deletions

View File

@@ -231,6 +231,46 @@ describe("discoverOpenClawPlugins", () => {
);
});
it("rejects package extension entries that are hardlinked aliases", async () => {
if (process.platform === "win32") {
return;
}
const stateDir = makeTempDir();
const globalExt = path.join(stateDir, "extensions", "pack");
const outsideDir = path.join(stateDir, "outside");
const outsideFile = path.join(outsideDir, "escape.ts");
const linkedFile = path.join(globalExt, "escape.ts");
fs.mkdirSync(globalExt, { recursive: true });
fs.mkdirSync(outsideDir, { recursive: true });
fs.writeFileSync(outsideFile, "export default {}", "utf-8");
try {
fs.linkSync(outsideFile, linkedFile);
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "EXDEV") {
return;
}
throw err;
}
fs.writeFileSync(
path.join(globalExt, "package.json"),
JSON.stringify({
name: "@openclaw/pack",
openclaw: { extensions: ["./escape.ts"] },
}),
"utf-8",
);
const { candidates, diagnostics } = await withStateDir(stateDir, async () => {
return discoverOpenClawPlugins({});
});
expect(candidates.some((candidate) => candidate.idHint === "pack")).toBe(false);
expect(diagnostics.some((entry) => entry.message.includes("escapes package directory"))).toBe(
true,
);
});
it.runIf(process.platform !== "win32")("blocks world-writable plugin paths", async () => {
const stateDir = makeTempDir();
const globalExt = path.join(stateDir, "extensions");

View File

@@ -1,6 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import { isPathInsideWithRealpath } from "../security/scan-paths.js";
import { openBoundaryFileSync } from "../infra/boundary-file-read.js";
import { resolveConfigDir, resolveUserPath } from "../utils.js";
import { resolveBundledPluginsDir } from "./bundled-dir.js";
import {
@@ -284,7 +284,7 @@ function addCandidate(params: {
if (params.seen.has(resolved)) {
return;
}
const resolvedRoot = path.resolve(params.rootDir);
const resolvedRoot = safeRealpathSync(params.rootDir) ?? path.resolve(params.rootDir);
if (
isUnsafePluginCandidate({
source: resolved,
@@ -319,11 +319,12 @@ function resolvePackageEntrySource(params: {
diagnostics: PluginDiagnostic[];
}): string | null {
const source = path.resolve(params.packageDir, params.entryPath);
if (
!isPathInsideWithRealpath(params.packageDir, source, {
requireRealpath: true,
})
) {
const opened = openBoundaryFileSync({
absolutePath: source,
rootPath: params.packageDir,
boundaryLabel: "plugin package directory",
});
if (!opened.ok) {
params.diagnostics.push({
level: "error",
message: `extension entry escapes package directory: ${params.entryPath}`,
@@ -331,7 +332,9 @@ function resolvePackageEntrySource(params: {
});
return null;
}
return source;
const safeSource = opened.path;
fs.closeSync(opened.fd);
return safeSource;
}
function discoverInDirectory(params: {

View File

@@ -651,6 +651,56 @@ describe("loadOpenClawPlugins", () => {
expect(registry.diagnostics.some((entry) => entry.message.includes("escapes"))).toBe(true);
});
it("rejects plugin entry files that escape plugin root via hardlink", () => {
if (process.platform === "win32") {
return;
}
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = "/nonexistent/bundled/plugins";
const pluginDir = makeTempDir();
const outsideDir = makeTempDir();
const outsideEntry = path.join(outsideDir, "outside.js");
const linkedEntry = path.join(pluginDir, "entry.js");
fs.writeFileSync(
outsideEntry,
'export default { id: "hardlinked", register() { throw new Error("should not run"); } };',
"utf-8",
);
fs.writeFileSync(
path.join(pluginDir, "openclaw.plugin.json"),
JSON.stringify(
{
id: "hardlinked",
configSchema: EMPTY_PLUGIN_SCHEMA,
},
null,
2,
),
"utf-8",
);
try {
fs.linkSync(outsideEntry, linkedEntry);
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "EXDEV") {
return;
}
throw err;
}
const registry = loadOpenClawPlugins({
cache: false,
config: {
plugins: {
load: { paths: [linkedEntry] },
allow: ["hardlinked"],
},
},
});
const record = registry.plugins.find((entry) => entry.id === "hardlinked");
expect(record?.status).not.toBe("loaded");
expect(registry.diagnostics.some((entry) => entry.message.includes("escapes"))).toBe(true);
});
it("prefers dist plugin-sdk alias when loader runs from dist", () => {
const root = makeTempDir();
const srcFile = path.join(root, "src", "plugin-sdk", "index.ts");

View File

@@ -4,8 +4,8 @@ import { fileURLToPath } from "node:url";
import { createJiti } from "jiti";
import type { OpenClawConfig } from "../config/config.js";
import type { GatewayRequestHandler } from "../gateway/server-methods/types.js";
import { openBoundaryFileSync } from "../infra/boundary-file-read.js";
import { createSubsystemLogger } from "../logging/subsystem.js";
import { isPathInsideWithRealpath } from "../security/scan-paths.js";
import { resolveUserPath } from "../utils.js";
import { clearPluginCommands } from "./commands.js";
import {
@@ -525,13 +525,15 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
continue;
}
if (
!isPathInsideWithRealpath(candidate.rootDir, candidate.source, {
requireRealpath: true,
})
) {
const pluginRoot = safeRealpathOrResolve(candidate.rootDir);
const opened = openBoundaryFileSync({
absolutePath: candidate.source,
rootPath: pluginRoot,
boundaryLabel: "plugin root",
});
if (!opened.ok) {
record.status = "error";
record.error = "plugin entry path escapes plugin root";
record.error = "plugin entry path escapes plugin root or fails alias checks";
registry.plugins.push(record);
seenIds.set(pluginId, candidate.origin);
registry.diagnostics.push({
@@ -542,10 +544,12 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
});
continue;
}
const safeSource = opened.path;
fs.closeSync(opened.fd);
let mod: OpenClawPluginModule | null = null;
try {
mod = getJiti()(candidate.source) as OpenClawPluginModule;
mod = getJiti()(safeSource) as OpenClawPluginModule;
} catch (err) {
recordPluginError({
logger,
@@ -707,3 +711,11 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
initializeGlobalHookRunner(registry);
return registry;
}
function safeRealpathOrResolve(value: string): string {
try {
return fs.realpathSync(value);
} catch {
return path.resolve(value);
}
}