forked from mtusi2026/mtusi2026lab2
Reject ambiguous PNG headers before pixel validation
This commit is contained in:
@@ -6,7 +6,7 @@ from PIL import Image
|
||||
|
||||
from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.infrastructure.png import verify_png_pixels
|
||||
from messenger.attachments.infrastructure.png import SIGNATURE, read_png_header, verify_png_pixels
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
@@ -27,6 +27,7 @@ class PillowImageInspector:
|
||||
|
||||
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
try:
|
||||
header = read_png_header(data) if data.startswith(SIGNATURE) else None
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
except BOMBS as error:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
|
||||
@@ -34,18 +35,18 @@ class PillowImageInspector:
|
||||
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
|
||||
with image:
|
||||
kind = KINDS[str(image.format)]
|
||||
width, height = image.size
|
||||
width, height = image.size if header is None else header[:2]
|
||||
if kind is not declared:
|
||||
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
|
||||
if width * height > self._max_pixels:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
|
||||
try:
|
||||
if kind is ImageKind.JPEG:
|
||||
if header is None:
|
||||
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
verify_png_pixels(data)
|
||||
verify_png_pixels(data, header)
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
|
||||
@@ -2,6 +2,11 @@ import struct
|
||||
import zlib
|
||||
from collections.abc import Iterator
|
||||
|
||||
type PngHeader = tuple[int, int, int, int, int, int, int]
|
||||
|
||||
SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
HEADER_BYTES = 13
|
||||
CHUNK_OVERHEAD = 12
|
||||
BLOCK_BYTES = 65_536
|
||||
MAX_FILTER = 4
|
||||
PIXELS = {
|
||||
@@ -22,10 +27,34 @@ ADAM7 = (
|
||||
)
|
||||
|
||||
|
||||
def _scanlines(data: bytes) -> Iterator[tuple[int, int]]:
|
||||
width, height, depth, color, compression, filtering, interlace = struct.unpack_from(
|
||||
">IIBBBBB", data, 16
|
||||
)
|
||||
def _chunks(data: bytes) -> Iterator[tuple[bytes, memoryview]]:
|
||||
view = memoryview(data)
|
||||
offset = len(SIGNATURE)
|
||||
while offset + CHUNK_OVERHEAD <= len(data):
|
||||
size = struct.unpack_from(">I", data, offset)[0]
|
||||
kind = data[offset + 4 : offset + 8]
|
||||
start, end = offset + 8, offset + 8 + size
|
||||
if end + 4 > len(data):
|
||||
raise ValueError("truncated PNG chunk")
|
||||
yield kind, view[start:end]
|
||||
if kind == b"IEND":
|
||||
return
|
||||
offset = end + 4
|
||||
raise ValueError("missing PNG end")
|
||||
|
||||
|
||||
def read_png_header(data: bytes) -> PngHeader:
|
||||
chunks = _chunks(data)
|
||||
kind, header = next(chunks)
|
||||
if kind != b"IHDR" or len(header) != HEADER_BYTES:
|
||||
raise ValueError("invalid first PNG header")
|
||||
if any(kind == b"IHDR" for kind, _ in chunks):
|
||||
raise ValueError("duplicate PNG header")
|
||||
return struct.unpack(">IIBBBBB", header)
|
||||
|
||||
|
||||
def _scanlines(header: PngHeader) -> Iterator[tuple[int, int]]:
|
||||
width, height, depth, color, compression, filtering, interlace = header
|
||||
samples, depths = PIXELS[color]
|
||||
if depth not in depths or compression or filtering or interlace not in (0, 1):
|
||||
raise ValueError("invalid PNG header")
|
||||
@@ -38,24 +67,16 @@ def _scanlines(data: bytes) -> Iterator[tuple[int, int]]:
|
||||
|
||||
|
||||
def _idat(data: bytes) -> Iterator[memoryview]:
|
||||
view = memoryview(data)
|
||||
offset = 8
|
||||
started = ended = False
|
||||
while offset < len(data):
|
||||
size = struct.unpack_from(">I", data, offset)[0]
|
||||
kind = data[offset + 4 : offset + 8]
|
||||
start, end = offset + 8, offset + 8 + size
|
||||
for kind, payload in _chunks(data):
|
||||
if kind == b"IDAT":
|
||||
if ended:
|
||||
raise ValueError("nonconsecutive PNG image data")
|
||||
started = True
|
||||
for position in range(start, end, BLOCK_BYTES):
|
||||
yield view[position : min(position + BLOCK_BYTES, end)]
|
||||
for position in range(0, len(payload), BLOCK_BYTES):
|
||||
yield payload[position : position + BLOCK_BYTES]
|
||||
elif started:
|
||||
ended = True
|
||||
if kind == b"IEND":
|
||||
break
|
||||
offset = end + 4
|
||||
|
||||
|
||||
def _inflate(data: bytes) -> Iterator[bytes]:
|
||||
@@ -74,8 +95,8 @@ def _inflate(data: bytes) -> Iterator[bytes]:
|
||||
raise ValueError("incomplete PNG compressed data")
|
||||
|
||||
|
||||
def verify_png_pixels(data: bytes) -> None:
|
||||
passes = _scanlines(data)
|
||||
def verify_png_pixels(data: bytes, header: PngHeader) -> None:
|
||||
passes = _scanlines(header)
|
||||
stride, remaining = next(passes)
|
||||
offset = 0
|
||||
for decoded in _inflate(data):
|
||||
|
||||
Reference in New Issue
Block a user