← Blog

Claude skill multipart upload advanced security — SA-SKL-MULTIPART2

Basic multipart upload security — MIME type validation, file size limits, virus scanning — is covered in SA-SKL-UPLOAD2. SA-SKL-MULTIPART2 covers four attack patterns that target the multipart parser itself rather than the uploaded content: boundary string spoofing that terminates a part before its actual content ends, a Content-Disposition filename that contains path separators and can be used as a form field name by some parsers, a nested multipart/mixed body that triggers unbounded recursive parsing, and a multipart/form-data endpoint that lacks CSRF protection because the developer relied on JSON Content-Type checking which does not apply to form posts. Each pattern exploits RFC-compliant behavior in ways that application-layer validation misses.

By SkillAudit  |  5 Nov 2026

Why multipart parser attacks bypass MIME-level defenses

MIME type validation, file extension checks, and content-based file type detection all operate on the content of a successfully parsed multipart body. If the parser's behavior can be manipulated before it finishes parsing — through boundary spoofing, nested content types, or exploiting how parsers handle edge cases in the RFC — then the content-level checks operate on the wrong content. Boundary spoofing causes the parser to end a part early, leaving the remaining content to be interpreted in an attacker-controlled way. The CSRF gap is different — it is not a parser attack, but a consequence of building an API that accepts both JSON (checked for CSRF via Content-Type) and form posts (not checked) and failing to realize that browsers can submit form posts cross-origin without pre-flight.

SA-SKL-MULTIPART2 in scope: MULTIPART2-001 (multipart boundary spoofing), MULTIPART2-002 (Content-Disposition filename path separators), MULTIPART2-003 (nested multipart/mixed recursive depth), MULTIPART2-004 (CSRF on multipart endpoint). For basic file upload security (MIME validation, storage path, size limits), see SA-SKL-UPLOAD2 and SA-SKL-UPLOAD.

MULTIPART2-001 — Multipart boundary spoofing

A multipart body's boundary string is specified in the Content-Type header: Content-Type: multipart/form-data; boundary=----boundary123. The parser splits the body on occurrences of --boundary123. If a file being uploaded contains the boundary string as part of its content — which can be crafted by an attacker — the parser splits the file at that point, treating the remainder as a new part with attacker-specified headers. The attack crafts a file whose content, when parsed, appears to be a new multipart part with a different filename, different MIME type, and different content — potentially overriding a previously parsed field value. The fix is to validate that the boundary is a UUID-like string (not user-influenced) and to verify that the number of boundary occurrences in the body matches the expected number of parts.

// VULNERABLE: boundary string predictable and potentially embedded in file content
// Attacker can craft a file that contains the boundary string, splitting the part early

// Client sets: Content-Type: multipart/form-data; boundary=----WebKitFormBoundary1234
// (browser-generated boundaries are predictable in structure)

// Attack: attacker crafts a "file.txt" with this content:
// (legitimate file content)
// \r\n----WebKitFormBoundary1234\r\n
// Content-Disposition: form-data; name="file"; filename="malicious.php"\r\n
// Content-Type: application/x-httpd-php\r\n\r\n
// <?php system($_GET["cmd"]); ?>

// Parser sees two parts:
// Part 1: file="file.txt", content="(legitimate content)"
// Part 2: file="malicious.php", content="<?php system...?>"

// MIME type check on Part 1 passes (legitimate content)
// Part 2 is processed as a valid file upload — PHP file stored to disk

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/api/upload', authMiddleware, upload.single('file'), (req, res) => {
  // VULNERABLE: req.file.mimetype is from Part 2 if boundary spoofing succeeded
  if (!['image/jpeg', 'image/png'].includes(req.file.mimetype)) {
    // This check may operate on the wrong part
    return res.status(400).json({ error: 'Invalid file type' });
  }
  // PHP file may have been stored to uploads/ as Part 2
});
// FIXED: validate boundary entropy; count boundary occurrences before parsing
const crypto = require('crypto');
const busboy = require('busboy');

