Claude skill multipart upload memory exhaustion and content sniffing — SA-SKL-MULTIPART6
File upload handlers in MCP skills are a dense concentration of security failure modes. Four patterns recur across community skill audits: busboy without a fileSize limit streams gigabyte payloads into Node.js memory before any application-level size check can fire; a single replace(/\.\./, '') on the filename only removes the first occurrence, leaving traversal sequences intact after path.normalize(); formidable with keepExtensions:true and no magic byte validation allows an attacker to upload a file with a spoofed safe extension that the server stores with the dangerous extension; and accepting concurrent uploads from the same user without a per-user active-upload counter lets a single account exhaust all available disk space with partial files.
Multipart upload in MCP skill deployments
An MCP skill accepting file input — ZIP archives for audit, source code tarballs, PDF reports — routes incoming data through a multipart parser before it reaches any application logic. The parser runs at the kernel/stream level, before authentication middleware in many frameworks, and before any Content-Length-based size check in the application layer. This means that resource limits must be applied inside the parser itself, not after. Each of the four findings in SA-SKL-MULTIPART6 reflects a decision point where the developer deferred safety validation to a later layer that the attacker can bypass or overwhelm before that layer is reached.
limits.fileSize; attacker streams 10GB file into Node.js heap before application maxSize check fires; OOM crash or extreme latencyfilename.replace(/\.\./, '') removes only the first .. occurrence; path.normalize("....//....//etc/passwd") resolves to ../../etc/passwd; use path.basename() insteadkeepExtensions:true with no magic byte check; attacker uploads shell.php.jpg; stored path has .jpg.php on Windows; execute via direct URLMULTIPART6-001 — busboy without limits.fileSize
busboy is the most widely used streaming multipart parser for Node.js MCP skills. Its limits option controls how much data it buffers: fileSize caps bytes per file, files caps the number of file fields, and parts caps total multipart parts. When fileSize is omitted, busboy streams the entire file into the application's pipe destination before emitting the limit event. If the application checks file size after the stream ends (e.g., if (buffer.length > MAX) throw), the gigabyte payload has already arrived. The fix is to set limits.fileSize in the busboy constructor and listen for the 'limit' event on the file stream, then drain and abort the request immediately — without draining, the client continues streaming and the socket stays open consuming memory.
// VULNERABLE — busboy without limits; application-level size check fires too late
import busboy from 'busboy';
app.post('/upload', auth, (req, res) => {
const bb = busboy({ headers: req.headers }); // VULNERABLE: no limits
bb.on('file', (name, file, info) => {
const chunks = [];
file.on('data', chunk => chunks.push(chunk));
file.on('close', () => {
const buf = Buffer.concat(chunks);
// VULNERABLE: 10GB has already streamed into chunks[] before this check
if (buf.length > 10 * 1024 * 1024) return res.status(413).send('Too large');
processUpload(buf, info.filename);
res.json({ ok: true });
});
});
req.pipe(bb);
});
// FIXED — limits.fileSize in busboy + drain-and-abort on limit event
import busboy from 'busboy';
import path from 'path';
const MAX_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
app.post('/upload', auth, (req, res) => {
const bb = busboy({
headers: req.headers,
limits: {
fileSize: MAX_FILE_BYTES, // busboy stops reading at this byte count
files: 1, // only one file field accepted
parts: 2, // filename field + file field
},
});
let limitHit = false;
bb.on('file', (name, file, info) => {
file.on('limit', () => {
// busboy emits 'limit' when fileSize is exceeded
limitHit = true;
// Drain the stream so the socket is released; don't buffer anything
file.resume();
});
const chunks = [];
file.on('data', chunk => { if (!limitHit) chunks.push(chunk); });
file.on('close', () => {
if (limitHit) return; // response already sent below
processUpload(Buffer.concat(chunks), path.basename(info.filename));
});
});
bb.on('finish', () => {
if (limitHit) return res.status(413).json({ error: 'File exceeds 10 MB limit' });
res.json({ ok: true });
});
bb.on('error', err => res.status(400).json({ error: err.message }));
req.pipe(bb);
});
MULTIPART6-002 — filename.replace(/\.\./, '') path traversal
A common attempt to sanitize uploaded filenames removes .. sequences with a regex replace. The critical flaw is that String.prototype.replace without the global flag /g replaces only the first match. The attacker crafts a filename like ....//....//etc/passwd: after one-pass sanitization this becomes ..//..//etc/passwd, which after path.normalize() resolves to ../../etc/passwd. The correct approach is to never use the original filename as a path component at all. path.basename() strips all directory components, returning only the final filename segment. Combined with a generated UUID for the actual stored filename, the user-supplied name is never used as a filesystem path — it is stored as metadata only.
// VULNERABLE — single replace() leaves traversal after path.normalize()
import path from 'path';
function saveUpload(filename, buf) {
// VULNERABLE: replace() only removes first '..' occurrence
const safe = filename.replace(/\.\./, ''); // '....//....//etc/passwd' → '..//..//etc/passwd'
const dest = path.join('/srv/uploads', path.normalize(safe));
// path.normalize('..//..//etc/passwd') = '../../etc/passwd'
// path.join('/srv/uploads', '../../etc/passwd') = '/etc/passwd'
fs.writeFileSync(dest, buf);
}
// FIXED — path.basename() + UUID; original filename stored as metadata only
import path from 'path';
import { randomUUID } from 'crypto';
const UPLOAD_DIR = '/srv/uploads';
function saveUpload(originalFilename, buf) {
// path.basename() strips ALL directory components — cannot traverse
const basename = path.basename(originalFilename);
// Extract extension from basename only (not the full path)
const ext = path.extname(basename).toLowerCase();
// Store under a UUID to prevent filename collisions and enumeration
const storedName = `${randomUUID()}${ext}`;
const dest = path.join(UPLOAD_DIR, storedName);
// Paranoia check: verify dest is still inside UPLOAD_DIR after join
if (!dest.startsWith(UPLOAD_DIR + path.sep)) {
throw new Error('Path traversal detected');
}
fs.writeFileSync(dest, buf);
// originalFilename stored in DB as display name only, never used as path
return { storedName, displayName: basename };
}
MULTIPART6-003 — formidable keepExtensions:true without magic byte check
formidable's keepExtensions:true option preserves the file extension from the client-supplied filename when generating the temporary storage path. On case-insensitive Windows filesystems, a filename like shell.php.jpg may be stored as upload_abc.jpg.php — with .php as the final extension, which Apache/PHP will execute if the file is served from a web-accessible directory. Even on Linux, if the upload directory is served by a web server with PHP or CGI enabled, the double-extension can trigger execution. The correct defense is to never trust the client-supplied extension. Use a magic byte check library (file-type) to determine the actual MIME type from the first bytes of the file, then derive a safe extension from the detected MIME type — never from the user-supplied filename.
// VULNERABLE — formidable keepExtensions:true; extension from client filename
import formidable from 'formidable';
app.post('/upload', auth, (req, res) => {
const form = formidable({
uploadDir: '/srv/uploads',
keepExtensions: true, // VULNERABLE: extension taken from client filename
// attacker uploads 'shell.php.jpg' → stored as 'upload_abc.jpg.php' on some configs
maxFileSize: 10 * 1024 * 1024,
});
form.parse(req, (err, fields, files) => {
if (err) return res.status(400).json({ error: err.message });
res.json({ path: files.file[0].filepath });
});
});
// FIXED — UUID filename; extension from magic bytes only; no keepExtensions
import formidable from 'formidable';
import { fileTypeFromFile } from 'file-type'; // detect MIME from magic bytes
import { randomUUID } from 'crypto';
import fs from 'fs/promises';
import path from 'path';
const ALLOWED_MIME_EXTENSIONS = {
'application/zip': '.zip',
'application/x-tar': '.tar',
'application/gzip': '.tar.gz',
'application/json': '.json',
'text/plain': '.txt',
'application/pdf': '.pdf',
};
app.post('/upload', auth, async (req, res) => {
const form = formidable({
uploadDir: '/tmp/uploads-staging',
keepExtensions: false, // never use client-supplied extension
maxFileSize: 10 * 1024 * 1024,
});
try {
const [, files] = await form.parse(req);
const tmpPath = files.file[0].filepath;
// Detect MIME type from magic bytes (first 12 bytes)
const detected = await fileTypeFromFile(tmpPath);
if (!detected || !ALLOWED_MIME_EXTENSIONS[detected.mime]) {
await fs.unlink(tmpPath);
return res.status(415).json({ error: 'Unsupported file type' });
}
const safeExt = ALLOWED_MIME_EXTENSIONS[detected.mime];
const finalPath = path.join('/srv/uploads', `${randomUUID()}${safeExt}`);
await fs.rename(tmpPath, finalPath);
res.json({ ok: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
MULTIPART6-004 — concurrent uploads without per-user active-upload count
An MCP skill audit upload endpoint that enforces a per-request file size limit is still vulnerable to a resource-exhaustion attack if it doesn't limit concurrent uploads per user. An attacker with a free account can open 100 simultaneous upload connections, each streaming a 10 MB file. The 1 GB of disk usage for in-progress partial files arrives before any per-user quota check runs, because that check typically fires on completion, not on start. With enough parallel connections, the attacker exhausts available inodes or disk space on the upload volume, causing failures for all users. The fix is to track active upload count per user in Redis with INCR at request start and DEL (or DECR) in a finally block, rejecting requests that would exceed the threshold before any streaming begins.
// VULNERABLE — no per-user concurrent upload limit
app.post('/upload', auth, async (req, res) => {
// VULNERABLE: 100 simultaneous connections from same user = 1GB partial files on disk
// per-user quota check only fires on completion
const result = await processUploadStream(req, res);
await enforceUserQuota(req.user.id, result.bytes); // too late — disk already used
res.json(result);
});
// FIXED — Redis INCR per user at start; DECR in finally; reject at threshold
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const MAX_CONCURRENT_UPLOADS = 3; // per user
const KEY_TTL_SECONDS = 300; // expire stale keys after 5 min if finally didn't run
app.post('/upload', auth, async (req, res) => {
const countKey = `upload:active:${req.user.id}`;
let acquired = false;
try {
// Atomically increment and read; reject if threshold exceeded
const count = await redis.incr(countKey);
await redis.expire(countKey, KEY_TTL_SECONDS);
acquired = true;
if (count > MAX_CONCURRENT_UPLOADS) {
return res.status(429).json({ error: 'Too many concurrent uploads; wait for existing uploads to complete' });
}
const result = await processUploadStream(req, res);
res.json(result);
} finally {
if (acquired) {
// Always decrement — even on error or early return
const remaining = await redis.decr(countKey);
if (remaining <= 0) await redis.del(countKey);
}
}
});
Related patterns: Multipart upload path traversal in MCP skills is closely related to SA-SKL-MULTIPART5: busboy part-count explosion which covers field-count DoS. For redirect chains that bypass upload origin validation, see SA-SKL-REDIRECT4. The MCP skill file read path traversal blog post covers the broader directory traversal class across read and write operations.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
MULTIPART6-001 | Critical | busboy without limits.fileSize; application size check fires after stream completes | limits:{fileSize:10485760} in busboy options; drain file stream on 'limit' event |
MULTIPART6-002 | Critical | filename.replace(/\.\./, '') removes only first occurrence; traversal survives path.normalize() | path.basename(filename) only; store under UUID; never join user filename to disk path |
MULTIPART6-003 | High | formidable keepExtensions:true; no magic byte check; double-extension execution on Windows | Detect MIME from magic bytes via file-type; map to safe extension; keepExtensions:false |
MULTIPART6-004 | High | No per-user concurrent upload count; 100 parallel uploads exhaust disk before quota check | Redis INCR per user at request start; reject at threshold; DECR in finally |