Skip to content

Commit c0d81fc

Browse files
cliffhallclaude
andcommitted
fix(filesystem): harden path handling
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 69b53e9 commit c0d81fc

5 files changed

Lines changed: 89 additions & 8 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-filesystem": patch
3+
---
4+
5+
Harden path validation.

‎src/filesystem/__tests__/path-utils.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, it, expect, afterEach } from "vitest";
22
import {
33
normalizePath,
4+
normalizePathFormat,
45
expandHome,
56
convertToWindowsPath,
67
} from "../path-utils.js";
@@ -69,6 +70,20 @@ describe("Path Utilities", () => {
6970
});
7071
});
7172

73+
describe("normalizePathFormat", () => {
74+
it("keeps surrounding quotes and whitespace, which are part of the name", () => {
75+
expect(normalizePathFormat("/allowed/proj'")).toBe("/allowed/proj'");
76+
expect(normalizePathFormat('/allowed/proj"')).toBe('/allowed/proj"');
77+
expect(normalizePathFormat("/allowed/proj ")).toBe("/allowed/proj ");
78+
});
79+
80+
it("normalizes the format as normalizePath does", () => {
81+
expect(normalizePathFormat("/usr/local//bin/app///")).toBe(
82+
"/usr/local/bin/app",
83+
);
84+
});
85+
});
86+
7287
describe("normalizePath", () => {
7388
it("preserves Unix paths", () => {
7489
expect(normalizePath("/usr/local/bin")).toBe("/usr/local/bin");

‎src/filesystem/__tests__/server-paths.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,52 @@ describe("the allow-list boundary", () => {
8989
}
9090
});
9191

92+
// A trailing quote or space is a legal filename character, so a sibling
93+
// named `<dir>'` is a different entry and must be checked as itself.
94+
// Windows refuses or strips these characters in names, so POSIX only.
95+
describe.skipIf(process.platform === "win32").each([
96+
["a single quote", "'"],
97+
["a double quote", '"'],
98+
["a space", " "],
99+
])("a sibling whose name is the allowed directory plus %s", (_, suffix) => {
100+
let sibling: string;
101+
102+
beforeEach(() => {
103+
sibling = `${dir}${suffix}`;
104+
});
105+
106+
afterEach(async () => {
107+
await fs.rm(sibling, { recursive: true, force: true });
108+
});
109+
110+
it("refuses to read it as a file", async () => {
111+
await fs.writeFile(sibling, "secret");
112+
const result = await read(sibling);
113+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
114+
});
115+
116+
it("refuses to list it", async () => {
117+
await fs.mkdir(sibling);
118+
const result = await call(client, "list_directory", { path: sibling });
119+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
120+
});
121+
122+
it("refuses to create it", async () => {
123+
const result = await call(client, "create_directory", { path: sibling });
124+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
125+
await expect(fs.stat(sibling)).rejects.toThrow();
126+
});
127+
128+
it("refuses to write it as a file", async () => {
129+
const result = await call(client, "write_file", {
130+
path: sibling,
131+
content: "x",
132+
});
133+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
134+
await expect(fs.stat(sibling)).rejects.toThrow();
135+
});
136+
});
137+
92138
it("allows the allowed directory itself", async () => {
93139
const result = await call(client, "list_directory", { path: dir });
94140
expect(result.isError).toBeFalsy();

‎src/filesystem/lib.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import path from "path";
33
import { StringDecoder } from "string_decoder";
44
import { createTwoFilesPatch } from "diff";
55
import { minimatch } from "minimatch";
6-
import { normalizePath, expandHome } from "./path-utils.js";
6+
import { normalizePathFormat, expandHome } from "./path-utils.js";
77
import { isPathWithinAllowedDirectories } from "./path-validation.js";
88

99
// Type definitions
@@ -75,7 +75,7 @@ function resolveRelativePathAgainstAllowedDirectories(
7575
// Try to resolve relative path against each allowed directory
7676
for (const allowedDir of allowedDirectories) {
7777
const candidate = path.resolve(allowedDir, relativePath);
78-
const normalizedCandidate = normalizePath(candidate);
78+
const normalizedCandidate = normalizePathFormat(candidate);
7979

8080
// Check if the resulting path lies within any allowed directory
8181
if (
@@ -140,7 +140,9 @@ async function resolveUnicodeEquivalentPath(
140140
const allowedDirectory = [...allowedDirectories]
141141
.sort((left, right) => right.length - left.length)
142142
.find((directory) =>
143-
isPathWithinAllowedDirectories(normalizePath(absolutePath), [directory]),
143+
isPathWithinAllowedDirectories(normalizePathFormat(absolutePath), [
144+
directory,
145+
]),
144146
);
145147

146148
/* v8 ignore next -- validatePath calls this only after the same allow-list check passed, so a containing directory always exists */
@@ -180,7 +182,7 @@ async function resolveUnicodeEquivalentPath(
180182
);
181183
if (
182184
!isPathWithinAllowedDirectories(
183-
normalizePath(currentPath),
185+
normalizePathFormat(currentPath),
184186
allowedDirectories,
185187
)
186188
) {
@@ -219,12 +221,15 @@ export async function validatePath(
219221
allowedDirectories,
220222
);
221223
if (
222-
!isPathWithinAllowedDirectories(normalizePath(absolute), allowedDirectories)
224+
!isPathWithinAllowedDirectories(
225+
normalizePathFormat(absolute),
226+
allowedDirectories,
227+
)
223228
) {
224229
absolute = respellAllowedDirectoryPrefix(absolute, allowedDirectories);
225230
}
226231

227-
const normalizedRequested = normalizePath(absolute);
232+
const normalizedRequested = normalizePathFormat(absolute);
228233

229234
// Security: Check if path is within allowed directories before any file operations
230235
const isAllowed = isPathWithinAllowedDirectories(
@@ -243,7 +248,7 @@ export async function validatePath(
243248
// This prevents attackers from creating symlinks that point outside allowed directories
244249
try {
245250
const realPath = await fs.realpath(absolute);
246-
const normalizedReal = normalizePath(realPath);
251+
const normalizedReal = normalizePathFormat(realPath);
247252
if (!isPathWithinAllowedDirectories(normalizedReal, allowedDirectories)) {
248253
throw new Error(
249254
`Access denied - symlink target outside allowed directories: ${realPath} not in ${allowedDirectories.join(", ")}`,

‎src/filesystem/path-utils.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,18 @@ export function convertToWindowsPath(p: string): string {
3838
*/
3939
export function normalizePath(p: string): string {
4040
// Remove any surrounding quotes and whitespace
41-
p = p.trim().replace(/^["']|["']$/g, "");
41+
return normalizePathFormat(p.trim().replace(/^["']|["']$/g, ""));
42+
}
4243

44+
/**
45+
* Normalizes a path's format exactly as normalizePath does, but without
46+
* stripping surrounding quotes or whitespace. Those are legal filename
47+
* characters, so stripping them names a different file: a path that a file
48+
* operation will use must be checked against the allow-list in this form.
49+
* @param p The path to normalize
50+
* @returns Normalized path
51+
*/
52+
export function normalizePathFormat(p: string): string {
4353
// Check if this is a Unix path that should not be converted
4454
// WSL paths (/mnt/) should ALWAYS be preserved as they work correctly in WSL with Node.js fs
4555
// Regular Unix paths should also be preserved

0 commit comments

Comments
 (0)