4: исправление по ревью — проверка смысла чанков PNG (палитра, tRNS, порядок, текст), регрессионные тесты, evidence

This commit is contained in:
kalibr456
2026-10-22 14:30:53 +03:00
parent 5c3a31db2e
commit 4d4b914676
26 changed files with 587 additions and 279 deletions
+183 -15
View File
@@ -183,7 +183,12 @@ def inspect(upload: Upload, declared: str) -> ImageInfo:
upload.file.seek(0)
try:
with _decode_slots:
width, height = check_png(upload.file) if detected == PNG else check_jpeg(upload.file)
if detected == PNG:
width, height = check_png(upload.file)
upload.file.seek(0)
check_png_metadata(upload.file)
else:
width, height = check_jpeg(upload.file)
except TooManyPixels:
raise payload_too_large(f"Image has more than {settings.MAX_IMAGE_PIXELS} pixels") from None
except Damaged as exc:
@@ -262,13 +267,40 @@ class PngRows:
return self.total == self.expected
# Чанки, содержимое которых проверяется (держим в памяти; размер ограничен спецификацией):
# IHDR — 13 байт, PLTE — до 256 x 3 = 768, tRNS — до 256 (палитра) / 6 (RGB).
SMALL_CHUNK_LIMIT = {b"IHDR": 13, b"PLTE": 768, b"tRNS": 256}
CRITICAL = (b"IHDR", b"PLTE", b"IDAT", b"IEND")
# После данных изображения допустимы только время и текст (строгий список).
AFTER_IDAT = {b"IEND", b"tIME", b"tEXt", b"zTXt", b"iTXt"}
TEXT_CHUNKS = (b"tEXt", b"zTXt", b"iTXt")
# Анимированные PNG (APNG) не поддерживаются: кадры — отдельная сущность, превью строится по одному кадру.
APNG_CHUNKS = (b"acTL", b"fcTL", b"fdAT")
# Как PngImagePlugin.MAX_TEXT_CHUNK в Pillow: больше 1 MiB распакованного текста в одном чанке — отказ.
TEXT_LIMIT = 1024 * 1024
# Чанки метаданных до IDAT Pillow (Image.open) читает целиком: ограничиваем, чтобы память не росла.
# ICC-профили и EXIF реальных картинок — единицы-сотни KiB.
PRE_IDAT_CHUNK_LIMIT = 2 * 1024 * 1024
# Чанки, которые по спецификации обязаны стоять ДО первого IDAT (PNG 3rd ed., 5.6 «Chunk ordering»).
# После IDAT допустимы только tIME, tEXt, zTXt, iTXt, кадры APNG и частные чанки.
BEFORE_IDAT = {b"PLTE", b"tRNS", b"cHRM", b"cICP", b"gAMA", b"iCCP", b"mDCV", b"cLLI", b"sBIT", b"sRGB",
b"bKGD", b"hIST", b"pHYs", b"sPLT", b"eXIf"}
def check_png(file: BinaryIO) -> tuple[int, int]:
"""Структура PNG по спецификации (PNG 3rd ed., гл. 5 и 11) без декодирования пикселей в память.
Кроме CRC каждого чанка проверяется СМЫСЛ критичных чанков и tRNS: CRC защищает только от
случайной порчи, а намеренно собранный файл с верными CRC может быть некорректным.
"""
if file.read(8) != PNG_SIGNATURE:
raise Damaged("signature")
rows = inflater = None
width = height = 0
seen_idat = idat_finished = have_plte = False
width = height = depth = 0
color = None
palette_entries = 0
seen = set() # какие чанки уже встречались
idat_started = idat_finished = False
first = True
while True:
header = file.read(8)
@@ -277,11 +309,37 @@ def check_png(file: BinaryIO) -> tuple[int, int]:
length, kind = struct.unpack(">I4s", header)
if length > 0x7FFFFFFF:
raise Damaged("chunk length")
if not kind.isalpha() or not kind.isascii():
raise Damaged("chunk type")
if first and kind != b"IHDR":
raise Damaged("IHDR must be first")
if kind[:1].isupper() and kind not in CRITICAL:
raise Damaged(f"unknown critical chunk {kind!r}") # такой чанк декодер обязан отвергнуть
if kind in SMALL_CHUNK_LIMIT and length > SMALL_CHUNK_LIMIT[kind]:
raise Damaged(f"{kind!r} is too long")
if kind == b"IDAT":
if rows is None or idat_finished:
raise Damaged("IDAT chunks must be consecutive")
idat_started = True
elif idat_started:
idat_finished = True
if kind in APNG_CHUNKS:
raise Damaged("animated PNG is not supported")
if kind in BEFORE_IDAT and idat_started:
raise Damaged(f"{kind!r} after IDAT")
if idat_finished and kind not in AFTER_IDAT:
raise Damaged(f"{kind!r} after IDAT")
if not idat_started and kind != b"IDAT" and length > PRE_IDAT_CHUNK_LIMIT:
raise Damaged(f"{kind!r} metadata chunk is too large")
if kind == b"tIME" and length != 7:
raise Damaged("tIME size")
if kind in (b"IHDR", b"PLTE", b"tRNS", b"IEND") and kind in seen:
raise Damaged(f"duplicate {kind!r}")
seen.add(kind)
crc = zlib.crc32(kind)
keep = kind in (b"IHDR",)
kept = b""
text = TextChunk(kind) if kind in TEXT_CHUNKS else None
left = length
while left:
piece = file.read(min(CRC_CHUNK, left))
@@ -289,18 +347,20 @@ def check_png(file: BinaryIO) -> tuple[int, int]:
raise Damaged("truncated chunk")
left -= len(piece)
crc = zlib.crc32(piece, crc)
if keep:
if kind in SMALL_CHUNK_LIMIT:
kept += piece
elif kind == b"IDAT":
if rows is None or idat_finished:
raise Damaged("IDAT out of order")
feed_inflate(inflater, rows, piece)
elif text is not None:
text.feed(piece)
if text is not None:
text.finish()
stored = file.read(4)
if len(stored) < 4 or struct.unpack(">I", stored)[0] != crc & 0xFFFFFFFF:
raise Damaged(f"CRC mismatch in {kind!r}")
if kind == b"IHDR":
if not first or length != 13:
if length != 13:
raise Damaged("IHDR")
width, height, depth, color, compression, filter_method, interlace = struct.unpack(">IIBBBBB", kept)
if width > 0x7FFFFFFF or height > 0x7FFFFFFF:
@@ -313,20 +373,34 @@ def check_png(file: BinaryIO) -> tuple[int, int]:
rows = PngRows(width, height, depth, color, interlace)
inflater = zlib.decompressobj()
elif kind == b"PLTE":
have_plte = True
elif kind == b"IDAT":
seen_idat = True
# 1-256 записей по 3 байта; для палитровых — не больше 2^глубина; у серых палитры быть не может.
if color in (0, 4):
raise Damaged("PLTE in a grayscale image")
if length == 0 or length % 3:
raise Damaged("palette size")
palette_entries = length // 3
if color == 3 and palette_entries > 1 << depth:
raise Damaged("palette larger than the bit depth allows")
elif kind == b"tRNS":
# Прозрачность: серое — 2 байта, RGB — 6, палитра — не больше записей PLTE; при альфа-канале запрещён.
if color in (4, 6):
raise Damaged("tRNS with an alpha channel")
if color == 3 and not palette_entries:
raise Damaged("tRNS before PLTE")
expected_ok = {0: length == 2, 2: length == 6, 3: 1 <= length <= palette_entries}[color]
if not expected_ok:
raise Damaged("tRNS size")
elif kind == b"IEND":
if length != 0:
raise Damaged("IEND with data")
break
if seen_idat and kind != b"IDAT":
idat_finished = True
first = False
if file.read(1):
raise Damaged("data after IEND")
if color == 3 and not have_plte:
if color == 3 and not palette_entries:
raise Damaged("palette image without PLTE")
if not seen_idat:
if not idat_started:
raise Damaged("no IDAT")
tail = inflater.flush(INFLATE_CHUNK)
if tail:
@@ -336,6 +410,100 @@ def check_png(file: BinaryIO) -> tuple[int, int]:
return width, height
def check_png_metadata(file: BinaryIO) -> None:
"""Второе мнение: стандартный парсер Pillow разбирает метаданные до IDAT (gAMA, iCCP, pHYs, tEXt…),
НЕ читая пиксели. Только open, без verify(): verify читает каждый чанк, включая IDAT до 10 MiB,
целиком в память, а CRC и данные после IDAT уже потоково проверил check_png.
Нужен для вспомогательных чанков: по спецификации их можно игнорировать, но если Pillow
не может их разобрать, файл нельзя будет обработать (превью в lab5) — лучше отклонить сразу.
"""
with Image.open(file, formats=["PNG"]):
pass # open разбирает все чанки до первого IDAT; после IDAT check_png пускает только время и текст
class TextChunk:
"""Потоковая проверка tEXt / zTXt / iTXt: ключ 1-79 байт, метод сжатия 0, сжатый текст —
корректный zlib не больше TEXT_LIMIT после распаковки (распаковка кусками, текст не хранится)."""
def __init__(self, kind: bytes):
self.kind = kind
self.head = b""
self.done_header = False
self.inflater = None
self.size = 0
def feed(self, piece: bytes) -> None:
if not self.done_header:
self.head += piece
rest = self._header()
if rest is None:
if len(self.head) > 4096:
raise Damaged("text chunk header")
return
piece = rest
if self.inflater is not None and piece:
self._inflate(piece)
def _keyword_end(self) -> int | None:
end = self.head.find(b"\x00")
if end == -1:
return None
if not 1 <= end <= 79:
raise Damaged("text keyword")
return end
def _header(self) -> bytes | None:
end = self._keyword_end()
if end is None:
return None
h = self.head
if self.kind == b"tEXt":
self.done_header = True
return b""
if self.kind == b"zTXt":
if len(h) < end + 2:
return None
if h[end + 1] != 0:
raise Damaged("zTXt compression method")
self.done_header, self.inflater = True, zlib.decompressobj()
return h[end + 2:]
# iTXt: keyword \0 flag method language \0 translated-keyword \0 text
if len(h) < end + 3:
return None
flag, method = h[end + 1], h[end + 2]
if flag not in (0, 1) or (flag and method != 0):
raise Damaged("iTXt compression")
lang_end = h.find(b"\x00", end + 3)
tkey_end = h.find(b"\x00", lang_end + 1) if lang_end != -1 else -1
if tkey_end == -1:
return None
self.done_header = True
if flag:
self.inflater = zlib.decompressobj()
return h[tkey_end + 1:]
def _inflate(self, data: bytes) -> None:
if self.inflater.eof:
raise Damaged("data after compressed text")
out = self.inflater.decompress(data, INFLATE_CHUNK)
self.size += len(out)
while self.inflater.unconsumed_tail and not self.inflater.eof and self.size <= TEXT_LIMIT:
out = self.inflater.decompress(self.inflater.unconsumed_tail, INFLATE_CHUNK)
self.size += len(out)
if self.size > TEXT_LIMIT:
raise Damaged("compressed text is too large")
if self.inflater.eof and self.inflater.unused_data:
raise Damaged("data after compressed text")
def finish(self) -> None:
if not self.done_header:
raise Damaged("text chunk header")
if self.inflater is not None:
self.size += len(self.inflater.flush(INFLATE_CHUNK))
if not self.inflater.eof or self.size > TEXT_LIMIT:
raise Damaged("compressed text")
def feed_inflate(inflater, rows: PngRows, data: bytes) -> None:
"""Распаковка кусками не больше 64 KiB: «zip-бомба» не раздует память."""
if inflater.eof: