Skip to content

File Upload and Parser Boundaries

github-actions[bot] edited this page Nov 29, 2026 · 1 revision

Last reviewed: 2026-11-28

Caution

Authorized use only. Zip slip archives, decompression bombs and XXE documents are hostile inputs. Build and use them only against your own code or the local Secure API lab, in a disposable directory. See LEGAL.md.

Prerequisites: API threat modeling ยท Rate limiting & resource exhaustion

๐ŸŽฏ Purpose

Treat every parser as a trust boundary: file uploads, archives (zip, tar), XML, and the content type a browser will infer when the file is served back. The guide shows how to accept only what you expect and process it without letting it choose a path, a size or an entity.

โš™๏ธ Function

Turns the OWASP File Upload and XXE Prevention cheat sheets and ASVS 5.0.0 V5 (File Handling) into code. Uses Python's zipfile, tarfile extraction filters and defusedxml 0.7.1. Each snippet was run as written; the upload and zip handlers are from the lab's impl/fixed_api.py.

๐Ÿ† Goal

Uploads are size-capped, type-checked by content, renamed by the server and stored where they cannot execute. Archives are checked before extraction. XML parsers refuse DTDs. Every served file has an explicit Content-Type and X-Content-Type-Options: nosniff.

๐Ÿ“‹ When To Use

  • Adding an avatar, document, import or attachment upload
  • Extracting zip or tar archives from users or third parties
  • Parsing XML (SAML, SOAP, SVG, Office formats, RSS, sitemaps)
  • Serving user-supplied files back to browsers

๐Ÿ“‹ Table Of Contents

Upload Handling

Control Source
Document allowed types, extensions and maximum size, including unpacked size ASVS 5.1.1
Size limit the service can process safely ASVS 5.2.1
Extension on an allowlist and content matching the type ASVS 5.2.2; File Upload CS
Do not trust Content-Type: it "can be spoofed" File Upload CS
Magic-byte checks alone: "This should not be used on its own" File Upload CS
Server-generated file names (for example a UUID); never a user path ASVS 5.3.2; File Upload CS
Store on another server or outside the webroot; uploads must not execute ASVS 5.3.1; File Upload CS
Images: decode and re-encode, strip metadata; check pixel dimensions File Upload CS; ASVS 5.2.6
Antivirus or sandbox, and CDR for document types where applicable ASVS 5.4.3; File Upload CS

The fixed lab avatar handler applies the size cap, the extension allowlist, a content check and a generated name:

if req.content_length > MAX_UPLOAD_BYTES:
    return problem(413, "Content Too Large")
if Path(req.arg("filename", "")).suffix.lower() != ".png":
    return problem(415, "Unsupported Media Type", "only .png is accepted")
data = req.body()
if not (data.startswith(PNG_SIGNATURE) and data[12:16] == b"IHDR"):
    return problem(415, "Unsupported Media Type", "content is not a PNG image")
target = self.env.sandbox / "uploads" / f"{uuid.uuid4().hex}.png"

In upload-type-by-content, HTML named avatar.png was stored by the vulnerable twin (201) and refused by the fixed twin (415). The signature check is a minimum, not the whole control. The lab does not re-encode the image, strip metadata or scan for malware, which the cheat sheet also recommends. In production, decode the image with an image library under pixel and size limits, and save a re-encoded copy.

If the web server reads per-directory configuration (.htaccess, web.config), an uploaded config file can change how the upload directory is served. The cheat sheet's second layer of defense is to disable per-directory overrides on upload directories (for example Apache AllowOverride None), in addition to storing uploads outside the webroot.

Archives: Zip Slip & Decompression Bombs

Zip slip, disclosed by Snyk in June 2018, is an archive member named like ../../evil.sh that is written outside the target directory. ASVS 5.3.3 asks that decompression "ignores user-provided path information to prevent vulnerabilities such as zip slip". ASVS 5.2.3 asks for checks of the maximum uncompressed size and file count before uncompressing. ASVS 5.2.5 asks that archives with symlinks are refused unless needed.

zip. zipfile.ZipFile.extract() strips absolute paths and .. components. Own the check anyway, so the rule is visible, tested and applied before any byte is written. The fixed lab checks every member, then extracts with a running byte cap in case the sizes in the archive headers lie:

if len(infos) > MAX_ARCHIVE_FILES:
    return problem(413, "Content Too Large", "too many files")
if sum(i.file_size for i in infos) > MAX_UNCOMPRESSED_BYTES:
    return problem(413, "Content Too Large", "uncompressed size over the limit")
for info in infos:
    target = (dest / info.filename).resolve()
    if info.filename.startswith(("/", "\\")) or not target.is_relative_to(dest):
        return problem(400, "Bad Request", "archive member escapes the destination")
    if stat.S_ISLNK(info.external_attr >> 16):
        return problem(400, "Bad Request", "symlinks are not accepted")
    if info.compress_size and info.file_size / info.compress_size > MAX_COMPRESSION_RATIO:
        return problem(413, "Content Too Large", "compression ratio over the limit")

