Threat Model
This document describes the threat categories that safeuploads protects against, the attack vectors for each, and the mitigations implemented in the library.
Filename Attacks
Directory Traversal (CWE-22)
Attack: Filenames containing ../, ..\\, or URL-encoded
variants (%2e%2e%2f) attempt to write files outside the
intended upload directory.
Mitigations:
UnicodeSecurityValidatorrejects filenames containing dangerous Unicode characters (including zero-width ones) withUnicodeSecurityErrorand normalizes the rest to NFC form before any path checks.- A filename whose NFKC form contains a path separator (
/,\) or..that its NFC form does not, such as a fullwidth solidus (U+FF0F), is rejected withFILENAME_INVALIDbeforeos.path.basenameruns. - Upload filenames are reduced to their last path component
(
os.path.basename), and the characters<>:"/\|?*are replaced with_, so traversal sequences cannot survive into the sanitized name. The traversal patterns inSuspiciousFilePattern.DIRECTORY_TRAVERSALare applied to ZIP entry names only. - Null bytes and other control characters are rejected, not stripped, so C-string truncation attacks and names that change meaning after cleaning never reach storage (see Unicode Obfuscation below).
- The extension and Windows reserved-name checks run again on
the final name after it is shortened to
max_sanitized_name_length, so truncation cannot expose a blocked extension.
Unicode Obfuscation (CWE-116)
Attack: Right-to-left override characters (U+202E) and
zero-width joiners can disguise file extensions so that
report.pdf visually appears safe while the real extension
is .exe.
Mitigations:
- All filenames are NFC-normalized before validation.
- Characters in
UnicodeAttackCategory(directional overrides, zero-width characters, confusing punctuation) are detected and rejected. - Every character in the Unicode general categories Cc
(controls, including NUL, DEL and C1), Cf (format characters,
including soft hyphen, bidi marks and zero-width joiner), Co
(private use), Cn (unassigned), Cs (surrogates), Zl and Zp is
rejected with
UnicodeSecurityError; none is stripped. A filename containing an emoji ZWJ sequence is therefore rejected. - Categories come from the running Python's Unicode database (14.0 on Python 3.11, 15.0 on 3.12, 15.1 on 3.13), so a character assigned in a later Unicode version is unassigned (Cn) and rejected on an older Python. Older versions only reject more.
- The Windows reserved-name and extension checks run on the NFC
name and on its NFKC form, so fullwidth letters or
superscript digits cannot disguise
CON,COM1or.php. The returned name stays NFC. - Fullwidth period (U+FF0E) and dot leader (U+2024) are flagged to prevent extension spoofing.
Windows Reserved Names (CWE-20)
Attack: Filenames like CON, PRN, NUL, or COM1
cause undefined behavior on Windows file systems, potentially
leading to denial of service.
Mitigations:
WindowsSecurityValidatorchecks the stem of each filename againstFileSecurityConfig.WINDOWS_RESERVED_NAMES(case-insensitive, compared case-folded). The list includescom0,lpt0,conin$,conout$andclock$.
Extension Attacks
Dangerous Extensions (CWE-434)
Attack: Uploading executable files (.exe, .bat, .ps1,
.php, .jsp) that could be executed if served or stored
improperly.
Mitigations:
ExtensionSecurityValidatormaintains a blocklist generated fromDangerousExtensionCategorycovering 16 categories: Windows executables, script files, web scripts, Unix/macOS executables, Java, mobile apps, browser extensions, package formats, archives, virtualization, Office macros, system files, drivers, themes, and help files.- Compound extensions (
.tar.gz,.user.js,.min.css) are checked viaCompoundExtensionCategory. - Trailing dots and spaces are ignored by the blocked-extension
check, because Windows drops them when it saves a file. The
check also runs on the NFKC form, so
run.exeorinvoice.docmfollowed by U+3000 (an ideographic space that NFKC folds to a space) is rejected. - Allowed extensions are validated against a configurable allowlist per file type.
Compression Attacks
ZIP Bombs (CWE-400)
Attack: A small ZIP archive that decompresses to an enormous size (e.g., 42.zip — 42 KB compressed, 4.5 PB uncompressed), exhausting disk and memory.
Mitigations:
CompressionSecurityValidatorenforcesmax_compression_ratio(default 100:1) by comparing compressed vs. reported uncompressed sizes.max_uncompressed_size(default 1 GB) caps total extraction.max_individual_file_size(default 500 MB) caps per-entry size.- A directory entry (name ending in
/) that declares uncompressed data is rejected withZIP_INVALID_STRUCTURE, so data cannot hide from the size and ratio checks behind a directory name. zip_analysis_timeout(default 5 s) prevents slow analysis; exceeding it raisesZipBombErrorwithZIP_ANALYSIS_TIMEOUT.- All timeout checks use
time.monotonic()to prevent bypass via NTP clock adjustment.
Metadata trust boundary:
- The size and ratio checks above read the ZIP central-
directory
file_size/compress_sizefields, which are attacker-controlled. A forged smallfile_sizecannot bomb azipfile-based consumer: Python'szipfilecaps reads at the declared size and raisesBadZipFileon the resulting CRC mismatch. The residual risk is a consumer that inflates the raw DEFLATE stream while ignoring the ZIP metadata. - safeuploads does not extract archives. Consumers must
extract safely — prefer
zipfile(which enforces the declared sizes) over rawzlibinflation. - Set
verify_zip_decompression=Trueto make safeuploads read every entry throughzipfile, forcing CRC and decompression validation. Archives whose real content does not match their declared metadata are then rejected asZIP_CORRUPT. This is off by default because it decompresses the full archive.
Recursive / Quine ZIP Archives
Attack: A ZIP containing itself (quine) or deeply nested ZIPs that cause infinite recursion during inspection.
Mitigations:
ZipContentInspector.inspect_nested_archives()tracks the SHA-256 hashes of an archive's ancestors; an inner archive whose hash matches one of its ancestors raisesZIP_QUINE_DETECTED. Identical sibling archives are not a quine and are accepted. Theseen_hashesargument holds ancestor hashes and is not modified.max_zip_depth(default 10) limits nesting level.max_total_entries_recursive(default 50,000) limits the cumulative entry count across all nesting levels. Together withmax_zip_depthand the analysis timeout, it bounds the work for many identical sibling archives.ZIP_RECURSIVE_STRUCTUREandZIP_COMPLEXITY_ATTACKerror codes provide precise feedback.
Nested Archive Detection
Attack: Archives hidden inside other archives to bypass single-level content inspection.
Mitigations:
- When
allow_nested_archives=False(default), any entry with an extension inZipThreatCategory.NESTED_ARCHIVESraisesZIP_NESTED_ARCHIVE. - Extensions are taken from the entry name after stripping trailing dots and spaces, as Windows drops them on extraction.
- When
scan_zip_contentis enabled (default) and nested archives are not allowed, the first bytes of each entry are checked againstZipThreatCategory.NESTED_ARCHIVE_SIGNATURES(ZIP and ZIP-based formats such as.docxand.jar, gzip, bzip2, xz, 7z and RAR). A renamed archive is rejected and reported underZIP_CONTENT_THREAT. Tar is recognised by extension only. - When allowed,
ZipContentInspector.inspect_nested_archives()inspects every inner ZIP, found by a recursable archive extension or a ZIP signature. The inner archive is streamed inchunk_sizechunks into a spooled temporary file and gets the same checks as the top level: the entry count, exact layout, size and ratio checks ofCompressionSecurityValidatorand the entry and structure checks ofZipContentInspector, plus the depth, count and ancestor hash checks above. - An inner archive that is larger than
max_individual_file_size(FILE_TOO_LARGE), cannot be read, is corrupt (ZIP_CORRUPT) or cannot be inspected is rejected, not skipped. Threats name the nesting path (entry names joined by/), and a nested ratio bomb raisesZipBombErrorwith the path in its message. - Nested archives need
scan_zip_content: a configuration withallow_nested_archives=Trueandscan_zip_content=Falseis rejected at construction with thenested_archives_require_scanconfiguration error. - Memory is bounded by the nesting depth times
max_memory_buffer_size, since each level holds one spooled temporary file that spills to disk beyond that size.
Ambiguous Archive Layout (Parser Differential)
Attack: A ZIP built so that zipfile, which reads the
central directory, sees different entries from an extractor
that walks local headers from the start of the file. Examples
are a fake end record or a whole benign archive hidden in the
archive comment, two concatenated archives, an unlisted entry
between listed ones, a local header whose sizes or name differ
from the central directory, a Unicode Path extra field naming
the entry differently from its raw header name, and a deflate
stream that ends before a data-descriptor entry's declared
size. The validated archive then passes while the extractor
writes hidden files.
Mitigations:
CompressionSecurityValidatorrequires the listed entries to fill the file exactly: local headers start at offset 0 and follow one another without gaps or overlaps, the central directory sits at its declared offset right after the last entry, and the end records with their declared comment end the file. Prepended or trailing bytes, including zero padding, are rejected.- Each local header must agree with its central-directory record: name bytes, name encoding flag, compression method, data-descriptor flag and, without a descriptor, CRC-32 and sizes (ZIP64 sizes are read from the local extra field). With a descriptor, each local CRC-32 and size must be zero or equal to the central value, so a streaming reader cannot end the entry early and read a hidden entry from its data.
- Every Info-ZIP Unicode Path extra field (
0x7075), local or central, must carry exactly the raw name bytes, and both extra fields must be well formed.zipfilenames an entry by the central field while other extractors use the raw name or the local field, so the name checks would otherwise see a benign alias of a traversal or executable name. - Entries with a data descriptor are accepted only when a
streaming reader can find the descriptor unambiguously: a
deflated entry is inflated in
chunk_sizechunks and its stream must end exactly at the declared compressed size, and a stored entry must be empty with a signed descriptor right after its header. Other descriptor entries are rejected. The descriptor values must equal the central directory's, in 8-byte sizes when the local header has a ZIP64 extra field and in 4-byte sizes otherwise (APPNOTE 4.3.9.2), so every reader parses the descriptor the same way. - This check runs after the size and ratio limits, so inflation
is bounded by them, and it raises
ZIP_INVALID_STRUCTURE. - With
allow_nested_archives=True, nested archives get the same layout check as the top level.
Content Threats (ZIP Entries)
Path Traversal in ZIP Entry Names (CWE-22)
Attack: ZIP entry filenames like ../../etc/passwd write
outside the extraction directory (Zip Slip).
Mitigations:
ZipContentInspector._inspect_zip_entry()checks for traversal patterns and absolute paths. AZipContentErrorcarries theerror_codeof the first threat found, in entry order and then structure checks:ZIP_DIRECTORY_TRAVERSAL,ZIP_ABSOLUTE_PATH,ZIP_SYMLINK_DETECTED,ZIP_NESTED_ARCHIVE, otherwiseZIP_CONTENT_THREAT. Itsthreatsattribute lists every message, and an inner archive keeps the code of its own threat.- Null bytes are rejected first, checked on the raw entry name
(
ZipInfo.orig_filename), to prevent C-string truncation bypasses (CWE-158). Python'szipfiletruncatesfilenameat the first NUL, so the raw name is needed.
Spoofed or Blocked Entry Names (CWE-184, CWE-434)
Attack: A file refused as a standalone upload (a
macro-enabled Office document, an .hta, a name with a
right-to-left override, CON.txt) is wrapped in a ZIP so that a
host extracting or listing the entries stores it anyway.
Mitigations:
- Every entry name gets the filename checks a top-level upload
gets, driven by the same
FileSecurityConfigfields, so a configuration that extends a list covers entries too: - the whole name is checked against
DANGEROUS_UNICODE_CHARSand the rejected Unicode categories, and its NFKC form must not introduce a path separator or..; - every path component is checked against
WINDOWS_RESERVED_NAMES; - a file's base name is checked against
BLOCKED_EXTENSIONS(every extension in the name) andCOMPOUND_BLOCKED_EXTENSIONS. - The reserved-name and extension checks run on the NFC name and its NFKC form, after stripping trailing dots and spaces that Windows drops on extraction.
- A failing name is reported as
ZIP_CONTENT_THREAT; the message shows the name with control and bidi characters escaped.
Executable Content in ZIP
Attack: Executables, scripts, system files, or shortcuts hidden inside ZIP archives.
Mitigations:
- Besides
BLOCKED_EXTENSIONS(see above), the entry's final extension, after stripping trailing dots and spaces, is checked againstZipThreatCategory.EXECUTABLE_FILES,SCRIPT_FILES, andSYSTEM_FILES, which also cover configuration files such as.ini,.cfgand.conf. - Binary content is scanned for executable magic bytes from
SuspiciousFilePattern.EXECUTABLE_SIGNATURES. The first 512 bytes of each entry are read for this scan. - Text content is scanned for script injection patterns from
SuspiciousFilePattern.SCRIPT_PATTERNS(shebangs,eval(),<?php,<script,<%) in the first 512 bytes of each entry. Unlike content analysis, this scan still counts a bare<%. - An entry that starts with the gzip magic (
\x1f\x8b) is decided by content, not name: its first 512 decompressed bytes are checked for executable signatures and script patterns, so compressed bytes cannot match a pattern by chance. The script scan is skipped when the name without.gzhas a binary extension (x.fit.gz). An entry with the gzip magic that is not a readable gzip stream, or whose content is itself gzip, is rejected as uninspectable. Only this start is decompressed, so the expansion of the whole stream is not checked here. - An entry whose content cannot be opened or read (encrypted,
unsupported compression method, local header name differing
from the central directory, or a CRC mismatch seen during
the read) is rejected with
ZIP_CONTENT_THREAT, because its content cannot be inspected. - A CRC mismatch is seen by this read only when the read
reaches the end of the entry's data, which is the case for
small entries. For larger entries it is caught only with
verify_zip_decompression=True.
Symbolic Links in ZIP (CWE-59)
Attack: Symlinks inside ZIP archives can point to arbitrary system files when extracted.
Mitigations:
- Symlink entries are detected and rejected when
allow_symlinks=False(default). An entry is a symlink when the file-type bits of its Unix mode equalS_IFLNK(stat.S_ISLNK), so other modes that share some of those bits are not mistaken for symlinks.
File Content Attacks
MIME Type Mismatch (CWE-434)
Attack: A file with a .jpg extension but containing
executable content, relying on the server trusting the
extension.
Mitigations:
python-magicdetects the actual MIME type from file content (first 8 KB).- Detection never falls back to the filename extension. If the
libmagic detector cannot be initialized,
FileValidatorstill constructs, logs an error and rejects every upload withMimeTypeError(MIME_DETECTION_FAILED). A libmagic failure or an empty result for a file is rejected the same way. If the libmagic library itself is missing,python-magicraisesImportErrorwhensafeuploadsis imported, so nothing is validated. - The detected MIME type is validated against the allowlist for the file type being validated.
- The filename's extension must be one the configuration lists
for the detected MIME type (
ALLOWED_*_TYPES), so a file that is a valid, allowed image under another image format's name (for example a WebP namedphoto.jpg) is rejected withEXTENSION_MIME_MISMATCH. Downstream tools that pick a decoder or aContent-Typefrom the extension never see a name that contradicts the content. - File signatures (magic bytes) are verified independently of
the MIME type. A WebP must carry
WEBPat bytes 8-11 of its RIFF container, so WAV, AVI and other RIFF files are not accepted as images. A HEIC must open with anftypbox that namesheicorheix(HEVC still images) as its major or a compatible brand, so AVIF, HEIF image sequences, MP4 and other ISO media are not accepted as HEIC.
Polyglot Files
Attack: Files valid in multiple formats simultaneously (e.g., GIFAR — a file that is both a valid GIF and a valid JAR) that bypass type checks but execute as the malicious format.
Mitigations:
ContentSecurityInspector(whenenable_content_analysis= True) scans for secondary format signatures (MalwareSignatureCategory.POLYGLOT_SIGNATURES) that should not appear in image or activity files: ZIP/JAR headers, Java class headers, RAR headers. A Java class magic counts only with a valid class-file version. The search starts at the first byte: no allowed image or activity signature begins with one of these, so a ZIP right after the 3-byte JPEG header is found.- Content analysis covers image, activity (GPX, TCX, FIT) and
PDF uploads; the polyglot signatures are checked for image and
activity uploads only. A PDF is rejected outright when its
header is not at offset 0 or data follows its final
%%EOF(see PDF Parser Differentials). ZIP uploads are not byte-scanned as a whole, because compressed bytes match signatures by chance; the ZIP inspector scans the decompressed entries instead.
Embedded Malware Signatures
Attack: Executable headers (PE, ELF, Mach-O, Java class, Windows shortcuts) embedded within uploaded files.
Mitigations:
ContentSecurityInspectorscans file content for byte signatures fromMalwareSignatureCategory: PE/MZ headers, ELF headers, Mach-O headers (32/64-bit, both endiannesses, and universal binaries), Java class magic, and Windows shortcut headers.- An executable signature counts only when the header structure
verifies at that offset, because a bare 2-4 byte magic occurs
by chance in random data. PE needs an
e_lfanewof any size that points atPE\0\0inside the scanned sample; ELF needs a valid class, byte order and version; Mach-O needs a known CPU type and file type; a universal Mach-O needs a plausible architecture count and CPU type; a Java class needs a valid class-file version; a Windows shortcut needs the Shell Link CLSID. - Web shell markers are
<?php,<scriptand the ASP/JSP directive forms<%@ pageand<%@ language(with or without the space). A bare<%is not a marker in content analysis. Patterns are matched on the raw bytes, lower-cased in ASCII, without decoding; memory use is about twice the scanned sample.
XML External Entity Injection (CWE-611)
Attack: GPX and TCX files are XML-based; malicious DTD declarations can trigger external entity resolution, leading to server-side file reads or SSRF.
Mitigations:
XmlSecurityValidatorparses withdefusedxml'sDefusedXMLParserandforbid_dtd=True, blocking all DTD declarations, external entities, and entity expansion attacks (billion laughs).- Entities and external references can only be declared in a
DTD, so any DOCTYPE raises
XmlSecurityError, aFileValidationError, withXML_DTD_FORBIDDEN. Malformed input (ParseError, an undeclared entity or an unknown encoding declaration) raises it withXML_MALFORMED. Only unexpected internal failures raiseFileProcessingError.ResourceLimitErroris re-raised unchanged. - The document is fed to the parser in
chunk_sizechunks with a target that builds no element tree, so memory does not grow with the document, and the resource limits are checked after each chunk.
Malformed FIT Files
Attack: A file with a valid .FIT header that carries
extra data before, between or after its sections, or a corrupt
body, so that a consumer parses something other than what was
validated.
Mitigations:
FitSecurityValidatorrequires a FIT upload to be one or more sections that cover the file exactly. Each section has a 12 or 14 byte header with the.FITsignature, a header CRC (checked when non-zero), a non-zero data size that fits in the file, and the FIT CRC-16 over header and data. Anything else raisesFileSignatureErrorwithFIT_INVALID_STRUCTURE.- The file is read in
chunk_sizechunks with resource limits checked after each. Record contents are not interpreted. - With
enable_content_analysis=True, GPX, TCX and FIT uploads also get content analysis.
PDF Active Content
Attack: A PDF runs JavaScript when opened or when a page, field or annotation is used, launches an application, carries an attached executable, submits form data to a remote server, or opens a remote document, all without any malformed bytes.
Mitigations:
PdfContentInspectortokenizes the whole file, so names in objects that no cross-reference entry lists (older revisions, orphans) are checked as well. Every name outside strings, comments and stream data is decoded (#xxescapes, so/J#61vaScriptis/JavaScript) and compared, case-sensitive as PDF names are, againstFileSecurityConfig.BLOCKED_PDF_NAMES. A match raisesPdfSecurityErrorwithPDF_ACTIVE_CONTENT.- Object streams (PDF 1.5+) hold objects inside compressed
streams, where a byte scan cannot see them. Every stream typed
/ObjStm, and every stream a compressed cross-reference entry names as its container, is decoded and its objects are parsed and checked the same way. - The default
BLOCKED_PDF_NAMEScovers JavaScript (/JS,/JavaScript),/Launch, embedded files (/EmbeddedFile,/EmbeddedFiles,/EF,/FileAttachment),/RichMedia, XFA forms (/XFA), form submission and import (/SubmitForm,/ImportData) and remote or embedded documents (/GoToR,/GoToE)./OpenActionand/AAare not blocked on their own: they also name harmless actions, such as the/OpenAction [page /Fit]that LaTeX writes, while the dangerous actions they can start are blocked by name./URIlinks and AcroForm fields without XFA are accepted. - A stream whose dictionary has
/F,/FFilteror/FDecodeParmsreads its data from another file and is rejected withPDF_ACTIVE_CONTENT. - The block-list is configurable; configuration validation
rejects an empty list (
empty_blocked_pdf_names) and entries that a decoded PDF name can never equal, such as one with a leading/, whitespace, a delimiter or#(invalid_pdf_name).
Residual risk:
- Bugs in a reader's font, image (JBIG2, JPX, CCITT) and colour decoders are triggered by rendering, which the library does not do; image codec data is not decoded.
- A
/URIlink can still point at afile:or UNC address, which some Windows readers follow, leaking NTLM credentials. Hosts that render or open PDFs for other users addURItoBLOCKED_PDF_NAMESor render in a sandbox.
PDF Parser Differentials
Attack: A PDF that two readers interpret differently, so
that the validator sees a harmless document and the reader sees
active content: a cross-reference offset pointing into a string
or into stream data, a stream /Length that ends before the
data a search for endstream finds, an object stream offset
inside another object, a key repeated with another value, or
data after %%EOF that another format parses (PDF/ZIP and
PDF/HTML polyglots).
Mitigations:
- The header must be
%PDF-1.xor%PDF-2.xat offset 0 (readers accept it anywhere in the first 1,024 bytes), and the file must end withstartxref, its offset and%%EOF, with only whitespace after it. - Every in-use entry of every cross-reference section, from
startxrefthrough/XRefStmand/Prev, must point (after whitespace) at the start of an object the scan parsed, with the same object and generation number. A loop of sections, an entry at offset 0 and an xref table whose counts do not match its entries are rejected rather than repaired: repairing readers rebuild the table by scanning, and may find objects the validator did not parse. - A stream's data ends at the first
endstream, and/Length(resolved when indirect) must end it there, with only whitespace between, so readers that trust/Lengthand readers that search forendstreamread the same bytes. - Object stream offsets must increase, and each object is parsed on its own from its offset, exactly as a reader does; the bytes between the header and the first object must hold no token. Every compressed cross-reference entry must point at its object in its container.
- A key repeated with a different value in a stream dictionary,
its
/DecodeParmsor a trailer is rejected; elsewhere it cannot change what the checks read, as every name is checked as a token. - Malformed syntax (unterminated strings, arrays or dictionaries,
invalid name escapes, unknown keywords, data between objects)
is rejected with
PDF_INVALID_STRUCTUREinstead of being repaired. Broken files that readers repair silently are therefore rejected.
Encrypted PDFs
Attack: An encrypted PDF hides its strings and stream data, including object streams, from inspection; one with an empty user password opens in readers without a prompt.
Mitigations:
- A
/Encryptname anywhere in the file is rejected withPDF_ENCRYPTED, including documents that only restrict permissions with an owner password.
Resource Exhaustion
Memory Exhaustion (CWE-400)
Attack: Uploading very large files or files that expand significantly during validation consumes all available memory.
Mitigations:
- Streaming validation via
SpooledTemporaryFilekeeps memory usage undermax_memory_buffer_size(default 10 MB) by spilling to disk for larger files. ResourceMonitortracks the process peak RSS (resource.getrusage()ru_maxrss, a high-water mark) and enforcesmax_validation_memory_mb(default 512 MB) as the increase in process peak RSS since the monitor started. This is not an upper bound for validation memory: an earlier, higher process peak hides later allocations. Concurrent work in the same process can also trip the limit; on Windows memory accounting is disabled.- The limit is checked at loop boundaries (upload streaming, ZIP
entry loops, gzip decompression, each XML chunk, each JPEG
segment before the frame header, each HEIC box and item
entry) and on exit,
and raises
ResourceLimitErrorwithRESOURCE_MEMORY_EXCEEDED. A single blocking call is not interrupted mid-call. - File size is enforced progressively during chunked reads, not after loading the entire file.
CPU Exhaustion (CWE-400)
Attack: Crafted files that trigger expensive validation paths (e.g., ZIP with many entries, deeply nested structures).
Mitigations:
ResourceMonitorenforcesmax_validation_time_seconds(default 30 s wall-clock,time.monotonic()) at the same loop boundaries and on exit, raisingResourceLimitErrorwithRESOURCE_TIME_EXCEEDED. The monitor is held in a context variable, which worker threads inherit through the copied context. A single blocking call, such as onezipfilecentral-directory parse, is not interrupted mid-call.- ZIP analysis has its own
zip_analysis_timeout(default 5 s), compared againsttime.monotonic()on each entry during iteration. max_zip_entries(default 10,000) caps per-archive entry count. Beforezipfileparses the archive, the central-directory headers are counted (located aszipfilelocates them, reading only the fixed headers and building noZipInfo) and the walk stops atmax_zip_entries + 1, so an archive with too many entries is rejected withZIP_TOO_MANY_ENTRIESat bounded cost, even if its end record under-reports the count. Malformed directories are left tozipfile(ZIP_CORRUPT), including names flagged as UTF-8 that are not, extract versions above 6.3 and ZIP featureszipfiledoes not support. The parsed count is checked again after parsing.
Gzip Decompression Bombs
Attack: A small gzip file that decompresses to massive size, similar to ZIP bombs.
Mitigations:
GzipContentInspectordecompresses gzip streams withzlibmember by member, reading and producing at mostchunk_sizebytes per step, and checks the compression ratio and uncompressed size againstSecurityLimitsprogressively.- The active
ResourceMonitoris checked on every step, so a stream of empty members or a long header field cannot run pastmax_validation_time_seconds. The same decompression samples gzip ZIP entries. Zero padding between and after members is accepted; other trailing data, reserved header flags and a mismatched header CRC are rejected withZIP_CORRUPT. - Exceeding either limit raises a validation error immediately, without reading the rest of the stream.
- Deflate data that
zlibcannot decode is rejected withCompressionSecurityError(ZIP_CORRUPT).
PDF Stream Decompression Bombs (CWE-409)
Attack: A small PDF whose Flate streams, possibly chained
([/FlateDecode /FlateDecode]), inflate to gigabytes when a
reader or thumbnailer renders it.
Mitigations:
PdfContentInspectorinflates every Flate stage of every stream,chunk_sizebytes at a time, and counts the output of all streams together. More thanmax_pdf_uncompressed_size(default 200 MB), or more thanmax_compression_ratiotimes the file size, raisesPdfSecurityErrorwithPDF_STREAM_BOMB. Only object and cross-reference streams are kept in memory.- ASCIIHex and ASCII85 stages are decoded so the Flate stages
after them are measured. A stream with an LZW, RunLength, Crypt
or unknown filter, or with an image codec before another filter,
is rejected with
PDF_INVALID_STRUCTURE; image codecs as the last filter are not decoded, so image pixel counts are not limited. - The whole PDF is read into memory, bounded by
max_pdf_size(default 50 MB), and the activeResourceMonitoris checked every 1,024 tokens and on every inflation step.
Image Decompression Bombs (CWE-400)
Attack: A small image whose header declares a huge canvas, such as a 50 KB PNG declaring 60,000 × 60,000 pixels or a WebP canvas of 16,777,216 × 16,777,216, passes every byte-level check and exhausts memory when the host decodes it, for example to make a thumbnail. A 24-bit decode needs 3 bytes per pixel, so 60,000 × 60,000 pixels is about 10 GB.
Mitigations:
ImageDimensionValidatorreads width and height from the image header without decoding pixel data, and rejects an image whose width × height exceedsmax_image_pixelswithImageDimensionError(IMAGE_DIMENSIONS_EXCEEDED). The default, 89,478,485, is Pillow'sImage.MAX_IMAGE_PIXELS, about 256 MB decoded at 24 bits per pixel. Configuration validation rejects a limit of 0 or less and warns above twice the default, where Pillow refuses to open an image.- PNG: the first chunk must be IHDR with 13 bytes of data, and width and height must be 1 to 2³¹ − 1.
- JPEG: the marker segments are walked from the start of image
to the first frame header (SOF0 to SOF15, except DHT, JPG and
DAC). Each segment's payload is skipped by its length, so a
frame header behind large EXIF, XMP or ICC segments is still
found. Scan data or end of image before a frame header, a
truncated segment, a segment length below 2, a standalone
marker before the frame, and a zero width or height
(including a height deferred to a DNL segment) are rejected
with
FileSignatureError(IMAGE_INVALID_STRUCTURE). - WebP: the first chunk after the
WEBPform type must beVP8(a key frame with a valid start code; the two upscaling bits of each dimension are ignored),VP8L(signature 0x2F, version 0) orVP8X, whose canvas size is checked. Any other first chunk is rejected withIMAGE_INVALID_STRUCTURE. - HEIC: the top-level boxes are walked to the one
metabox, whosehdlrmust bepict. The primary item (pitm) must be an HEVC image (hvc1) or a grid, and its size is its oneispeproperty. Everyispein the file is checked against the limit, so a thumbnail, alpha, depth or tile image cannot declare a larger size than the primary. For a grid, which a decoder sizes from its descriptor rather than itsispe, the descriptor is read from the location iniloc(inidator at a file offset, at most 12 bytes) and its output size must equal theispe. The grid must reference (dimg) exactly rows × columns HEVC tiles of one size that cover the output, trimmed only at the right and bottom edges, so the tiles decoded add up to about the output size. Missing, repeated, truncated or oversized boxes, unsupported box versions, protected (encrypted) items, other codecs or derivations as the primary item, and data outside the file oridatare rejected withIMAGE_INVALID_STRUCTURE. - The check runs after the signature check and before content
analysis, on the upload streamed to a spooled temp file. The
JPEG walk checks the active
ResourceMonitoron every segment; its cost grows with the number of segments before the frame header, so a 20 MB JPEG made only of 4-byte segments takes seconds, bounded bymax_image_sizeandmax_validation_time_seconds. A run of 0xFF fill bytes is skippedchunk_sizebytes at a time. The HEIC walk checks it on every box and everyipmaandilocentry; themetabox is read into memory whole, bounded bymax_image_size.
Decoding trust boundary:
- safeuploads does not decode images. Only the dimension header is parsed: compressed pixel data, ancillary chunks and metadata are not validated, so a truncated or corrupt image body is accepted.
- Bugs in image decoders (for example CVE-2023-4863 in libwebp) are triggered by decoding. The library cannot detect them, and decoding inside the validator would expose the validating process to them.
- Only the first image is checked. The APNG and WebP specifications require animation frames to fit the declared canvas, but the number of frames is not limited, and data after a JPEG's end of image (such as the secondary images of an MPO file) is not parsed.
- HEIC: the size an HEVC bitstream's own parameter sets declare
is not read, so a coded image larger than its
ispeis not detected; libheif's security limits bound it when decoding. HEIF image sequences are rejected rather than inspected. - A host that decodes uploads should decode in an isolated
worker process with a memory limit, keep the decoder's own
pixel limit set (for example Pillow's
Image.MAX_IMAGE_PIXELS) and store a re-encoded copy instead of the original bytes; re-encoding also drops metadata and data appended to the image. See the integration checklist.
Audit & Observability
Undetected Security Events (CWE-778)
Attack: Security-relevant events (validation failures, threat detections) go unlogged, preventing incident response.
Mitigations:
SecurityAuditLoggeremits structured log records under thesafeuploads.auditlogger for every validation start, success, failure, and threat detection.- Correlation IDs (via
contextvars) link all log messages from a single validation call. A correlation ID the host has already set is reused, so host logs and audit records share it, and the previous value is restored after validation. - The
filename,resultanddetailsfields of an audit record are attacker-controlled, soSecurityAuditLoggerescapes control, format (such as bidi overrides), surrogate, private-use, unassigned and line or paragraph separator characters withrepr()-style escapes and caps each field at 1,024 characters, marking a cut with...[truncated]. A newline in a filename therefore cannot forge a second log record. Other log messages that print a filename use%r. - The correlation ID and source IP can come from the host's
request, so audit records escape and cap them the same way,
and
log_extra()adds the escaped correlation ID to other records. The host still reads back the ID it set. - Audit logging is off by default (
enable_audit_logging= False) to avoid noise in development, enabled in production.
Error Information Leakage (CWE-209)
Attack: Detailed internal error messages in API responses help attackers understand the validation pipeline and craft bypass attempts.
Mitigations:
- Exception messages use static, generic text rather than including raw internal error details.
ErrorCodeconstants provide machine-readable classification without exposing implementation details.- Application code controls what error text reaches the client by catching specific exception types.
- Every
FileSecurityErrorsubclass has a defaultErrorCode, so a host can always readerror_codeon the library's exceptions.FileSecurityConfigurationErroris not one of them and exposes itserrorsinstead.