fix(security): harden root file guards and host writes

This commit is contained in:
Peter Steinberger
2026-02-26 13:32:02 +01:00
parent 2ca2d5ab1c
commit e3385a6578
8 changed files with 387 additions and 81 deletions

View File

@@ -2,6 +2,7 @@ import fs from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import path from "node:path";
import type { OpenClawConfig } from "../config/config.js";
import { openBoundaryFileSync } from "../infra/boundary-file-read.js";
import { resolveControlUiRootSync } from "../infra/control-ui-assets.js";
import { isWithinDir } from "../infra/path-safety.js";
import { openVerifiedFileSync } from "../infra/safe-open-sync.js";
@@ -210,11 +211,6 @@ function serveResolvedIndexHtml(res: ServerResponse, body: string) {
res.end(body);
}
function isContainedPath(baseDir: string, targetPath: string): boolean {
const relative = path.relative(baseDir, targetPath);
return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}
function isExpectedSafePathError(error: unknown): boolean {
const code =
typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
@@ -237,25 +233,20 @@ function resolveSafeControlUiFile(
rootReal: string,
filePath: string,
): { path: string; fd: number } | null {
try {
const fileReal = fs.realpathSync(filePath);
if (!isContainedPath(rootReal, fileReal)) {
return null;
const opened = openBoundaryFileSync({
absolutePath: filePath,
rootPath: rootReal,
rootRealPath: rootReal,
boundaryLabel: "control ui root",
skipLexicalRootCheck: true,
});
if (!opened.ok) {
if (opened.reason === "io") {
throw opened.error;
}
const opened = openVerifiedFileSync({ filePath: fileReal, resolvedPath: fileReal });
if (!opened.ok) {
if (opened.reason === "io") {
throw opened.error;
}
return null;
}
return { path: opened.path, fd: opened.fd };
} catch (error) {
if (isExpectedSafePathError(error)) {
return null;
}
throw error;
return null;
}
return { path: opened.path, fd: opened.fd };
}
function isSafeRelativePath(relPath: string) {

View File

@@ -1,4 +1,3 @@
import { constants as fsConstants } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import {
@@ -29,7 +28,7 @@ import {
import { loadConfig, writeConfigFile } from "../../config/config.js";
import { resolveSessionTranscriptsDirForAgent } from "../../config/sessions/paths.js";
import { sameFileIdentity } from "../../infra/file-identity.js";
import { SafeOpenError, readLocalFileSafely } from "../../infra/fs-safe.js";
import { SafeOpenError, readLocalFileSafely, writeFileWithinRoot } from "../../infra/fs-safe.js";
import { assertNoPathAliasEscape } from "../../infra/path-alias-guards.js";
import { isNotFoundPathError } from "../../infra/path-guards.js";
import { DEFAULT_AGENT_ID, normalizeAgentId } from "../../routing/session-key.js";
@@ -121,13 +120,6 @@ type ResolvedAgentWorkspaceFilePath =
reason: string;
};
const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in fsConstants;
const OPEN_WRITE_FLAGS =
fsConstants.O_WRONLY |
fsConstants.O_CREAT |
fsConstants.O_TRUNC |
(SUPPORTS_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0);
async function resolveWorkspaceRealPath(workspaceDir: string): Promise<string> {
try {
return await fs.realpath(workspaceDir);
@@ -238,25 +230,6 @@ async function statFileSafely(filePath: string): Promise<FileMeta | null> {
}
}
async function writeFileSafely(filePath: string, content: string): Promise<void> {
const handle = await fs.open(filePath, OPEN_WRITE_FLAGS, 0o600);
try {
const [stat, lstat] = await Promise.all([handle.stat(), fs.lstat(filePath)]);
if (lstat.isSymbolicLink() || !stat.isFile()) {
throw new Error("unsafe file path");
}
if (stat.nlink > 1) {
throw new Error("hardlinked file path is not allowed");
}
if (!sameFileIdentity(stat, lstat)) {
throw new Error("path changed during write");
}
await handle.writeFile(content, "utf-8");
} finally {
await handle.close().catch(() => {});
}
}
async function listAgentFiles(workspaceDir: string, options?: { hideBootstrap?: boolean }) {
const files: Array<{
name: string;
@@ -729,7 +702,12 @@ export const agentsHandlers: GatewayRequestHandlers = {
}
const content = String(params.content ?? "");
try {
await writeFileSafely(resolvedPath.ioPath, content);
await writeFileWithinRoot({
rootDir: workspaceDir,
relativePath: name,
data: content,
encoding: "utf8",
});
} catch {
respond(
false,

View File

@@ -22,7 +22,7 @@ import {
type SessionEntry,
type SessionScope,
} from "../config/sessions.js";
import { openVerifiedFileSync } from "../infra/safe-open-sync.js";
import { openBoundaryFileSync } from "../infra/boundary-file-read.js";
import {
normalizeAgentId,
normalizeMainKey,
@@ -102,14 +102,13 @@ function resolveIdentityAvatarUrl(
return undefined;
}
try {
const resolvedReal = fs.realpathSync(resolvedCandidate);
if (!isPathWithinRoot(workspaceRoot, resolvedReal)) {
return undefined;
}
const opened = openVerifiedFileSync({
filePath: resolvedReal,
resolvedPath: resolvedReal,
const opened = openBoundaryFileSync({
absolutePath: resolvedCandidate,
rootPath: workspaceRoot,
rootRealPath: workspaceRoot,
boundaryLabel: "workspace root",
maxBytes: AVATAR_MAX_BYTES,
skipLexicalRootCheck: true,
});
if (!opened.ok) {
return undefined;