Skip to content

Security guidance: tool-input file paths written without containment (arbitrary file write class) #3191

Open

Description

@stillmarcus24

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:

  1. 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).
  2. 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.

Activity

  1. A7mdMe commented on Nov 16, 2026

    @A7mdMe

    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

    1. 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.
    2. 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.
    3. 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.
    4. 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:

    import path from 'node:path';
    
    export class PathTraversalError extends Error {
      constructor(message: string, public readonly attemptedPath: string) {
        super(message);
        this.name = 'PathTraversalError';
      }
    }
    
    const WINDOWS_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.
     */
    export function resolveWithin(rootDir: string, untrustedPath: string): string {
      if (typeof untrustedPath !== 'string' || untrustedPath.includes('\0')) {
        throw new PathTraversalError('Invalid path: null byte or non-string detected', String(untrustedPath));
      }
    
      const resolvedRoot = path.resolve(rootDir);
    
      // Strip file:// schemes, drive letters, and leading separators
      let sanitized = 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 names
      const baseName = path.basename(sanitized);
      if (WINDOWS_RESERVED_NAMES.test(baseName)) {
        throw new PathTraversalError(`Access to reserved device name "${baseName}" is prohibited`, untrustedPath);
      }
    
      const candidatePath = path.resolve(resolvedRoot, sanitized || '.');
    
      // Exact relative boundary check prevents sibling prefix breakout
      const rel = path.relative(resolvedRoot, candidatePath);
      if (rel.startsWith('..') || path.isAbsolute(rel)) {
        throw new PathTraversalError('Path traversal detected: target escapes workspace root', untrustedPath);
      }
    
      return candidatePath;
    }

    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).

  2. stillmarcus24 commented on Nov 16, 2026

    @stillmarcus24
    Author

    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:

    resolveWithin(root, '/etc/passwd')            -> <root>/etc/passwd
    resolveWithin(root, 'C:\\Windows\\System32\\x') -> <root>/Windows/System32/x
    

    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.

  3. A7mdMe commented on Nov 17, 2026

    @A7mdMe

    @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)) {
      const rootReal = fs.realpathSync(resolvedRoot);
    
      // Traverse to find the deepest existing ancestor
      let checkDir = candidatePath;
      while (checkDir !== resolvedRoot && !fs.existsSync(checkDir)) {
        const parent = path.dirname(checkDir);
        if (parent === checkDir) break;
        checkDir = parent;
      }
    
      if (fs.existsSync(checkDir)) {
        // Forbid direct leaf symlinks
        if (checkDir === candidatePath && fs.lstatSync(candidatePath).isSymbolicLink()) {
          throw new PathTraversalError('Symlink target rejected by policy', untrustedPath);
        }
    
        // Assert canonical ancestor resides within canonical root
        const actualReal = fs.realpathSync(checkDir);
        const relReal = path.relative(rootReal, actualReal);
        if (relReal.startsWith('..') || path.isAbsolute(relReal)) {
          throw new PathTraversalError('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:

    export function isAbsolutePath(p: string): boolean {
      const trimmed = p.trim();
      if (trimmed.startsWith('/') || trimmed.startsWith('\\')) return true;
      if (/^[a-zA-Z]:[/\\]/.test(trimmed)) return true;
      if (trimmed.startsWith('file://')) return true;
      return path.isAbsolute(trimmed);
    }
    
    // In resolveWithin:
    if (options.rejectAbsolute !== false && isAbsolutePath(untrustedPath)) {
      throw new PathTraversalError('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.

  4. added
    v1Issues / PRs related to v1.x
    v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes
    on Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    v1Issues / PRs related to v1.xv2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions