303 lines
11 KiB
Python
303 lines
11 KiB
Python
"""Content-based validation of uploaded PNG/JPEG images.
|
|
|
|
The declared Content-Type is never trusted: the format is detected from the
|
|
first bytes and must match it. Dimensions are read from the header and the
|
|
pixel limit is applied BEFORE any decoding, so a small "pixel bomb" file
|
|
cannot make the API allocate gigabytes.
|
|
|
|
- PNG is validated by our own streaming reader: critical chunks, CRC of every
|
|
chunk, IHDR, and the IDAT zlib stream is decompressed in 64 KiB pieces.
|
|
Scanline sizes and filter bytes (also in Adam7 passes) are checked without
|
|
retaining any row. Memory stays O(64 KiB) for any image.
|
|
- JPEG: Pillow reads the header (lazy open); then the image is decoded with
|
|
draft() at 1/8 scale, which makes libjpeg read the whole entropy-coded
|
|
stream (a truncated/corrupted file raises) while allocating only 1/64 of
|
|
the full-size pixel buffer. Large progressive JPEGs can still retain DCT
|
|
coefficients; the caller must bound concurrent validation and memory.
|
|
Their entropy stream is checked as well: there is no header-only bypass.
|
|
|
|
The functions are synchronous (CPU work); call them via asyncio.to_thread.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import struct
|
|
import zlib
|
|
from dataclasses import dataclass
|
|
from typing import BinaryIO
|
|
|
|
from PIL import Image
|
|
|
|
# Our own limit is applied before Pillow decodes anything.
|
|
Image.MAX_IMAGE_PIXELS = None
|
|
|
|
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
JPEG_SIGNATURE = b"\xff\xd8\xff"
|
|
CHUNK = 64 * 1024
|
|
|
|
|
|
class InvalidImage(Exception):
|
|
"""Not a PNG/JPEG, a corrupted file or a Content-Type mismatch (-> 415)."""
|
|
|
|
|
|
class TooManyPixels(Exception):
|
|
"""Decoded image would exceed MAX_IMAGE_PIXELS (-> 413)."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ImageInfo:
|
|
content_type: str
|
|
width: int
|
|
height: int
|
|
|
|
|
|
def sniff_content_type(head: bytes) -> str | None:
|
|
if head.startswith(PNG_SIGNATURE):
|
|
return "image/png"
|
|
if head.startswith(JPEG_SIGNATURE):
|
|
return "image/jpeg"
|
|
return None
|
|
|
|
|
|
def validate_image(
|
|
file: BinaryIO,
|
|
declared_content_type: str,
|
|
max_pixels: int,
|
|
) -> ImageInfo:
|
|
file.seek(0)
|
|
detected = sniff_content_type(file.read(len(PNG_SIGNATURE)))
|
|
file.seek(0)
|
|
|
|
if detected is None:
|
|
raise InvalidImage("Content is not a PNG or JPEG image.")
|
|
|
|
if detected != declared_content_type:
|
|
raise InvalidImage("Content-Type does not match the image content.")
|
|
|
|
if detected == "image/png":
|
|
width, height = _validate_png(file, max_pixels)
|
|
else:
|
|
width, height = _validate_jpeg(file, max_pixels)
|
|
|
|
return ImageInfo(detected, width, height)
|
|
|
|
|
|
# --- PNG -------------------------------------------------------------------
|
|
|
|
# color type -> (channels, allowed bit depths)
|
|
_PNG_COLOR_TYPES = {
|
|
0: (1, {1, 2, 4, 8, 16}),
|
|
2: (3, {8, 16}),
|
|
3: (1, {1, 2, 4, 8}),
|
|
4: (2, {8, 16}),
|
|
6: (4, {8, 16}),
|
|
}
|
|
_ADAM7_PASSES = (
|
|
(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4),
|
|
(0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2),
|
|
)
|
|
|
|
|
|
def _read_exact(file: BinaryIO, size: int) -> bytes:
|
|
data = file.read(size)
|
|
if len(data) != size:
|
|
raise InvalidImage("Image file is truncated.")
|
|
return data
|
|
|
|
|
|
def _png_scanlines(width: int, height: int, bits_per_pixel: int,
|
|
interlace: int) -> list[tuple[int, int]]:
|
|
"""At most seven (packed row bytes, row count) pairs; no row allocation."""
|
|
if interlace == 0:
|
|
return [((width * bits_per_pixel + 7) // 8, height)]
|
|
passes = []
|
|
for x0, y0, dx, dy in _ADAM7_PASSES:
|
|
w = (width - x0 + dx - 1) // dx if width > x0 else 0
|
|
h = (height - y0 + dy - 1) // dy if height > y0 else 0
|
|
if w and h:
|
|
passes.append(((w * bits_per_pixel + 7) // 8, h))
|
|
return passes
|
|
|
|
|
|
class _PngScanlines:
|
|
"""Validate filter positions across arbitrary decompression boundaries."""
|
|
def __init__(self, passes: list[tuple[int, int]]) -> None:
|
|
self.passes = iter(passes)
|
|
self.row_bytes, self.rows_left = next(self.passes)
|
|
self.row_remaining = 0
|
|
self.expected = sum((row_bytes + 1) * count for row_bytes, count in passes)
|
|
self.produced = 0
|
|
|
|
def feed(self, data: bytes) -> None:
|
|
self.produced += len(data)
|
|
if self.produced > self.expected:
|
|
raise InvalidImage("PNG image data is larger than IHDR declares.")
|
|
position = 0
|
|
while position < len(data):
|
|
if self.row_remaining == 0:
|
|
if self.rows_left == 0:
|
|
try:
|
|
self.row_bytes, self.rows_left = next(self.passes)
|
|
except StopIteration:
|
|
raise InvalidImage("PNG has too many scanlines.") from None
|
|
if data[position] > 4:
|
|
raise InvalidImage("Invalid PNG scanline filter.")
|
|
position += 1
|
|
self.rows_left -= 1
|
|
self.row_remaining = self.row_bytes
|
|
consumed = min(self.row_remaining, len(data) - position)
|
|
self.row_remaining -= consumed
|
|
position += consumed
|
|
|
|
|
|
def _validate_png(file: BinaryIO, max_pixels: int) -> tuple[int, int]:
|
|
_read_exact(file, len(PNG_SIGNATURE))
|
|
|
|
width = height = 0
|
|
scanlines = None
|
|
inflater = zlib.decompressobj()
|
|
color_type = -1
|
|
bit_depth = 0
|
|
seen_plte = False
|
|
palette_entries = 0
|
|
seen_trns = False
|
|
idat_state = "before" # before -> inside -> after
|
|
first = True
|
|
|
|
while True:
|
|
header = _read_exact(file, 8)
|
|
length, chunk_type = struct.unpack(">I4s", header)
|
|
|
|
if length > 0x7FFFFFFF:
|
|
raise InvalidImage("Invalid PNG chunk length.")
|
|
|
|
if first and chunk_type != b"IHDR":
|
|
raise InvalidImage("PNG must start with IHDR.")
|
|
if not all(65 <= ch <= 90 or 97 <= ch <= 122 for ch in chunk_type) \
|
|
or not 65 <= chunk_type[2] <= 90:
|
|
raise InvalidImage("Invalid PNG chunk type.")
|
|
if chunk_type == b"IHDR" and (not first or length != 13):
|
|
# Check before reading/buffering: an attacker cannot turn a
|
|
# bogus multi-megabyte IHDR into a large allocation.
|
|
raise InvalidImage("Invalid or duplicate PNG IHDR.")
|
|
if chunk_type[0] < 97 and chunk_type not in {b"IHDR", b"PLTE", b"IDAT", b"IEND"}:
|
|
raise InvalidImage("Unknown critical PNG chunk.")
|
|
if chunk_type == b"IEND" and length != 0:
|
|
raise InvalidImage("Invalid PNG IEND.")
|
|
if chunk_type == b"PLTE":
|
|
if seen_plte or seen_trns or idat_state != "before" or color_type in {0, 4} \
|
|
or not 3 <= length <= 768 or length % 3:
|
|
raise InvalidImage("Invalid PNG palette.")
|
|
palette_entries = length // 3
|
|
if color_type == 3 and palette_entries > 1 << bit_depth:
|
|
raise InvalidImage("PNG palette exceeds its bit depth.")
|
|
if chunk_type == b"tRNS":
|
|
valid_length = ((color_type == 0 and length == 2) or
|
|
(color_type == 2 and length == 6) or
|
|
(color_type == 3 and seen_plte and 1 <= length <= palette_entries))
|
|
if seen_trns or idat_state != "before" or not valid_length:
|
|
raise InvalidImage("Invalid PNG transparency chunk.")
|
|
seen_trns = True
|
|
|
|
crc = zlib.crc32(chunk_type)
|
|
is_idat = chunk_type == b"IDAT"
|
|
|
|
if is_idat:
|
|
if idat_state == "after":
|
|
raise InvalidImage("PNG IDAT chunks are not consecutive.")
|
|
if color_type == 3 and not seen_plte:
|
|
raise InvalidImage("PNG palette image without PLTE.")
|
|
idat_state = "inside"
|
|
elif idat_state == "inside":
|
|
idat_state = "after"
|
|
|
|
data = b""
|
|
remaining = length
|
|
while remaining:
|
|
piece = _read_exact(file, min(CHUNK, remaining))
|
|
remaining -= len(piece)
|
|
crc = zlib.crc32(piece, crc)
|
|
|
|
if is_idat:
|
|
_inflate_scanlines(inflater, piece, scanlines)
|
|
elif chunk_type == b"IHDR":
|
|
data += piece
|
|
|
|
(stored_crc,) = struct.unpack(">I", _read_exact(file, 4))
|
|
if stored_crc != crc:
|
|
raise InvalidImage("PNG chunk CRC mismatch.")
|
|
|
|
if first:
|
|
first = False
|
|
(width, height, bit_depth, color_type,
|
|
compression, filter_method, interlace) = struct.unpack(">IIBBBBB", data)
|
|
|
|
if width == 0 or height == 0 or width > 0x7FFFFFFF or height > 0x7FFFFFFF:
|
|
raise InvalidImage("Invalid PNG dimensions.")
|
|
if width * height > max_pixels:
|
|
# Before a single IDAT byte is decompressed.
|
|
raise TooManyPixels()
|
|
if color_type not in _PNG_COLOR_TYPES:
|
|
raise InvalidImage("Invalid PNG color type.")
|
|
channels, depths = _PNG_COLOR_TYPES[color_type]
|
|
if bit_depth not in depths or compression != 0 or filter_method != 0 \
|
|
or interlace not in (0, 1):
|
|
raise InvalidImage("Invalid PNG IHDR.")
|
|
scanlines = _PngScanlines(
|
|
_png_scanlines(width, height, channels * bit_depth, interlace)
|
|
)
|
|
elif chunk_type == b"PLTE":
|
|
seen_plte = True
|
|
elif chunk_type == b"IEND":
|
|
break
|
|
|
|
if idat_state == "before":
|
|
raise InvalidImage("PNG has no image data.")
|
|
|
|
# decompress(max_length) drains every unconsumed_tail above. No flush()
|
|
# is needed (and its output would not have a strict allocation bound).
|
|
if not inflater.eof or scanlines.produced != scanlines.expected:
|
|
raise InvalidImage("PNG image data is corrupted or truncated.")
|
|
|
|
return width, height
|
|
|
|
|
|
def _inflate_scanlines(inflater, data: bytes, scanlines: _PngScanlines) -> None:
|
|
"""Decompress at most 64 KiB at once, validate, then discard."""
|
|
try:
|
|
while data:
|
|
if inflater.eof:
|
|
raise InvalidImage("PNG has data after the end of the zlib stream.")
|
|
out = inflater.decompress(data, CHUNK)
|
|
scanlines.feed(out)
|
|
if inflater.unused_data:
|
|
raise InvalidImage("PNG has data after the end of the zlib stream.")
|
|
data = inflater.unconsumed_tail
|
|
except zlib.error:
|
|
raise InvalidImage("PNG image data is corrupted.") from None
|
|
|
|
|
|
# --- JPEG ------------------------------------------------------------------
|
|
|
|
def _validate_jpeg(file: BinaryIO, max_pixels: int) -> tuple[int, int]:
|
|
try:
|
|
with Image.open(file, formats=["JPEG"]) as image:
|
|
width, height = image.size
|
|
|
|
if width < 1 or height < 1:
|
|
raise InvalidImage("Invalid JPEG dimensions.")
|
|
if width * height > max_pixels:
|
|
# Header only: no pixel has been decoded yet.
|
|
raise TooManyPixels()
|
|
|
|
image.draft("RGB", (max(1, width // 8), max(1, height // 8)))
|
|
image.load()
|
|
except (InvalidImage, TooManyPixels):
|
|
raise
|
|
except Exception:
|
|
# Pillow raises OSError/SyntaxError/ValueError/... for broken data.
|
|
raise InvalidImage("JPEG image is corrupted or truncated.") from None
|
|
|
|
return width, height
|
|
|
|
|