forked from mtusi2026/mtusi2026lab4
Reject corrupt PNG pixels with bounded stream validation
This commit is contained in:
@@ -6,6 +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
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
@@ -44,6 +45,7 @@ class PillowImageInspector:
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
verify_png_pixels(data)
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import struct
|
||||
import zlib
|
||||
from collections.abc import Iterator
|
||||
|
||||
BLOCK_BYTES = 65_536
|
||||
MAX_FILTER = 4
|
||||
PIXELS = {
|
||||
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 = (
|
||||
(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 _scanlines(data: bytes) -> Iterator[tuple[int, int]]:
|
||||
width, height, depth, color, compression, filtering, interlace = struct.unpack_from(
|
||||
">IIBBBBB", data, 16
|
||||
)
|
||||
samples, depths = PIXELS[color]
|
||||
if depth not in depths or compression or filtering or interlace not in (0, 1):
|
||||
raise ValueError("invalid PNG header")
|
||||
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
|
||||
for x, y, dx, dy in passes:
|
||||
columns, rows = (width - x + dx - 1) // dx, (height - y + dy - 1) // dy
|
||||
if columns > 0 and rows > 0:
|
||||
stride = 1 + (columns * samples * depth + 7) // 8
|
||||
yield stride, stride * rows
|
||||
|
||||
|
||||
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
|
||||
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)]
|
||||
elif started:
|
||||
ended = True
|
||||
if kind == b"IEND":
|
||||
break
|
||||
offset = end + 4
|
||||
|
||||
|
||||
def _inflate(data: bytes) -> Iterator[bytes]:
|
||||
decoder = zlib.decompressobj()
|
||||
for block in _idat(data):
|
||||
if decoder.eof:
|
||||
continue
|
||||
pending = block
|
||||
while True:
|
||||
decoded = decoder.decompress(pending, BLOCK_BYTES)
|
||||
yield decoded
|
||||
pending = decoder.unconsumed_tail
|
||||
if decoder.eof or (not pending and len(decoded) < BLOCK_BYTES):
|
||||
break
|
||||
if not decoder.eof:
|
||||
raise ValueError("incomplete PNG compressed data")
|
||||
|
||||
|
||||
def verify_png_pixels(data: bytes) -> None:
|
||||
passes = _scanlines(data)
|
||||
stride, remaining = next(passes)
|
||||
offset = 0
|
||||
for decoded in _inflate(data):
|
||||
cursor = 0
|
||||
while cursor < len(decoded):
|
||||
if not remaining:
|
||||
stride, remaining = next(passes, (0, 0))
|
||||
offset = 0
|
||||
if not remaining:
|
||||
raise ValueError("extra PNG pixel data")
|
||||
size = min(remaining, len(decoded) - cursor)
|
||||
filters = decoded[cursor + (-offset % stride) : cursor + size : stride]
|
||||
if max(filters, default=0) > MAX_FILTER:
|
||||
raise ValueError("invalid PNG filter")
|
||||
cursor += size
|
||||
offset += size
|
||||
remaining -= size
|
||||
if remaining or next(passes, None) is not None:
|
||||
raise ValueError("incomplete PNG pixel data")
|
||||
Reference in New Issue
Block a user