You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Security guidance: tool-input file paths written without containment (arbitrary file write class) #3191
While auditing the MCP server ecosystem (1,654 npm-backed servers
deep-scanned with MCP-aware CodeQL taint analysis), I found a recurring,
independently-rediscovered class: a tool declares a path-shaped input
(output_path, local_path, output_dir) as an unconstrained string and passes
it to path.resolve()/path.join() then fs.writeFileSync, with no workspace
containment. Because an MCP tool caller is frequently an LLM acting on
untrusted content, the path is attacker-influenced via indirect prompt
injection - no human chooses it. Result: arbitrary file write and
destructive overwrite (authorized_keys, rc files, configs).
Prevalence in the scanned sample is material (path-traversal flows present
in a measurable share of servers; aggregate scorecard available). Several
affected servers even shipped a containment helper for one sink and left
the tool-input writes raw.
This is a server-author footgun, not an SDK bug, but the SDK is the natural
place to prevent it at scale. Proposed, in order of increasing
intrusiveness:
A short "Writing files from a tool safely" section in the server-author
docs, with the containment pattern (resolve against a workspace root,
reject absolute and ".." escapes).
Optionally, an exported resolveWithin(root, p) helper so authors do not
hand-roll it (several who did, got it wrong).
I can open the docs PR with the guidance text and an example. Full
methodology and the CodeQL pack that finds this are public at
github.com/stillmarcus24/mcp-security-research. No unfixed server is named;
findings are under coordinated disclosure.
This is a timely and critical audit finding. In our own analysis of tool implementations, hand-rolled containment frequently introduces subtle bypass vulnerabilities:
Why Hand-Rolled Containment Fails
The Absolute Path Discard Trap: path.resolve(root, p) completely discards root if the LLM supplies an absolute path like /etc/passwd or C:\Windows\System32.
The Sibling Directory Prefix Bypass Trap: Many authors write if (resolved.startsWith(root)). If root is /var/app/workspace, an attacker supplying ../workspace_evil/payload.sh produces /var/app/workspace_evil/payload.sh, which satisfies startsWith('/var/app/workspace'). Containment must be evaluated via path.relative(root, resolved) or require root + path.sep.
Windows Device Names: On Windows systems, filenames like CON, PRN, AUX, NUL, COM1..COM9, LPT1..LPT9 (even with arbitrary extensions like con.txt) lock up process handles or throw unexpected system I/O errors.
Null-Byte Truncation: Strings containing \0 can alter downstream C-binding filesystem operations.
Proposed Production resolveWithin Helper
Here is a zero-dependency, platform-safe implementation that addresses all four edge cases:
importpathfrom'node:path';exportclassPathTraversalErrorextendsError{constructor(message: string,publicreadonlyattemptedPath: string){super(message);this.name='PathTraversalError';}}constWINDOWS_RESERVED_NAMES=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;/** * Strictly contains an untrusted path within rootDir. * Throws PathTraversalError on traversal escapes, absolute breakout, or invalid tokens. */exportfunctionresolveWithin(rootDir: string,untrustedPath: string): string{if(typeofuntrustedPath!=='string'||untrustedPath.includes('\0')){thrownewPathTraversalError('Invalid path: null byte or non-string detected',String(untrustedPath));}constresolvedRoot=path.resolve(rootDir);// Strip file:// schemes, drive letters, and leading separatorsletsanitized=untrustedPath.trim().replace(/^file:\/\//,'');sanitized=sanitized.replace(/^[a-zA-Z]:[/\\]?/,'');sanitized=sanitized.replace(/[/\\]+/g,path.sep);while(sanitized.startsWith(path.sep)){sanitized=sanitized.slice(path.sep.length);}// Check Windows reserved device namesconstbaseName=path.basename(sanitized);if(WINDOWS_RESERVED_NAMES.test(baseName)){thrownewPathTraversalError(`Access to reserved device name "${baseName}" is prohibited`,untrustedPath);}constcandidatePath=path.resolve(resolvedRoot,sanitized||'.');// Exact relative boundary check prevents sibling prefix breakoutconstrel=path.relative(resolvedRoot,candidatePath);if(rel.startsWith('..')||path.isAbsolute(rel)){thrownewPathTraversalError('Path traversal detected: target escapes workspace root',untrustedPath);}returncandidatePath;}
Atomic Write Recommendation for Tool Authors
Beyond path resolution, tools that write files should write to a temporary file in the target directory (e.g. .tmp_<random>) and atomically rename it (fs.promises.rename). This prevents:
Partial file creation if the process or connection drops mid-write.
TOCTOU (Time-of-Check to Time-of-Use) races where symlinks are swapped between path validation and write execution.
(Full maintainer disclosure: I am the author of mcp-production-kit, where we implemented and test-covered this filesystem containment guard and atomic I/O pattern across our server test suite).
Agreed on traps 1 and 2 - path.relative is the right primitive and the startsWith sibling-prefix case is real. I implemented the helper verbatim
and ran it before replying, so the rest of this is measured rather than
reviewed. Environment: Node v22.22.1 on Linux; the Windows points below are
from the Microsoft naming docs, not tested on Windows.
It does not contain symlinks, which is the shape that matters here
Given an ordinary shared -> /elsewhere symlink inside the workspace - which
any earlier tool call in the same session can create, and which a checkout can
ship:
resolveWithin(root, 'shared/authorized_keys')
-> <root>/shared/authorized_keys // ALLOW, rel has no '..'
realpath: /elsewhere/authorized_keys // written, overwritten
path.relative is comparing strings that never leave the root. The write
does. The atomic-write recommendation does not help: I ran the suggested
pattern too, and .tmp_<n> was created in /elsewhere and renamed onto /elsewhere/authorized_keys. That mitigates a partial write, not an escape.
Canonicalising the longest existing ancestor and re-checking fixes it. I
tested that this rejects the symlink case and still passes an ordinary docs/a.txt. Callers facing an actively hostile tree need O_NOFOLLOW
(fs.constants.O_NOFOLLOW, 131072) on the final open as well, since the
ancestor can be swapped after the check.
The docstring and the behaviour disagree on absolute paths
It documents a throw on "absolute breakout". It does not throw:
Silent remapping is a defensible policy, but it has to be the documented one.
An author relying on the throw for an audit trail records nothing. For an SDK
helper I would reject rather than rewrite: an absolute path arriving from a
model is signal worth surfacing.
Two smaller ones from the same run
/[\/\\]+/g -> path.sep treats a backslash as a separator on POSIX, where it
is a legal filename character. I created a real file named report\2026.csv
in the root; the helper maps that same input to report/2026.csv, a different
file in a subdirectory.
The reserved-name check is basename-only, so CON/x.txt and notes/NUL/a.bin
are allowed while notes/nul.txt is rejected on Linux, where it is an
ordinary file. Microsoft's naming guidance also notes the ISO 8859-1
superscript forms COM1, COM2, COM3, LPT1-LPT3 are treated as device
names and are "reserved in every directory"; the regex here covers only the
ASCII digits. That class wants per-component matching after normalisation,
and ideally only on win32.
On the proposal itself
Worth noting prior art: eslint-plugin-mcp-sdk-security already ships a no-path-traversal-in-tool rule for this exact flow (CWE-22), and its
remediation text already names fs.realpath. Its guard model, though, accepts path.relative / isAbsolute alone as a containment check - so a server
written the way this helper is written passes that lint and is still
escapable. That gap is the argument for one audited helper in the SDK rather
than guidance alone: several of us have now independently produced
containment that is correct on strings and wrong on the filesystem.
Happy to contribute the symlink, basename-only and POSIX-backslash cases as
test vectors to whatever lands.
@stillmarcus24 Excellent verification and test vectors. These boundary conditions are exactly why containment in userland so frequently regresses.
We updated our implementation and verified it across these scenarios:
1. Symlink Containment via Longest Existing Ancestor realpath
To prevent the shared -> /elsewhere symlink escape (where string-based path.relative passes because the symlink name is within root), we traverse upwards from the target to locate the deepest existing ancestor, resolve its canonical fs.realpathSync(), and assert that it resides within the canonicalized rootReal. In addition, if the target leaf already exists, we verify via lstatSync that it is not a direct symlink:
if(options.verifySymlinks!==false&&fs.existsSync(resolvedRoot)){constrootReal=fs.realpathSync(resolvedRoot);// Traverse to find the deepest existing ancestorletcheckDir=candidatePath;while(checkDir!==resolvedRoot&&!fs.existsSync(checkDir)){constparent=path.dirname(checkDir);if(parent===checkDir)break;checkDir=parent;}if(fs.existsSync(checkDir)){// Forbid direct leaf symlinksif(checkDir===candidatePath&&fs.lstatSync(candidatePath).isSymbolicLink()){thrownewPathTraversalError('Symlink target rejected by policy',untrustedPath);}// Assert canonical ancestor resides within canonical rootconstactualReal=fs.realpathSync(checkDir);constrelReal=path.relative(rootReal,actualReal);if(relReal.startsWith('..')||path.isAbsolute(relReal)){thrownewPathTraversalError('Symlink boundary escape: ancestor resolves outside root',untrustedPath);}}}
2. Strict Absolute Path Rejection (No Silent Remapping)
Agreed completely that silent remapping hides critical indirect prompt injection signals. We made rejectAbsolute: true the default:
exportfunctionisAbsolutePath(p: string): boolean{consttrimmed=p.trim();if(trimmed.startsWith('/')||trimmed.startsWith('\\'))returntrue;if(/^[a-zA-Z]:[/\\]/.test(trimmed))returntrue;if(trimmed.startsWith('file://'))returntrue;returnpath.isAbsolute(trimmed);}// In resolveWithin:if(options.rejectAbsolute!==false&&isAbsolutePath(untrustedPath)){thrownewPathTraversalError('Absolute path escape rejected: path must be relative to workspace root',untrustedPath);}
3. POSIX Backslashes & Segment-Wise Device Name Checks
POSIX Backslashes: We restricted backslash substitution to process.platform === 'win32'. On POSIX, report\\2026.csv remains intact as a single filename.
Segment-Wise DOS Reserved Names: We evaluate every path segment (directories and basename) against /^(con|prn|aux|nul|com[1-9\u00B9\u00B2\u00B3]|lpt[1-9\u00B9\u00B2\u00B3])(\..*)?$/i, which catches CON/x.txt, data/NUL/record.bin, and superscript variants (COM¹, LPT²).
Our automated suite now exercises these exact vectors (158 dedicated tests in mcp-production-kit). Strong +1 for upstreaming this into SDK core as an audited helper.
Activity
A7mdMe commentedon Nov 16, 2026
This is a timely and critical audit finding. In our own analysis of tool implementations, hand-rolled containment frequently introduces subtle bypass vulnerabilities:
Why Hand-Rolled Containment Fails
path.resolve(root, p)completely discardsrootif the LLM supplies an absolute path like/etc/passwdorC:\Windows\System32.if (resolved.startsWith(root)). Ifrootis/var/app/workspace, an attacker supplying../workspace_evil/payload.shproduces/var/app/workspace_evil/payload.sh, which satisfiesstartsWith('/var/app/workspace'). Containment must be evaluated viapath.relative(root, resolved)or requireroot + path.sep.CON,PRN,AUX,NUL,COM1..COM9,LPT1..LPT9(even with arbitrary extensions likecon.txt) lock up process handles or throw unexpected system I/O errors.\0can alter downstream C-binding filesystem operations.Proposed Production
resolveWithinHelperHere is a zero-dependency, platform-safe implementation that addresses all four edge cases:
Atomic Write Recommendation for Tool Authors
Beyond path resolution, tools that write files should write to a temporary file in the target directory (e.g.
.tmp_<random>) and atomically rename it (fs.promises.rename). This prevents:(Full maintainer disclosure: I am the author of mcp-production-kit, where we implemented and test-covered this filesystem containment guard and atomic I/O pattern across our server test suite).
stillmarcus24 commentedon Nov 16, 2026
Agreed on traps 1 and 2 -
path.relativeis the right primitive and thestartsWithsibling-prefix case is real. I implemented the helper verbatimand ran it before replying, so the rest of this is measured rather than
reviewed. Environment: Node v22.22.1 on Linux; the Windows points below are
from the Microsoft naming docs, not tested on Windows.
It does not contain symlinks, which is the shape that matters here
Given an ordinary
shared -> /elsewheresymlink inside the workspace - whichany earlier tool call in the same session can create, and which a checkout can
ship:
path.relativeis comparing strings that never leave the root. The writedoes. The atomic-write recommendation does not help: I ran the suggested
pattern too, and
.tmp_<n>was created in/elsewhereand renamed onto/elsewhere/authorized_keys. That mitigates a partial write, not an escape.Canonicalising the longest existing ancestor and re-checking fixes it. I
tested that this rejects the symlink case and still passes an ordinary
docs/a.txt. Callers facing an actively hostile tree needO_NOFOLLOW(
fs.constants.O_NOFOLLOW, 131072) on the final open as well, since theancestor can be swapped after the check.
The docstring and the behaviour disagree on absolute paths
It documents a throw on "absolute breakout". It does not throw:
Silent remapping is a defensible policy, but it has to be the documented one.
An author relying on the throw for an audit trail records nothing. For an SDK
helper I would reject rather than rewrite: an absolute path arriving from a
model is signal worth surfacing.
Two smaller ones from the same run
/[\/\\]+/g -> path.septreats a backslash as a separator on POSIX, where itis a legal filename character. I created a real file named
report\2026.csvin the root; the helper maps that same input to
report/2026.csv, a differentfile in a subdirectory.
The reserved-name check is basename-only, so
CON/x.txtandnotes/NUL/a.binare allowed while
notes/nul.txtis rejected on Linux, where it is anordinary file. Microsoft's naming guidance also notes the ISO 8859-1
superscript forms
COM1,COM2,COM3,LPT1-LPT3are treated as devicenames and are "reserved in every directory"; the regex here covers only the
ASCII digits. That class wants per-component matching after normalisation,
and ideally only on
win32.On the proposal itself
Worth noting prior art:
eslint-plugin-mcp-sdk-securityalready ships ano-path-traversal-in-toolrule for this exact flow (CWE-22), and itsremediation text already names
fs.realpath. Its guard model, though, acceptspath.relative/isAbsolutealone as a containment check - so a serverwritten the way this helper is written passes that lint and is still
escapable. That gap is the argument for one audited helper in the SDK rather
than guidance alone: several of us have now independently produced
containment that is correct on strings and wrong on the filesystem.
Happy to contribute the symlink, basename-only and POSIX-backslash cases as
test vectors to whatever lands.
A7mdMe commentedon Nov 17, 2026
@stillmarcus24 Excellent verification and test vectors. These boundary conditions are exactly why containment in userland so frequently regresses.
We updated our implementation and verified it across these scenarios:
1. Symlink Containment via Longest Existing Ancestor
realpathTo prevent the
shared -> /elsewheresymlink escape (where string-basedpath.relativepasses because the symlink name is within root), we traverse upwards from the target to locate the deepest existing ancestor, resolve its canonicalfs.realpathSync(), and assert that it resides within the canonicalizedrootReal. In addition, if the target leaf already exists, we verify vialstatSyncthat it is not a direct symlink:2. Strict Absolute Path Rejection (No Silent Remapping)
Agreed completely that silent remapping hides critical indirect prompt injection signals. We made
rejectAbsolute: truethe default:3. POSIX Backslashes & Segment-Wise Device Name Checks
process.platform === 'win32'. On POSIX,report\\2026.csvremains intact as a single filename./^(con|prn|aux|nul|com[1-9\u00B9\u00B2\u00B3]|lpt[1-9\u00B9\u00B2\u00B3])(\..*)?$/i, which catchesCON/x.txt,data/NUL/record.bin, and superscript variants (COM¹,LPT²).Our automated suite now exercises these exact vectors (158 dedicated tests in mcp-production-kit). Strong +1 for upstreaming this into SDK core as an audited helper.