In the lab, the vulnerable twin wrote ../zip-slip-escaped.txt outside the destination and extracted 16,777,216 bytes from a zip of about 16 KiB. The fixed twin refused both (400 and 413) with nothing extracted.

tar. Python 3.12 added extraction filters, and Python 3.14 made data the default. The data filter refuses absolute paths, paths outside the destination, links that point outside or to absolute paths, and device files. Pass it explicitly so behaviour does not depend on the interpreter version. The Python docs warn that "None of the available filters blocks all dangerous archive features", so keep size and count limits as well. This snippet gave the same result on Python 3.12.13 and 3.14.10:

import io, tarfile, tempfile

buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tar:
    info = tarfile.TarInfo("../escape.txt")
    info.size = 2
    tar.addfile(info, io.BytesIO(b"hi"))
buf.seek(0)
with tempfile.TemporaryDirectory() as d, tarfile.open(fileobj=buf) as tar:
    try:
        tar.extractall(d, filter="data")
    except tarfile.OutsideDestinationError as exc:
        print("refused:", type(exc).__name__)      # refused: OutsideDestinationError

XML: XXE & Entity Expansion

The OWASP XXE Prevention Cheat Sheet's general rule is to disable DTDs where possible and keep XInclude disabled. For Python it says to use the defusedxml parsing interfaces for untrusted XML and to set forbid_dtd=True when DTDs are not needed. It adds that Expat versions below 2.7.2 may be affected by entity-expansion and related denial-of-service problems, so check pyexpat.EXPAT_VERSION in the deployed interpreter.

from defusedxml import DefusedXmlException
from defusedxml.ElementTree import ParseError, fromstring

def parse_untrusted_xml(data: bytes, max_bytes: int = 16 * 1024):
    if len(data) > max_bytes:
        raise ValueError("XML document too large")
    try:
        return fromstring(data, forbid_dtd=True)   # no DTD, so no entities of any kind
    except (DefusedXmlException, ParseError) as exc:
        raise ValueError(f"XML refused: {type(exc).__name__}") from None

With defusedxml 0.7.1 on Python 3.12.13, a document with an external entity and one with nested internal entities were both refused with DTDForbidden, and malformed XML with ParseError.

What the lab shows and does not show:

  • In xml-external-entity, the vulnerable twin used a SAX parser with external general entities switched on (feature_external_ges) and returned a file from the lab sandbox. The fixed twin refused the document (400). The flaw comes from that parser setting. The OWASP sheet notes that Expat itself does not access files or the network by default, but higher-level APIs and custom handlers can.
  • Entity expansion ("billion laughs") is not a lab case. In local runs (not CI), the standard-library ElementTree parser refused a nested-entity document with "limit on input amplification factor (from DTD and entities) breached" on expat_2.8.1 and expat_2.10.0, so the vulnerable side would not show a flaw. The CI runner recorded expat_2.9.0, but no expansion test ran there. Python's XML documentation says Expat versions lower than 2.7.2 may be vulnerable; check pyexpat.EXPAT_VERSION.
  • Keep a byte cap on XML input. defusedxml rejects constructs; it does not replace size limits.

Serving Files Back

  • Send an explicit Content-Type that matches the content (ASVS 4.1.1) and X-Content-Type-Options: nosniff on all responses (ASVS 3.4.4), so a browser does not sniff an "image" as HTML.
  • Send Content-Disposition: attachment with a server-chosen file name for downloads, encoded per RFC 6266 (ASVS 5.4.1, 5.4.2).
  • Serve user content from a separate origin where possible, so a file that is rendered as HTML cannot read the main site's cookies.

Verification Tests

Test Expected
HTML or script content with a .png name and Content-Type: image/png 415
File one byte over the size limit 413, nothing stored
Stored file name Server-generated, not the uploaded name
Zip with ../x, /x or a symlink member 400, nothing extracted
Zip whose total uncompressed size or file count is over the limit 413, nothing extracted
Zip whose headers under-state the size Extraction stops at the byte cap
Tar with ../x Refused by filter="data"
XML with a DOCTYPE Refused
Download of an uploaded file Explicit Content-Type, nosniff, Content-Disposition

The lab's upload-type-by-content, archive-zip-slip, archive-decompression-bomb and xml-external-entity cases passed in CI run 46241150192, on synthetic, illustrative teaching code only.

๐Ÿ“š References

See also

Related Files


โฌ…๏ธ Web Application Security index | Master Index | ๐ŸŽฏ Role Navigation | Legal Notice


๐Ÿ“„ Source: WebAppSecurity/file-upload-and-parser-boundaries.md | โœ๏ธ Suggest an edit | โฌ…๏ธ Back to Web App Security

Clone this wiki locally