app.post('/api/upload', authMiddleware, (req, res) => {
  const contentType = req.headers['content-type'] || '';

  // Extract boundary from Content-Type
  const boundaryMatch = contentType.match(/boundary=([^\s;]+)/i);
  if (!boundaryMatch) {
    return res.status(400).json({ error: 'Missing multipart boundary' });
  }

  const boundary = boundaryMatch[1].replace(/^["']|["']$/g, '');

  // FIXED: validate boundary has sufficient entropy (UUID-like)
  // Reject boundaries shorter than 16 chars or matching browser-predictable patterns
  if (boundary.length < 16) {
    return res.status(400).json({ error: 'Boundary too short' });
  }

  // Count expected parts before parsing (from application logic)
  // For single-file upload: expect exactly 1 file part
  const MAX_PARTS = 1;
  let partCount = 0;

  const bb = busboy({
    headers: req.headers,
    limits: {
      fileSize: 10 * 1024 * 1024, // 10 MB
      files: MAX_PARTS,           // busboy enforces max file count
      fields: 5,                  // max non-file fields
    },
  });

  bb.on('file', (fieldname, fileStream, info) => {
    partCount++;
    if (partCount > MAX_PARTS) {
      // Extra parts — possible boundary spoofing — reject
      fileStream.resume(); // Drain the stream
      req.unpipe(bb);
      return res.status(400).json({ error: 'Unexpected additional file parts' });
    }

    // Validate field name is from allowlist
    if (fieldname !== 'file') {
      fileStream.resume();
      return res.status(400).json({ error: 'Unexpected field name' });
    }

    // Process file...
    handleFileUpload(fileStream, info, res);
  });

  bb.on('error', (err) => {
    res.status(400).json({ error: 'Multipart parse error' });
  });

  req.pipe(bb);
});
HIGH
SA-SKL-MULTIPART2-001 — MCP skill multipart parser does not validate boundary string entropy or count boundary occurrences in the request body; an attacker can craft a file whose content contains the boundary string, causing the parser to split the file early and treat the remaining content as a new part with attacker-specified headers including filename and Content-Type; this bypass defeats MIME type and filename extension checks applied to the originally declared part. Fix: validate boundary has at least 16 characters of entropy; use busboy with limits.files set to the expected part count; reject on part count exceeding the limit. Detection: SkillAudit flags multipart handlers that do not set limits.files on the busboy/multer parser configuration.

MULTIPART2-002 — Content-Disposition filename with path separators

The Content-Disposition header's filename parameter is frequently used as a form field name or storage path. The basic path traversal attack (filename="../../etc/passwd") is covered in SA-SKL-UPLOAD. A distinct attack targets parsers that use the filename as a form field name in the parsed result. Some older multipart parsers (and certain configurations of formidable) use the filename value as the key in the parsed fields object. An attacker who sets filename="__proto__.isAdmin" can inject into the parsed object's prototype chain. An attacker who sets filename="config[NODE_ENV]" exploits parsers that interpret bracket notation as nested object paths. Even parsers that sanitize the storage path may not sanitize the in-memory field name representation.

// VULNERABLE: filename used as field key in parsed object without sanitization
const formidable = require('formidable');

app.post('/api/upload', authMiddleware, (req, res) => {
  const form = formidable({ uploadDir: '/tmp/uploads', keepExtensions: true });

  form.parse(req, (err, fields, files) => {
    if (err) return res.status(400).json({ error: 'Parse error' });

    // VULNERABLE: some formidable versions use filename as the key in `files` object
    // files["__proto__[isAdmin]"] = { ... } — prototype pollution via filename
    // files["config[db]"] = { ... } — bracket-path injection

    // VULNERABLE: filename passed to storage without field name validation
    const uploadedFile = files.file; // if filename was "__proto__", this is undefined
    // ... proceed with upload

    res.json({ uploaded: true, fields });
    // Also VULNERABLE: returning `fields` to client may reveal injected keys
  });
});
// FIXED: explicit field name allowlist with busboy; never use filename as field key
const busboy = require('busboy');
const path = require('path');
const crypto = require('crypto');

const ALLOWED_FIELD_NAMES = new Set(['file', 'repoZip', 'attachment']);

app.post('/api/upload', authMiddleware, (req, res) => {
  const bb = busboy({ headers: req.headers, limits: { files: 1, fileSize: 10 * 1024 * 1024 } });

  bb.on('file', (fieldname, fileStream, info) => {
    // FIXED: validate fieldname against allowlist (never use filename as key)
    if (!ALLOWED_FIELD_NAMES.has(fieldname)) {
      fileStream.resume();
      return res.status(400).json({ error: `Unexpected field: ${fieldname}` });
    }

    // FIXED: generate a new storage filename — never use info.filename from client
    const storageFilename = `${crypto.randomUUID()}${path.extname(info.filename || '').toLowerCase()}`;

    // Validate the extension derived from info.filename against allowlist
    const ext = path.extname(info.filename || '').toLowerCase();
    if (!['.zip', '.tar', '.gz', '.tgz'].includes(ext)) {
      fileStream.resume();
      return res.status(400).json({ error: 'Invalid file extension' });
    }

    // Store with generated name — never the client-supplied filename
    const writePath = path.join('/tmp/uploads', storageFilename);
    // path.basename() as extra defense: strips any path components
    const safeStorageName = path.basename(storageFilename);

    saveFile(fileStream, path.join('/tmp/uploads', safeStorageName), res);
  });

  req.pipe(bb);
});
MEDIUM
SA-SKL-MULTIPART2-002 — MCP skill multipart parser uses the filename parameter from Content-Disposition as a form field key or passes it without sanitization to storage path logic; a filename of __proto__[isAdmin] or constructor.prototype.admin can pollute the parsed object's prototype depending on the parser; a filename with path separators (/, \) can reach storage paths outside the intended directory. Fix: use busboy with an explicit field name allowlist; generate a random UUID as the storage filename; use only path.extname(info.filename) (not the full filename) for extension validation; pass through path.basename() as defence-in-depth. Detection: SkillAudit flags multipart handlers that pass req.file.originalname or info.filename directly to file system path construction or object key assignment.

MULTIPART2-003 — Nested multipart/mixed recursive depth

RFC 2046 permits nesting: a part within a multipart/form-data body can itself be of type multipart/mixed, containing further parts. This is used in email to attach multiple files in a single field. Most multipart parsers used in Node.js web applications do not expect nested multipart bodies and either ignore the nesting (treating the inner body as an opaque blob) or recursively parse it. If the parser recursively parses nested multipart bodies without a depth limit, an attacker can craft a deeply nested multipart body (100+ levels) that causes stack overflow or excessive CPU consumption — a denial-of-service vector. The fix is straightforward: reject any part whose Content-Type is multipart/*.

// VULNERABLE: multipart parser processes nested multipart/mixed without depth limit
// Some custom multipart implementations recurse into nested parts
const { parseMultipart } = require('./lib/custom-multipart'); // internal parser

app.post('/api/upload', authMiddleware, async (req, res) => {
  // VULNERABLE: custom parser recurses into nested multipart/mixed parts
  // Attack: 100+ levels of nesting → stack overflow → DoS

  // Crafted attack body:
  // Content-Type: multipart/form-data; boundary=A
  // --A
  // Content-Disposition: form-data; name="file"
  // Content-Type: multipart/mixed; boundary=B
  // --B
  // Content-Disposition: form-data; name="file"
  // Content-Type: multipart/mixed; boundary=C
  // ... (100 levels deep)
  // --C--
  // --B--
  // --A--

  const { fields, files } = await parseMultipart(req); // Recurses 100 levels → crash
  res.json({ files: files.length });
});
// FIXED: reject nested multipart/* content types in part headers
const busboy = require('busboy');

app.post('/api/upload', authMiddleware, (req, res) => {
  const bb = busboy({
    headers: req.headers,
    limits: { files: 1, fileSize: 10 * 1024 * 1024, fields: 5 },
  });

  bb.on('file', (fieldname, fileStream, info) => {
    // FIXED: reject multipart/* content type in file part headers
    // This prevents nested multipart/mixed bodies from being processed
    const partContentType = (info.mimeType || '').toLowerCase();
    if (partContentType.startsWith('multipart/')) {
      fileStream.resume();
      req.unpipe(bb);
      return res.status(400).json({ error: 'Nested multipart content is not allowed' });
    }

    // Continue with validated content type
    processUpload(fieldname, fileStream, info, res);
  });

  bb.on('field', (name, value, info) => {
    // Also reject nested multipart in field values (less common but possible)
    // Field values are strings — no content-type concern, but validate field names
    if (!ALLOWED_FIELD_NAMES.has(name)) {
      return res.status(400).json({ error: `Unexpected field: ${name}` });
    }
  });

  bb.on('error', (err) => res.status(400).json({ error: 'Parse error' }));
  req.pipe(bb);
});

// If using a framework middleware (multer), add a custom content-type check:
const checkForNestedMultipart = (req, res, next) => {
  const contentType = req.headers['content-type'] || '';
  // The top-level content-type is multipart/form-data — that is expected
  // We need to check part-level content types during parsing, not here
  // Use the busboy approach above for part-level checks
  next();
};
MEDIUM
SA-SKL-MULTIPART2-003 — MCP skill multipart handler does not reject parts whose Content-Type header is multipart/*; a crafted request with 100+ levels of nested multipart/mixed parts can exhaust the call stack in recursive parsers or consume excessive CPU in iterative ones, causing a denial-of-service condition; RFC 2046 permits nested multipart bodies, so the nesting is structurally valid and not rejected by standard parser validation. Fix: in the busboy file event handler, check info.mimeType.startsWith('multipart/') and drain the stream and reject the request if true; for custom parsers, enforce a maximum recursion depth of 1. Detection: SkillAudit flags multipart handlers that do not include a multipart/ content type rejection check for file part MIME types.

MULTIPART2-004 — CSRF on multipart/form-data endpoint

A common CSRF mitigation for JSON APIs is to require a Content-Type: application/json header on all state-changing requests. Because browsers cannot set a custom Content-Type on a cross-origin form post without a pre-flight, this check blocks simple CSRF attacks against JSON endpoints. Developers who implement this Content-Type check sometimes believe their entire API is CSRF-protected. It is not: multipart/form-data is one of the three content types browsers will send cross-origin without a pre-flight (along with application/x-www-form-urlencoded and text/plain). An endpoint that accepts multipart/form-data submissions — such as a file upload endpoint that also processes form fields triggering state changes — is vulnerable to CSRF via a crafted HTML form on an attacker-controlled page, regardless of the JSON Content-Type check on other routes.

// VULNERABLE: CSRF protection only on JSON routes; multipart endpoint unprotected
const csrf = require('csurf');

// CSRF middleware applied to JSON API routes
app.use('/api/', (req, res, next) => {
  if (req.headers['content-type']?.includes('application/json')) {
    // VULNERABLE: assumes all state-changing requests use JSON
    // This skips CSRF check for multipart/form-data requests
    return next();
  }
  csrf({ cookie: true })(req, res, next);
  // This logic is backwards — CSRF check is applied when content-type is NOT json
  // But the developer intended to protect JSON routes, leaving multipart unprotected
});

// VULNERABLE: file upload endpoint accepts form post without CSRF token
app.post('/api/upload', authMiddleware, multer().single('file'), (req, res) => {
  // This endpoint accepts multipart/form-data
  // A cross-origin HTML form can POST to this endpoint with victim's cookies:
  //   <form action="https://skillaudit.dev/api/upload" method="post" enctype="multipart/form-data">
  //     <input type="file" name="file">
  //     <input type="hidden" name="action" value="replace_audit">
  //   </form>
  // Browser sends this cross-origin with victim's session cookies — no pre-flight needed
  const action = req.body.action; // 'replace_audit' — attacker-controlled state change
});
// FIXED: CSRF token in hidden form field for multipart endpoints
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: { httpOnly: true, secure: true, sameSite: 'strict' } });

// Apply CSRF protection to ALL state-changing routes regardless of content type
app.use('/api/', csrfProtection);

// File upload endpoint — CSRF token validated by csrfProtection middleware
app.post('/api/upload', authMiddleware, multer().single('file'), (req, res) => {
  // csrfProtection checks req.body._csrf OR req.headers['x-csrf-token']
  // For multipart forms: include _csrf as a hidden field in the form
  // For programmatic (fetch/XHR) uploads: include X-CSRF-Token header

  // ... process upload
  res.json({ uploaded: true });
});

// For the HTML form that submits the upload:
// <form action="/api/upload" method="post" enctype="multipart/form-data">
//   <input type="hidden" name="_csrf" value="<%= csrfToken %>">
//   <input type="file" name="file">
// </form>

// For programmatic uploads via fetch():
// const response = await fetch('/api/upload', {
//   method: 'POST',
//   headers: { 'X-CSRF-Token': document.cookie.match(/csrfToken=([^;]+)/)[1] },
//   body: formData,
// });

// Alternative: SameSite=Strict cookie is defense-in-depth but not sufficient alone
// — it requires HTTPS everywhere and doesn't protect older browsers
// CSRF token is the reliable defense for multipart endpoints
HIGH
SA-SKL-MULTIPART2-004 — MCP skill state-changing endpoint that accepts multipart/form-data does not validate a CSRF token; multipart/form-data is one of three browser-native content types that do not trigger CORS pre-flight — a cross-origin HTML form can POST to this endpoint with the victim's session cookies without any browser warning; if the CSRF check is implemented only via Content-Type header (application/json requirement), it does not protect multipart/form-data endpoints. Fix: apply CSRF middleware globally to all state-changing routes, not conditionally on content type; include _csrf as a hidden field in HTML forms; accept X-CSRF-Token header for programmatic fetch uploads. Detection: SkillAudit flags endpoints that use multer() or busboy middleware but are not wrapped by CSRF middleware.

SkillAudit detection summary — SA-SKL-MULTIPART2

Pattern IDSeverityWhat SkillAudit flagsFix
MULTIPART2-001HIGHMultipart handlers without limits.files set on busboy/multer configuration; predictable or short boundary stringslimits.files: 1 (or expected count); boundary entropy validation; count boundary occurrences before parsing
MULTIPART2-002MEDIUMreq.file.originalname or info.filename used as object key or file path without field name allowlistExplicit field name allowlist in busboy; path.extname() only for extension; crypto.randomUUID() for storage name
MULTIPART2-003MEDIUMMultipart handlers that do not check info.mimeType.startsWith('multipart/') before processing file partsDrain stream and reject 400 on multipart/* part content type; maximum recursion depth of 1
MULTIPART2-004HIGHRoutes using multer/busboy middleware not wrapped by CSRF middleware; CSRF check conditional on application/json content typeGlobal CSRF middleware on all state-changing routes; _csrf hidden field in forms; X-CSRF-Token header for fetch

Related patterns: For basic file upload security (MIME validation, storage path, virus scanning), see SA-SKL-UPLOAD and SA-SKL-UPLOAD2. For CSRF protection patterns beyond the multipart case, see SA-SKL-CSRF. For prototype pollution via parsed request bodies, see SA-SKL-PROTOTYPE2.