Skip to content

Commit b3fe0cf

Browse files
authored
Merge pull request #5584 from modelcontextprotocol/v2/fix/GHSA-rq2p-q7c4-6g27
fix(filesystem): GHSA-rq2p-q7c4-6g27
2 parents d58b50e + 438e6f3 commit b3fe0cf

9 files changed

Lines changed: 402 additions & 29 deletions

File tree

‎.changeset/ghsa-rq2p-q7c4-6g27.md‎

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+
Fix GHSA-rq2p-q7c4-6g27.

‎src/filesystem/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ The server's directory access control follows this flow:
125125
/Users/username/project
126126
```
127127
- Server requires at least ONE allowed directory to operate
128+
- A path is checked and then used, so on macOS and Linux each write, each read of a file's content or metadata, and each directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) acts from inside the directory that was checked. If a directory on the path is replaced in between, the call is refused with "Access denied - a directory on the path changed during the operation" rather than following the replacement. A listing therefore needs to enter the directory it lists: a directory the server can read but not enter (read permission without execute) is refused with `EACCES`, as an unreadable one is
128129
- On Windows, a path naming an NTFS alternate data stream (`file.txt:stream`, `file.txt::$DATA`) is refused with "Access denied - NTFS alternate data stream paths are not supported", even inside an allowed directory: a colon is accepted only as a drive letter's (`C:\`, `\\?\C:\`). A stream holds data that no directory listing or diff of the file shows. On macOS and Linux a colon is an ordinary file-name character and is not refused
129130
- On Windows, a path any of whose components is a reserved device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, in any case and with or without an extension, such as `NUL.txt`) is refused with "Access denied - Windows reserved device names ... are not supported", and one any of whose components ends in a dot or a space (`file.txt.`, `dir \file.txt`) with "Access denied - Windows path components ending in a dot or a space are not supported". Windows opens the device rather than a file in the directory, and strips trailing dots and spaces so the name refers to a different file. `.` and `..` are not affected. On macOS and Linux these are ordinary file names and are not refused
130131
- **Limit on Windows: a parent directory swapped during an operation.** A path is checked and then used, and a directory on it could be replaced in between. On Linux and macOS the server anchors every write, and every read of a file's content or metadata, to the directory it validated, so a directory replaced with a symlink after the check cannot redirect the operation. **On Windows it cannot do that, and the operation is not protected**: a second local process that can already write inside an allowed directory can replace a parent directory with a junction (or a directory symlink) between the server's check and its open, and so redirect a read or a write outside the allowed directories. The server still checks the final component there (a write refuses a symlink or junction at the file's own name, and the file opened must be the one the directory holds at that name afterwards), which narrows the window without closing it

‎src/filesystem/__tests__/bounded-walk.test.ts‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
// they do not single out goes to the real filesystem.
88

99
import fs from "fs/promises";
10+
import fsSync from "fs";
1011
import type { Dirent, PathLike } from "fs";
1112
import path from "path";
1213
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -23,6 +24,7 @@ import { FS_CALL_TIMEOUT_MS, MAX_WALK_ENTRIES } from "../lib.js";
2324

2425
const realReaddir = fs.readdir.bind(fs);
2526
const realRealpath = fs.realpath.bind(fs);
27+
const realReaddirSync = fsSync.readdirSync.bind(fsSync);
2628

2729
// The cap tests walk MAX_WALK_ENTRIES + 1 entries on purpose, so their cost is
2830
// the bound they check and scales with the runner: about 1 s locally, near
@@ -110,6 +112,29 @@ function fileEntries(parent: string, count: number): Dirent[] {
110112
);
111113
}
112114

115+
/**
116+
* Make `dir` list MAX_WALK_ENTRIES + 1 plain files that are not on disk, both
117+
* in the bounded first read (fs.readdir) and in the anchored listing that
118+
* follows it, which reads "." from inside the directory (pinned-directory.ts).
119+
*/
120+
function listManyFiles(): void {
121+
const entries = fileEntries(dir, MAX_WALK_ENTRIES + 1);
122+
vi.spyOn(fs, "readdir").mockImplementation(((target: PathLike) =>
123+
target.toString() === dir
124+
? Promise.resolve(entries)
125+
: realReaddir(target)) as typeof fs.readdir);
126+
vi.spyOn(fsSync, "readdirSync").mockImplementation(((
127+
target: PathLike,
128+
...rest: unknown[]
129+
) =>
130+
target.toString() === "." && process.cwd() === dir
131+
? entries
132+
: (realReaddirSync as (target: PathLike, ...rest: unknown[]) => unknown)(
133+
target,
134+
...rest,
135+
)) as typeof fsSync.readdirSync);
136+
}
137+
113138
describe("search_files", () => {
114139
it("applies excludePatterns before touching an entry: an excluded subtree is never realpath'd or read", async () => {
115140
const realpath = vi.spyOn(fs, "realpath");
@@ -154,10 +179,7 @@ describe("search_files", () => {
154179
`stops with an error after visiting ${MAX_WALK_ENTRIES} entries`,
155180
WALK_CAP,
156181
async () => {
157-
vi.spyOn(fs, "readdir").mockImplementation(((target: PathLike) =>
158-
target.toString() === dir
159-
? Promise.resolve(fileEntries(dir, MAX_WALK_ENTRIES + 1))
160-
: realReaddir(target)) as typeof fs.readdir);
182+
listManyFiles();
161183
// The listed names do not exist on disk; resolve them as themselves so
162184
// each entry costs a string check rather than a real lookup.
163185
vi.spyOn(fs, "realpath").mockImplementation(((target: PathLike) =>
@@ -203,10 +225,7 @@ describe("directory_tree", () => {
203225
`stops with an error after visiting ${MAX_WALK_ENTRIES} entries`,
204226
WALK_CAP,
205227
async () => {
206-
vi.spyOn(fs, "readdir").mockImplementation(((target: PathLike) =>
207-
target.toString() === dir
208-
? Promise.resolve(fileEntries(dir, MAX_WALK_ENTRIES + 1))
209-
: realReaddir(target)) as typeof fs.readdir);
228+
listManyFiles();
210229
const result = await call(client, "directory_tree", { path: dir });
211230
expect(result.isError).toBe(true);
212231
expect(textOf(result)).toContain(
@@ -216,10 +235,7 @@ describe("directory_tree", () => {
216235
);
217236

218237
it("does not count excluded entries toward the cap", WALK_CAP, async () => {
219-
vi.spyOn(fs, "readdir").mockImplementation(((target: PathLike) =>
220-
target.toString() === dir
221-
? Promise.resolve(fileEntries(dir, MAX_WALK_ENTRIES + 1))
222-
: realReaddir(target)) as typeof fs.readdir);
238+
listManyFiles();
223239
const result = await call(client, "directory_tree", {
224240
path: dir,
225241
excludePatterns: ["f*"],

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,11 @@ describe("Lib Functions", () => {
781781
];
782782

783783
mockReaddir.mockResolvedValueOnce(mockEntries as Dirent[]);
784+
// The anchored listing the search uses (the readdir above is only
785+
// its bounded first read; see listValidatedDirectory).
786+
mockPinned.readDirectoryInPlace.mockReturnValueOnce(
787+
mockEntries as Dirent[],
788+
);
784789

785790
const testDir =
786791
process.platform === "win32" ? "C:\\allowed\\dir" : "/allowed/dir";
@@ -815,6 +820,11 @@ describe("Lib Functions", () => {
815820
];
816821

817822
mockReaddir.mockResolvedValueOnce(mockEntries as Dirent[]);
823+
// The anchored listing the search uses (the readdir above is only
824+
// its bounded first read; see listValidatedDirectory).
825+
mockPinned.readDirectoryInPlace.mockReturnValueOnce(
826+
mockEntries as Dirent[],
827+
);
818828

819829
// Mock validatePath to throw error for invalid_file.txt
820830
mockFs.realpath.mockImplementation(async (path: PathLike) => {
@@ -852,6 +862,11 @@ describe("Lib Functions", () => {
852862
];
853863

854864
mockReaddir.mockResolvedValueOnce(mockEntries as Dirent[]);
865+
// The anchored listing the search uses (the readdir above is only
866+
// its bounded first read; see listValidatedDirectory).
867+
mockPinned.readDirectoryInPlace.mockReturnValueOnce(
868+
mockEntries as Dirent[],
869+
);
855870

856871
const testDir =
857872
process.platform === "win32" ? "C:\\allowed\\dir" : "/allowed/dir";
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
// Protocol-level tests that every directory listing is anchored to the
2+
// directory validation resolved, as every read and write is
3+
// (pinned-directory.ts). The swap an attacker would race is staged
4+
// deterministically, as read-anchored.test.ts stages it: right after
5+
// validation realpath's a directory the tool is about to list, that directory
6+
// is swapped for a symlink to a directory outside the allowed one. Each
7+
// listing must then refuse rather than return the outside directory's entry
8+
// names. Before listings were anchored, each of these returned them.
9+
10+
import fs from "fs/promises";
11+
import fsSync from "fs";
12+
import path from "path";
13+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14+
import type { Client } from "@modelcontextprotocol/client";
15+
import {
16+
call,
17+
connect,
18+
makeTempDir,
19+
quietStderr,
20+
textOf,
21+
type Connected,
22+
} from "./helpers.js";
23+
24+
// The name is what a listing would leak, so it is the marker.
25+
const OUTSIDE_NAME = "OUTSIDE-NAME-CANARY.txt";
26+
const INSIDE_NAME = "inside-marker.txt";
27+
28+
let dir: string;
29+
let outside: string;
30+
let flip: string;
31+
let flipReal: string;
32+
let conn: Connected;
33+
let client: Client;
34+
35+
beforeEach(async () => {
36+
quietStderr();
37+
dir = await makeTempDir("mcp-fs-list-anchor-");
38+
outside = await makeTempDir("mcp-fs-list-anchor-outside-");
39+
flip = path.join(dir, "flip");
40+
flipReal = path.join(dir, "flip-real");
41+
await fs.mkdir(flip);
42+
await fs.writeFile(path.join(flip, INSIDE_NAME), "inside");
43+
await fs.writeFile(path.join(outside, OUTSIDE_NAME), "outside");
44+
conn = await connect([dir]);
45+
client = conn.client;
46+
});
47+
48+
afterEach(async () => {
49+
vi.restoreAllMocks();
50+
await conn.close();
51+
await fs.rm(dir, { recursive: true, force: true });
52+
await fs.rm(outside, { recursive: true, force: true });
53+
});
54+
55+
/** Swap `flip` for a symlink to `outside`, once, right after it is realpath'd. */
56+
function swapAfterRealpath(): void {
57+
const realRealpath = fs.realpath.bind(fs);
58+
let swapped = false;
59+
vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => {
60+
const resolved = await realRealpath(p, opts);
61+
if (!swapped && p === flip) {
62+
swapped = true;
63+
fsSync.renameSync(flip, flipReal);
64+
fsSync.symlinkSync(outside, flip);
65+
}
66+
return resolved;
67+
});
68+
}
69+
70+
const DIRECTORY_CHANGED =
71+
/Access denied - a directory on the path changed during the operation/;
72+
73+
describe.skipIf(process.platform === "win32")(
74+
"a listed directory swapped for a symlink after validation",
75+
() => {
76+
it.each([
77+
["list_directory", {}],
78+
["list_directory_with_sizes", {}],
79+
["directory_tree", {}],
80+
["search_files", { pattern: "**" }],
81+
])("%s does not list through it", async (tool, extra) => {
82+
swapAfterRealpath();
83+
const result = await call(client, tool, { path: flip, ...extra });
84+
expect(result.isError).toBe(true);
85+
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
86+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
87+
});
88+
89+
it("directory_tree does not list a subdirectory through it", async () => {
90+
swapAfterRealpath();
91+
const result = await call(client, "directory_tree", { path: dir });
92+
expect(result.isError).toBe(true);
93+
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
94+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
95+
});
96+
97+
it("search_files does not search a subdirectory through it, and says so", async () => {
98+
swapAfterRealpath();
99+
const result = await call(client, "search_files", {
100+
path: dir,
101+
pattern: "**",
102+
});
103+
expect(result.isError).toBeFalsy();
104+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
105+
// The swapped directory is reported as unreadable, not as empty.
106+
expect(textOf(result)).toContain(`${flip}`);
107+
expect(textOf(result)).toMatch(/could not be read/i);
108+
});
109+
},
110+
);
111+
112+
describe("listings that are not swapped", () => {
113+
it("list every tool's way, from the directory validation resolved", async () => {
114+
expect(textOf(await call(client, "list_directory", { path: flip }))).toBe(
115+
`[FILE] ${INSIDE_NAME}`,
116+
);
117+
expect(
118+
textOf(await call(client, "list_directory_with_sizes", { path: flip })),
119+
).toContain(`[FILE] ${INSIDE_NAME}`);
120+
expect(
121+
JSON.parse(textOf(await call(client, "directory_tree", { path: dir }))),
122+
).toEqual([
123+
{
124+
name: "flip",
125+
type: "directory",
126+
children: [{ name: INSIDE_NAME, type: "file" }],
127+
},
128+
]);
129+
expect(
130+
textOf(
131+
await call(client, "search_files", { path: dir, pattern: "**/*.txt" }),
132+
),
133+
).toBe(path.join(flip, INSIDE_NAME));
134+
});
135+
136+
it("refuses a static symlink to a directory outside, as before", async () => {
137+
const link = path.join(dir, "link");
138+
await fs.symlink(outside, link);
139+
for (const tool of ["list_directory", "directory_tree"]) {
140+
const result = await call(client, tool, { path: link });
141+
expect(result.isError).toBe(true);
142+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
143+
}
144+
});
145+
});

‎src/filesystem/__tests__/pinned-directory.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
moveFileAcrossDevices,
1717
openFileForReading,
1818
overwriteFileInDirectory,
19+
readDirectoryInPlace,
1920
readFileInDirectory,
2021
renameIntoDirectory,
2122
statInDirectory,
@@ -1395,3 +1396,93 @@ describe("the anchored reads", () => {
13951396
expect(chdir).not.toHaveBeenCalled();
13961397
});
13971398
});
1399+
1400+
describe("readDirectoryInPlace", () => {
1401+
// Run as root, the process enters a directory without search permission.
1402+
const enforcesModes =
1403+
process.platform !== "win32" && process.getuid?.() !== 0;
1404+
1405+
it("lists the entries with their types, and restores the working directory", () => {
1406+
fs.mkdirSync(path.join(dir, "sub"));
1407+
fs.writeFileSync(path.join(dir, "f.txt"), "");
1408+
const entries = readDirectoryInPlace(dir)
1409+
.map((entry) => `${entry.name}:${entry.isDirectory()}`)
1410+
.sort();
1411+
expect(entries).toEqual(["f.txt:false", "sub:true"]);
1412+
// parentPath names the directory, as fs.readdir(dir) would, not ".".
1413+
expect(readDirectoryInPlace(dir).map((entry) => entry.parentPath)).toEqual([
1414+
dir,
1415+
dir,
1416+
]);
1417+
expect(process.cwd()).toBe(cwd);
1418+
});
1419+
1420+
it.skipIf(!symlinks)(
1421+
"refuses a path that no longer leads to the directory validated",
1422+
() => {
1423+
fs.writeFileSync(path.join(outside, "secret.txt"), "");
1424+
fs.symlinkSync(outside, path.join(dir, "link"));
1425+
expect(() => readDirectoryInPlace(path.join(dir, "link"))).toThrow(
1426+
/^Access denied - a directory on the path changed during the operation/,
1427+
);
1428+
expect(process.cwd()).toBe(cwd);
1429+
},
1430+
);
1431+
1432+
it("reports a missing directory as readdir would, without the working directory", () => {
1433+
const missing = path.join(dir, "missing");
1434+
let error: NodeJS.ErrnoException | undefined;
1435+
try {
1436+
readDirectoryInPlace(missing);
1437+
} catch (e) {
1438+
error = e as NodeJS.ErrnoException;
1439+
}
1440+
expect(error?.message).toBe(
1441+
`ENOENT: no such file or directory, scandir '${missing}'`,
1442+
);
1443+
expect(error?.code).toBe("ENOENT");
1444+
expect(error?.message).not.toContain(cwd);
1445+
});
1446+
1447+
it("keeps the code of an enter failure that carries no errno", () => {
1448+
vi.spyOn(process, "chdir").mockImplementationOnce(() => {
1449+
throw errno("EIO");
1450+
});
1451+
expect(() => readDirectoryInPlace(dir)).toThrow(
1452+
`EIO: cannot enter directory, scandir '${dir}'`,
1453+
);
1454+
});
1455+
1456+
it("names the directory, not '.', when the listing itself fails", () => {
1457+
vi.spyOn(fs, "readdirSync").mockImplementationOnce(() => {
1458+
throw Object.assign(new Error("EACCES: permission denied, scandir '.'"), {
1459+
code: "EACCES",
1460+
path: ".",
1461+
});
1462+
});
1463+
expect(() => readDirectoryInPlace(dir)).toThrow(
1464+
`EACCES: permission denied, scandir '${dir}'`,
1465+
);
1466+
expect(process.cwd()).toBe(cwd);
1467+
});
1468+
1469+
it.skipIf(!enforcesModes)(
1470+
"refuses a directory it can read but not enter (r without x)",
1471+
() => {
1472+
const locked = path.join(dir, "locked");
1473+
fs.mkdirSync(locked);
1474+
fs.writeFileSync(path.join(locked, "f.txt"), "");
1475+
fs.chmodSync(locked, 0o600);
1476+
try {
1477+
// A plain readdir by path still lists it; the anchored listing
1478+
// cannot enter it, and refuses.
1479+
expect(fs.readdirSync(locked)).toEqual(["f.txt"]);
1480+
expect(() => readDirectoryInPlace(locked)).toThrow(
1481+
`EACCES: permission denied, scandir '${locked}'`,
1482+
);
1483+
} finally {
1484+
fs.chmodSync(locked, 0o755);
1485+
}
1486+
},
1487+
);
1488+
});

0 commit comments

Comments
 (0)