File upload vulnerability: what your server accepts, keeps and hands back
An upload feature lets a stranger put a file on your server.
This guide covers what the server should accept, how it decides what a file is, where it stores it, what it names it and how it serves it back, with a harmless fixture set, a four-check verification table and a local Node.js lab with a regression test.
In this guide
Upload fixture set, verification table and Node.js lab
An illustration for learning and for testing an upload feature you own. Part 1 is a harmless fixture set in four groups: renamed extensions, mismatched content types, oversized files and archive entries.
How to use itHide the instructions
Part 2 is a four-check verification table for server-side inspection, generated names, isolated storage and safe download headers, with the evidence to keep and the source behind each check. Parts 3 to 5 are a local Node.js lab, a photo upload feature in a flawed and a fixed version with a runner, an archive check and a regression test, run as shown on Node.js 26.0.0.
file-upload-security.txt
Introduction11 lines
Part 1: The harmless upload fixture set31 lines
Part 2: The verification table25 lines
Part 3: The lab files811 lines
Part 4: Send every fixture to both versions164 lines
Part 5: The regression test86 lines
Part 6: Point the checks at your own upload feature6 lines
Whole template1,168 lines
ILLUSTRATION FOR LEARNING. The photo upload feature, its two versions and every fixture below were written for this page. They are not a client's code or a client's result. Use the fixtures and the lab to learn, and to test an upload feature you own or are authorised in writing to test, on a test or staging copy where you can.
Written and run on: Node.js v26.0.0 on macOS, the only version it was run on. It uses only modules that ship with Node.js (node:http, node:crypto, node:fs, node:os, node:path, node:zlib, node:test and node:assert), so there is nothing to install. zlib.crc32(), which fixtures.mjs uses, was added in Node.js 22.2.0 and 20.15.0. Every output below was copied from that run by a script. Stack trace lines that held local file paths were removed, and each removal is marked. Ports are picked by the system and never printed, stored names are random, and test timings vary, so your output will differ in those places.
Source names used below:
ASVS OWASP Application Security Verification Standard 5.0.0, chapter V5 File Handling. The level follows each requirement number.
CWE MITRE CWE version 5.0: CWE-434 Unrestricted Upload of File with Dangerous Type, CWE-646 Reliance on File Name or Extension of Externally-Supplied File
WSTG OWASP Web Security Testing Guide v4.2: WSTG-BUSL-08 Test Upload of Unexpected File Types, WSTG-BUSL-09 Test Upload of Malicious Files
OWASP CS OWASP File Upload Cheat Sheet
OWASP UFU OWASP Unrestricted File Upload
MDN MDN Web Docs pages for X-Content-Type-Options, Content-Disposition, the CSP guide and the CSP sandbox directive
================================================================
PART 1: THE HARMLESS UPLOAD FIXTURE SET
Fifteen fixtures in four groups. fixtures.mjs (Part 3) builds every one in memory, so there is nothing to download. Each text fixture holds one line of marker text with its own ID, for example:
UPLOAD-LAB-MARKER R2: plain text, not an image and not a program.
Columns: ID, the file name sent, the declared Content-Type, the body, and what a sound upload feature does with it.
GROUP 1: RENAMED EXTENSIONS, INCLUDING DOUBLE EXTENSIONS AND UPPER CASE
R1 photo.png image/png a real 1 by 1 pixel PNG, 69 bytes (the baseline) accept
R2 photo.png image/png marker text refuse: the leading bytes are not a PNG signature
R3 photo.png.html image/png marker text refuse: .html is not on the allow-list
R4 notes.html.png image/png marker text refuse: the leading bytes are not a PNG signature
R5 HOLIDAY.PNG image/png the real PNG accept: extensions compared without regard to case
R6 notes.HTML image/png marker text refuse: .html is not on the allow-list in any case
GROUP 2: MISMATCHED CONTENT TYPES (the declared type, the extension and the leading bytes disagree)
M1 photo.png text/html the real PNG accept as image/png: the declared type does not decide
M2 photo.png image/png the PNG signature, then marker text, 74 bytes passes a leading-bytes check, so storage and serving must make it harmless
M3 photo.html image/png the real PNG refuse: the extension does not match the content
GROUP 3: OVERSIZED FILES (the lab's limit is 65,536 bytes)
S1 big.png image/png 65,537 bytes: a PNG signature, then generated padding, with Content-Length refuse with 413 before reading the body
S2 big-stream.png image/png 300,000 bytes, sent in pieces with no Content-Length header refuse with 413 while reading
GROUP 4: ARCHIVE ENTRIES (every entry is a marker text file; the lab's archive limits are 100 entries and 1,000,000 bytes after extraction)
A1 many-entries.zip 200 entries, each a one-line marker file refuse: too many entries
A2 large-total.zip one entry of marker lines, 1,560,000 bytes after extraction, 3,957 bytes packed refuse: too large after extraction
A3 untrusted-names.zip ../outside-marker.txt, /absolute-marker.txt and docs/inside-marker.txt refuse: two names cannot be used as paths
A4 small.zip 3 entries, 77 bytes after extraction pass the archive check
Every archive is sent with the declared type application/zip. A feature that does not take archives refuses all four at the upload. A feature that does take them runs the archive check (archive-check.mjs) before extracting anything. Resolving and confining real paths during extraction is the subject of the path traversal guide.
None of the fixtures is a program, none contains a scanner test file, and the lab never extracts an archive.
================================================================
PART 2: THE VERIFICATION TABLE
Four checks for any upload feature. Run them against a local or staging copy you own, with a test account, and send each fixture straight to the endpoint rather than through your own form or its script.
CHECK 1: SERVER-SIDE INSPECTION
Check: Send all fifteen fixtures and record the status and reason for each.
Expected: R1, R5 and M1 accepted. R2, R3, R4, R6 and M3 refused. S1 and S2 refused with 413, S2 with no Content-Length header. A1 to A4 refused at the upload, or, where the feature takes archives, A1 to A3 refused by the archive check before anything is extracted and A4 passed. M2 may pass this check; checks 2 to 4 decide what it can do.
Evidence: each request (name, declared type, size, whether Content-Length was sent), the response status and reason, and for archives the listing the check read.
Basis: ASVS 5.2.1 (L1) size; ASVS 5.2.2 (L1) extension and contents; ASVS 5.2.3 (L2) archives checked before uncompressing; CWE-434 mitigations (server-side checks, one extension, case-insensitive comparison); CWE-646; WSTG-BUSL-08.
CHECK 2: GENERATED NAMES
Check: Upload R1, M1 and R5 (the first two share the name photo.png) and read the stored names from storage, logs or the code.
Expected: every stored name generated by the server, ending in an allow-listed extension, containing nothing from the uploaded name, and no upload replacing another.
Evidence: each stored name beside the uploaded name, and the number of uploads accepted against the number of distinct stored files.
Basis: ASVS 5.3.2 (L1); CWE-434 (generate a new, unique file name; only generate names that end in allowed extensions); OWASP CS Filename Safety.
CHECK 3: ISOLATED STORAGE
Check: Request each stored file by its stored name and by its uploaded name under every public path the server has, and read the storage location from the configuration.
Expected: 404 for every direct request. Files reachable only through a handler that maps an ID to a file. Storage outside the web root, or on another host.
Evidence: the direct requests and their status codes, and the storage path from the configuration.
Basis: ASVS 5.3.1 (L1); CWE-434 (consider storing uploads outside the web document root entirely); OWASP CS File Storage Location; OWASP UFU (no execute permission or script handlers in upload folders).
CHECK 4: SAFE DOWNLOAD HEADERS
Check: Download every accepted fixture, R1, R5, M1 and M2, and record the full response headers.
Expected: a Content-Type the server set from its allow-list; X-Content-Type-Options: nosniff; Content-Disposition: attachment with a file name the server chose; and a Content-Security-Policy on the file's own response (the lab sends sandbox).
Evidence: the full response headers for each download, including any CDN in front of the storage.
Basis: ASVS 5.4.1 (L2) and 5.4.2 (L2); MDN X-Content-Type-Options, Content-Disposition, the CSP guide (set a policy on all responses) and the CSP sandbox directive; OWASP UFU (attachment and nosniff for every file users download).
================================================================
PART 3: THE LAB FILES
================================================================
Upload format: to keep the server short and correct with built-in modules only, the lab takes POST /upload?name=FILE_NAME with the file's bytes as the whole request body and the declared type in the Content-Type header. A browser form sends the same three claims in a multipart/form-data part instead; the checks do not change.
The lab listens on 127.0.0.1 only, writes only inside a temporary folder it creates for each version, and removes both folders when it stops. The size limit (65,536 bytes) and archive limits (100 entries, 1,000,000 bytes) are values picked for the illustration, not recommendations.
Make an empty folder, save the six files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 6: upload-lab-server.mjs
================================================================
// upload-lab-server.mjs: an invented photo upload feature, in a flawed
// version and a fixed version. Illustration only. It listens on 127.0.0.1 on
// a port the system picks, writes only inside a temporary folder it creates,
// and removes that folder when it closes. Each mistake in the flawed version
// is marked FLAWED.
//
// Upload format, chosen to keep the lab small: POST /upload?name=FILE_NAME
// with the file's bytes as the whole request body and the declared type in
// the Content-Type header. A browser form sends the same three claims inside
// a multipart/form-data part instead.
import { createServer } from 'node:http'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, extname, join } from 'node:path'
// The lab's own size limit, picked for the illustration.
export const SIZE_LIMIT_BYTES = 64 * 1024
// The fixed version's allow-list: the extension a name must end in, the
// leading bytes the file must start with, and the type the server serves.
const ALLOWED_TYPES = [
{
extension: '.png',
contentType: 'image/png',
signature: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
},
]
// FLAWED: the declared types the flawed version accepts.
const FLAWED_DECLARED_TYPES = ['image/png', 'application/zip']
// FLAWED: how the flawed file server picks a Content-Type. The keys are
// lowercase, so an upper-case extension finds nothing.
const FLAWED_TYPE_BY_EXTENSION = {
'.png': 'image/png',
'.html': 'text/html',
'.txt': 'text/plain',
'.zip': 'application/zip',
}
function sendJson(response, status, body, extraHeaders) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, extraHeaders || {})
response.writeHead(status, headers)
response.end(JSON.stringify(body))
}
function refuse(request, response, status, reason) {
request.resume()
sendJson(response, status, { accepted: false, reason: reason }, { Connection: 'close' })
}
// FLAWED: reads the whole body, however large.
function readWholeBody(request) {
return new Promise(function (resolve, reject) {
const chunks = []
request.on('data', function (chunk) {
chunks.push(chunk)
})
request.on('end', function () {
resolve(Buffer.concat(chunks))
})
request.on('error', reject)
})
}
async function handleFlawedUpload(lab, request, response, upload) {
// FLAWED: trusts the declared Content-Type, which the uploader chose.
if (!FLAWED_DECLARED_TYPES.includes(upload.declaredType)) {
return refuse(request, response, 415, 'declared type ' + upload.declaredType + ' is not accepted')
}
const body = await readWholeBody(request)
// FLAWED: keeps the uploader's file name. basename() is its only change,
// so the lab never writes outside its own folder.
const storedName = basename(upload.name)
// FLAWED: stores the file in the folder the server also serves from.
writeFileSync(join(lab.publicFolder, storedName), body)
sendJson(response, 201, {
accepted: true,
storedAs: 'public/' + storedName,
bytes: body.length,
downloadPath: '/uploads/' + encodeURIComponent(storedName),
})
}
// FLAWED: serves the upload folder directly, with a type picked from the
// stored name's extension, and no nosniff or attachment header.
function serveFlawedDownload(lab, request, response, path) {
const storedName = basename(decodeURIComponent(path.slice('/uploads/'.length)))
const filePath = join(lab.publicFolder, storedName)
if (storedName === '' || !existsSync(filePath)) return refuse(request, response, 404, 'not found')
const headers = {}
const contentType = FLAWED_TYPE_BY_EXTENSION[extname(storedName)]
if (contentType) headers['Content-Type'] = contentType
response.writeHead(200, headers)
response.end(readFileSync(filePath))
}
// Keeps at most limit bytes. Once the count passes the limit it stops
// keeping data and reports how many bytes had arrived.
function readLimitedBody(request, limit) {
return new Promise(function (resolve, reject) {
const chunks = []
let received = 0
function onData(chunk) {
received = received + chunk.length
if (received > limit) {
request.off('data', onData)
resolve({ tooLarge: true, received: received })
return
}
chunks.push(chunk)
}
request.on('data', onData)
request.on('end', function () {
resolve({ tooLarge: false, body: Buffer.concat(chunks) })
})
request.on('error', reject)
})
}
// Decides the type on the server: the extension must be on the allow-list
// and the leading bytes must match that entry. The declared type is ignored.
function matchAllowedType(name, body) {
const extension = extname(name).toLowerCase()
const allowed = ALLOWED_TYPES.find(function (entry) {
return entry.extension === extension
})
if (!allowed) return { problem: 'extension ' + (extension || '(none)') + ' is not on the allow-list' }
const leadingBytes = body.subarray(0, allowed.signature.length)
if (!leadingBytes.equals(allowed.signature)) {
return { problem: 'leading bytes do not match the ' + allowed.contentType + ' signature' }
}
return { allowed: allowed }
}
async function handleFixedUpload(lab, request, response, upload) {
const declaredLength = Number(request.headers['content-length'] || 0)
if (declaredLength > SIZE_LIMIT_BYTES) {
return refuse(request, response, 413, 'Content-Length ' + declaredLength + ' is over the limit, body not read')
}
const result = await readLimitedBody(request, SIZE_LIMIT_BYTES)
if (result.tooLarge) {
return refuse(request, response, 413, 'stopped keeping data after ' + result.received + ' bytes, over the limit')
}
const match = matchAllowedType(upload.name, result.body)
if (match.problem) return refuse(request, response, 415, match.problem)
const id = randomUUID()
const storedName = id + match.allowed.extension
writeFileSync(join(lab.storeFolder, storedName), result.body)
lab.storedFiles.set(id, { storedName: storedName, contentType: match.allowed.contentType })
sendJson(response, 201, {
accepted: true,
storedAs: 'store/' + storedName,
bytes: result.body.length,
downloadPath: '/files/' + id,
})
}
// Serves only ids this server issued, from a folder no route serves directly.
function serveFixedDownload(lab, request, response, path) {
const record = lab.storedFiles.get(path.slice('/files/'.length))
if (!record) return refuse(request, response, 404, 'not found')
response.writeHead(200, {
'Content-Type': record.contentType,
'X-Content-Type-Options': 'nosniff',
'Content-Disposition': 'attachment; filename="' + record.storedName + '"',
'Content-Security-Policy': 'sandbox',
})
response.end(readFileSync(join(lab.storeFolder, record.storedName)))
}
async function routeRequest(lab, request, response) {
const url = new URL(request.url, 'http://127.0.0.1')
const isFlawed = lab.version === 'flawed'
if (request.method === 'POST' && url.pathname === '/upload') {
const upload = {
name: url.searchParams.get('name') || '',
declaredType: request.headers['content-type'] || '(none)',
}
if (isFlawed) return handleFlawedUpload(lab, request, response, upload)
return handleFixedUpload(lab, request, response, upload)
}
if (request.method === 'GET' && isFlawed && url.pathname.startsWith('/uploads/')) {
return serveFlawedDownload(lab, request, response, url.pathname)
}
if (request.method === 'GET' && !isFlawed && url.pathname.startsWith('/files/')) {
return serveFixedDownload(lab, request, response, url.pathname)
}
refuse(request, response, 404, 'not found')
}
function createLabFolders(version) {
const root = mkdtempSync(join(tmpdir(), 'upload-lab-' + version + '-'))
const lab = {
version: version,
root: root,
publicFolder: join(root, 'public'),
storeFolder: join(root, 'store'),
storedFiles: new Map(),
}
mkdirSync(lab.publicFolder)
mkdirSync(lab.storeFolder)
return lab
}
// Starts one version. close() stops the server, removes the temporary
// folder and resolves to true once the folder is gone.
export function startUploadLab(version) {
const lab = createLabFolders(version)
const server = createServer(function (request, response) {
routeRequest(lab, request, response).catch(function (error) {
refuse(request, response, 500, error.message)
})
})
function close() {
return new Promise(function (resolve) {
server.closeAllConnections()
server.close(function () {
rmSync(lab.root, { recursive: true, force: true })
resolve(!existsSync(lab.root))
})
})
}
return new Promise(function (resolve) {
server.listen(0, '127.0.0.1', function () {
resolve({ version: version, port: server.address().port, close: close })
})
})
}
================================================================
FILE 2 OF 6: fixtures.mjs
================================================================
// fixtures.mjs: builds the harmless fixture set in memory. Every file is
// marker text, a 1 by 1 pixel PNG, generated padding, or a zip archive whose
// entries are marker text files. Nothing here is a program, and the lab
// never extracts an archive. For learning, and for testing an upload
// feature you own.
import { crc32, deflateRawSync, deflateSync } from 'node:zlib'
import { SIZE_LIMIT_BYTES } from './upload-lab-server.mjs'
export const MARKER = 'UPLOAD-LAB-MARKER'
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
function markerText(id) {
return Buffer.from(MARKER + ' ' + id + ': plain text, not an image and not a program.\n')
}
function pngChunk(kind, data) {
const length = Buffer.alloc(4)
length.writeUInt32BE(data.length)
const kindAndData = Buffer.concat([Buffer.from(kind, 'latin1'), data])
const checksum = Buffer.alloc(4)
checksum.writeUInt32BE(crc32(kindAndData))
return Buffer.concat([length, kindAndData, checksum])
}
// A real PNG of one white pixel: signature, header chunk, pixel data, end.
export function makeTinyPng() {
const header = Buffer.alloc(13)
header.writeUInt32BE(1, 0)
header.writeUInt32BE(1, 4)
header.writeUInt8(8, 8)
header.writeUInt8(2, 9)
const pixelRow = Buffer.from([0, 255, 255, 255])
return Buffer.concat([
PNG_SIGNATURE,
pngChunk('IHDR', header),
pngChunk('IDAT', deflateSync(pixelRow)),
pngChunk('IEND', Buffer.alloc(0)),
])
}
// Generated filler that starts with the PNG signature, to a set size.
function makePadding(totalBytes) {
const padding = Buffer.alloc(totalBytes, 0x41)
PNG_SIGNATURE.copy(padding, 0)
return padding
}
function writeLocalHeader(entry) {
const header = Buffer.alloc(30)
header.writeUInt32LE(0x04034b50, 0)
header.writeUInt16LE(20, 4)
header.writeUInt16LE(8, 8)
header.writeUInt32LE(entry.checksum, 14)
header.writeUInt32LE(entry.packed.length, 18)
header.writeUInt32LE(entry.data.length, 22)
header.writeUInt16LE(entry.name.length, 26)
return header
}
function writeDirectoryHeader(entry, offset) {
const header = Buffer.alloc(46)
header.writeUInt32LE(0x02014b50, 0)
header.writeUInt16LE(20, 4)
header.writeUInt16LE(20, 6)
header.writeUInt16LE(8, 10)
header.writeUInt32LE(entry.checksum, 16)
header.writeUInt32LE(entry.packed.length, 20)
header.writeUInt32LE(entry.data.length, 24)
header.writeUInt16LE(entry.name.length, 28)
header.writeUInt32LE(offset, 42)
return header
}
function writeEndRecord(entryCount, directory, directoryOffset) {
const record = Buffer.alloc(22)
record.writeUInt32LE(0x06054b50, 0)
record.writeUInt16LE(entryCount, 8)
record.writeUInt16LE(entryCount, 10)
record.writeUInt32LE(directory.length, 12)
record.writeUInt32LE(directoryOffset, 16)
return record
}
// A zip archive of text entries, compressed with deflate. Every size it
// lists is the real one.
export function makeZip(files) {
const bodyParts = []
const directoryParts = []
let offset = 0
for (const file of files) {
const data = Buffer.from(file.text, 'utf8')
const entry = { name: Buffer.from(file.name, 'utf8'), data: data, packed: deflateRawSync(data), checksum: crc32(data) }
const localHeader = writeLocalHeader(entry)
bodyParts.push(localHeader, entry.name, entry.packed)
directoryParts.push(writeDirectoryHeader(entry, offset), entry.name)
offset = offset + localHeader.length + entry.name.length + entry.packed.length
}
const directory = Buffer.concat(directoryParts)
return Buffer.concat(bodyParts.concat([directory, writeEndRecord(files.length, directory, offset)]))
}
function makeManyEntries(count) {
const files = []
for (let index = 1; index <= count; index = index + 1) {
files.push({ name: 'notes/marker-' + index + '.txt', text: MARKER + ' A1 entry ' + index + '\n' })
}
return files
}
function makeArchives() {
const largeText = (MARKER + ' A2 line\n').repeat(60000)
return [
{ id: 'A1', group: 'archive', label: 'many entries', name: 'many-entries.zip', declaredType: 'application/zip', body: makeZip(makeManyEntries(200)) },
{ id: 'A2', group: 'archive', label: 'large total after extraction', name: 'large-total.zip', declaredType: 'application/zip', body: makeZip([{ name: 'big-marker.txt', text: largeText }]) },
{
id: 'A3', group: 'archive', label: 'entry names not to trust', name: 'untrusted-names.zip', declaredType: 'application/zip',
body: makeZip([
{ name: '../outside-marker.txt', text: MARKER + ' A3 one\n' },
{ name: '/absolute-marker.txt', text: MARKER + ' A3 two\n' },
{ name: 'docs/inside-marker.txt', text: MARKER + ' A3 three\n' },
]),
},
{
id: 'A4', group: 'archive', label: 'small, ordinary archive', name: 'small.zip', declaredType: 'application/zip',
body: makeZip([
{ name: 'docs/one.txt', text: MARKER + ' A4 one\n' },
{ name: 'docs/two.txt', text: MARKER + ' A4 two\n' },
{ name: 'three.txt', text: MARKER + ' A4 three\n' },
]),
},
]
}
export function buildFixtures() {
const png = makeTinyPng()
const signatureThenText = Buffer.concat([PNG_SIGNATURE, markerText('M2')])
return [
{ id: 'R1', group: 'baseline', label: 'real PNG', name: 'photo.png', declaredType: 'image/png', body: png },
{ id: 'R2', group: 'renamed', label: 'text renamed .png', name: 'photo.png', declaredType: 'image/png', body: markerText('R2') },
{ id: 'R3', group: 'renamed', label: 'double extension, .html last', name: 'photo.png.html', declaredType: 'image/png', body: markerText('R3') },
{ id: 'R4', group: 'renamed', label: 'double extension, .png last', name: 'notes.html.png', declaredType: 'image/png', body: markerText('R4') },
{ id: 'R5', group: 'renamed', label: 'real PNG, upper-case name', name: 'HOLIDAY.PNG', declaredType: 'image/png', body: png },
{ id: 'R6', group: 'renamed', label: 'text, upper-case .HTML', name: 'notes.HTML', declaredType: 'image/png', body: markerText('R6') },
{ id: 'M1', group: 'mismatch', label: 'real PNG declared text/html', name: 'photo.png', declaredType: 'text/html', body: png },
{ id: 'M2', group: 'mismatch', label: 'PNG signature, then text', name: 'photo.png', declaredType: 'image/png', body: signatureThenText },
{ id: 'M3', group: 'mismatch', label: 'real PNG named .html', name: 'photo.html', declaredType: 'image/png', body: png },
{ id: 'S1', group: 'oversized', label: 'one byte over, with Content-Length', name: 'big.png', declaredType: 'image/png', body: makePadding(SIZE_LIMIT_BYTES + 1) },
{ id: 'S2', group: 'oversized', label: 'over the limit, no Content-Length', name: 'big-stream.png', declaredType: 'image/png', body: makePadding(300000), chunked: true },
].concat(makeArchives())
}
export function findFixture(fixtures, id) {
return fixtures.find(function (fixture) {
return fixture.id === id
})
}
================================================================
FILE 3 OF 6: archive-check.mjs
================================================================
// archive-check.mjs: checks a zip archive before anything is extracted.
// Stage one reads the archive's own list of entries; stage two inflates
// each entry in memory with a cap on its output. It never writes a file.
// Illustration only.
import { inflateRawSync } from 'node:zlib'
// The lab's own limits, picked for the illustration.
export const ARCHIVE_LIMITS = { maxEntries: 100, maxTotalBytes: 1000000 }
const END_RECORD_SIGNATURE = 0x06054b50
const DIRECTORY_ENTRY_SIGNATURE = 0x02014b50
function findEndRecord(archive) {
for (let position = archive.length - 22; position >= 0; position = position - 1) {
if (archive.readUInt32LE(position) === END_RECORD_SIGNATURE) return position
}
throw new Error('no end record found, so this is not a zip archive')
}
function readDirectoryEntry(archive, position) {
if (archive.readUInt32LE(position) !== DIRECTORY_ENTRY_SIGNATURE) throw new Error('damaged directory entry')
const nameLength = archive.readUInt16LE(position + 28)
const extraLength = archive.readUInt16LE(position + 30)
const commentLength = archive.readUInt16LE(position + 32)
return {
name: archive.toString('utf8', position + 46, position + 46 + nameLength),
method: archive.readUInt16LE(position + 10),
packedBytes: archive.readUInt32LE(position + 20),
listedBytes: archive.readUInt32LE(position + 24),
localOffset: archive.readUInt32LE(position + 42),
nextPosition: position + 46 + nameLength + extraLength + commentLength,
}
}
// The entries the archive says it holds. Every value here is the archive's
// own claim, written by whoever made it.
export function listEntries(archive) {
const endRecord = findEndRecord(archive)
const entryCount = archive.readUInt16LE(endRecord + 10)
let position = archive.readUInt32LE(endRecord + 16)
const entries = []
for (let index = 0; index < entryCount; index = index + 1) {
const entry = readDirectoryEntry(archive, position)
entries.push(entry)
position = entry.nextPosition
}
return entries
}
// Why a name cannot be used as a path, or null when it can. See the path
// traversal guide for resolving and checking real paths.
export function describeUntrustedName(name) {
if (name === '') return 'is empty'
if (name.startsWith('/')) return 'is an absolute path'
if (name.includes('\\') || name.includes(':')) return 'contains a backslash or a colon'
if (name.split('/').includes('..')) return 'climbs out of the folder with ..'
return null
}
function checkListing(entries, limits) {
const problems = []
if (entries.length > limits.maxEntries) {
problems.push(entries.length + ' entries listed, over the limit of ' + limits.maxEntries)
}
let listedTotal = 0
for (const entry of entries) {
const nameProblem = describeUntrustedName(entry.name)
if (nameProblem) problems.push('entry name ' + entry.name + ' ' + nameProblem)
listedTotal = listedTotal + entry.listedBytes
}
if (listedTotal > limits.maxTotalBytes) {
problems.push(listedTotal + ' bytes listed after extraction, over the limit of ' + limits.maxTotalBytes)
}
return problems
}
// Inflates one entry in memory and throws once the output passes maxBytes.
export function inflateEntry(archive, entry, maxBytes) {
const nameLength = archive.readUInt16LE(entry.localOffset + 26)
const extraLength = archive.readUInt16LE(entry.localOffset + 28)
const start = entry.localOffset + 30 + nameLength + extraLength
const packed = archive.subarray(start, start + entry.packedBytes)
if (entry.method !== 8) throw new Error('compression method ' + entry.method + ' is not handled by this check')
return inflateRawSync(packed, { maxOutputLength: maxBytes + 1 })
}
// Stage two: the listed sizes are claims, so count the real bytes.
function checkInflatedSizes(archive, entries, limits) {
let remaining = limits.maxTotalBytes
for (const entry of entries) {
let data
try {
data = inflateEntry(archive, entry, remaining)
} catch (error) {
return 'inflating ' + entry.name + ' stopped: ' + (error.code || error.message)
}
if (data.length > remaining) return 'inflating ' + entry.name + ' passed the limit of ' + limits.maxTotalBytes + ' bytes'
if (data.length !== entry.listedBytes) return entry.name + ' inflated to ' + data.length + ' bytes but lists ' + entry.listedBytes
remaining = remaining - data.length
}
return null
}
export function checkArchive(archive, limits) {
const entries = listEntries(archive)
const problems = checkListing(entries, limits)
if (problems.length > 0) return { verdict: 'REJECT', stage: 'listing', problems: problems }
const sizeProblem = checkInflatedSizes(archive, entries, limits)
if (sizeProblem) return { verdict: 'REJECT', stage: 'inflating', problems: [sizeProblem] }
let total = 0
for (const entry of entries) total = total + entry.listedBytes
return { verdict: 'PASS', stage: 'both', problems: [], summary: entries.length + ' entries, ' + total + ' bytes after extraction, every name relative' }
}
================================================================
FILE 4 OF 6: lab-client.mjs
================================================================
// lab-client.mjs: sends one fixture to a running lab and fetches a
// download, using node:http so every header is visible. Illustration only.
import { request } from 'node:http'
export const DOWNLOAD_HEADERS = ['Content-Type', 'X-Content-Type-Options', 'Content-Disposition', 'Content-Security-Policy']
function readJson(response, resolve) {
const chunks = []
response.on('data', function (chunk) {
chunks.push(chunk)
})
response.on('end', function () {
resolve({ status: response.statusCode, body: JSON.parse(Buffer.concat(chunks).toString('utf8')) })
})
}
// Writes the body in one piece, or in 16 KB pieces with no Content-Length,
// which node:http then sends with chunked transfer encoding.
function writeBody(outgoing, fixture) {
if (!fixture.chunked) return outgoing.end(fixture.body)
for (let start = 0; start < fixture.body.length; start = start + 16384) {
outgoing.write(fixture.body.subarray(start, start + 16384))
}
outgoing.end()
}
export function sendUpload(port, fixture) {
return new Promise(function (resolve, reject) {
const headers = { 'Content-Type': fixture.declaredType }
if (!fixture.chunked) headers['Content-Length'] = fixture.body.length
const outgoing = request({
host: '127.0.0.1',
port: port,
method: 'POST',
path: '/upload?name=' + encodeURIComponent(fixture.name),
headers: headers,
})
let answered = false
outgoing.on('response', function (response) {
answered = true
readJson(response, resolve)
})
// A server that refuses early may close the connection while the body
// is still being sent. Once an answer has arrived, that is expected.
outgoing.on('error', function (error) {
if (!answered) reject(error)
})
writeBody(outgoing, fixture)
})
}
export function fetchDownload(port, path) {
return new Promise(function (resolve, reject) {
const outgoing = request({ host: '127.0.0.1', port: port, method: 'GET', path: path })
outgoing.on('response', function (response) {
const headers = {}
for (const name of DOWNLOAD_HEADERS) headers[name] = response.headers[name.toLowerCase()] || null
response.resume()
response.on('end', function () {
resolve({ status: response.statusCode, headers: headers })
})
})
outgoing.on('error', reject)
outgoing.end()
})
}
// The stored file's own name, requested from the folder a flawed server
// serves. The fixed server has no such route, so this should be 404.
export function directPathFor(storedAs) {
const parts = storedAs.split('/')
return '/uploads/' + encodeURIComponent(parts.pop())
}
================================================================
FILE 5 OF 6: run-fixtures.mjs
================================================================
// run-fixtures.mjs: sends every fixture to both versions and prints what
// each accepted, where it stored it and the download response headers,
// then runs the archive check. Run with: node run-fixtures.mjs
import { ARCHIVE_LIMITS, checkArchive, inflateEntry, listEntries } from './archive-check.mjs'
import { buildFixtures, findFixture } from './fixtures.mjs'
import { DOWNLOAD_HEADERS, directPathFor, fetchDownload, sendUpload } from './lab-client.mjs'
import { SIZE_LIMIT_BYTES, startUploadLab } from './upload-lab-server.mjs'
const INDENT = ' '
function describeSent(fixture) {
const framing = fixture.chunked ? 'no Content-Length (chunked)' : 'Content-Length ' + fixture.body.length
return ' sent: name ' + fixture.name + ', declared ' + fixture.declaredType + ', ' + fixture.body.length + ' bytes, ' + framing
}
// One line per header that was sent, then one line naming those missing.
function printHeaders(headers) {
const missing = []
for (const name of DOWNLOAD_HEADERS) {
if (headers[name] === null) missing.push(name)
else console.log(INDENT + name + ': ' + headers[name])
}
if (missing.length > 0) console.log(INDENT + 'missing: ' + missing.join(', '))
}
async function reportOneVersion(lab, fixture, storedNames) {
const label = ' ' + lab.version.padEnd(7)
const upload = await sendUpload(lab.port, fixture)
if (!upload.body.accepted) {
console.log(label + 'REFUSED ' + upload.status + ' ' + upload.body.reason)
return
}
storedNames.push(upload.body.storedAs)
console.log(label + 'ACCEPTED ' + upload.status + ' stored as ' + upload.body.storedAs)
const download = await fetchDownload(lab.port, upload.body.downloadPath)
console.log(INDENT + 'GET ' + upload.body.downloadPath + ' ' + download.status)
printHeaders(download.headers)
const directPath = directPathFor(upload.body.storedAs)
if (directPath === upload.body.downloadPath) return
const direct = await fetchDownload(lab.port, directPath)
console.log(INDENT + 'GET ' + directPath + ' ' + direct.status + ' (stored name requested directly)')
}
function reportOverwrites(version, storedNames) {
const distinct = new Set(storedNames).size
const overwritten = storedNames.length - distinct
console.log(version + ': ' + storedNames.length + ' uploads accepted, ' + distinct + ' distinct stored names, ' + overwritten + ' replaced an earlier file')
}
function reportArchives(fixtures) {
console.log('ARCHIVE CHECK (limits: ' + ARCHIVE_LIMITS.maxEntries + ' entries, ' + ARCHIVE_LIMITS.maxTotalBytes + ' bytes after extraction)')
for (const fixture of fixtures.filter(function (item) { return item.group === 'archive' })) {
const result = checkArchive(fixture.body, ARCHIVE_LIMITS)
const detail = result.verdict === 'PASS' ? result.summary : 'at ' + result.stage + ': ' + result.problems.join('; ')
console.log(' ' + fixture.id + ' ' + fixture.name.padEnd(20) + result.verdict + ' ' + detail)
}
// Stage two on its own: what happens if the listed sizes had been false.
const largeArchive = findFixture(fixtures, 'A2').body
const cap = 'A2 entry inflated in memory with a cap of ' + ARCHIVE_LIMITS.maxTotalBytes + ' bytes: '
try {
inflateEntry(largeArchive, listEntries(largeArchive)[0], ARCHIVE_LIMITS.maxTotalBytes)
console.log(' ' + cap + 'not stopped')
} catch (error) {
console.log(' ' + cap + 'stopped with ' + (error.code || error.message))
}
}
async function main() {
const fixtures = buildFixtures()
const labs = [await startUploadLab('flawed'), await startUploadLab('fixed')]
const storedNames = { flawed: [], fixed: [] }
console.log('Node.js ' + process.version + ', upload size limit ' + SIZE_LIMIT_BYTES + ' bytes')
console.log('')
for (const fixture of fixtures) {
console.log(fixture.id + ' ' + fixture.group + ': ' + fixture.label)
console.log(describeSent(fixture))
for (const lab of labs) await reportOneVersion(lab, fixture, storedNames[lab.version])
console.log('')
}
for (const lab of labs) reportOverwrites(lab.version, storedNames[lab.version])
console.log('')
reportArchives(fixtures)
console.log('')
const removed = []
for (const lab of labs) removed.push(lab.version + ' ' + ((await lab.close()) ? 'yes' : 'NO'))
console.log('Temporary folders removed: ' + removed.join(', '))
}
main()
================================================================
FILE 6 OF 6: upload.test.mjs
================================================================
// upload.test.mjs: the verification checks as a regression test, on Node's
// built-in test runner. Run with:
// node upload.test.mjs checks the fixed version, which passes
// node upload.test.mjs flawed checks the flawed version, which fails
import { after, before, test } from 'node:test'
import assert from 'node:assert/strict'
import { ARCHIVE_LIMITS, checkArchive } from './archive-check.mjs'
import { MARKER, buildFixtures, findFixture, makeZip } from './fixtures.mjs'
import { directPathFor, fetchDownload, sendUpload } from './lab-client.mjs'
import { startUploadLab } from './upload-lab-server.mjs'
const version = process.argv[2] || 'fixed'
const fixtures = buildFixtures()
const GENERATED_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[.]png$/
let lab
before(async function () {
lab = await startUploadLab(version)
})
after(async function () {
await lab.close()
})
function upload(id) {
return sendUpload(lab.port, findFixture(fixtures, id))
}
// Rewrites a one-entry archive so it lists 100 bytes for its entry while
// still holding the full text: a modest stand-in for a misleading archive.
function understateListedSize(archive) {
const directoryOffset = archive.readUInt32LE(archive.length - 22 + 16)
archive.writeUInt32LE(100, 22)
archive.writeUInt32LE(100, directoryOffset + 24)
return archive
}
test('1. a real PNG is accepted (R1)', async function () {
const result = await upload('R1')
assert.equal(result.body.accepted, true, 'R1 was refused: ' + result.body.reason)
})
test('2. renamed and double extensions are refused (R2, R3, R4, R6)', async function () {
for (const id of ['R2', 'R3', 'R4', 'R6']) {
const result = await upload(id)
assert.equal(result.body.accepted, false, id + ' was accepted and stored as ' + result.body.storedAs)
}
})
test('3. the server decides the type, not the declared type (M1, M3)', async function () {
const declaredWrong = await upload('M1')
assert.equal(declaredWrong.body.accepted, true, 'M1, a real PNG declared text/html, was refused')
const namedWrong = await upload('M3')
assert.equal(namedWrong.body.accepted, false, 'M3, a real PNG named photo.html, was accepted')
})
test('4. uploads over the limit are refused, with or without Content-Length (S1, S2)', async function () {
for (const id of ['S1', 'S2']) {
const result = await upload(id)
assert.equal(result.status, 413, id + ' answered ' + result.status)
}
})
test('5. the stored name is generated by the server (R5)', async function () {
const result = await upload('R5')
const storedName = String(result.body.storedAs).split('/').pop()
assert.match(storedName, GENERATED_NAME, 'R5 was stored as ' + storedName)
})
test('6. stored files cannot be fetched by stored or uploaded name (R1)', async function () {
const result = await upload('R1')
for (const path of [directPathFor(result.body.storedAs), '/uploads/photo.png']) {
const response = await fetchDownload(lab.port, path)
assert.equal(response.status, 404, path + ' answered ' + response.status)
}
})
test('7. downloads carry a fixed type, nosniff, attachment and a sandbox policy (R1, M2)', async function () {
for (const id of ['R1', 'M2']) {
const result = await upload(id)
const headers = (await fetchDownload(lab.port, result.body.downloadPath)).headers
assert.equal(headers['Content-Type'], 'image/png', id + ' Content-Type')
assert.equal(headers['X-Content-Type-Options'], 'nosniff', id + ' X-Content-Type-Options')
assert.match(String(headers['Content-Disposition']), /^attachment;/, id + ' Content-Disposition')
assert.equal(headers['Content-Security-Policy'], 'sandbox', id + ' Content-Security-Policy')
}
})
test('8. this endpoint refuses archives (A1 to A4)', async function () {
for (const id of ['A1', 'A2', 'A3', 'A4']) {
const result = await upload(id)
assert.equal(result.body.accepted, false, id + ' was accepted and stored as ' + result.body.storedAs)
}
})
test('9. the archive check refuses A1 to A3 from the listing and passes A4', function () {
for (const id of ['A1', 'A2', 'A3']) {
const result = checkArchive(findFixture(fixtures, id).body, ARCHIVE_LIMITS)
assert.equal(result.stage, 'listing', id + ' reached stage ' + result.stage)
}
assert.equal(checkArchive(findFixture(fixtures, 'A4').body, ARCHIVE_LIMITS).verdict, 'PASS')
})
test('10. an archive that understates its size is stopped while inflating', function () {
const archive = makeZip([{ name: 'big-marker.txt', text: (MARKER + ' T10 line\n').repeat(60000) }])
const result = checkArchive(understateListedSize(archive), ARCHIVE_LIMITS)
assert.equal(result.verdict, 'REJECT')
assert.equal(result.stage, 'inflating', 'the check stopped at ' + result.stage)
})
================================================================
PART 4: SEND EVERY FIXTURE TO BOTH VERSIONS
================================================================
Command: node run-fixtures.mjs
Node.js v26.0.0, upload size limit 65536 bytes
R1 baseline: real PNG
sent: name photo.png, declared image/png, 69 bytes, Content-Length 69
flawed ACCEPTED 201 stored as public/photo.png
GET /uploads/photo.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed ACCEPTED 201 stored as store/0fe3f271-f9e6-4420-876b-c907df256e2a.png
GET /files/0fe3f271-f9e6-4420-876b-c907df256e2a 200
Content-Type: image/png
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="0fe3f271-f9e6-4420-876b-c907df256e2a.png"
Content-Security-Policy: sandbox
GET /uploads/0fe3f271-f9e6-4420-876b-c907df256e2a.png 404 (stored name requested directly)
R2 renamed: text renamed .png
sent: name photo.png, declared image/png, 66 bytes, Content-Length 66
flawed ACCEPTED 201 stored as public/photo.png
GET /uploads/photo.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 leading bytes do not match the image/png signature
R3 renamed: double extension, .html last
sent: name photo.png.html, declared image/png, 66 bytes, Content-Length 66
flawed ACCEPTED 201 stored as public/photo.png.html
GET /uploads/photo.png.html 200
Content-Type: text/html
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .html is not on the allow-list
R4 renamed: double extension, .png last
sent: name notes.html.png, declared image/png, 66 bytes, Content-Length 66
flawed ACCEPTED 201 stored as public/notes.html.png
GET /uploads/notes.html.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 leading bytes do not match the image/png signature
R5 renamed: real PNG, upper-case name
sent: name HOLIDAY.PNG, declared image/png, 69 bytes, Content-Length 69
flawed ACCEPTED 201 stored as public/HOLIDAY.PNG
GET /uploads/HOLIDAY.PNG 200
missing: Content-Type, X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed ACCEPTED 201 stored as store/3903b0d0-34ae-4faf-a3c7-12859df7d2f2.png
GET /files/3903b0d0-34ae-4faf-a3c7-12859df7d2f2 200
Content-Type: image/png
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="3903b0d0-34ae-4faf-a3c7-12859df7d2f2.png"
Content-Security-Policy: sandbox
GET /uploads/3903b0d0-34ae-4faf-a3c7-12859df7d2f2.png 404 (stored name requested directly)
R6 renamed: text, upper-case .HTML
sent: name notes.HTML, declared image/png, 66 bytes, Content-Length 66
flawed ACCEPTED 201 stored as public/notes.HTML
GET /uploads/notes.HTML 200
missing: Content-Type, X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .html is not on the allow-list
M1 mismatch: real PNG declared text/html
sent: name photo.png, declared text/html, 69 bytes, Content-Length 69
flawed REFUSED 415 declared type text/html is not accepted
fixed ACCEPTED 201 stored as store/3d2e9cd3-6ff1-489e-8b33-fce47c4a58ce.png
GET /files/3d2e9cd3-6ff1-489e-8b33-fce47c4a58ce 200
Content-Type: image/png
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="3d2e9cd3-6ff1-489e-8b33-fce47c4a58ce.png"
Content-Security-Policy: sandbox
GET /uploads/3d2e9cd3-6ff1-489e-8b33-fce47c4a58ce.png 404 (stored name requested directly)
M2 mismatch: PNG signature, then text
sent: name photo.png, declared image/png, 74 bytes, Content-Length 74
flawed ACCEPTED 201 stored as public/photo.png
GET /uploads/photo.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed ACCEPTED 201 stored as store/7599af10-cec3-4f5d-9e13-e4ef200d838e.png
GET /files/7599af10-cec3-4f5d-9e13-e4ef200d838e 200
Content-Type: image/png
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="7599af10-cec3-4f5d-9e13-e4ef200d838e.png"
Content-Security-Policy: sandbox
GET /uploads/7599af10-cec3-4f5d-9e13-e4ef200d838e.png 404 (stored name requested directly)
M3 mismatch: real PNG named .html
sent: name photo.html, declared image/png, 69 bytes, Content-Length 69
flawed ACCEPTED 201 stored as public/photo.html
GET /uploads/photo.html 200
Content-Type: text/html
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .html is not on the allow-list
S1 oversized: one byte over, with Content-Length
sent: name big.png, declared image/png, 65537 bytes, Content-Length 65537
flawed ACCEPTED 201 stored as public/big.png
GET /uploads/big.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 413 Content-Length 65537 is over the limit, body not read
S2 oversized: over the limit, no Content-Length
sent: name big-stream.png, declared image/png, 300000 bytes, no Content-Length (chunked)
flawed ACCEPTED 201 stored as public/big-stream.png
GET /uploads/big-stream.png 200
Content-Type: image/png
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 413 stopped keeping data after 81920 bytes, over the limit
A1 archive: many entries
sent: name many-entries.zip, declared application/zip, 29498 bytes, Content-Length 29498
flawed ACCEPTED 201 stored as public/many-entries.zip
GET /uploads/many-entries.zip 200
Content-Type: application/zip
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .zip is not on the allow-list
A2 archive: large total after extraction
sent: name large-total.zip, declared application/zip, 3957 bytes, Content-Length 3957
flawed ACCEPTED 201 stored as public/large-total.zip
GET /uploads/large-total.zip 200
Content-Type: application/zip
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .zip is not on the allow-list
A3 archive: entry names not to trust
sent: name untrusted-names.zip, declared application/zip, 459 bytes, Content-Length 459
flawed ACCEPTED 201 stored as public/untrusted-names.zip
GET /uploads/untrusted-names.zip 200
Content-Type: application/zip
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .zip is not on the allow-list
A4 archive: small, ordinary archive
sent: name small.zip, declared application/zip, 399 bytes, Content-Length 399
flawed ACCEPTED 201 stored as public/small.zip
GET /uploads/small.zip 200
Content-Type: application/zip
missing: X-Content-Type-Options, Content-Disposition, Content-Security-Policy
fixed REFUSED 415 extension .zip is not on the allow-list
flawed: 14 uploads accepted, 12 distinct stored names, 2 replaced an earlier file
fixed: 4 uploads accepted, 4 distinct stored names, 0 replaced an earlier file
ARCHIVE CHECK (limits: 100 entries, 1000000 bytes after extraction)
A1 many-entries.zip REJECT at listing: 200 entries listed, over the limit of 100
A2 large-total.zip REJECT at listing: 1560000 bytes listed after extraction, over the limit of 1000000
A3 untrusted-names.zip REJECT at listing: entry name ../outside-marker.txt climbs out of the folder with ..; entry name /absolute-marker.txt is an absolute path
A4 small.zip PASS 3 entries, 77 bytes after extraction, every name relative
A2 entry inflated in memory with a cap of 1000000 bytes: stopped with ERR_BUFFER_TOO_LARGE
Temporary folders removed: flawed yes, fixed yes
The process exited with code 0.
Reading the output:
Renamed extensions Flawed: accepted R2 to R6 under the names sent, served R3 as text/html, and served R5 and R6 with no Content-Type because its type table only had lowercase keys. Fixed: refused R2, R3, R4 and R6, and accepted R5 because it compares extensions without regard to case.
Mismatched types Flawed: refused the real PNG declared text/html (M1) and accepted the PNG named photo.html (M3), then served it as text/html. Fixed: accepted M1 as image/png, refused M3, and accepted M2, whose first eight bytes are a PNG signature.
Oversized files Flawed: stored both. Fixed: refused S1 from its Content-Length before reading the body, and S2, which had no Content-Length, once the count passed the limit.
Archives Flawed: stored all four in the served folder. Fixed: refused all four at the upload. The archive check refused A1, A2 and A3 from the listing alone and passed A4, and A2's entry, inflated on its own with a cap, stopped with ERR_BUFFER_TOO_LARGE.
Names and storage Flawed: three uploads named photo.png left one file. Fixed: every accepted file got a generated name in store/, and every request for a stored name under /uploads/ answered 404.
Download headers Flawed: none of its downloads sent nosniff, Content-Disposition or a Content-Security-Policy. Fixed: every download sent image/png, nosniff, attachment and sandbox, M2 included.
================================================================
PART 5: THE REGRESSION TEST
================================================================
The same checks on Node's built-in test runner. Keep it in the pipeline that deploys your upload feature.
Command: node upload.test.mjs
✔ 1. a real PNG is accepted (R1) (10.15125ms)
✔ 2. renamed and double extensions are refused (R2, R3, R4, R6) (2.698541ms)
✔ 3. the server decides the type, not the declared type (M1, M3) (2.015167ms)
✔ 4. uploads over the limit are refused, with or without Content-Length (S1, S2) (1.327125ms)
✔ 5. the stored name is generated by the server (R5) (0.706917ms)
✔ 6. stored files cannot be fetched by stored or uploaded name (R1) (1.121416ms)
✔ 7. downloads carry a fixed type, nosniff, attachment and a sandbox policy (R1, M2) (1.332709ms)
✔ 8. this endpoint refuses archives (A1 to A4) (1.139ms)
✔ 9. the archive check refuses A1 to A3 from the listing and passes A4 (0.700709ms)
✔ 10. an archive that understates its size is stopped while inflating (3.828666ms)
ℹ tests 10
ℹ suites 0
ℹ pass 10
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 31.666125
The process exited with code 0.
Command: node upload.test.mjs flawed
✔ 1. a real PNG is accepted (R1) (10.113333ms)
✖ 2. renamed and double extensions are refused (R2, R3, R4, R6) (1.455708ms)
✖ 3. the server decides the type, not the declared type (M1, M3) (0.836625ms)
✖ 4. uploads over the limit are refused, with or without Content-Length (S1, S2) (1.486583ms)
✖ 5. the stored name is generated by the server (R5) (0.862708ms)
✖ 6. stored files cannot be fetched by stored or uploaded name (R1) (2.12275ms)
✖ 7. downloads carry a fixed type, nosniff, attachment and a sandbox policy (R1, M2) (0.895459ms)
✖ 8. this endpoint refuses archives (A1 to A4) (0.590875ms)
✔ 9. the archive check refuses A1 to A3 from the listing and passes A4 (0.65475ms)
✔ 10. an archive that understates its size is stopped while inflating (3.903333ms)
ℹ tests 10
ℹ suites 0
ℹ pass 3
ℹ fail 7
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 29.36075
✖ failing tests:
test at upload.test.mjs:43:1
✖ 2. renamed and double extensions are refused (R2, R3, R4, R6) (1.455708ms)
AssertionError [ERR_ASSERTION]: R2 was accepted and stored as public/photo.png
(stack trace and error details removed here)
test at upload.test.mjs:50:1
✖ 3. the server decides the type, not the declared type (M1, M3) (0.836625ms)
AssertionError [ERR_ASSERTION]: M1, a real PNG declared text/html, was refused
(stack trace and error details removed here)
test at upload.test.mjs:57:1
✖ 4. uploads over the limit are refused, with or without Content-Length (S1, S2) (1.486583ms)
AssertionError [ERR_ASSERTION]: S1 answered 201
(stack trace and error details removed here)
test at upload.test.mjs:64:1
✖ 5. the stored name is generated by the server (R5) (0.862708ms)
AssertionError [ERR_ASSERTION]: R5 was stored as HOLIDAY.PNG
(stack trace and error details removed here)
test at upload.test.mjs:70:1
✖ 6. stored files cannot be fetched by stored or uploaded name (R1) (2.12275ms)
AssertionError [ERR_ASSERTION]: /uploads/photo.png answered 200
(stack trace and error details removed here)
test at upload.test.mjs:78:1
✖ 7. downloads carry a fixed type, nosniff, attachment and a sandbox policy (R1, M2) (0.895459ms)
AssertionError [ERR_ASSERTION]: R1 X-Content-Type-Options
(stack trace and error details removed here)
test at upload.test.mjs:89:1
✖ 8. this endpoint refuses archives (A1 to A4) (0.590875ms)
AssertionError [ERR_ASSERTION]: A1 was accepted and stored as public/many-entries.zip
(stack trace and error details removed here)
The process exited with code 1, so a pipeline step running the test fails.
Checks 1, 9 and 10 pass on both versions. Check 1 confirms a real PNG still gets through, so the fixed version is not passing by refusing everything. Checks 9 and 10 test the archive check, which both versions share; check 10 edits a modest archive so its listing understates the size of its one entry, and the check stops it while inflating.
================================================================
PART 6: POINT THE CHECKS AT YOUR OWN UPLOAD FEATURE
================================================================
1. Copy fixtures.mjs, lab-client.mjs and upload.test.mjs into your project's tests.
2. Change sendUpload to the format your endpoint expects. For a browser form, build a multipart/form-data body with the fixture's name as the part's filename and its declared type as the part's Content-Type.
3. Point the port and paths at a local or staging copy, signed in as a test account, and replace directPathFor with every public path your server serves files from.
4. Match the fixtures to your allow-list. If you accept JPEG or PDF, add a real file of that type as a baseline and keep a renamed, a double-extension, an upper-case and a mismatched case for it.
5. Record each response, where the file landed and its download headers against the four checks in Part 2.
6. Delete every file the run uploaded, and do not upload over a file you did not create.What a file upload vulnerability is
An upload feature is a way for a stranger to put a file on your server.
A profile photo, a CV on a careers form, an invoice attached to a quote request: in each case someone outside your business chooses the bytes, the name and the type the file claims to be, and your server keeps the result. OWASP's page on unrestricted file upload puts it plainly: the first step in many attacks is to get some code onto the system being attacked, the attack then only needs a way to get that code run, and a file upload helps with the first step.
A file upload vulnerability is any way that file, or what the server does with it, causes harm. OWASP lists consequences including complete system takeover, an overloaded file system or database, attacks forwarded to back-end systems, client-side attacks and simple defacement, and says which one applies depends on what the application does with the file and especially where it is stored.
It separates two kinds of problem: the file's metadata, such as its path and name, which can trick an application into overwriting a critical file or storing the file in a bad location, and the file's size or content.
MITRE catalogues the weakness as CWE-434, Unrestricted Upload of File with Dangerous Type: the product allows the upload or transfer of dangerous file types that are automatically processed within its environment. MITRE lists unrestricted file upload as an alternate term and calls that phrase insufficiently precise, because it could be read as a lack of limits on the size or number of uploaded files, which is a resource consumption issue.
This guide covers both meanings: what the server accepts, how it decides what a file is, where it puts it, what it calls it and how it hands it back.
Neighbouring guides in this library take the rest. When a server runs a stored file as code, the remote code execution guide covers what that process can then reach. File names that climb out of a folder, and archive entries that do the same on extraction, belong to the path traversal guide.
The web server settings that decide what may run inside an upload folder are a security misconfiguration question. Uploaded files that the wrong people can open are a sensitive data exposure question. The WordPress guide covers that platform's roles and plugins beyond the upload handler.
Content type validation: the name, extension and type are all claims
Every detail that arrives with an upload comes from the uploader.
In a browser form, the file travels as one part of a multipart/form-data body, and its name arrives as the filename parameter of that part's Content-Disposition header. MDN describes that parameter as the original name of the file transmitted, providing mostly indicative information, and repeats RFC 2183's advice to strip any path information and not to overwrite an existing file.
Nothing obliges the sender to use your form: OWASP's unrestricted upload page notes that a check on the request's Content-Type header can be bypassed by changing the header with a web proxy.
OWASP's File Upload Cheat Sheet is direct about the declared type. The Content-Type for uploaded files is provided by the user, cannot be trusted and is trivial to spoof. It still gives that check a job: it should not be relied on for security, but it is a quick check that stops people uploading a file of the wrong type by mistake.
The extension is a claim too. The WHATWG MIME Sniffing Standard says file extensions are not used to determine the supplied MIME type of a resource retrieved over HTTP because they are unreliable and easily spoofed. MITRE has a separate weakness for trusting them, CWE-646: an upload feature that relies on the file name or extension to decide what to do with a file, which attackers could use to have the file misclassified and processed in a dangerous fashion.
Its mitigation is to make decisions on the server side based on file content and not on file name or extension.
Where an extension is checked, the check has known weak points. The cheat sheet asks for validation after the file name has been decoded, and lists bypasses to filter against, including double extensions, null bytes, changes of letter case, alternative extensions that a server may map to the same interpreter depending on its configuration, and Windows NTFS alternate data streams, for which it says to reject any file name containing a colon.
CWE-434 adds two of its own: allow only one extension in a file name, because some web servers, including some versions of Apache, may process files based on inner extensions, and compare extensions without regard to case when the web server supports case-insensitive file names.
The cheat sheet calls blocking specific extensions a weak protection method on its own, so start from an allow-list of the few types the feature needs.
Checks in the browser do not count. CWE-434 says to duplicate on the server side any security check performed on the client side, because attackers can change values after the check has run or remove the check entirely. WSTG-BUSL-08 lists three shortcuts to look for: checking the file type only in client-side JavaScript, only by the Content-Type of the request, or only by the extension.
The lab's flawed version shows what trusting the declared type does. It accepted R2, a text file named photo.png and declared image/png, and refused M1, a real PNG declared text/html. The fixed version did the opposite on both, because it ignores the declared type and decides from the extension and the bytes.
What checking the leading bytes proves, and what it does not
Some formats begin with a fixed sequence of bytes, which ASVS calls magic bytes and MDN calls magic numbers.
MDN's guide to MIME types gives two examples: GIF files start with 47 49 46 38 39 (GIF89) and PNG files with 89 50 4E 47. The MIME Sniffing Standard's pattern table gives the full eight-byte PNG signature, 89 50 4E 47 0D 0A 1A 0A, which is what the lab's fixed version compares.
Reading those bytes on the server is a check that a renamed text file cannot pass: R2 and R4, text files whose names end in .png, were refused because their first bytes were text.
What the check proves is narrow. It confirms that the first eight bytes match and says nothing about the rest of the file. MDN notes that not all file types have magic numbers, so inferring a type from bytes is not completely reliable either.
OWASP's cheat sheet describes a signature check as one to run in conjunction with content-type validation, and says it should not be used on its own, as bypassing it is pretty common and easy.
OWASP's unrestricted upload page explains why: a check that reads only the first few characters can be passed by putting other content after a valid header or inside the file's metadata. CWE-434 says not to rely exclusively on sanity checks of file contents, since it may be possible to hide code in parts of a file that the server will still execute, and gives the free-form comment field in GIF images as an example.
Fixture M2 shows the limit. It is the PNG signature followed by a line of marker text, named photo.png and declared image/png, and the fixed version accepted it. That is the expected result, and it is why the next section matters more than this one.
M2 was stored under a generated name outside any served folder and came back as image/png with nosniff and attachment, so a browser that honours those headers uses the type as given and offers the file as a download rather than rendering it.
ASVS 5.0 requirement 5.2.2, at Level 1, asks for both halves: the extension must match an expected extension, and the contents must correspond to the type the extension represents, which includes, but is not limited to, checking the initial magic bytes, image re-writing and specialised libraries for file content validation.
At Level 1 this can focus on files used to make specific business or security decisions; from Level 2 up it applies to every file accepted.
The lab uses only modules that ship with Node.js, so it stops at the extension and the leading bytes; re-writing is covered in the section on images and documents below.
File upload security best practices: storage, names and download headers
OWASP's cheat sheet says there is no silver bullet in validating user content, that defence in depth is key, and that no one technique is enough to secure the service.
The controls that still hold when a file gets past a check are the ones about where it lives, what it is called and how it leaves, because they decide what a file that got through can do.
ASVS 5.0 requirement 5.3.1, at Level 1, asks that files uploaded or generated by untrusted input and stored in a public folder are not executed as server-side program code when requested directly over HTTP. CWE-434 goes further: consider storing uploads outside the web document root entirely and delivering them through other mechanisms.
The cheat sheet ranks the options: a different host first, then outside the web root with administrative access only, then inside the web root with write permissions only and proper controls if read access is needed.
For files the public must reach, it suggests a handler that maps an ID to a file inside the application, which is what the fixed version's /files/ route does.
Two more details come from the same sources. An attacker may try to upload a web server configuration file such as .htaccess or web.config into the upload folder, so the cheat sheet recommends turning off per-directory configuration overrides there, for example with Apache's AllowOverride None, as a second layer on top of storing files outside the web root.
OWASP's unrestricted upload page recommends removing execute permission and every script handler from upload folders, and, where files are saved on a file system, considering an isolated server on a different domain to serve them.
In the lab, the fixed version answered 404 to every request for a stored name under /uploads/, while the flawed version served each file straight from the folder it was written to.
CWE-434's first mitigation is to generate a new, unique file name for an upload instead of using the user-supplied name, so that no external input is used at all, and it adds that generated names should end in one of a very limited set of allowed extensions.
The cheat sheet calls a random name such as a UUID essential. ASVS 5.3.2, at Level 1, asks that file paths are built from internally generated or trusted data rather than user-submitted file names, and that where a user's name must be used it is strictly validated and sanitised, to protect against path traversal, local or remote file inclusion and SSRF.
The fixed version names every file with crypto.randomUUID() plus .png. The flawed version kept the uploaded names, and three uploads called photo.png left one file behind: its run ends with 14 uploads accepted, 12 distinct stored names and 2 that replaced an earlier file.
Overwriting an existing file is on the cheat sheet's list of upload threats. If people need to see the original name, keep it as data for display, validated as the cheat sheet describes, and not as a path.
A browser decides what to do with a file from the download response, not from the upload. MDN's guide to MIME types says browsers use the MIME type, not the file extension, to decide how to process a URL, and that where the type is missing, or a browser believes it is wrong, the browser may sniff, guessing the type from the bytes, with each browser doing so differently.
The MIME Sniffing Standard spells out one case: when a response has no Content-Type, its rules for an unknown type, with sniffing of scriptable types allowed, return text/html for a resource that begins with patterns such as <HTML or <SCRIPT.
The flawed version shows how that happens by accident. Its file server looked up types in a table with lowercase keys, so R5 (HOLIDAY.PNG) and R6 (notes.HTML) went out with no Content-Type header at all, and R3 and M3 went out as text/html because their stored names ended in .html.
Two headers on every download, beside a Content-Type the server chose, narrow that gap. X-Content-Type-Options: nosniff tells the browser to use the declared Content-Type as-is instead of examining the content; MDN's example is a response sent as text/plain with nosniff, which the browser will not interpret as HTML even if it contains HTML markup, and MDN says this prevents XSS attacks where user-uploaded content is executed as an HTML document.
Content-Disposition: attachment says the response should be downloaded, where inline, the default, lets it display in the browser. ASVS 5.4.1, at Level 2, asks the application to validate or ignore user-submitted file names and to specify a file name in Content-Disposition, and 5.4.2, also Level 2, asks for served file names to be encoded or sanitised, for example following RFC 6266. OWASP's unrestricted upload page recommends attachment and nosniff for every file users download.
A Content-Security-Policy belongs on the download as well. MDN's CSP guide says a policy should be set on all responses to all requests, not just the main document. A download is a response of its own. The fixed version sends Content-Security-Policy: sandbox with each file.
MDN says the sandbox directive applies restrictions including preventing the execution of plugins and scripts and enforcing a same-origin policy, and that it is not supported in a meta element, so it has to be sent as a header.
The fixed version takes the Content-Type from its allow-list entry, never from the request, and puts its generated name in Content-Disposition, so no text from the upload reaches a header.
Size limits, archives and decompression bombs
ASVS 5.2.1, at Level 1, asks that the application only accepts files of a size it can process without a loss of performance or a denial of service.
The limit has to hold while the body arrives, not only when a Content-Length header announces the size. S1 sent one byte over the lab's 65,536-byte limit with a Content-Length header, and the fixed version refused it with 413 without reading the body.
S2 sent 300,000 bytes in 16,384-byte pieces with no Content-Length, and the fixed version counted as it read, stopped keeping data once the count passed the limit at 81,920 bytes, and refused it.
The flawed version stored both. ASVS 5.2.4, at Level 3, adds a per-user quota on file size and the number of files, so one account cannot fill the storage.
Archives move the size that matters to after extraction. CWE-409 describes a product that does not handle, or incorrectly handles, compressed input with a very high compression ratio that produces a large output, and its first example is a decompression bomb, a small ZIP file that can produce a large amount of data when it is decompressed.
WSTG-BUSL-09 says such a file is intended to cause a denial of service by exhausting the disk space or memory of the system that extracts it, that formats other than Zip, including gzip, are affected too, and that a successful attack can also raise costs on an auto-scaling cloud platform.
It says not to carry out this kind of attack without considering those risks and getting written approval.
The lab stays modest by design: A2, the archive that unpacks the most, is 3,957 bytes packed and holds 1,560,000 bytes of marker text, enough to cross the lab's limit.
ASVS 5.2.3, at Level 2, asks that compressed files, such as zip, gz, docx and odt, are checked against a maximum uncompressed size and a maximum number of files before they are uncompressed. ASVS 5.2.5, at Level 3, asks that archives containing symlinks are refused unless they are specifically required, and that an allowlist then limits which files they can link to.
ASVS 5.3.3, also Level 3, asks that server-side processing such as decompression ignores user-provided path information to prevent vulnerabilities such as zip slip. The cheat sheet adds that where a system extracts or processes files, the size limit should be considered after decompression, using secure methods to calculate zip file sizes, and OWASP's unrestricted upload page says that where an application extracts compressed files, each file inside should be checked one by one as a new file.
The lab's archive check works in two stages and never writes a file. The first reads the list of entries the archive declares and refuses it if there are more than 100 entries, if any name is absolute, contains a backslash or a colon, or climbs out of the folder with .., or if the listed sizes add up to more than 1,000,000 bytes.
That refused A1, A2 and A3 before anything was inflated, and passed A4.
The listed sizes are written by whoever made the archive, so the second stage inflates each entry in memory with zlib's maxOutputLength option, which the Node.js documentation says limits output size when using the convenience methods, set one byte above the remaining budget.
Run on its own against A2's entry, it stopped with ERR_BUFFER_TOO_LARGE, and the regression test edits a modest archive so its listing understates its entry's size, which the second stage also stopped.
The fixed upload endpoint refuses archives outright, in line with the cheat sheet, which does not recommend ZIP files because they can contain all types of files and the attack vectors pertaining to them are numerous. The archive check is for features that have to take archives, and it runs before extraction, not instead of the checks on each extracted file.
Malicious file uploads: what scanning adds and where it stops
WSTG-BUSL-09, Test Upload of Malicious Files, starts where type checks end: a file of an accepted type can still be malicious.
It notes that restrictions based on a list of permitted or blocked extensions are not sufficient to stop legitimate file types with malicious contents, that malicious means different things to different systems, and that malicious files could be detected and stopped at various points, including intrusion detection or prevention, anti-virus software on the application server, or scanning by the application as files are uploaded.
ASVS 5.4.3, at Level 2, asks that files obtained from untrusted sources are scanned by antivirus scanners to prevent serving of known malicious content. The requirement's own words set its scope: known malicious content. The cheat sheet lists running a file through an antivirus or a sandbox, if available, among its principles, along with Content Disarm and Reconstruct for applicable types such as PDF and DOCX.
It also notes that some services scan files against well known malicious file hashes, and warns about data leakage threats and information gathering by public services, so think before sending customers' files to one.
The scanner is also software that reads untrusted files. OWASP's unrestricted upload page says uploaded files might trigger vulnerabilities in broken real-time monitoring tools, with an antivirus exploited by unpacking a RAR file as its example, and CWE-434 notes that the weakness can overlap with interpretation errors in intermediaries, such as anti-virus products that do not remove or quarantine attachments with certain file extensions.
WSTG-BUSL-09 adds that, depending on how the application processes a file, it may not be obvious whether a malicious file was detected and quarantined or deleted. Treat scanning as one layer on top of the type decision, the storage and the download headers, and keep a record of each verdict so you can show a file was checked. The fixture set contains no scanner test files; to confirm scanning runs, follow your scanner's own documentation.
Images and documents that can carry active content
Some formats people think of as passive are not.
MDN documents a script element for SVG, which allows you to add scripts to an SVG document. WSTG-BUSL-08's example is a picture-sharing site that accepts .gif and .jpg files, and it asks what happens if an attacker uploads an HTML file with a script tag in it.
CWE-434 says to consider cross-site scripting before allowing .html or .htm file types. If a feature does not need SVG or HTML, leave them off the allow-list. If it does, serve them as attachments with nosniff and a sandbox policy, and consider a separate domain for them, an option OWASP's unrestricted upload page raises for serving uploaded files. Script that runs inside one of your own pages is the subject of the XSS guide.
For images, the cheat sheet's advice is to decode and re-encode to an allowed image format, explicitly removing unnecessary metadata. It is candid about the limits: rewriting may not remove all malicious content, and the image processor itself handles untrusted input, so use an up-to-date library with restricted formats, resource limits and sandboxing.
The documentation for sharp, a Node.js image library, shows what those settings look like: by default all metadata is removed from output images; limitInputPixels refuses input images whose width times height exceeds a limit, which is on by default and assumes the dimensions in the input metadata can be trusted; and the failOn option should stay at its default, warning, for untrusted input.
ASVS 5.2.6, at Level 3, asks the application to reject images with a pixel size larger than the maximum allowed, to prevent pixel flood attacks.
Documents carry their own risks. WSTG-BUSL-09 notes that CSV files may allow CSV injection attacks, Office files may contain malicious macros or PowerShell code, and PDFs may contain malicious JavaScript. The cheat sheet suggests Content Disarm and Reconstruct for applicable types such as PDF and DOCX, and Apache POI for validating Microsoft documents, and ASVS 5.2.3 counts docx and odt among the compressed files whose unpacked size and file count it asks you to check.
Serving documents as attachments matters here too: OWASP's unrestricted upload page says the attachment and nosniff headers mitigate PDF-based cross-site content hijacking, especially when PDF uploads are permitted.
File uploads on WordPress sites
WordPress handles uploads in core, and its developer reference shows what the core path does.
Uploading starts with a capability: the default Author role holds upload_files, and the Contributor role does not. The core handler, _wp_handle_upload(), sanitises file names, checks extensions for mime type and moves the file into the uploads directory, and on success returns the file name, its URL and its type.
With its type test on, which is the default, it asks wp_check_filetype_and_ext() for the file's type, and when no allowed extension and type match it refuses the upload with "Sorry, you are not allowed to upload this file type.", unless the user holds the unfiltered_upload capability.
wp_check_filetype_and_ext() attempts to determine a file's real type, and if it cannot, uses the file name's extension. When it finds that an extension does not match the real type it can supply a corrected name, though for now only for images validated by wp_get_image_mime(). The allowed list comes from get_allowed_mime_types(), which starts from wp_get_mime_types(), removes swf and exe, removes htm|html and js for users without the unfiltered_html capability, and passes the list through the upload_mimes filter, where plugins and themes can change it.
The list in wp_get_mime_types() has no SVG entry, so a site that accepts SVG uploads through core has changed something: added the type with a filter, had code pass the upload handler its own list of types or switch off its type check, or given the uploading user the unfiltered_upload capability.
unfiltered_upload is a special case. WordPress's roles documentation says it is not available to any role by default, including Super Admins, and needs to be enabled by defining the constant ALLOW_UNFILTERED_UPLOADS as true; with the constant defined, any role on a single site can be given the capability, and on Multisite only Super Admins can. Check wp-config.php for that constant, and if it is there, check who holds the capability.
Core is not the only upload path. Plugins can add upload fields of their own, so test each one with the fixtures rather than assuming it goes through core. Because core hands back a URL for each upload, the server settings for the uploads folder decide whether a stored file could ever run as code, which is the concern of ASVS 5.3.1.
The Clever Ops WordPress security audit tests each upload path with files that are not what their extension claims, such as SVG or HTML content, to see what the server stores and serves back to other users, and the WordPress guide covers the roles and plugins behind those paths.
Uploads to object storage, with Amazon S3 as the example
Some applications let the browser send files straight to object storage, so the file never passes through the application server.
On Amazon S3 that is done with a presigned URL, which AWS documents as a way to let someone upload a specific object without needing AWS credentials of their own. The controls above still apply, but three details from AWS's documentation change where they sit.
The key is the stored name
If an object with the same key already exists, S3 replaces it with the upload, and a presigned URL can be used more than once until it expires. Generate the key on your server for each upload, never from the uploaded file name, and consider PutObject's If-None-Match condition, which uploads the object only if the key does not already exist and otherwise returns 412 Precondition Failed.
AWS also describes presigned URLs as bearer tokens that grant access to whoever holds them, so issue one per upload and protect it as AWS recommends.
The stored type is still a claim
S3's metadata documentation lists Content-Type and Content-Disposition among the system-defined metadata whose values the user can modify, and PutObject takes Content-Type as a request header. The type stored with an object is the one its upload request set, which is the same claim as before, now kept beside the file.
The bytes also never passed through your code, so treat a new object as unchecked until your server has read its leading bytes, its size and, for an archive, its listing, and only then move it under a new key to where downloads come from.
Downloads come from a private bucket with signed links
AWS says new buckets, access points and objects do not allow public access by default, that policies and permissions can open them, and that Block Public Access settings override those policies and permissions. A signed GetObject request can override the response's Content-Disposition and Content-Type with the response-content-disposition and response-content-type parameters; AWS says these cannot be used with an unsigned request and are included only in a successful 200 OK response.
That lets each download link ask for attachment and a fixed type.
Check what actually comes back, through any CDN in front of the bucket, with check 4 of the verification table, because the headers a browser receives are the ones that count.
File upload testing: fixtures, evidence and conduct
WSTG-BUSL-08 asks testers to prepare a library of files that are not approved for upload, submit them and confirm they are prevented, and to check whether the file type is only checked in client-side JavaScript, by the Content-Type or by the extension, whether uploaded files can be reached directly by URL, and whether a ZIP can carry paths that unpack files to an intended location.
WSTG-BUSL-09's objectives add determining how uploaded files are processed, and trying to upload malicious files to see whether they are accepted and processed. The fixture set on this page is a library of that kind built from harmless files: marker text, a real 1 by 1 pixel PNG, generated padding and archives of marker text. None of the files is a program, and none contains a scanner test file.
Use the fixtures on an upload feature you own, or one you are authorised in writing to test, on a test or staging copy where you can. Upload as a test account, keep a list of what you uploaded and where it was stored, and delete it afterwards.
Do not upload over a file you did not create: OWASP's unrestricted upload page warns that replacing configuration files such as web.config or .htaccess can lead to a denial of service for the whole website.
For size and archive limits, a modest generated file one step over the limit shows whether the limit holds.
For each fixture, keep the request (name, declared type, size and whether a Content-Length header was sent), the response status and reason, where the file was stored and under what name, and the full headers of its download. The verification table in the asset maps that evidence to four checks: server-side inspection, generated names, isolated storage and safe download headers, each with the source behind it.
In a Clever Ops web application and API penetration test, file uploads are in scope. Each upload point is tried with file types the business does not accept and with harmless files whose content does not match their extension, stored files are requested directly to see whether any is run as server-side code, and the processing that follows an upload, such as resizing an image or attaching a file to a generated PDF, is tried with harmless test files.
Whether another account can download an upload is tested as an access question.
If Clever Ops built or hosts the application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Running the lab and reading its results
The lab in the asset is an illustration written for this page.
It needs Node.js and nothing else: it uses only modules that ship with Node.js, binds to 127.0.0.1 on a port the operating system picks, writes only inside a temporary folder it creates, and removes that folder when it stops. The Node.js documentation says that when a server listens on port 0, the operating system assigns an arbitrary unused port.
The lab was run on Node.js v26.0.0 on macOS; zlib.crc32(), which builds the fixtures, was added in Node.js 22.2.0 and 20.15.0, and the documentation marks the test runner stable from 20.0.0.
To keep the server short and correct with built-in modules only, the lab takes uploads as POST /upload?name=FILE_NAME, with the file's bytes as the whole request body and the declared type in the Content-Type header. A browser form sends the same three claims in a multipart/form-data part instead, so the checks are the same.
S2 is written in pieces with no Content-Length header; the Node.js documentation says sending a Content-Length header disables the default chunked encoding, so without one node:http sends the body chunked.
In the output of run-fixtures.mjs, the flawed version accepted 14 of the 15 fixtures, refusing only M1 because its declared type was text/html. It stored each under the uploaded name in its public folder, served R3 and M3 as text/html because their names ended in .html, served R5 and R6 with no Content-Type because its type table was case-sensitive, and sent none of nosniff, Content-Disposition or a Content-Security-Policy with any download.
The fixed version accepted four: R1, R5, M1 and M2.
Each was stored under a generated name in a folder no route serves, came back from /files/ with image/png, nosniff, attachment and sandbox, and answered 404 when requested by its stored name.
The regression test, upload.test.mjs, runs ten checks on Node's built-in test runner. Against the fixed version all ten passed and the process exited with code 0. Against the flawed version seven failed and the exit code was 1; the Node.js documentation says the process exit code is set to 1 when any test fails, which is what lets a pipeline step stop a deploy.
Checks 1, 9 and 10 pass on both: the first confirms a real PNG still gets through, so the fixed version is not passing by refusing everything, and the last two test the archive check, which both versions share.
Frequently asked questions
It is any way a file someone uploads, or what your server does with it, causes harm: code run on the server, a page that runs script in other visitors' browsers, a file that overwrites another, storage filled up, or private files reachable by the wrong people. MITRE catalogues the core weakness as CWE-434, the upload of dangerous file types that are automatically processed within the product's environment. The fixes sit in five places: what the server accepts, how it decides what a file is, where it stores it, what it names it and how it serves it back.
MITRE lists unrestricted file upload as an alternate term for CWE-434, Unrestricted Upload of File with Dangerous Type, and calls the phrase insufficiently precise: it could be read as a lack of limits on the size or number of uploaded files, which is a resource consumption issue. Both meanings need fixing. Type, storage and serving controls deal with the dangerous file, and size limits, per-user quotas and archive checks deal with the volume.
No. The extension is chosen by the uploader, and the WHATWG MIME Sniffing Standard calls extensions unreliable and easily spoofed. ASVS 5.2.2 asks for the extension to match an expected one and the contents to match the type it represents, and OWASP's cheat sheet calls blocking extensions a weak protection on its own. In the lab, a text file named photo.png got past the flawed version, which trusted names and declared types, and was refused by the fixed one, which reads the leading bytes.
They prove the first few bytes match a signature, and nothing about the rest. OWASP's cheat sheet says a signature check should not be used on its own, as bypassing it is pretty common and easy, and MDN notes that not every file type has a magic number. The lab's fixture M2, a PNG signature followed by marker text, passed the fixed version's check. What kept it harmless was the generated name, storage outside any served folder, and a download sent as image/png with nosniff and attachment.
ASVS 5.4.3, a Level 2 requirement, asks for files from untrusted sources to be scanned by antivirus scanners to prevent serving of known malicious content, and OWASP's cheat sheet lists an antivirus or a sandbox where available. Scanning covers known content, and the scanner itself reads untrusted files, so treat it as one layer beside the type decision, the storage and the download headers, not a replacement for them.
Use harmless fixtures like the ones on this page: marker text with misleading names and types, a real tiny image, generated padding one step over the size limit, and small archives of marker text. Test a feature you own or are authorised in writing to test, on a staging copy where you can, as a test account, and delete what you uploaded afterwards. Do not upload over existing files, and record each request, response, stored location and download header as evidence.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.