Claude skill arbitrary file read via path traversal in MCP skill static file serving and template loading — SA-SKL-FILEREAD2
Path traversal vulnerabilities — where user-supplied input is used to construct a file path without verifying the result stays within an intended directory — remain one of the most reliably exploitable classes of web vulnerabilities. SA-SKL-FILEREAD2 covers four distinct traversal patterns in MCP skill Node.js backends: direct fs.readFileSync with a request parameter, misconfigured express.static, EJS include with user input, and the subtle distinction between a ZIP archive entry's submitted name and its parsed extraction path.
FILEREAD2-001 — fs.readFileSync(path.join(templatesDir, req.params.name)) without bounds check
path.join() resolves ../ sequences within the resulting path string — it is a string manipulation function, not a security boundary. When an MCP skill endpoint uses path.join(templatesDir, req.params.name) to construct a template file path and passes the result directly to fs.readFileSync(), an attacker who requests ../../../etc/passwd as the template name causes path.join('/app/views/templates', '../../../etc/passwd') to resolve to /etc/passwd. The critical mistake is assuming that path.join() sandboxes the path — it does not. The correct check is to call path.resolve() on the joined result (which produces an absolute path with all ../ sequences expanded) and then verify that the resolved absolute path starts with the template directory prefix followed by the OS path separator. The separator suffix prevents a directory named /app/views/templates-extra from matching a check for /app/views/templates.
# VULNERABLE — FILEREAD2-001: path.join without startsWith bounds check
const path = require('path');
const fs = require('fs');
const TEMPLATES_DIR = path.resolve('/app/views/templates');
app.get('/template/:name', (req, res) => {
// VULNERABLE: path.join resolves '../' sequences in the user-supplied name
const filePath = path.join(TEMPLATES_DIR, req.params.name);
// If req.params.name = '../../../../etc/passwd'
// path.join('/app/views/templates', '../../../../etc/passwd')
// => '/etc/passwd' (resolved past the templates directory)
// filePath = '/etc/passwd' — no error, no check
try {
const content = fs.readFileSync(filePath, 'utf8');
res.type('text/plain').send(content);
} catch {
res.status(404).send('Not found');
}
});
# Attack:
# GET /template/../../../../etc/passwd → returns /etc/passwd
# GET /template/../../../app/config.json → returns application config (secrets)
# GET /template/../../package.json → returns package.json (dependency versions)
# URL-encoded variants:
# GET /template/%2e%2e%2f%2e%2e%2fetc%2fpasswd (Express decodes %2f to /)
# GET /template/..%2F..%2Fetc%2Fpasswd (mixed encoding)
# FIXED — FILEREAD2-001: path.resolve + startsWith(prefix + sep) bounds check
const path = require('path');
const fs = require('fs');
const TEMPLATES_DIR = path.resolve('/app/views/templates');
// Add trailing separator to prevent prefix confusion with sibling directories:
// Without it: '/app/views/templates-extra/evil' would pass the check if it started
// with '/app/views/templates' — the separator ensures an exact directory boundary
const TEMPLATES_DIR_PREFIX = TEMPLATES_DIR + path.sep;
app.get('/template/:name', (req, res) => {
// path.resolve() expands all '../' sequences to an absolute path
const resolvedPath = path.resolve(TEMPLATES_DIR, req.params.name);
// Check that the resolved path starts with the template directory prefix
// The startsWith check with path.sep ensures we don't match sibling directories
const isWithinDir = resolvedPath.startsWith(TEMPLATES_DIR_PREFIX) ||
resolvedPath === TEMPLATES_DIR; // allow exact dir match
if (!isWithinDir) {
return res.status(403).json({ error: 'Access denied' });
}
try {
const content = fs.readFileSync(resolvedPath, 'utf8');
res.type('text/plain').send(content);
} catch {
res.status(404).send('Not found');
}
});
// Alternative: allowlist approach — only serve files explicitly in an allowlist
// This is safer because it fails closed: new files are not served unless explicitly listed
const ALLOWED_TEMPLATES = new Set(['report.html', 'badge.svg', 'summary.txt']);
app.get('/template/:name', (req, res) => {
if (!ALLOWED_TEMPLATES.has(req.params.name)) {
return res.status(403).json({ error: 'Template not found' });
}
const filePath = path.join(TEMPLATES_DIR, req.params.name);
res.sendFile(filePath);
});
fs.readFileSync(path.join(templatesDir, req.params.name)) without a bounds check allows arbitrary file read because path.join() resolves ../ sequences in the user-supplied parameter, enabling traversal to any file readable by the Node.js process including /etc/passwd, environment files, and application configs; fix by calling path.resolve(templatesDir, name) and verifying the result startsWith(TEMPLATES_DIR + path.sep), or by using an explicit allowlist of permitted filenames. Detection: SkillAudit flags fs.readFileSync, fs.readFile, and res.sendFile calls where the path argument includes a string concatenated with any request parameter, body field, or query string value without a preceding path.resolve + startsWith check.FILEREAD2-002 — express.static without dotfiles: 'deny' and root resolve check allows directory escape
Express's static middleware (serve-static) is designed to serve files from a named directory safely — it has built-in path traversal protection in modern versions. However, several misconfigurations re-enable traversal or expand the attack surface beyond what developers intend. The first is dotfiles: 'allow' (or the absence of dotfiles: 'deny'): with dotfile access enabled, requests for /.env, /.git/config, and /.ssh/authorized_keys are served if the Express process can read them and they happen to be inside the served directory tree. The second is using a relative path as the root option: express.static('public') resolves relative to the current working directory at the time the middleware is registered; if the app's CWD changes (via process.chdir() in a startup script, or when run from a different directory in production), the served root shifts and may expose a wider path. The third is mounting the middleware at a prefix without also validating that the prefix is preserved in the requested path — some reverse proxy configurations strip or rewrite path prefixes, potentially causing the middleware to serve files from paths it was not intended to reach.
# VULNERABLE — FILEREAD2-002: express.static with relative path, dotfiles allowed
const express = require('express');
const app = express();
// VULNERABLE: relative path — CWD-dependent
// If CWD is /app, serves from /app/public/
// If process runs from /, serves from /public/ — may not exist or may be /
app.use(express.static('public'));
// No dotfiles restriction — .env, .git/config, .htpasswd are served if present
// Even with absolute path, dotfiles are served by default:
app.use(express.static(path.resolve('/app/public')));
// GET /.env serves /app/public/.env (if present)
// GET /.git/config serves /app/public/.git/config (if public/ is in a git repo)
# Attack scenarios:
# 1. Developer accidentally places .env in public/ during testing — it's served
# 2. Web server cloned into public/ — .git directory served, exposing commit history
# 3. Misconfigured build outputs .npmrc into public/ — served with npm auth token
# 4. CWD mismatch in production causes wrong directory to be served
# FIXED — FILEREAD2-002: absolute path + dotfiles: 'deny' + explicit root option
const express = require('express');
const path = require('path');
const app = express();
// Always use an absolute resolved path as the static root — never relative
const PUBLIC_DIR = path.resolve(__dirname, 'public');
app.use(express.static(PUBLIC_DIR, {
// Deny access to all dotfiles — .env, .git, .htpasswd, .DS_Store, etc.
dotfiles: 'deny',
// Explicit root ensures middleware knows its own safe base path for validation
root: PUBLIC_DIR,
// Disable directory index — don't serve listing or index.html for directories
index: false,
// Disable ETags if you don't want file modification time leakage
etag: false,
// Set correct fallthrough behavior — false means 404 on miss, not pass to next
fallthrough: false,
}));
// Belt-and-suspenders: add a middleware before express.static to block known sensitive paths
app.use((req, res, next) => {
const p = req.path.toLowerCase();
const blocked = ['.env', '.git', '.htpasswd', '.ssh', '.npmrc', 'node_modules'];
if (blocked.some(b => p.includes(b))) {
return res.status(403).end();
}
next();
});
// Serve static files after the security middleware
app.use(express.static(PUBLIC_DIR, { dotfiles: 'deny', root: PUBLIC_DIR }));
express.static('public') with a relative path resolves to a CWD-dependent directory and without dotfiles: 'deny' serves hidden files including .env, .git/config, and .npmrc that may be present in the served directory tree, exposing credentials and secrets; fix by using path.resolve(__dirname, 'public') as an absolute path, setting dotfiles: 'deny', and adding a path-blocking middleware for known sensitive filename patterns. Detection: SkillAudit flags express.static calls with a relative path argument or without an explicit dotfiles: 'deny' option in the configuration object.FILEREAD2-003 — EJS renderFile with user input interpolated into template path
Template engines like EJS support an include directive that loads another template file: <%- include(templateName) %>. When the included template name is derived from user input — a URL parameter, a query string, or a database field that an attacker can influence — the template engine traverses to the specified path relative to the current template's directory. An attacker who controls templateName can supply ../../package.json to load package.json as a template (which EJS parses as plain text since it contains no EJS tags), or ../../.env to read the environment file. Even if the file being read does not exist as a template, EJS's error message often reveals the file path it attempted to load, disclosing the filesystem layout. The same vulnerability applies to ejs.renderFile(path.join('views', userSupplied + '.ejs')): the user supplies ../../config, the path becomes ../../config.ejs (which EJS tries and fails), or if the attacker omits the extension and the template engine tries multiple extensions, it may find ../../config.js or ../../config. The fix is to never interpolate user input into template paths — use an allowlist of valid template identifiers and map them to hardcoded paths.
# VULNERABLE — FILEREAD2-003: EJS renderFile with user-supplied template name
const ejs = require('ejs');
const path = require('path');
app.get('/report/:templateId', async (req, res) => {
const { templateId } = req.params;
// VULNERABLE: user input interpolated directly into template path
const templatePath = path.join('/app/views', templateId + '.ejs');
// templateId = '../../package' → path = '/app/package.ejs' (not found)
// templateId = '../../../etc/passwd' → path = '/etc/passwd.ejs'
// → EJS tries to open /etc/passwd.ejs — doesn't exist
// → EJS error message: "Could not find include file. /etc/passwd.ejs" — leaks path
// templateId = '../../.env' → path = '/app/.env.ejs' (might exist as .env)
// → EJS tries extensions including no extension: loads /app/.env
try {
const html = await ejs.renderFile(templatePath, { data: req.query });
res.send(html);
} catch (err) {
// Error message leaks the attempted file path
res.status(500).send(`Error: ${err.message}`);
}
});
# EJS include directive (another attack surface):
// In an EJS template:
// <%- include(req.query.section) %>
// If section = '../../package.json', EJS loads it and renders its content as text
// package.json content (dependency versions) returned in HTTP response
# FIXED — FILEREAD2-003: allowlist of valid template identifiers mapped to hardcoded paths
const ejs = require('ejs');
const path = require('path');
// Allowlist: map external identifiers to internal template file paths
// No user input ever touches the filesystem path
const TEMPLATE_MAP = new Map([
['basic', path.resolve('/app/views/report-basic.ejs')],
['detailed', path.resolve('/app/views/report-detailed.ejs')],
['summary', path.resolve('/app/views/report-summary.ejs')],
['badge', path.resolve('/app/views/badge.ejs')],
]);
app.get('/report/:templateId', async (req, res) => {
const { templateId } = req.params;
// Look up in allowlist — if not found, reject
const templatePath = TEMPLATE_MAP.get(templateId);
if (!templatePath) {
return res.status(404).json({ error: 'Template not found' });
}
// Even though templatePath is from the allowlist (safe), verify it's within views/:
const VIEWS_DIR = path.resolve('/app/views') + path.sep;
if (!templatePath.startsWith(VIEWS_DIR)) {
return res.status(500).json({ error: 'Internal configuration error' });
}
try {
const html = await ejs.renderFile(templatePath, { data: req.query });
res.send(html);
} catch {
// Generic error — never expose the file path in error messages
res.status(500).json({ error: 'Template rendering failed' });
}
});
// For EJS include directives: pass a render function that enforces the allowlist
// rather than allowing raw string paths in <%- include() %> tags:
// app.locals.safeInclude = (name) => {
// const p = TEMPLATE_MAP.get(name);
// if (!p) throw new Error('Unknown template');
// return p;
// };
// In template: <%- include(safeInclude('header')) %>
renderFile(path.join('views', userSupplied + '.ejs')) and inline EJS include(userInput) directives allow path traversal to arbitrary files readable by the Node.js process because the template engine loads files relative to the template directory without bounds checking; fix by using an allowlist Map that maps external identifiers to hardcoded absolute template paths, never passing user input directly to renderFile or EJS include directives, and catching errors generically to avoid leaking filesystem paths. Detection: SkillAudit flags ejs.renderFile, pug.renderFile, or res.render calls where the first argument includes a string concatenated with any request parameter, body field, or query string value.FILEREAD2-004 — ZIP archive entry name validated but extraction uses parsed entry.path
ZIP archive entries contain two distinct path fields that are easy to confuse: the name field (the filename string as it appears in the central directory) and the path field that the extraction library derives by normalizing the entry's local file header path. When a developer validates the name field — checking that it doesn't contain ../ — but then extracts using the library's parsed entry.path, these two values can differ if the library normalizes encoding or resolves path separators differently from the validation code. For example, in some ZIP parsers name might be safe.ejs (the raw central directory entry) while entry.path is resolved to ../../config.js (the actual extraction path after the library normalizes the local file header). Similarly, URL-encoded sequences like ..%2F in ZIP entry names may pass a string ../ check but be decoded to ../ by the extraction library before writing to disk. The fix is to validate the parsed extraction path — the value the library will actually use to open the file — not the submitted entry name, and to perform the validation after the library has had a chance to normalize it.
# VULNERABLE — FILEREAD2-004: ZIP entry name validated but extraction path used directly
const AdmZip = require('adm-zip');
const path = require('path');
app.post('/upload-skill', (req, res) => {
const zip = new AdmZip(req.body); // receives zip buffer
const entries = zip.getEntries();
for (const entry of entries) {
// VULNERABLE: validates entry.entryName (central directory name)
// but extracts using entry.entryName which may differ from the normalization
// used when writing to disk
if (entry.entryName.includes('../')) {
continue; // appears to block traversal — but entry.entryName might be encoded
}
// AdmZip uses entry.entryName for the extraction path — but the library
// may normalize differently between the check above and the write below.
// On some versions: entry.entryName = 'sub/../../../etc/cron.d/evil'
// The includes('../') check passes for some encoding variants:
// '%2e%2e/' — URL-encoded dot-dot — passes .includes('../')
// '..\\' on Windows — backslash traversal on Windows hosts
const extractPath = path.join('/app/skills', entry.entryName);
zip.extractEntryTo(entry, '/app/skills/', true, true);
}
res.json({ extracted: entries.length });
});
# More subtle variant: the ZIP spec allows entry name and local header name to differ.
# Some libraries use the local header name for extraction, not the central directory name.
# Validating central directory name, extracting via local header path = bypass.
# FIXED — FILEREAD2-004: validate the resolved extraction path, not the submitted name
const AdmZip = require('adm-zip');
const path = require('path');
const SKILLS_DIR = path.resolve('/app/skills');
const SKILLS_DIR_PREFIX = SKILLS_DIR + path.sep;
app.post('/upload-skill', async (req, res) => {
const zip = new AdmZip(req.body);
const entries = zip.getEntries();
const extracted = [];
for (const entry of entries) {
if (entry.isDirectory) continue; // skip directory entries
// Step 1: get the actual name the library will use for extraction
// Use the same normalization the library uses internally
const entryName = entry.entryName;
// Step 2: resolve the FULL extraction path as the filesystem will see it
// path.resolve() normalizes all '../', './', and encoded sequences
const resolvedPath = path.resolve(SKILLS_DIR, entryName);
// Step 3: validate the resolved path is within the target directory
if (!resolvedPath.startsWith(SKILLS_DIR_PREFIX)) {
console.warn(`ZIP traversal attempt blocked: ${entryName} → ${resolvedPath}`);
continue; // skip this entry — do not extract
}
// Step 4: also validate against the sanitized filename component only
const basename = path.basename(resolvedPath);
if (basename.startsWith('.') || basename === '') {
continue; // skip hidden files and empty names
}
// Step 5: extract to a temp path, then move to final destination
const data = entry.getData();
await fs.promises.mkdir(path.dirname(resolvedPath), { recursive: true, mode: 0o755 });
await fs.promises.writeFile(resolvedPath, data, { flag: 'wx' }); // wx: fail if exists
extracted.push(path.relative(SKILLS_DIR, resolvedPath));
}
res.json({ extracted });
});
// Key principle: validate the value AFTER all normalization has been applied.
// If the library produces a different path than path.resolve(SKILLS_DIR, entryName),
// trust the library's output — validate that, not the raw name from the ZIP header.
entry.entryName for ../ sequences but then uses the library's parsed extraction path (which may be normalized differently) for the actual file write allows ZIP path traversal to overwrite arbitrary files outside the target extraction directory; fix by computing the full resolved path with path.resolve(targetDir, entryName) and verifying it startsWith(targetDir + path.sep) before extracting, and by using flag: 'wx' on the write call to fail on existing files rather than overwriting them. Detection: SkillAudit flags ZIP extraction code where the traversal check runs on entry.entryName or entry.name before the extraction call rather than on the path.resolve() result of the full extraction path.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| FILEREAD2-001 | CRITICAL | fs.readFileSync(path.join(dir, req.params.name)) — path.join() resolves ../ silently, traverses to /etc/passwd |
path.resolve(dir, name).startsWith(DIR_PREFIX) check; or allowlist of permitted filenames |
| FILEREAD2-002 | HIGH | express.static('public') with relative path and no dotfiles: 'deny' — serves .env, .git/config |
path.resolve(__dirname, 'public') + dotfiles: 'deny' + blocked-path middleware |
| FILEREAD2-003 | CRITICAL | ejs.renderFile(path.join('views', userInput + '.ejs')) — traverses to ../../.env, leaks config via error message |
Allowlist Map of identifier → hardcoded path; never interpolate user input into template paths |
| FILEREAD2-004 | HIGH | ZIP entry name checked for ../ but extraction uses parsed entry.path which may differ — encoding bypass |
Validate path.resolve(targetDir, entry.name).startsWith(prefix); use flag: 'wx' on write |
Related patterns: ZIP Slip and Path Traversal in MCP Skill File Uploads covers the broader ZIP Slip vulnerability class including zip bomb decompression limits, symlink attacks in tar entries, and executable bit preservation that complement these static-serving and template-loading traversal patterns. MCP server SSRF security covers server-side request forgery vulnerabilities that are often chained with file read vulnerabilities to exfiltrate credentials from internal metadata endpoints and config files discovered through path traversal.