Path Traversal and Symlink Attacks in MCP Skill Asset Storage
Four file system vulnerabilities affecting MCP skill registries: filename traversal via multer diskStorage, symlink extraction from skill ZIP packages, manifest thumbnail path escape, and express.static directory enumeration. SA-SKL-UPLOAD13 with full exploit walkthroughs and mitigations.
diskStorage using file.originalname
path.join() without bounds validation
express.static directory listing exposing extracted skill files and secrets
MCP skill registries face a distinctive class of file system threat that sits squarely between classic web upload vulnerabilities and the newer attack surface created by the agent skill packaging workflow. When a Claude MCP skill is published, it typically arrives as a ZIP archive containing assets, a manifest, and optional static resources. The registry server unpacks that archive, stores the results in a per-skill directory, and then serves those assets back to browsers or agent runtimes that consume the skill. Each step in that pipeline introduces opportunities for file-system escapes that can overwrite server configuration, read sensitive credentials, or enumerate confidential internal file structures.
These vulnerabilities are not theoretical. The same class of path traversal bugs that enabled the original Zip Slip disclosures in 2018 reappear today in MCP registry codebases precisely because developers reach for convenient Node.js libraries — multer, unzipper, adm-zip — without reading the security advisories attached to their extraction behaviour. UPLOAD13-001 through UPLOAD13-004 describe the four most common failure modes we encounter when auditing skill registry backends.
Scope note: This post covers file system path traversal attacks specific to asset storage in MCP skill registries — UPLOAD13. For command injection vulnerabilities arising from archive member filenames passed to shell commands during extraction, see SA-SKL-UPLOAD12. For dynamic require() injection via untrusted module paths at skill runtime, see SA-SKL-INJECTION10.
Filename path traversal in fs.createWriteStream via multer diskStorage
The most direct path traversal in an MCP skill upload endpoint is also the most common: the developer configures multer's diskStorage engine and passes file.originalname — the browser-supplied filename — directly to the destination callback without any sanitization. The result is an upload endpoint where the filename is an attacker-controlled parameter that dictates where on disk the uploaded bytes are written.
The attack is straightforward. Consider a skill registry endpoint that accepts a skill asset bundle. The developer wants to preserve the original filename for usability — a natural instinct. They write the following multer storage configuration:
// UPLOAD13-001: DO NOT USE — originalname passed without sanitization
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(SKILL_ASSETS_DIR, req.params.skillId));
},
filename: (req, file, cb) => {
// VULNERABILITY: file.originalname is fully attacker-controlled
cb(null, file.originalname);
}
});
const upload = multer({ storage });
app.post('/api/skills/:skillId/assets', upload.single('file'), (req, res) => {
res.json({ path: req.file.path });
});
An attacker submits a multipart POST request with Content-Disposition: form-data; name="file"; filename="../config/admin.json". Multer calls the filename callback, which returns ../config/admin.json verbatim. The final write path resolves to something like /app/skill-assets/skill-abc/../config/admin.json — which the OS normalizes to /app/config/admin.json. The attacker has just overwritten the application's admin configuration file with arbitrary content.
The impact extends well beyond config files. If the registry runs as a user with broad filesystem write permissions (common in containers deployed without an explicit UID), an attacker can target ../../.env to overwrite environment variable definitions, ../../views/layout.ejs to inject a persistent XSS payload into every page served by the registry, or ../../node_modules/.bin/node if write permissions are permissive enough. Because the write happens before any validation of the returned req.file.path, there is no after-the-fact check that could catch it.
Beyond the basic ../ traversal sequence, attackers use URL and percent-encoding variants to bypass naive string filters. A filter that checks for ../ literally in the original filename will miss %2e%2e%2f (percent-encoded), %2e%2e/ (mixed), ..%2f (trailing slash encoded), and double-encoded forms like %252e%252e%252f which some middleware layers decode twice. A robust fix does not attempt to strip traversal sequences — it derives the safe filename from scratch.
import path from 'path';
import crypto from 'crypto';
// Allowed extensions for skill assets
const ALLOWED_EXT = new Set(['.png', '.jpg', '.jpeg', '.svg', '.webp', '.css', '.js', '.json', '.wasm']);
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const dest = path.join(SKILL_ASSETS_DIR, req.params.skillId);
// Ensure destination exists and is a child of SKILL_ASSETS_DIR
if (!dest.startsWith(SKILL_ASSETS_DIR + path.sep)) {
return cb(new Error('Invalid skill ID'));
}
cb(null, dest);
},
filename: (req, file, cb) => {
// Extract only the extension from the original name — never the path component
const ext = path.extname(path.basename(file.originalname)).toLowerCase();
if (!ALLOWED_EXT.has(ext)) {
return cb(new Error('File type not permitted'));
}
// Generate a random storage name; store the original name in metadata separately
const safeName = crypto.randomUUID() + ext;
cb(null, safeName);
}
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 } // 5 MB per file
});
The fix applies three independent controls. First, path.basename() strips any directory component from the original filename before extracting the extension — even if the attacker encodes traversal sequences in the name, path.basename('../config/admin.json') returns admin.json. Second, the extension is checked against an explicit allowlist so that only expected asset types are accepted; this also prevents uploading executable files. Third, the actual storage filename is a UUID rather than anything derived from user input, eliminating any possibility of name collision or traversal via the storage path. The original filename can be stored in a database record or metadata file if it needs to be surfaced to users, without it ever touching the filesystem.
Symlink extraction from skill ZIP packages via unchecked Unix mode bits
The ZIP file format predates modern operating systems, but it carries a surprisingly complete representation of Unix filesystem metadata. Each entry in a ZIP archive has a 32-bit external file attributes field. For archives created on Unix-like systems (or by tools that emulate them), the upper 16 bits of that field contain the Unix file mode — the same st_mode value returned by stat(2). When those bits indicate a symbolic link (octal 0120000, or hex 0xA000 in the file type nibble), the entry's data is not file content — it is a link target path.
Several popular Node.js ZIP libraries — including unzipper and older versions of adm-zip — do not validate entry type before extracting. They treat every entry as a regular file and write the entry data verbatim to the destination path. If the entry is a symlink whose data is /etc/passwd, the library creates a file on disk at outputDir/link.txt whose bytes spell out /etc/passwd — not a symlink. That is benign. The dangerous behaviour occurs with libraries that do honour Unix mode bits in order to faithfully reconstruct archive metadata: they call fs.symlink(entryData, destPath), creating a real symlink pointing at an arbitrary location. Any subsequent operation that follows that symlink — including express.static serving the extracted directory — then reads from the attacker-chosen target.
// UPLOAD13-002: DO NOT USE — no symlink check before extraction
import unzipper from 'unzipper';
import fs from 'fs';
import path from 'path';
async function extractSkillPackage(zipPath, outputDir) {
// unzipper honours symlink entries if the platform supports them
await fs.createReadStream(zipPath)
.pipe(unzipper.Extract({ path: outputDir }))
.promise();
// All entries written — including any symlinks in the archive
}
An attacker constructs a ZIP archive with a symlink entry using Python's zipfile module or a hex editor. The entry has external attributes 0xA1ED0000 (Unix mode 0120755 = symlink), a name of token.txt, and data of /var/run/secrets/kubernetes.io/serviceaccount/token. After extraction, the registry's static asset server follows the symlink whenever a request arrives for GET /assets/skill-abc/token.txt, and returns the contents of the Kubernetes service account token to the caller — granting them the ability to authenticate against the cluster API server with the registry pod's identity.
High-value symlink targets in containerised MCP registry deployments include:
/var/run/secrets/kubernetes.io/serviceaccount/token— the pod's JWT for the Kubernetes API/var/run/secrets/kubernetes.io/serviceaccount/ca.crt— the cluster CA certificate/proc/self/environ— the process environment, which typically containsDATABASE_URL,SECRET_KEY_BASE, and other secrets injected as environment variables/proc/self/cmdline— command line of the running process, potentially revealing internal configuration flags/etc/hostname— cluster node or pod name useful for lateral movement reconnaissance../../.env— application-level secrets if the attacker also knows the directory depth
import yauzl from 'yauzl';
import fs from 'fs/promises';
import path from 'path';
import { createWriteStream } from 'fs';
const S_IFLNK = 0xA000; // Unix symlink file type nibble
const FILE_TYPE_MASK = 0xF000;
async function extractSkillPackage(zipPath, outputDir) {
return new Promise((resolve, reject) => {
yauzl.open(zipPath, { lazyEntries: true }, (err, zipfile) => {
if (err) return reject(err);
zipfile.readEntry();
zipfile.on('entry', async (entry) => {
const unixMode = (entry.externalFileAttributes >> 16) & 0xFFFF;
const isSymlink = (unixMode & FILE_TYPE_MASK) === S_IFLNK;
if (isSymlink) {
// Reject the entire archive — a well-formed skill package never needs symlinks
zipfile.close();
return reject(new Error(`Skill package rejected: symlink entry detected (${entry.fileName})`));
}
// Prevent path traversal in entry filename
const entryPath = path.resolve(outputDir, entry.fileName);
if (!entryPath.startsWith(outputDir + path.sep)) {
zipfile.close();
return reject(new Error(`Skill package rejected: path traversal in entry (${entry.fileName})`));
}
if (/\/$/.test(entry.fileName)) {
// Directory entry
await fs.mkdir(entryPath, { recursive: true });
zipfile.readEntry();
} else {
await fs.mkdir(path.dirname(entryPath), { recursive: true });
zipfile.openReadStream(entry, (err, readStream) => {
if (err) { zipfile.close(); return reject(err); }
const writeStream = createWriteStream(entryPath);
readStream.pipe(writeStream);
writeStream.on('finish', () => zipfile.readEntry());
writeStream.on('error', (e) => { zipfile.close(); reject(e); });
});
}
});
zipfile.on('end', resolve);
zipfile.on('error', reject);
});
});
}
The fix uses yauzl, which provides entry-level access to external attributes before extraction begins. The check (unixMode & 0xF000) === 0xA000 isolates the file type nibble from the Unix mode bits. If any entry identifies as a symlink, the archive is rejected before any bytes are written to disk. The same loop also checks each entry's filename against the output directory using path.resolve() and startsWith(), catching traditional Zip Slip traversal sequences in the same pass. Because both checks happen before openReadStream is called, there is no window in which a partial extraction leaves a dangling symlink on disk.
Manifest thumbnail path traversal via path.join() without bounds validation
Once a skill package is extracted and its manifest is parsed, the registry often needs to serve individual resources specified inside that manifest — a thumbnail image, a schema file, a locale bundle. Developers frequently build the filesystem path to these resources by joining the skill's extracted directory with the manifest field value using path.join(). This is where a subtle but important misunderstanding of path.join() semantics leads to path traversal.
The misunderstanding is this: developers expect path.join() to confine the result within the base directory, the same way a URL path join might. It does not. path.join('/srv/skills/abc', '../../static/admin.html') returns /srv/static/admin.html. The function faithfully normalizes the path segments — it does not check whether the result is still a descendant of the first argument. An attacker who controls the manifest thumbnail field (by uploading a crafted skill package or by exploiting a manifest editing API) can therefore cause res.sendFile() to serve any file on the filesystem that the Node process can read.
// UPLOAD13-003: DO NOT USE — path.join() does not confine to skillAssetsDir
app.get('/api/skills/:skillId/thumbnail', async (req, res) => {
const skill = await db.skills.findById(req.params.skillId);
if (!skill) return res.status(404).end();
// skill.manifest.thumbnail comes from the uploaded manifest.json
// VULNERABILITY: path.join normalises ../ without bounding the result
const thumbPath = path.join(skillAssetsDir, skill.id, skill.manifest.thumbnail);
res.sendFile(thumbPath);
});
A skill manifest containing "thumbnail": "../../static/admin.html" results in thumbPath resolving two levels above the skill assets directory. If the registry serves an internal admin panel at /static/admin.html, requests to the thumbnail endpoint now return that panel to any unauthenticated caller. More dangerously, a path like "thumbnail": "../../../etc/passwd" or "thumbnail": "../../../proc/self/environ" exposes system files. Because res.sendFile() follows the resolved path without question, the response includes whatever content lives at the resolved location.
The same pattern appears with other manifest fields: schemaPath, iconPath, localeDir, and similar keys. Any manifest-controlled string that feeds into a filesystem read without bounding creates the same class of vulnerability. Notably, the attack does not require the attacker to upload a malicious ZIP — if the registry exposes any API that lets a skill author update manifest fields after publication, that endpoint is equally exploitable.
// UPLOAD13-003: safe version — path.resolve + startsWith bounds check
app.get('/api/skills/:skillId/thumbnail', async (req, res) => {
const skill = await db.skills.findById(req.params.skillId);
if (!skill) return res.status(404).end();
// Establish the absolute base that all skill assets must remain within
const skillBase = path.resolve(skillAssetsDir, skill.id);
// path.resolve() normalises the joined path to an absolute path
const thumbPath = path.resolve(skillBase, skill.manifest.thumbnail);
// Verify the resolved path is still a descendant of skillBase
if (!thumbPath.startsWith(skillBase + path.sep)) {
return res.status(400).json({ error: 'Invalid thumbnail path' });
}
// Additional: restrict to known image extensions
const ext = path.extname(thumbPath).toLowerCase();
if (!['.png', '.jpg', '.jpeg', '.svg', '.webp'].includes(ext)) {
return res.status(400).json({ error: 'Invalid thumbnail type' });
}
res.sendFile(thumbPath);
});
The critical difference is the use of path.resolve() rather than path.join(), combined with a bounds check. path.resolve(skillBase, '../../static/admin.html') returns the absolute path /srv/static/admin.html — but the subsequent startsWith(skillBase + path.sep) test catches that the result is outside the permitted directory and rejects the request with a 400 before any file read occurs. The trailing path.sep in the bounds check is important: without it, a skill ID of abc and a path that resolves to /srv/skills/abcdef/secret would pass a naive startsWith('/srv/skills/abc') check even though it refers to a different skill's directory.
express.static directory listing exposing extracted skill files
The final pattern in SA-SKL-UPLOAD13 is less dramatic than the previous three but consistently underestimated in severity. MCP skill registries that serve extracted skill assets directly through express.static often invoke it with default options on the user-controlled extraction directory. The default configuration for express.static in Express 4 and 5 does not serve directory listings — but it does follow a specific fallback order. When a request arrives for a directory path (such as /assets/skill-abc/) and no index.html exists in that directory, Express returns a 403 by default.
The problem arises when developers explicitly enable directory listing for usability — to let skill authors browse their uploaded assets — or when they use a middleware combination that inadvertently exposes it. More subtly, the default express.static configuration will serve any file in the directory tree unconditionally, including dotfiles and files with sensitive names, unless the dotfiles option is set to 'deny'. A skill package that includes .npmrc, .env, or a bundled credentials.json for a third-party service integration will have those files served verbatim to any caller who guesses or enumerates the filename. Combined with the directory listing from an explicitly-enabled or middleware-triggered listing, this becomes a systematic credential harvesting opportunity across every skill published to the registry.
// UPLOAD13-004: DO NOT USE — default options expose dotfiles; explicit dotfiles:true exposes .env
app.use('/assets/:skillId', (req, res, next) => {
// req.skillPath is the extracted directory for this skill
express.static(req.skillPath)(req, res, next);
});
// Even worse — explicit directory listing enabled for "developer convenience"
app.use('/assets/:skillId', (req, res, next) => {
express.static(req.skillPath, {
dotfiles: 'allow',
index: 'index.html' // falls back to listing if index.html absent
})(req, res, next);
});
When a skill package lacks an index.html — which is true of the majority of back-end-only MCP skills that expose no web UI — the directory served by express.static at the root path will trigger the fallback behaviour. An attacker probing for .env will find it immediately. The dotfiles: 'allow' variant makes this worse: even a default Express static setup protects dotfiles, so this configuration actively regresses security in the name of developer convenience.
Beyond credential exposure, directory listing in a skill registry creates a reconnaissance surface that benefits subsequent attacks. An attacker who can list all files in an extracted skill directory can identify the structure of the skill's backend integration, discover endpoint paths hard-coded in bundled JavaScript, and find test fixture files left in the package that contain sample credentials or internal service URLs. Skills are contributed by external authors; not all authors follow secure development practices for what they include in their packages.
// UPLOAD13-004: safe version — explicit deny for dotfiles, no directory index, no redirect
app.use('/assets/:skillId', (req, res, next) => {
const skillId = req.params.skillId;
// Validate skillId is alphanumeric to prevent path injection in the route parameter itself
if (!/^[a-zA-Z0-9_-]+$/.test(skillId)) {
return res.status(400).end();
}
const skillPath = path.resolve(SKILL_ASSETS_DIR, skillId);
// Ensure resolved path is within SKILL_ASSETS_DIR
if (!skillPath.startsWith(SKILL_ASSETS_DIR + path.sep)) {
return res.status(400).end();
}
express.static(skillPath, {
index: false, // never serve directory indexes or fall back to index.html
dotfiles: 'deny', // reject requests for files beginning with .
redirect: false, // do not redirect /dir to /dir/ — prevents fishing for dirs
etag: true,
lastModified: true,
maxAge: '1h'
})(req, res, next);
});
The three key options are index: false, dotfiles: 'deny', and redirect: false. Setting index: false prevents Express from ever returning a directory listing or falling back to an index.html file — requests to directory paths return 404. Setting dotfiles: 'deny' causes any request whose final path component begins with a period to return 403, protecting .env, .npmrc, .git, and similar files. Setting redirect: false prevents the middleware from issuing a 301 to /dir/ when /dir is requested, which would otherwise help an attacker confirm the existence of directories they cannot directly list. The route parameter validation using a strict regex further prevents the skillId itself from being used as a path traversal vector at the routing layer.
An additional hardening layer worth considering for production registries: serve skill assets from a separate subdomain (e.g., assets.skillaudit.dev) with a strict Content-Security-Policy: default-src 'none' header. This prevents any JavaScript or HTML that an attacker manages to upload from executing in the context of the main registry origin, containing the blast radius of a successful file upload bypass to the asset subdomain only.
SA-SKL-UPLOAD13 detection
The table below summarises each finding, its severity, the attack surface through which it is exploitable, and SkillAudit's approach to detecting it in MCP skill registry codebases during static analysis.
| Finding | Severity | Attack surface | SkillAudit detection approach |
|---|---|---|---|
| UPLOAD13-001 Filename path traversal via file.originalname |
Critical | Skill asset upload endpoint; multipart POST with crafted Content-Disposition filename |
Taint-tracks req.file.originalname / req.files[*].originalname into multer filename callbacks and fs.createWriteStream / fs.writeFile calls; flags when no path.basename() or UUID substitution breaks the taint chain |
| UPLOAD13-002 Symlink extraction from skill ZIP packages |
Critical | Skill package upload; crafted ZIP with Unix mode 0120000 symlink entries |
Detects unzipper.Extract() and AdmZip.extractAll() calls without adjacent externalFileAttributes inspection; also flags yauzl entry loops lacking the (unixMode & 0xF000) === 0xA000 guard |
| UPLOAD13-003 Manifest thumbnail path traversal via path.join() |
High | Manifest field editing API or skill package upload; thumbnail, iconPath, or similar manifest string fields |
Identifies path.join() calls where one argument is a database or manifest field (tainted via ORM query result or JSON.parse output) and the result flows into res.sendFile(), fs.readFile(), or createReadStream() without a startsWith() bounds check on a path.resolve()-normalized result |
UPLOAD13-004express.static directory listing |
Medium | Skill asset static serving route; unauthenticated GET requests to skill asset paths | Flags express.static() invocations on user-submitted content directories where options lack index: false; additionally warns when dotfiles is omitted (defaults to 'ignore' rather than 'deny') or explicitly set to 'allow' |
How the patterns chain together
These four vulnerabilities are not isolated weaknesses — in a typical MCP skill registry they form an exploit chain. An attacker begins with UPLOAD13-002 to extract a symlink into the registry's static asset directory. With a symlink pointing at /proc/self/environ in place, they exploit UPLOAD13-004's default dotfiles handling (or the absence of index: false) to retrieve the symlink target's contents via a simple GET request. The environment variables retrieved from the process environ include the database connection string. With database access, the attacker can update skill manifest records directly, setting a thumbnail field to an arbitrary filesystem path and then triggering UPLOAD13-003 to read any file the Node process can access via the manifest thumbnail endpoint.
UPLOAD13-001 completes the chain in a different direction: rather than reading files, it enables writes. An attacker who can write to ../../views/error.ejs can inject a persistent server-side template that executes arbitrary JavaScript in the Node.js process context on every 404 response. Combined with the read primitives from UPLOAD13-002 and UPLOAD13-003, this provides full read-write access to the server filesystem and, depending on the deployment, remote code execution.
The practical lesson is that file system security in skill registries requires defence in depth at every layer of the pipeline: the upload handler, the extraction logic, the manifest processing step, and the static serving configuration. A single missing check at any stage creates exposure. The fixes shown in each section above are independent controls — implementing all four eliminates the entire UPLOAD13 attack surface for the patterns described here.
For further reading on adjacent attack surface in MCP skill pipelines, the SA-SKL-UPLOAD13 reference page provides a comprehensive listing of detection rules, affected library versions, and remediation guidance cross-referenced with CVE identifiers for known vulnerable package versions. If your registry uses shell commands during extraction or asset processing rather than pure Node.js library calls, also review SA-SKL-UPLOAD12, which covers command injection via archive member filenames — a distinct but often co-located vulnerability class.
SkillAudit automated detection: SkillAudit's static analysis scans detect all four UPLOAD13 patterns in MCP skill registry codebases. UPLOAD13-001 is flagged when string concatenation or path.join() uses req.file.originalname or similar user-supplied filename; UPLOAD13-002 when ZIP extraction code lacks mode/type checks before writing entries; UPLOAD13-003 when path.join() with manifest fields lacks startsWith() validation; UPLOAD13-004 when express.static() on user-submitted content directories lacks index: false. Get started with a free audit scan.