Claude skill file access security — SA-SKL-FILEACCESS
MCP skills that handle file uploads or serve files using user-supplied filenames expose four file access vulnerabilities: path traversal via ../ sequences that escape the upload directory, symlink attacks where attacker-uploaded symlinks point to /etc/shadow, race conditions on predictable temp file paths, and CRLF injection via filenames passed into Content-Disposition headers. SA-SKL-FILEACCESS covers all four patterns with the attack mechanics and correct Node.js defenses.
Why file access is a high-risk surface in MCP skills
MCP skills that audit GitHub repositories or accept user-uploaded ZIP files process attacker-controlled filenames, paths, and directory structures. The model-driven call order means an attacker can influence which tool calls the model makes and in what sequence, increasing the probability that a crafted payload reaches a vulnerable file handler. Node.js's fs module does not sandbox paths by default — every path string is resolved relative to the filesystem root, not a confined directory. Without explicit path confinement, any filename argument that reaches fs.readFileSync() is a potential path traversal.
SA-SKL-FILEACCESS in scope: FILEACCESS-001 (path traversal via ../ in filename), FILEACCESS-002 (symlink escape from upload directory), FILEACCESS-003 (predictable temp file race condition), FILEACCESS-004 (CRLF injection via filename in Content-Disposition header). Each pattern includes SkillAudit detection rules and remediation code.
FILEACCESS-001 — Path traversal via ../ in filename argument
When a skill's file handler constructs a filesystem path by string-concatenating a user-supplied filename argument with a base directory prefix, an attacker can supply ../../etc/passwd as the filename. String concatenation with the base prefix produces /uploads/../../etc/passwd, which the OS path resolver normalizes to /etc/passwd. The file handler reads and returns the system password file.
// VULNERABLE: naive path construction via string concatenation
app.post('/api/skill/read_uploaded_file', authMiddleware, async (req, res) => {
const { filename } = req.body;
const UPLOAD_DIR = '/uploads';
// VULNERABLE: string concatenation — attacker supplies '../../etc/passwd'
// Resulting path: '/uploads/../../etc/passwd' → resolves to '/etc/passwd'
const filePath = UPLOAD_DIR + '/' + filename;
const content = await fs.promises.readFile(filePath, 'utf8');
return res.json({ content });
});
// Attack:
// POST /api/skill/read_uploaded_file
// { "filename": "../../etc/passwd" }
// -> reads /etc/passwd, returns root:x:0:0 etc.
// FIXED: path.basename() normalization + realpath confinement check
import path from 'path';
import fs from 'fs';
const UPLOAD_DIR = '/uploads';
app.post('/api/skill/read_uploaded_file', authMiddleware, async (req, res) => {
const { filename } = req.body;
// Step 1: strip all directory components from the filename
const safeName = path.basename(filename); // '../../etc/passwd' → 'passwd'
// Step 2: construct full path and resolve symlinks
const fullPath = path.join(UPLOAD_DIR, safeName);
const realPath = await fs.promises.realpath(fullPath);
// Step 3: confirm resolved path is still within upload directory
if (!realPath.startsWith(UPLOAD_DIR + path.sep)) {
return res.status(403).json({ error: 'Access denied' });
}
const content = await fs.promises.readFile(realPath, 'utf8');
return res.json({ content });
});
../ sequences traverse outside the intended directory. Fix: path.basename() normalization + path.join() + fs.realpath() confinement check. Detection: SkillAudit AST rule flags any fs.readFileSync() or fs.promises.readFile() call where the path argument is a string concatenation or template literal that includes a tool argument variable without a preceding path.basename() normalization step.FILEACCESS-002 — Symlink escape from upload directory
An attacker uploads a file that is actually a symbolic link pointing to a file outside the upload directory, such as /etc/shadow or /proc/self/environ. When the skill subsequently calls fs.readFileSync() on the uploaded "file", Node.js follows the symlink transparently and reads the target file. The path.basename() normalization from FILEACCESS-001 does not help here: the symlink itself has an innocuous filename like audit.zip; the traversal happens when the symlink is followed, not when the name is parsed.
// VULNERABLE: fs.readFile follows symlinks silently
// Attacker uploads: audit.zip → /etc/shadow (symbolic link)
// multer saves it to: /uploads/audit.zip (the symlink file itself)
app.get('/api/skill/download/:filename', async (req, res) => {
const filename = path.basename(req.params.filename); // safe name ✓
const fullPath = path.join(UPLOAD_DIR, filename);
// VULNERABLE: readFile follows symlinks — returns /etc/shadow content
const content = await fs.promises.readFile(fullPath);
res.send(content);
});
// Attack:
// Upload a symlink: ln -s /etc/shadow audit.zip
// GET /api/skill/download/audit.zip → returns shadow file contents
// FIXED: check lstat (does not follow symlinks) before readFile
app.get('/api/skill/download/:filename', async (req, res) => {
const filename = path.basename(req.params.filename);
const fullPath = path.join(UPLOAD_DIR, filename);
// lstat does NOT follow symlinks — reveals the link itself
const stat = await fs.promises.lstat(fullPath);
if (stat.isSymbolicLink()) {
return res.status(403).json({ error: 'Symlinks not allowed' });
}
// Also confirm real path is within upload directory (double-check)
const realPath = await fs.promises.realpath(fullPath);
if (!realPath.startsWith(UPLOAD_DIR + path.sep)) {
return res.status(403).json({ error: 'Access denied' });
}
const content = await fs.promises.readFile(realPath);
res.send(content);
});
fs.readFile() without first checking for symbolic links via fs.lstat(); attacker uploads a symlink pointing to /etc/shadow or /proc/self/environ; readFile() silently follows the link and returns the target. Fix: fs.lstat() check for isSymbolicLink() before readFile(); reject symlinks; additionally apply fs.realpath() confinement check. Detection: SkillAudit flags fs.readFile()/readFileSync() calls on user-controlled paths without a preceding lstat() symlink check on the same path.FILEACCESS-003 — Predictable temp file race condition
When a skill creates temporary files using a predictable naming scheme based on the user ID or a low-entropy timestamp, two parallel invocations for the same user will attempt to create the same temp file simultaneously. The first write wins; the second invocation reads stale data from the first. In adversarial conditions, an attacker with two active sessions can deliberately collide temp files: session A creates the temp file with attacker-controlled content; session B reads it and processes the attacker's data as if it were legitimate. This is a TOCTOU (time-of-check/time-of-use) race applied to filesystem state.
// VULNERABLE: predictable temp file path based on userId
app.post('/api/skill/process_upload', authMiddleware, async (req, res) => {
const userId = req.user.id;
const TEMP_DIR = '/tmp';
// VULNERABLE: attacker with two parallel sessions collides these paths
// Session A and Session B both write to /tmp/audit-${userId}.json
// Last write wins; first reader gets stale (possibly attacker-injected) data
const tempPath = `${TEMP_DIR}/audit-${userId}.json`;
await fs.promises.writeFile(tempPath, JSON.stringify(req.body));
const result = await processAuditJob(tempPath);
await fs.promises.unlink(tempPath); // cleanup
return res.json(result);
});
// FIXED: crypto.randomUUID() for unpredictable temp file names
import crypto from 'crypto';
import os from 'os';
app.post('/api/skill/process_upload', authMiddleware, async (req, res) => {
// crypto.randomUUID() produces a 128-bit random identifier — not guessable
const tempPath = path.join(os.tmpdir(), `audit-${crypto.randomUUID()}.json`);
try {
await fs.promises.writeFile(tempPath, JSON.stringify(req.body), { flag: 'wx' });
// flag: 'wx' = O_CREAT | O_EXCL — fails if file already exists (race-safe)
const result = await processAuditJob(tempPath);
return res.json(result);
} finally {
await fs.promises.unlink(tempPath).catch(() => {}); // always cleanup
}
});
userId, Unix timestamp, or low-entropy counter; two parallel invocations collide and produce stale-read or attacker-injection race; temp files not cleaned up in finally block create residual disclosure. Fix: crypto.randomUUID() suffix + { flag: 'wx' } exclusive-create flag + finally cleanup. Detection: SkillAudit flags template literal temp paths that include user-controlled or time-based values without a randomUUID() or randomBytes() component.FILEACCESS-004 — CRLF injection via filename in Content-Disposition header
When a skill serves uploaded files and uses the original filename in the Content-Disposition: attachment; filename="..." response header, a filename containing \r\n (carriage return + newline) sequences can inject arbitrary HTTP response headers. HTTP header injection via CRLF is a classic attack vector: the attacker uploads a file named audit.zip\r\nX-Injected: evil; when the skill serves the file, the response header becomes two separate headers, with the second one being attacker-controlled. This can be used to inject Set-Cookie headers, override Content-Type, or add Location headers that redirect the victim.
// VULNERABLE: raw originalname from multer used in Content-Disposition header
app.get('/api/skill/download/:fileId', async (req, res) => {
const file = await db.files.findById(req.params.fileId);
// VULNERABLE: file.originalname may contain \r\n sequences
// Attacker uploads file named: "audit.zip\r\nX-Injected-Header: evil"
// Response headers become:
// Content-Disposition: attachment; filename="audit.zip
// X-Injected-Header: evil"
res.setHeader('Content-Disposition', `attachment; filename="${file.originalname}"`);
res.sendFile(file.storedPath);
});
// FIXED: sanitize filename to ASCII alphanumeric + safe punctuation only
app.get('/api/skill/download/:fileId', async (req, res) => {
const file = await db.files.findById(req.params.fileId);
// Strip everything except alphanumeric, hyphen, underscore, period
const safeFilename = file.originalname
.replace(/[^a-zA-Z0-9._-]/g, '_') // replace unsafe chars with underscore
.slice(0, 255); // limit length
// Use RFC 5987 encoding for non-ASCII filenames if needed:
// filename*=UTF-8''encodeURIComponent(safeFilename)
res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`);
res.sendFile(file.storedPath);
});
Content-Disposition: attachment; filename="..." using an unsanitized user-supplied filename; attacker filename with \r\n sequences injects arbitrary response headers including Set-Cookie and Location. Fix: sanitize filename to /[^a-zA-Z0-9._-]/g before header insertion; limit length to 255 chars. Detection: SkillAudit flags res.setHeader('Content-Disposition', ...) calls where the filename argument includes a tool argument or database-sourced variable without a regex sanitization step removing CR/LF/special characters.