Claude skill multipart form-data boundary injection and MIME confusion in MCP skill HTTP parsing — SA-SKL-MULTIPART5
Multipart form-data parsing is deceptively complex: the boundary parameter in Content-Type is attacker-controlled, file-descriptor limits are opt-in, MIME-type validation is typically skipped for performance, and temp file naming is rarely hardened. SA-SKL-MULTIPART5 covers four patterns that turn these oversights into hidden-field injection, resource exhaustion, same-origin script execution, and race-condition file overwrite in MCP skill upload endpoints.
MULTIPART5-001 — Boundary CR/LF injection: hidden MIME parts add attacker-controlled fields
RFC 2046 defines the multipart boundary as a sequence of printable characters excluding spaces and special characters. The boundary value itself is transmitted verbatim in the Content-Type header as a parameter: Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxk. Many server-side parsers accept boundaries without validating that the value is free of CR or LF characters. An attacker who controls the Content-Type header (or the first field in a crafted request) can supply a boundary such as boundary=legit\r\nContent-Disposition: form-data; name="admin"\r\n\r\ntrue. Because the parser reads the boundary literally and splits parts on it, the injected CR/LF sequence causes the parser to see an extra MIME part named admin with value true — a field the original HTML form never transmitted. If the server uses the parsed fields directly for authorization checks (e.g., req.body.admin === 'true'), the attacker escalates privileges with no authentication bypass needed elsewhere. The fix is to validate the boundary value before passing it to the parser: RFC 2046 §5.1.1 restricts boundary to bchars — alphanumeric, hyphen, underscore, period, comma, colon, semicolon, equal, question mark, forward slash — with no carriage return or linefeed permitted.
# VULNERABLE — MULTIPART5-001: boundary parameter accepted without CR/LF validation
# Node.js Express with busboy:
const busboy = require('busboy');
app.post('/upload', (req, res) => {
// Content-Type header passed directly to busboy — no boundary validation
const bb = busboy({ headers: req.headers });
bb.on('field', (name, val) => {
// If attacker injects boundary=real\r\nContent-Disposition: form-data; name="admin"\r\n\r\ntrue
// busboy parses it and fires this event with name='admin', val='true'
// Server-side code trusting req.body.admin is now bypassed
console.log(`Field: ${name} = ${val}`);
if (name === 'admin' && val === 'true') grantAdminAccess(req);
});
req.pipe(bb);
});
# Attacker crafts:
# POST /upload HTTP/1.1
# Content-Type: multipart/form-data; boundary=legit\r\nContent-Disposition: form-data; name="admin"\r\n\r\ntrue
# (some parsers accept %0d%0a URL-encoding in the boundary parameter)
# Result: busboy fires field('admin', 'true') even though the HTML form had no admin field
# FIXED — MULTIPART5-001: validate boundary against RFC 2046 bchars before parsing
const busboy = require('busboy');
// RFC 2046 §5.1.1 bchars: 0-9 A-Z a-z and ' ( ) + _ , - . / : = ?
const BOUNDARY_RE = /^[0-9A-Za-z'()+_,\-.\/:=? ]{1,70}$/;
app.post('/upload', (req, res) => {
const contentType = req.headers['content-type'] || '';
const boundaryMatch = contentType.match(/boundary=([^\s;]+)/i);
if (!boundaryMatch) {
return res.status(400).json({ error: 'Missing multipart boundary' });
}
const boundary = boundaryMatch[1];
// Reject boundary values containing CR, LF, or characters outside RFC 2046 bchars
if (!BOUNDARY_RE.test(boundary)) {
return res.status(400).json({ error: 'Invalid multipart boundary' });
}
// Also reject URL-encoded CR/LF sequences attackers might try in boundary:
if (/%0[da]/i.test(boundary)) {
return res.status(400).json({ error: 'Invalid multipart boundary encoding' });
}
const bb = busboy({ headers: req.headers });
bb.on('field', (name, val) => {
// Now safe — boundary was validated before parsing began
processField(name, val);
});
req.pipe(bb);
});
boundary parameter in Content-Type: multipart/form-data accepted without RFC 2046 character validation allows an attacker to inject CR/LF sequences that cause the multipart parser to see additional MIME parts with attacker-controlled field names and values, enabling field injection and privilege escalation bypasses; fix by validating the boundary value against /^[0-9A-Za-z'()+_,\-.\/:=? ]{1,70}$/ and rejecting URL-encoded CR/LF sequences before passing the request to any multipart parser. Detection: SkillAudit flags multipart-parsing endpoints that pass req.headers to busboy, formidable, or multer without a preceding boundary character validation step.MULTIPART5-002 — Missing limits.files: unlimited concurrent upload slots exhaust fd limit
Both busboy and formidable accept a limits configuration object that caps the number of files, fields, and total bytes in a single multipart request. Without these limits, a single request with thousands of Content-Disposition: form-data; filename="f" parts causes the parser to open one file descriptor per part — either to a temp file on disk or to an in-memory buffer. On Linux the per-process fd limit is typically 1024 (soft) or 4096 (hard) for Node processes without tuning. An attacker who sends a request with 2000 file parts can silently push the process past its fd limit, causing all subsequent file opens — including config reads, database connections, and log writes — to fail with EMFILE: too many open files. The process does not crash immediately; it enters a degraded state where any I/O that requires a new fd throws, producing inconsistent behavior and partial writes. Setting limits.files: 5 and limits.parts: 10 in busboy caps the total part count per request to a small multiple of what any legitimate upload form would send, eliminating the exhaustion vector entirely.
# VULNERABLE — MULTIPART5-002: no limits on busboy file count
const busboy = require('busboy');
const { pipeline } = require('stream');
const fs = require('fs');
const os = require('os');
const path = require('path');
app.post('/upload', (req, res) => {
// No limits object — busboy accepts unlimited file and field parts
const bb = busboy({ headers: req.headers });
const saves = [];
bb.on('file', (fieldname, fileStream, info) => {
// Each part opens a new file descriptor — no cap on how many
const tmpPath = path.join(os.tmpdir(), `upload-${Date.now()}`);
const writeStream = fs.createWriteStream(tmpPath); // fd consumed per part
saves.push(new Promise((resolve, reject) => {
pipeline(fileStream, writeStream, err => err ? reject(err) : resolve(tmpPath));
}));
});
bb.on('finish', async () => {
// With 2000 parts, 2000 file descriptors were consumed — process may now fail on
// any subsequent open(), connect(), or accept() call
const paths = await Promise.all(saves);
res.json({ uploaded: paths.length });
});
req.pipe(bb);
});
# Attacker sends a single POST with 2000 file parts:
# python3 -c "
# import socket, struct
# hdr = 'POST /upload HTTP/1.1\r\nHost: target\r\nContent-Type: multipart/form-data; boundary=X\r\n\r\n'
# part = '--X\r\nContent-Disposition: form-data; name=\"f\"; filename=\"x\"\r\n\r\ndata\r\n'
# payload = hdr + (part * 2000) + '--X--\r\n'
# ... send ..."
# FIXED — MULTIPART5-002: enforce limits.files, limits.parts, and limits.fileSize
const busboy = require('busboy');
const UPLOAD_LIMITS = {
files: 5, // maximum 5 file parts per request
parts: 10, // maximum 10 total parts (files + fields combined)
fields: 10, // maximum 10 non-file field parts
fieldSize: 1024, // 1 KB max per text field value
fileSize: 10 * 1024 * 1024, // 10 MB max per file
headerPairs: 20, // 20 header pairs per part
};
app.post('/upload', (req, res) => {
const bb = busboy({ headers: req.headers, limits: UPLOAD_LIMITS });
const saves = [];
let limitHit = false;
bb.on('file', (fieldname, fileStream, info) => {
if (limitHit) {
fileStream.resume(); // drain and discard
return;
}
const tmpPath = path.join(os.tmpdir(), `upload-${crypto.randomUUID()}`);
const writeStream = fs.createWriteStream(tmpPath);
// Detect per-file size limit being hit
fileStream.on('limit', () => {
limitHit = true;
writeStream.destroy();
fs.unlink(tmpPath, () => {});
});
saves.push(new Promise((resolve, reject) => {
pipeline(fileStream, writeStream, err => err ? reject(err) : resolve(tmpPath));
}));
});
// Busboy fires 'filesLimit' and 'partsLimit' events when limits are exceeded
bb.on('filesLimit', () => { limitHit = true; });
bb.on('partsLimit', () => { limitHit = true; });
bb.on('finish', async () => {
if (limitHit) {
return res.status(400).json({ error: 'Upload limit exceeded' });
}
const paths = await Promise.all(saves);
res.json({ uploaded: paths.length });
});
req.pipe(bb);
});
limits configuration object accepts unlimited file and field parts per request, allowing a single request with thousands of file parts to exhaust the Node.js process file descriptor limit and cause all subsequent I/O operations to fail with EMFILE; fix by passing { limits: { files: 5, parts: 10, fileSize: 10MB } } to busboy and handling the filesLimit/partsLimit events by draining and discarding excess streams. Detection: SkillAudit flags busboy/formidable/multer instantiation without a limits property in MCP skill upload handlers.MULTIPART5-003 — Missing MIME-type validation: polyglot JPEG/JS executes as script from same origin
A polyglot file is a byte sequence that is simultaneously valid in two different formats. The most dangerous for web upload endpoints is the JPEG/JavaScript polyglot: a file that begins with the JPEG magic bytes FF D8 FF (so file(1) and most magic-byte libraries identify it as a JPEG image) but whose content, when interpreted as JavaScript, executes attacker code. If an MCP skill upload endpoint accepts any file whose Content-Type header is image/jpeg and stores it at a URL reachable from the same origin as the web UI (e.g., https://skillaudit.dev/uploads/abc123.jpg), an attacker can include a <script src="https://skillaudit.dev/uploads/abc123.jpg"></script> tag that the browser fetches and executes. The Content-Type: image/jpeg response header does not prevent script execution in older browsers without X-Content-Type-Options: nosniff; even with that header, same-origin fetches for scripts are not blocked in all contexts. The root fix is to serve all user-uploaded content from an isolated origin — a separate subdomain or a CDN bucket domain — so that even if a polyglot file is served, its JavaScript cannot access the main app's cookies, localStorage, or DOM. When a separate origin is not feasible, combine magic-byte validation, discard of attacker-supplied Content-Type, and Content-Disposition: attachment response headers.
# VULNERABLE — MULTIPART5-003: trusting client-supplied Content-Type, serving from same origin
const multer = require('multer');
// Multer configured to store in /public/uploads — served from same origin as app
const upload = multer({
dest: 'public/uploads/',
// No fileFilter — accepts whatever Content-Type the client sends
// No mimetype check — an image/jpeg Content-Type with JS content passes through
});
app.post('/upload', upload.single('avatar'), (req, res) => {
// File stored at /public/uploads/randomhex (no extension added by default)
// Attacker renames or references it as .jpg
res.json({ url: `/uploads/${req.file.filename}` });
});
# Polyglot file construction (conceptual):
# Start with valid JPEG header bytes: \xFF\xD8\xFF\xE0
# Add JFIF marker, then EXIF comment field containing JavaScript:
# /*\xFF\xD8\xFF\xE0...*/alert(document.cookie)/*
# Most JPEG validators see the leading magic bytes and approve
# Browser's JS engine ignores the binary JPEG prefix as a comment and executes alert()
# Attack chain:
# 1. Attacker uploads polyglot.jpg to /upload
# 2. Server saves it to /public/uploads/abc123 — served at https://skillaudit.dev/uploads/abc123
# 3. Attacker posts on forum: <script src="https://skillaudit.dev/uploads/abc123"></script>
# 4. Browser fetches from same origin — script runs — cookies stolen
# FIXED — MULTIPART5-003: magic-byte validation + serve uploads from isolated origin
const multer = require('multer');
const { createReadStream } = require('fs');
const sharp = require('sharp'); // For image re-encoding
// Upload to temp dir only — never directly to public/
const upload = multer({
dest: '/tmp/uploads/',
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
// Reject based on MIME type claim — this is a first gate only, not the real check
if (!allowed.includes(file.mimetype)) {
return cb(new Error('File type not allowed'), false);
}
cb(null, true);
}
});
// Magic byte validation helper (first 4 bytes)
async function validateImageMagicBytes(filepath, mimetype) {
const fd = await fs.promises.open(filepath, 'r');
const buf = Buffer.alloc(4);
await fd.read(buf, 0, 4, 0);
await fd.close();
const sigs = {
'image/jpeg': [0xFF, 0xD8, 0xFF], // JPEG magic bytes (3-byte prefix)
'image/png': [0x89, 0x50, 0x4E, 0x47], // PNG magic bytes
'image/gif': [0x47, 0x49, 0x46, 0x38], // GIF87a or GIF89a
'image/webp': [0x52, 0x49, 0x46, 0x46], // RIFF (WebP container)
};
const expected = sigs[mimetype];
if (!expected) return false;
return expected.every((byte, i) => buf[i] === byte);
}
app.post('/upload', upload.single('avatar'), async (req, res) => {
const tmpPath = req.file.path;
// 1. Validate magic bytes — rejects polyglots that fake Content-Type
const valid = await validateImageMagicBytes(tmpPath, req.file.mimetype);
if (!valid) {
await fs.promises.unlink(tmpPath);
return res.status(400).json({ error: 'File content does not match declared type' });
}
// 2. Re-encode through sharp — strips EXIF, comment fields, and any polyglot payload
const finalPath = `/data/uploads/${crypto.randomUUID()}.jpg`;
await sharp(tmpPath).jpeg({ quality: 85 }).toFile(finalPath);
await fs.promises.unlink(tmpPath);
// 3. Serve from isolated CDN origin — NOT from the app's own origin
// The CDN domain (assets.skillaudit.dev) cannot read skillaudit.dev cookies
const cdnUrl = `https://assets.skillaudit.dev/${path.basename(finalPath)}`;
res.json({ url: cdnUrl });
});
Content-Type header without magic-byte validation and serve uploads from the same origin as the application allow polyglot JPEG/JavaScript files to execute as scripts in the browser, enabling stored XSS with same-origin cookie access; fix by validating the first 4 bytes of every uploaded file against expected magic byte signatures, re-encoding images through sharp to strip polyglot payloads, and serving all user-uploaded content from an isolated CDN subdomain. Detection: SkillAudit flags multer/busboy upload handlers that store files in a public/ directory served by the same Express app without magic-byte validation middleware.MULTIPART5-004 — Predictable /tmp path: race condition between write and processing
When a multipart upload handler creates a temporary file for processing before moving it to its final destination, the temp file path must be unpredictable and not guessable by other processes on the same host. A common pattern is path.join(os.tmpdir(), `upload-${Date.now()}`) or path.join(os.tmpdir(), `upload-${req.ip}-${filename}`). Both are predictable: timestamps have millisecond resolution and can be raced by any other process watching /tmp with inotify, and IP addresses plus filenames are known to the attacker who controls the upload. If the processing step reads the file after writing it — for example, to run a virus scanner, extract EXIF data, or push it to object storage — an attacker who creates a symlink at the predicted path before the write can redirect the write to an arbitrary filesystem location, overwriting a config file, an SSH authorized_keys file, or another user's uploads. On shared hosting or multi-tenant VPS environments where other processes share the same /tmp, this race is real and exploitable. The fix is to generate temp file paths using a cryptographically random UUID so the path is unpredictable, create the file atomically before the stream write begins, and perform an atomic rename (not copy-then-delete) when moving to the final destination so there is no window during which the file exists at two paths.
# VULNERABLE — MULTIPART5-004: predictable temp path enables race-condition symlink attack
const os = require('os');
const path = require('path');
const fs = require('fs');
app.post('/upload', (req, res) => {
const bb = busboy({ headers: req.headers });
bb.on('file', (fieldname, fileStream, info) => {
// VULNERABLE: timestamp-based temp path — predictable within 1ms window
const tmpPath = path.join(os.tmpdir(), `upload-${Date.now()}-${info.filename}`);
// If attacker creates a symlink at this path before we write:
// ln -s /home/ubuntu/.ssh/authorized_keys /tmp/upload-1699355000000-photo.jpg
// The write goes into authorized_keys instead
const ws = fs.createWriteStream(tmpPath);
fileStream.pipe(ws);
ws.on('finish', async () => {
await runVirusScanner(tmpPath); // processes the (possibly redirected) file
const finalPath = `/data/uploads/${info.filename}`;
fs.rename(tmpPath, finalPath, () => res.json({ saved: finalPath }));
});
});
req.pipe(bb);
});
# Race condition window:
# T=0: server receives request, begins preparing tmpPath
# T=0: attacker script polls /tmp every 0.1ms looking for upload-* files
# T=1ms: server opens tmpPath for writing (follows symlink — writes to authorized_keys)
# T=1ms: upload data streamed into /home/ubuntu/.ssh/authorized_keys
# T=2ms: attacker SSH key added to authorized_keys
# T=5ms: virus scanner runs on symlink — attacker key survives
# FIXED — MULTIPART5-004: UUID-based tmpdir per upload + atomic rename to final destination
const { randomUUID } = require('crypto');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fsp = require('fs').promises;
app.post('/upload', async (req, res) => {
// Create an isolated temp directory per request — UUID makes path unguessable
const tmpDir = path.join(os.tmpdir(), `upload-${randomUUID()}`);
await fsp.mkdir(tmpDir, { mode: 0o700 }); // owner-only permissions
const bb = busboy({ headers: req.headers, limits: { files: 5, fileSize: 10 * 1024 * 1024 } });
const saves = [];
bb.on('file', (fieldname, fileStream, info) => {
// Temp file inside the UUID directory — still UUID-named to prevent collisions
const tmpPath = path.join(tmpDir, randomUUID());
// Open with O_CREAT | O_EXCL — fails if the path already exists (no symlink follow)
// Node's fs.createWriteStream opens with O_WRONLY | O_CREAT | O_TRUNC by default.
// Use fsp.open with O_WRONLY | O_CREAT | O_EXCL to prevent symlink follow:
saves.push((async () => {
const fd = await fsp.open(tmpPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
const ws = fd.createWriteStream();
await new Promise((resolve, reject) => {
fileStream.pipe(ws);
ws.on('finish', resolve);
ws.on('error', reject);
});
await fd.close();
// Scan or process the file
await runVirusScanner(tmpPath);
// Atomic rename — no window where file exists at two paths
const finalPath = path.join('/data/uploads', randomUUID());
await fsp.rename(tmpPath, finalPath); // atomic on same filesystem
return finalPath;
})());
});
bb.on('finish', async () => {
try {
const paths = await Promise.all(saves);
res.json({ uploaded: paths });
} finally {
// Clean up tmpDir regardless of outcome
await fsp.rm(tmpDir, { recursive: true, force: true });
}
});
req.pipe(bb);
});
/tmp directory create a race condition window where an attacker who can place a symlink at the predicted path redirects the write to an arbitrary filesystem location such as SSH authorized_keys or a config file; fix by generating a UUID-based isolated temp directory per upload (crypto.randomUUID()), opening files with O_CREAT | O_EXCL to prevent symlink follow, and moving to the final destination via atomic fs.rename(). Detection: SkillAudit flags upload handlers that construct temp paths with Date.now(), req.ip, or user-supplied filenames rather than a cryptographically random identifier.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| MULTIPART5-001 | HIGH | Boundary CR/LF injection injects hidden MIME parts with attacker-controlled field names into the parsed body | Validate boundary against RFC 2046 bchars regex; reject CR, LF, and URL-encoded equivalents before parsing |
| MULTIPART5-002 | HIGH | busboy/formidable without limits.files/limits.parts — 2000-part request exhausts process fd limit |
limits: { files: 5, parts: 10, fileSize: 10MB }; handle filesLimit event; drain excess streams |
| MULTIPART5-003 | HIGH | No magic-byte validation; polyglot JPEG/JS stored on same origin executes as script | Magic-byte check; re-encode through sharp; serve uploads from isolated CDN subdomain |
| MULTIPART5-004 | MEDIUM | Predictable /tmp path (timestamp/IP/filename) allows race-condition symlink attack during write |
UUID tmpdir per upload; O_CREAT | O_EXCL open; atomic rename() to final destination |
Related patterns: SA-SKL-UPLOAD4 covers ZIP Slip path traversal in MCP skill archive extraction including zip bomb decompression limits and symlink attack vectors in tar/zip entries. MCP server file upload security covers the full upload hardening checklist including content-length limits, storage path isolation, and virus scanning integration for MCP skill endpoints that accept user-supplied files.