Files
mtusi2026lab5/internal/imagecheck/imagecheck.go
T
Vladislav Kunetskiy b965350cc9 lab5: исправления второго ревью
Reprocess of a queued/processing/failed upload now sources from verified staging instead of the not-yet-written final original, which used to supersede v1 and strand the attachment in queued. PNG uploads now inflate the concatenated IDAT stream (bounded by IHDR dimensions) before acceptance, so a structurally valid PNG whose IDAT is not a zlib stream is rejected with 415 instead of 202.
2026-10-31 00:41:38 +03:00

471 lines
11 KiB
Go

// Package imagecheck validates PNG and JPEG structure without decoding the
// raster. A full decode of a 40-megapixel image would allocate hundreds of
// megabytes; attachment uploads must stay bounded. The parser verifies chunk
// CRCs and the JPEG marker/scan structure, which catches truncation and
// corruption while using constant memory.
package imagecheck
import (
"bufio"
"bytes"
"compress/zlib"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
)
var (
ErrUnsupported = errors.New("unsupported image format")
ErrCorrupt = errors.New("corrupt image")
ErrTooLarge = errors.New("image has too many pixels")
)
const (
pngSignature = "\x89PNG\r\n\x1a\n"
maxChunkSize = 1 << 30
)
// Info is the validated header. ContentType is one of image/png or image/jpeg.
type Info struct {
ContentType string
Width int64
Height int64
}
func ValidateFile(path string, maxPixels int64) (Info, error) {
file, err := os.Open(path)
if err != nil {
return Info{}, fmt.Errorf("open upload: %w", err)
}
defer func() { _ = file.Close() }()
return Validate(file, maxPixels)
}
// Validate consumes the reader to EOF (so a caller hashing the stream gets all
// bytes) and returns the detected format and dimensions.
func Validate(r io.Reader, maxPixels int64) (Info, error) {
reader := bufio.NewReaderSize(r, 64<<10)
header, err := reader.Peek(8)
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return Info{}, fmt.Errorf("%w: image is empty or truncated", ErrUnsupported)
}
return Info{}, err
}
switch {
case string(header[:8]) == pngSignature:
return validatePNG(reader, maxPixels)
case header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF:
return validateJPEG(reader, maxPixels)
default:
return Info{}, fmt.Errorf("%w: unrecognised signature", ErrUnsupported)
}
}
func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
if _, err := reader.Discard(len(pngSignature)); err != nil {
return Info{}, corrupt("png signature", err)
}
var (
info Info
seen = make(map[string]bool, 4)
first = true
hasIDAT bool
idat bytes.Buffer
maxInflated int64
maxIDAT int64 = -1
)
info.ContentType = "image/png"
for {
var lengthBytes [4]byte
if _, err := io.ReadFull(reader, lengthBytes[:]); err != nil {
return Info{}, corrupt("png chunk length", err)
}
length := int64(binary.BigEndian.Uint32(lengthBytes[:]))
if length < 0 || length > maxChunkSize {
return Info{}, corruptf("png chunk length %d", length)
}
var typeBytes [4]byte
if _, err := io.ReadFull(reader, typeBytes[:]); err != nil {
return Info{}, corrupt("png chunk type", err)
}
chunkType := string(typeBytes[:])
checksum := crc32.NewIEEE()
_, _ = checksum.Write(typeBytes[:])
if first && chunkType != "IHDR" {
return Info{}, corruptf("png first chunk is %q, want IHDR", chunkType)
}
first = false
if err := checkCriticalChunk(chunkType, seen); err != nil {
return Info{}, err
}
var chunkSink io.Writer
if chunkType == "IDAT" {
if maxIDAT >= 0 && int64(idat.Len())+length > maxIDAT {
return Info{}, corruptf("png idat compressed data exceeds %d bytes", maxIDAT)
}
chunkSink = &idat
}
data, err := readChunkData(reader, checksum, length, chunkSink)
if err != nil {
return Info{}, corrupt("png chunk data", err)
}
var crcBytes [4]byte
if _, err := io.ReadFull(reader, crcBytes[:]); err != nil {
return Info{}, corrupt("png chunk crc", err)
}
if binary.BigEndian.Uint32(crcBytes[:]) != checksum.Sum32() {
return Info{}, corruptf("png chunk %q crc mismatch", chunkType)
}
switch chunkType {
case "IHDR":
if length != 13 {
return Info{}, corruptf("png IHDR length %d", length)
}
info.Width = int64(binary.BigEndian.Uint32(data[0:4]))
info.Height = int64(binary.BigEndian.Uint32(data[4:8]))
if info.Width <= 0 || info.Height <= 0 {
return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height)
}
// Short-circuit before multiplying: a malicious IHDR can contain
// 32-bit dimensions whose product overflows int64.
if maxPixels > 0 && (info.Width > maxPixels || info.Height > maxPixels || info.Width*info.Height > maxPixels) {
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
}
bound, err := pngInflateBound(info, data[8], data[9])
if err != nil {
return Info{}, err
}
maxInflated = bound
if maxInflated <= 1<<40 {
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
// images where the relative term vanishes.
maxIDAT = maxInflated + maxInflated/256 + 1<<20
}
case "IDAT":
hasIDAT = true
case "IEND":
if length != 0 {
return Info{}, corruptf("png IEND length %d", length)
}
if !hasIDAT {
return Info{}, corruptf("png has no IDAT chunk")
}
// The chunk walker proves structure, but a stream whose bytes
// merely look like a chunk layout (valid length/type/CRC) may
// still not be a zlib stream at all. Inflate the concatenated
// IDAT payload to catch those before the upload is accepted.
if err := inflateIDAT(idat.Bytes(), maxInflated); err != nil {
return Info{}, err
}
if _, err := io.Copy(io.Discard, reader); err != nil {
return Info{}, corrupt("png trailing data", err)
}
return info, nil
}
}
}
// pngInflateBound returns the exact decompressed size of a full PNG raster:
// one filter byte per row plus ceil(width*bitsPerPixel/8) row bytes, with
// slack for the extra passes of an Adam7-interlaced stream.
func pngInflateBound(info Info, bitDepth, colorType byte) (int64, error) {
var bitsPerPixel int64
switch colorType {
case 0: // grayscale
bitsPerPixel = int64(bitDepth)
case 2: // truecolor
bitsPerPixel = 3 * int64(bitDepth)
case 3: // palette
bitsPerPixel = int64(bitDepth)
case 4: // grayscale + alpha
bitsPerPixel = 2 * int64(bitDepth)
case 6: // RGBA
bitsPerPixel = 4 * int64(bitDepth)
default:
return 0, corruptf("png invalid color type %d", colorType)
}
switch bitDepth {
case 1, 2, 4, 8, 16:
default:
return 0, corruptf("png invalid bit depth %d", bitDepth)
}
rowBytes := (info.Width*bitsPerPixel + 7) / 8
rows := info.Height + 8
if rowBytes+1 > (1<<62)/rows {
return 0, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
}
return (rowBytes + 1) * rows, nil
}
// inflateIDAT decompresses the concatenated IDAT payload and requires a clean
// zlib EOF, which verifies stream framing and the Adler-32 trailer. Corrupt
// streams (e.g. an IDAT filled with bytes that are not a zlib stream at all)
// fail here; streams that inflate beyond the IHDR-declared raster size are
// rejected as compression bombs.
func inflateIDAT(compressed []byte, maxInflated int64) error {
reader, err := zlib.NewReader(bytes.NewReader(compressed))
if err != nil {
return corrupt("png idat zlib header", err)
}
count, err := io.CopyN(io.Discard, reader, maxInflated+1)
switch {
case errors.Is(err, io.EOF):
return nil
case err != nil:
return corrupt("png idat zlib stream", err)
default:
_ = count
return fmt.Errorf("%w: png idat inflates beyond declared dimensions", ErrTooLarge)
}
}
func checkCriticalChunk(chunkType string, seen map[string]bool) error {
if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" {
seen[chunkType] = true
return nil
}
if chunkType[0] >= 'A' && chunkType[0] <= 'Z' {
return corruptf("png unknown critical chunk %q", chunkType)
}
return nil
}
func readChunkData(reader io.Reader, checksum io.Writer, length int64, sink io.Writer) ([]byte, error) {
if length <= 64<<10 {
data := make([]byte, length)
if _, err := io.ReadFull(reader, data); err != nil {
return nil, err
}
_, _ = checksum.Write(data)
if sink != nil {
_, _ = sink.Write(data)
}
return data, nil
}
destination := checksum
if sink != nil {
destination = io.MultiWriter(checksum, sink)
}
if _, err := io.CopyN(destination, reader, length); err != nil {
return nil, err
}
return nil, nil
}
func validateJPEG(reader *bufio.Reader, maxPixels int64) (Info, error) {
if _, err := reader.Discard(2); err != nil {
return Info{}, corrupt("jpeg SOI", err)
}
var (
info Info
hasSOF bool
hasSOS bool
pending byte
markerErr error
)
info.ContentType = "image/jpeg"
for {
marker := pending
pending = 0
if marker == 0 {
marker, markerErr = nextMarker(reader)
if markerErr != nil {
return Info{}, corrupt("jpeg marker", markerErr)
}
}
switch {
case marker == 0xD9: // EOI
if !hasSOF || !hasSOS {
return Info{}, corruptf("jpeg missing SOF or SOS")
}
if _, err := io.Copy(io.Discard, reader); err != nil {
return Info{}, corrupt("jpeg trailing data", err)
}
return info, nil
case isStandalone(marker):
continue
}
length, err := readUint16(reader)
if err != nil {
return Info{}, corrupt("jpeg segment length", err)
}
if length < 2 {
return Info{}, corruptf("jpeg segment %02x length %d", marker, length)
}
data := make([]byte, int(length)-2)
if _, err := io.ReadFull(reader, data); err != nil {
return Info{}, corrupt("jpeg segment data", err)
}
switch {
case isSOF(marker):
if len(data) < 5 {
return Info{}, corruptf("jpeg SOF %02x is too short", marker)
}
info.Height = int64(binary.BigEndian.Uint16(data[1:3]))
info.Width = int64(binary.BigEndian.Uint16(data[3:5]))
if info.Width <= 0 || info.Height <= 0 {
return Info{}, corruptf("jpeg dimensions %dx%d", info.Width, info.Height)
}
hasSOF = true
if maxPixels > 0 && info.Width*info.Height > maxPixels {
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
}
case marker == 0xDA: // SOS
hasSOS = true
next, err := scanEntropy(reader)
if err != nil {
return Info{}, corrupt("jpeg scan", err)
}
pending = next
}
}
}
func nextMarker(reader *bufio.Reader) (byte, error) {
for {
value, err := reader.ReadByte()
if err != nil {
return 0, err
}
if value != 0xFF {
return 0, fmt.Errorf("unexpected byte %02x before marker", value)
}
value, err = reader.ReadByte()
if err != nil {
return 0, err
}
if value == 0xFF {
continue
}
return value, nil
}
}
// scanEntropy consumes entropy-coded data after SOS and returns the next
// non-RST marker (0xFF prefix consumed).
func scanEntropy(reader *bufio.Reader) (byte, error) {
for {
value, err := reader.ReadByte()
if err != nil {
return 0, err
}
if value != 0xFF {
continue
}
value, err = reader.ReadByte()
if err != nil {
return 0, err
}
switch {
case value == 0x00:
continue
case value >= 0xD0 && value <= 0xD7:
continue
default:
return value, nil
}
}
}
func readUint16(reader io.Reader) (uint16, error) {
var raw [2]byte
if _, err := io.ReadFull(reader, raw[:]); err != nil {
return 0, err
}
return binary.BigEndian.Uint16(raw[:]), nil
}
func isSOF(marker byte) bool {
switch marker {
case 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF:
return true
default:
return false
}
}
func isStandalone(marker byte) bool {
return marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)
}
func corrupt(context string, err error) error {
return fmt.Errorf("%w: %s: %w", ErrCorrupt, context, err)
}
func corruptf(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrCorrupt, fmt.Sprintf(format, args...))
}