Security and Operations for Media Processing
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. A media pipeline feeds untrusted files to some of the most complex parsers in a typical stack: image decoders, demuxers and codecs. Those parsers have a long history of memory-safety bugs, and they run with whatever rights the worker has. The controls below limit what an attacker can submit, what a bug can reach, and what the pipeline costs when somebody abuses it. They apply to every language page in this section.
Validate what was uploaded
-
Magic bytes, not extension or
Content-Type. Both are chosen by the client. Read the first bytes and check them against the format you expect (JPEG starts withFF D8 FF, PNG with89 50 4E 47, WebP withRIFF....WEBP, ISO media files such as AVIF, HEIC and MP4 haveftypat offset 4). Libraries do this for you:ImageIO.getImageReaders, Pillow’sImage.openwithformatandverify, sharp’smetadata(), the Rustimagecrate’swith_guessed_format, andffprobefor video. Reject anything that is not on your allow list. -
Allow list of formats. Accept the formats you can handle, not "everything FFmpeg can read". FFmpeg and ImageMagick support hundreds of formats, and some of them (playlists, SVG with external references) can read local files or make network requests. In FFmpeg, restrict the protocols (
-protocol_whitelist file) and the demuxers (-format_whitelist mov,mp4,matroska,webm; the-formatsoption only lists what is available) for user input, and do not feed user-provided URLs to ImageMagick or FFmpeg at all (SSRF). -
Size and duration caps. Limit the object size in the pre-signed URL, in the HTTP server and in the worker. Probe a video first (
ffprobe) and refuse files above your maximum duration, resolution and frame rate before you transcode. -
Decompression bombs. A tiny file can decode to gigabytes of pixels (a 1 MB PNG of 60000 x 60000 pixels). Check the declared width and height from the header before you decode, and cap pixels (Pillow’s
Image.MAX_IMAGE_PIXELSmakesImage.openemit aDecompressionBombWarningabove the limit and raiseDecompressionBombErrorabove twice the limit, the Rustimagecrate hasLimits, libvips decodes lazily with sequential access, and ImageSharp can read the size without decoding throughImage.IdentifyAsync). Videos can be bombs too: a short clip with extreme resolution. -
Virus scanning. If the files are shared with other users (documents, archives), scan the upload with an engine such as ClamAV or the cloud provider’s malware protection before it is made available.
Strip metadata
EXIF holds GPS coordinates, device model and serial numbers, timestamps and sometimes a thumbnail of the original, including regions you cropped out. Strip it from every public variant:
| Tool | How |
|---|---|
sharp |
Metadata is stripped by default. |
libvips, pyvips, NetVips |
Metadata is kept by default. Pass |
Pillow |
Saving without |
Thumbnailator |
Written images carry no EXIF unless you copy it. |
ImageSharp |
EXIF loaded from the source is written back on save. Set |
FFmpeg |
|
Apply the orientation to the pixels first, then strip the tag, see image formats and encoding. Keep the original in private storage if you need it, and treat it as personal data.
Worked example: a hostile batch
The controls above are easy to nod at and easy to get wrong, so the rest of this page runs them on a batch of files that stand for the usual attacks and mistakes. The batch (all generated for the test) is: a phone JPEG with GPS
tags, a GIF named fake.mov, an SVG with a script named svg.jpg, a 388 KB PNG that declares 20000 by 20000 pixels, a 35 KB Matroska file that declares 16000 by 9000 pixels, a 3.4 MB Matroska file that lasts three hours, and an HLS playlist whose segments are
file:///etc/hostname and an http://169.254.169.254/latest/meta-data/ metadata URL. The tools were Python 3.13 with Pillow 13.0.0 and pyvips 3.2.0, and FFmpeg 6.1.1 and 7.1 in Docker (Ubuntu 24.04 and jrottenberg/ffmpeg:7-ubuntu).
Sniff the bytes first
A few lines of Python identify the containers on an allow list from the first 32 bytes, before any decoder sees the file:
def sniff(head: bytes) -> str | None:
"""Detect the container from the first 32 bytes. Returns None for anything not on the allow list."""
if head.startswith(b"\xff\xd8\xff"):
return "jpeg"
if head.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "webp"
if head[4:8] == b"ftyp":
brand = head[8:12]
if brand in (b"avif", b"avis"):
return "avif"
if brand in (b"heic", b"heix", b"hevc", b"mif1", b"msf1"):
return "heic"
if brand == b"qt ":
return "mov"
if brand in (b"isom", b"iso2", b"mp41", b"mp42", b"M4V ", b"avc1"):
return "mp4"
if head[:4] == b"\x1a\x45\xdf\xa3":
return "matroska-or-webm"
return None
| File | First bytes | Result |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
A file named .jpg that starts with <svg is rejected, and so is a playlist, which is exactly the class of input that makes FFmpeg open other files and URLs. The check is a filter, not a validator: a
file that starts with the right bytes can still be malformed, so the decoder must still run in a sandbox, and ftyp only tells you the brand, not that the rest of the file is sane.
Decompression bombs, measured
The bomb is a 20000 by 20000 8-bit grey PNG: 388,332 bytes on disk and 400,000,000 pixels once decoded (a ratio above 1000 to 1). Three runs:
-
Pillow with its default limit raises
DecompressionBombError: Image size (400000000 pixels) exceeds limit of 178956970 pixelsatImage.open, before any pixel is read. The defaultMAX_IMAGE_PIXELSis 89,478,485 and the error appears at twice that, which is the 178,956,970 in the message. Between the limit and twice the limit there is only a warning, so set your own, lower limit and check the size yourself, as the examples in the Python page do. -
With
Image.MAX_IMAGE_PIXELS = None(a setting that is sometimes suggested to silence the error), Pillow’sthumbnailtook 214 ms and 436 MB of resident memory to reduce it. In a container limited to 128 MB (docker run --memory 128m) the same script was killed by the kernel and the process exit code was 137, with the host unaffected, which is the failure you want a limit to produce, and the reason to set one even when the code checks first. -
pyvips reduced it in 154 ms with 101 MB, because libvips decodes PNG as a stream, so memory does not grow with the pixel count. That helps with memory, not with time: a 400-megapixel decode of a real photograph would still take CPU seconds, so check the declared size anyway.
The same shape applies to video: the 35 KB Matroska declares 16000 by 9000 pixels per frame, 144 megapixels, and nothing about its size betrays it.
Probe before you transcode
import json, subprocess
from fractions import Fraction
LIMITS = {"max_seconds": 600, "max_side": 4096, "max_fps": 60, "max_pixels_per_second": 4096 * 2160 * 30}
def check_video(path: str) -> dict:
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0", "-probesize", "5000000", "-analyzeduration", "5000000",
"-show_entries", "format=duration,format_name:stream=codec_name,width,height,avg_frame_rate",
"-of", "json", path],
check=True, capture_output=True, text=True, timeout=30)
info = json.loads(out.stdout)
stream = info["streams"][0]
seconds = float(info["format"]["duration"])
fps = float(Fraction(stream["avg_frame_rate"]))
if seconds > LIMITS["max_seconds"]:
raise ValueError(f"duration {seconds:.0f} s exceeds {LIMITS['max_seconds']} s")
if max(stream["width"], stream["height"]) > LIMITS["max_side"]:
raise ValueError(f"{stream['width']}x{stream['height']} exceeds {LIMITS['max_side']} px on one side")
if fps > LIMITS["max_fps"]:
raise ValueError(f"{fps:.0f} fps exceeds {LIMITS['max_fps']} fps")
if stream["width"] * stream["height"] * fps > LIMITS["max_pixels_per_second"]:
raise ValueError("pixel rate too high")
return {"seconds": seconds, "width": stream["width"], "height": stream["height"], "fps": fps, "codec": stream["codec_name"]}
Run with FFmpeg 6.1.1, the probe accepted the 10 second 1080p clip and rejected the others before any transcode:
vid/input.mov -> {'seconds': 10.0, 'width': 1920, 'height': 1080, 'fps': 24.0, 'codec': 'h264'}
vid/huge-res.mkv -> rejected: 16000x9000 exceeds 4096 px on one side
vid/long.mkv -> rejected: duration 10800 s exceeds 600 s
vid/fake.mov -> ffprobe failed: vid/fake.mov: Invalid data found when processing input
vid/evil.m3u8 -> ffprobe failed: vid/evil.m3u8: Invalid data found when processing input
-probesize and -analyzeduration bound the time ffprobe itself spends on a hostile file, and avg_frame_rate is a fraction such as 24/1, so parse it with Fraction, not float. The last two files do not even reach the limits because ffprobe
refuses them: a GIF behind a .mov name has no moov atom, and the playlist is blocked for the reasons below.
FFmpeg with restricted inputs
Opened from a local file, the hostile playlist is already mostly neutralised by recent FFmpeg defaults, and the options below close the rest. Default run:
[hls] Filename extension of 'file:///etc/hostname' is not a common multimedia extension, blocked for security reasons.
[hls] Failed to open segment 0 of playlist 0
[http] Protocol 'http' not on whitelist 'file,crypto,data'!
[hls] Failed to open segment 1 of playlist 0
[hls] Error when loading first segment 'file:///etc/hostname'
With -protocol_whitelist file the message becomes Protocol 'http' not on whitelist 'file'!, and with -format_whitelist mov,mp4,matroska,webm ffprobe refuses the playlist before reading it (Format not on whitelist 'mov,mp4,matroska,webm', Invalid argument),
while the same options still probe the real clip (format_name=mov,mp4,m4a,3gp,3g2,mj2, duration=10.000000). The extension check and the default whitelist are defence in depth that can change between versions: state the whitelists
explicitly in your commands, so that an upgrade does not widen what an uploaded file can reach.
A hardened run
docker run --rm --network none --read-only --tmpfs /tmp:rw,size=64m \
--cap-drop ALL --security-opt no-new-privileges --pids-limit 128 --memory 512m --cpus 2 --user 10001:10001 \
-v "$PWD/input.mov":/in/input.mov:ro -v "$PWD/out":/out \
--entrypoint ffmpeg jrottenberg/ffmpeg:7-ubuntu \
-hide_banner -nostdin -loglevel error -protocol_whitelist file -format_whitelist mov,mp4,matroska,webm \
-i /in/input.mov -map_metadata -1 -fflags +bitexact -flags:v +bitexact -flags:a +bitexact \
-vf scale=-2:720 -c:v libx264 -preset veryfast -crf 22 -g 48 -c:a aac -b:a 128k -movflags +faststart -y /out/720p.mp4
The run (FFmpeg 7.1, emulated amd64 on an arm64 host, so no timing is quoted) wrote 720p.mp4: 2,248,134 bytes, H.264 1280 by 720 with AAC, 10.008 seconds and 1,797,068 bits per second. Inside such a container,
touch /x failed with Read-only file system, and name resolution failed (--network none), so a payload cannot write outside /out or call out. The input file carried a location tag with GPS coordinates and an encoder tag; the output had
neither (ffprobe -show_entries format_tags printed only the three brand tags), because of -map_metadata -1 and the bitexact flags. A timeout 3 sleep 10 in the same image returned 124, the exit code to treat as "time limit hit" when
you wrap FFmpeg in timeout. The output directory is the only writable bind mount, and it is writable by the unprivileged user, which is why it was created with matching permissions.
Which metadata survives
The metadata table above was checked on the phone file. sharp’s default output had no EXIF, and keepExif(), keepMetadata() and withMetadata() each produced a file with EXIF and orientation 6 (314 bytes of EXIF after keepExif()), so a pipeline that
keeps metadata for convenience keeps the GPS block with it. Thumbnailator’s output had no exif or gps field, Pillow’s none, and libvips only with keep=none, as in the table.
Sandbox and limit the workers
-
Least privilege. The worker’s identity can read
uploads/, writemedia/and update its own status, and nothing else. No broad storage or database credentials. -
Isolation. Run FFmpeg and image libraries in a container with a read-only root filesystem, no network egress (they do not need it, which also blocks SSRF and data exfiltration), a non-root user, dropped capabilities and a seccomp profile. For stronger isolation, use gVisor or a microVM runtime, or run each job in its own short-lived container or cloud function, see Docker security and Kubernetes pod security.
-
Resource limits. Set CPU and memory limits, a process time limit (
timeout,ulimit, the language’s process timeouts), a disk quota for the scratch directory and a maximum number of processes. A single hostile or merely unlucky file must not exhaust a node. See Kubernetes resource management. -
No shell. Pass arguments to FFmpeg and
vipsas an array, never concatenated into a shell string, and never use the user’s file name on the command line. Use generated names (<uuid>.<ext>). A file name starting with-is an option. -
Delete scratch files. Clean the temporary directory after each job, and on startup.
Keep it patched
Decoders are a common source of CVEs. Track the releases and security advisories of FFmpeg, libvips, libheif, libwebp, libavif, libjpeg-turbo, ImageMagick (if you use it) and of the language bindings that bundle them (sharp ships its own libvips, Pillow wheels bundle libraries, JAVE2 bundles FFmpeg binaries). Rebuild the worker image regularly, scan it (see image best practices and security), and pin versions so that an update is a deliberate change. libwebp had a widely exploited heap overflow in 2023 (CVE-2023-4863), which is the example of why bundled libraries matter.
Storage layout, cost and lifecycle
-
Separate prefixes or buckets for
uploads/(private, short retention),originals/(private), andmedia/(served through the CDN). The CDN has read access tomedia/only. -
Lifecycle rules: delete
uploads/after processing (a few days is enough to debug), expire incomplete multipart uploads, and move originals to a cheaper storage class. See the lifecycle sections in S3, Cloud Storage and Blob Storage. -
Cost drivers: storage for every variant of every image (hence the short list of widths), egress at the CDN (hence AVIF and WebP), compute for the encodes (hence the slow AVIF encode on a queue, and spot or preemptible instances for video), and per-minute fees of managed transcoders. Prices are not quoted here, use the provider calculators.
-
Do not process the same bytes twice: key outputs by a content hash and skip files already processed (deduplication).
-
Rate-limit uploads per user and per tenant, and cap the number of concurrent jobs per tenant, so one user cannot fill the queue.
Monitoring
Track these metrics and alert on them:
| Metric | Why |
|---|---|
Queue depth and age of the oldest message |
The main signal that workers are behind. Alert when age exceeds your target. |
Job duration (histogram) per recipe, and per input resolution for video |
Detects regressions and slow encodes. Compare against the input duration. |
Success, failure and retry counts, by error type |
Corrupt uploads are normal. A jump in one error type is not. |
Dead-letter queue depth |
Anything there needs a human. |
Worker CPU, memory and out-of-memory kills |
Right-size the limits. |
Output size versus input size |
A sudden drop or growth shows an encoder setting problem. |
Time from upload to |
The user-visible metric. |
Use structured logs with the media id and job id in each line, and traces across API, queue and worker, as described in observability for Kubernetes workloads and the messaging pages linked from upload pipelines.
Related pages
-
Apache Tika: media types and detection and robustness, limits and timeouts, the same controls for documents