fix: reject undecodable JPEG without tables or with a bad scan header

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 03:23:00 +03:00
co-authored by Claude Opus 5.5
parent e30b6496f1
commit 844306d5cb
9 changed files with 576 additions and 46 deletions
+79 -3
View File
@@ -3,8 +3,9 @@
PNG собираются на stdlib — любые IHDR и IDAT, Adam7, точный размер файла
чанком-заполнителем `tEXt`, «бомба», порча CRC. JPEG — через Pillow
(dev-группа): прогрессивный, серый, CMYK, с EXIF, с подменой размеров в
SOF. Большие файлы и «бомбы» живут только в памяти теста и в git не
попадают (`tests/fixtures/README.md`).
SOF, без таблиц, с изменённым заголовком скана и без данных скана.
Большие файлы и «бомбы» живут только в памяти теста и в git не попадают
(`tests/fixtures/README.md`).
"""
import functools
@@ -15,6 +16,16 @@ import zlib
from pathlib import Path
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
# маркеры JPEG: таблицы квантования и Хаффмана, начало скана, конец
JPEG_DQT = 0xDB
JPEG_DHT = 0xC4
JPEG_SOS = 0xDA
JPEG_EOI = b"\xff\xd9"
# 27 байт из замечания к PR: SOI, SOF0 1 × 1, SOS без данных и EOI — ни
# таблицы квантования, ни таблиц Хаффмана
JPEG_WITHOUT_TABLES = bytes.fromhex(
"ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9",
)
SAMPLE_PNG_PATH = (
Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png"
)
@@ -217,6 +228,45 @@ def jpeg_huge(width: int, height: int) -> bytes:
return bytes(data)
def _jpeg_header(data: bytes) -> list[tuple[int, int, int]]:
"""Сегменты до первого скана включительно: маркер, начало, конец."""
segments = []
pos = 2
while True:
marker = data[pos + 1]
(length,) = struct.unpack_from(">H", data, pos + 2)
segments.append((marker, pos, pos + 2 + length))
pos += 2 + length
if marker == JPEG_SOS:
return segments
def jpeg_without(marker: int, data: bytes | None = None) -> bytes:
"""JPEG без сегментов `marker` (`JPEG_DQT`, `JPEG_DHT`) до первого
скана."""
data = data or jpeg()
out = bytearray(data)
for found, start, end in reversed(_jpeg_header(data)):
if found == marker:
del out[start:end]
return bytes(out)
def jpeg_scan_byte(data: bytes, index: int, value: int) -> bytes:
"""Байт `index` тела первого SOS заменён на `value`: 1 — id первой
компоненты, -3, -2, -1 — Ss, Se и Ah/Al."""
_, start, end = _jpeg_header(data)[-1]
out = bytearray(data)
out[start + 4 + index if index >= 0 else end + index] = value
return bytes(out)
def jpeg_empty_scan(data: bytes | None = None) -> bytes:
"""JPEG, у которого за заголовком первого скана сразу EOI."""
data = data or jpeg()
return data[: _jpeg_header(data)[-1][2]] + JPEG_EOI
def png_variants() -> dict[str, bytes]:
"""Разновидности PNG спека: палитра, альфа, серый с альфой, 16 и 1
бит, Adam7."""
@@ -231,10 +281,36 @@ def png_variants() -> dict[str, bytes]:
def jpeg_variants() -> dict[str, bytes]:
"""Разновидности JPEG спека: прогрессивный, серый, CMYK, с EXIF."""
"""Разновидности JPEG спека: прогрессивный, серый, CMYK, с EXIF,
baseline без таблиц Хаффмана (кадр Motion JPEG: декодер берёт
стандартные)."""
return {
"progressive": jpeg(progressive=True),
"gray": jpeg("L"),
"cmyk": jpeg("CMYK"),
"exif": jpeg(exif=True),
"no-huffman-tables": jpeg_without(JPEG_DHT),
}
def jpeg_undecodable() -> dict[str, bytes]:
"""JPEG, которые проходят разбор маркеров, но не декодируются или
заведомо оборваны (спек `attachments`, «Недекодируемый JPEG»)."""
progressive = jpeg(progressive=True)
return {
"27 bytes without tables": JPEG_WITHOUT_TABLES,
"no quantization tables": jpeg_without(JPEG_DQT),
"progressive without huffman tables": jpeg_without(
JPEG_DHT,
progressive,
),
"scan of unknown component": jpeg_scan_byte(jpeg(), 1, 9),
# первый скан Pillow — DC трёх компонент; полоса 1–63 делает его
# AC-сканом, а у AC-скана компонента одна
"progressive ac band of 3 components": jpeg_scan_byte(
jpeg_scan_byte(progressive, -3, 1),
-2,
63,
),
"empty scan data": jpeg_empty_scan(),
}
+20
View File
@@ -298,6 +298,26 @@ def test_damaged_png_data(
)
@pytest.mark.spec("attachments", "Недекодируемый JPEG")
def test_undecodable_jpeg(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
assert_errors(
{
name: api.post_attachment(
alice,
chat["id"],
data,
content_type="image/jpeg",
)
for name, data in images.jpeg_undecodable().items()
},
415,
)
@pytest.mark.spec("attachments", "Хвост после конца изображения")
def test_tail_after_end(
api: Api,