Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions .changeset/filesystem-windows-listing-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/server-filesystem": patch
---

On Windows, `list_directory`, `list_directory_with_sizes`, `directory_tree` and `search_files` now check the directory they list before and after reading it: its path must have no junction or symlink on it and must name the same directory both times, or the call is refused with "Access denied - a directory on the path changed during the operation". A directory swapped for a junction after the path was validated is no longer listed. A swap made and undone while the directory is being read is still not detected; the README's "Limit on Windows" entry says what holds. macOS and Linux are unchanged.
2 changes: 1 addition & 1 deletion src/filesystem/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ The server's directory access control follows this flow:
- 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
- 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
- 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
- **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
- **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, every read of a file's content or metadata, and every directory listing, 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, a write or a directory listing 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. A directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) is checked on both sides of the read instead: before and after it, the listed path must have no junction or symlink on it and must name the same directory, or the call is refused with "Access denied - a directory on the path changed during the operation". That refuses a replacement still in place when the read starts or when it ends. One made and undone in between is not detected, and returns the entry names of the directory it pointed to, so this too narrows the window without closing it
- **What it takes**: a concurrent local process with write access inside an allowed directory, winning a race against the server. No tool of this server creates a junction or a symlink, so it cannot be set up through the server alone
- **Guidance**: on Windows, do not allow a directory that untrusted local processes or users can write to
- **Why it is not fixed**: closing the window needs opens relative to a directory handle, which Node does not expose, so it would take native code, and that is out of scope for a reference server ([#5260](https://github.com/modelcontextprotocol/servers/issues/5260)). It may be revisited when Node ships a stable built-in FFI under this package's `engines` floor
Expand Down
180 changes: 180 additions & 0 deletions src/filesystem/__tests__/list-anchored-windows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// The Windows listing check (#5600): readDirectoryInPlace cannot anchor a
// listing on Windows (the working directory is a path string there), so it
// checks the listed directory before and after the read: the path must
// resolve to itself, with no junction or symlink on it, and must name the
// same directory both times (pinned-directory.ts).
//
// These tests run that branch on every host. On Windows (the CI Windows leg)
// it runs for real, against real junctions. Elsewhere process.platform is
// set to "win32", which is all the branch reads; the filesystem stays the
// host's, so the swaps are real there too, and the coverage gate (which runs
// on Linux) sees the branch.
//
// A swap staged from inside the read can be refused by the host: Windows will
// not rename a directory a process is in, and the server is in the listed
// directory. So those tests assert what must hold either way: the entries
// returned are never the outside directory's, and a swap that did happen is
// refused. The protocol-level tests of a swap staged before the listing are
// in list-anchored.test.ts, and run on Windows too.

import fsSync from "fs";
import path from "path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readDirectoryInPlace } from "../pinned-directory.js";
import { makeTempDir } from "./helpers.js";

const OUTSIDE_NAME = "OUTSIDE-NAME-CANARY.txt";
const INSIDE_NAME = "inside-marker.txt";
const DIRECTORY_CHANGED =
/Access denied - a directory on the path changed during the operation/;

const realPlatform = process.platform;

let dir: string;
let outside: string;
let middle: string;
let listed: string;

beforeEach(async () => {
dir = await makeTempDir("mcp-fs-list-win-");
outside = await makeTempDir("mcp-fs-list-win-outside-");
middle = path.join(dir, "middle");
listed = path.join(middle, "listed");
fsSync.mkdirSync(listed, { recursive: true });
fsSync.writeFileSync(path.join(listed, INSIDE_NAME), "inside");
// The outside tree mirrors the inside one, so a swapped parent still leads
// to a real directory named "listed".
fsSync.mkdirSync(path.join(outside, "listed"));
fsSync.writeFileSync(path.join(outside, OUTSIDE_NAME), "outside");
fsSync.writeFileSync(path.join(outside, "listed", OUTSIDE_NAME), "outside");
Object.defineProperty(process, "platform", { value: "win32" });
});

afterEach(() => {
vi.restoreAllMocks();
Object.defineProperty(process, "platform", { value: realPlatform });
fsSync.rmSync(dir, { recursive: true, force: true });
fsSync.rmSync(outside, { recursive: true, force: true });
});

/** A junction on Windows, which needs no privilege; a symlink elsewhere. */
function link(target: string, at: string): void {
fsSync.symlinkSync(target, at, "junction");
}

/** Run `swap` on the first readdirSync, before the real read; say if it ran. */
function swapDuringRead(swap: () => void): { swapped: () => boolean } {
const realReaddirSync = fsSync.readdirSync.bind(fsSync) as (
target: fsSync.PathLike,
options: { withFileTypes: true },
) => fsSync.Dirent[];
let attempted = false;
let swapped = false;
vi.spyOn(fsSync, "readdirSync").mockImplementation(((
target: fsSync.PathLike,
options: { withFileTypes: true },
) => {
if (!attempted) {
attempted = true;
try {
swap();
swapped = true;
} catch {
// The host refused the swap (see the header); nothing changed.
}
}
return realReaddirSync(target, options);
}) as typeof fsSync.readdirSync);
return { swapped: () => swapped };
}

/** List `listed`; the names it returned, or the refusal it threw. */
function listNames(): { names?: string[]; refusal?: string } {
try {
return { names: readDirectoryInPlace(listed).map((entry) => entry.name) };
} catch (error) {
return { refusal: (error as Error).message };
}
}

describe("the Windows listing check", () => {
it("lists a directory nothing was swapped on, naming it as the parent", () => {
const entries = readDirectoryInPlace(listed);
expect(entries.map((entry) => entry.name)).toEqual([INSIDE_NAME]);
expect(entries[0].parentPath).toBe(listed);
expect(entries[0].isFile()).toBe(true);
});

it("refuses a directory that is now a link to one outside", () => {
fsSync.renameSync(listed, path.join(middle, "listed-real"));
link(outside, listed);
const { names, refusal } = listNames();
expect(names).toBeUndefined();
expect(refusal).toMatch(DIRECTORY_CHANGED);
});

it("refuses a directory whose parent is now a link to one outside", () => {
// The last component is a real directory, the outside tree's "listed", so
// only the path's real location shows the swap.
fsSync.renameSync(middle, path.join(dir, "middle-real"));
link(outside, middle);
const { names, refusal } = listNames();
expect(names).toBeUndefined();
expect(refusal).toMatch(DIRECTORY_CHANGED);
});

it("never returns the outside entries when the directory is swapped for a link during the read", () => {
const { swapped } = swapDuringRead(() => {
fsSync.renameSync(listed, path.join(middle, "listed-real"));
link(outside, listed);
});
const { names, refusal } = listNames();
expect(names ?? []).not.toContain(OUTSIDE_NAME);
if (swapped()) {
expect(refusal).toMatch(DIRECTORY_CHANGED);
} else {
expect(names).toEqual([INSIDE_NAME]);
}
});

it("never returns the outside entries when a parent is swapped for a link during the read", () => {
const { swapped } = swapDuringRead(() => {
fsSync.renameSync(middle, path.join(dir, "middle-real"));
link(outside, middle);
});
const { names, refusal } = listNames();
expect(names ?? []).not.toContain(OUTSIDE_NAME);
if (swapped()) {
expect(refusal).toMatch(DIRECTORY_CHANGED);
} else {
expect(names).toEqual([INSIDE_NAME]);
}
});

it("refuses when another directory takes the name during the read", () => {
// No link anywhere, so only the identity shows it is not the directory
// the first check saw.
const { swapped } = swapDuringRead(() => {
fsSync.renameSync(listed, path.join(middle, "listed-real"));
fsSync.mkdirSync(listed);
});
const { names, refusal } = listNames();
if (swapped()) {
expect(refusal).toMatch(DIRECTORY_CHANGED);
} else {
expect(names).toEqual([INSIDE_NAME]);
}
});

it.skipIf(realPlatform === "win32")(
"is not applied off Windows, where the listing is anchored",
() => {
Object.defineProperty(process, "platform", { value: realPlatform });
const lstat = vi.spyOn(fsSync, "lstatSync");
expect(readDirectoryInPlace(listed).map((entry) => entry.name)).toEqual([
INSIDE_NAME,
]);
expect(lstat).not.toHaveBeenCalled();
},
);
});
80 changes: 42 additions & 38 deletions src/filesystem/__tests__/list-anchored.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
// is swapped for a symlink to a directory outside the allowed one. Each
// listing must then refuse rather than return the outside directory's entry
// names. Before listings were anchored, each of these returned them.
//
// They run on Windows too (#5600), where the swap is a junction, which needs
// no privilege, and the refusal comes from the check made around the read
// rather than from an anchor (list-anchored-windows.test.ts).

import fs from "fs/promises";
import fsSync from "fs";
Expand Down Expand Up @@ -52,16 +56,19 @@ afterEach(async () => {
await fs.rm(outside, { recursive: true, force: true });
});

/** Swap `flip` for a symlink to `outside`, once, right after it is realpath'd. */
/**
* Swap `flip` for a link to `outside`, once, right after it is realpath'd.
* "junction" picks the link type on Windows and is ignored elsewhere.
*/
function swapAfterRealpath(): void {
const realRealpath = fs.realpath.bind(fs);
let swapped = false;
vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => {
const resolved = await realRealpath(p, opts);
if (!swapped && p === flip) {
if (!swapped && String(p).toLowerCase() === flip.toLowerCase()) {
swapped = true;
fsSync.renameSync(flip, flipReal);
fsSync.symlinkSync(outside, flip);
fsSync.symlinkSync(outside, flip, "junction");
}
return resolved;
});
Expand All @@ -70,44 +77,41 @@ function swapAfterRealpath(): void {
const DIRECTORY_CHANGED =
/Access denied - a directory on the path changed during the operation/;

describe.skipIf(process.platform === "win32")(
"a listed directory swapped for a symlink after validation",
() => {
it.each([
["list_directory", {}],
["list_directory_with_sizes", {}],
["directory_tree", {}],
["search_files", { pattern: "**" }],
])("%s does not list through it", async (tool, extra) => {
swapAfterRealpath();
const result = await call(client, tool, { path: flip, ...extra });
expect(result.isError).toBe(true);
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
});
describe("a listed directory swapped for a link after validation", () => {
it.each([
["list_directory", {}],
["list_directory_with_sizes", {}],
["directory_tree", {}],
["search_files", { pattern: "**" }],
])("%s does not list through it", async (tool, extra) => {
swapAfterRealpath();
const result = await call(client, tool, { path: flip, ...extra });
expect(result.isError).toBe(true);
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
});

it("directory_tree does not list a subdirectory through it", async () => {
swapAfterRealpath();
const result = await call(client, "directory_tree", { path: dir });
expect(result.isError).toBe(true);
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
});
it("directory_tree does not list a subdirectory through it", async () => {
swapAfterRealpath();
const result = await call(client, "directory_tree", { path: dir });
expect(result.isError).toBe(true);
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
});

it("search_files does not search a subdirectory through it, and says so", async () => {
swapAfterRealpath();
const result = await call(client, "search_files", {
path: dir,
pattern: "**",
});
expect(result.isError).toBeFalsy();
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
// The swapped directory is reported as unreadable, not as empty.
expect(textOf(result)).toContain(`${flip}`);
expect(textOf(result)).toMatch(/could not be read/i);
it("search_files does not search a subdirectory through it, and says so", async () => {
swapAfterRealpath();
const result = await call(client, "search_files", {
path: dir,
pattern: "**",
});
},
);
expect(result.isError).toBeFalsy();
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
// The swapped directory is reported as unreadable, not as empty.
expect(textOf(result)).toContain(`${flip}`);
expect(textOf(result)).toMatch(/could not be read/i);
});
});

describe("listings that are not swapped", () => {
it("list every tool's way, from the directory validation resolved", async () => {
Expand Down
Loading
Loading