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.
This commit is contained in:
@@ -7,6 +7,8 @@ package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -73,10 +75,13 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
}
|
||||
|
||||
var (
|
||||
info Info
|
||||
seen = make(map[string]bool, 4)
|
||||
first = true
|
||||
hasIDAT bool
|
||||
info Info
|
||||
seen = make(map[string]bool, 4)
|
||||
first = true
|
||||
hasIDAT bool
|
||||
idat bytes.Buffer
|
||||
maxInflated int64
|
||||
maxIDAT int64 = -1
|
||||
)
|
||||
|
||||
info.ContentType = "image/png"
|
||||
@@ -111,7 +116,16 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
data, err := readChunkData(reader, checksum, length)
|
||||
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)
|
||||
}
|
||||
@@ -143,6 +157,19 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
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":
|
||||
@@ -154,6 +181,14 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
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)
|
||||
}
|
||||
@@ -163,9 +198,71 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -176,7 +273,7 @@ func checkCriticalChunk(chunkType string, seen map[string]bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte, error) {
|
||||
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 {
|
||||
@@ -184,11 +281,19 @@ func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte,
|
||||
}
|
||||
|
||||
_, _ = checksum.Write(data)
|
||||
if sink != nil {
|
||||
_, _ = sink.Write(data)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(checksum, reader, length); err != nil {
|
||||
destination := checksum
|
||||
if sink != nil {
|
||||
destination = io.MultiWriter(checksum, sink)
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(destination, reader, length); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package imagecheck_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
@@ -85,6 +87,37 @@ func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
// Builds a structurally valid PNG (signature, well-formed IHDR/IDAT/IEND,
|
||||
// correct CRCs) whose IDAT payload is not a zlib stream at all. Merely a
|
||||
// stream-like structure must not make the upload pass: it has to inflate.
|
||||
func TestValidateRejectsPNGIDATNotAZlibStream(t *testing.T) {
|
||||
chunk := func(ctype string, payload []byte) []byte {
|
||||
out := make([]byte, 12+len(payload))
|
||||
binary.BigEndian.PutUint32(out[0:4], uint32(len(payload)))
|
||||
copy(out[4:8], ctype)
|
||||
copy(out[8:], payload)
|
||||
|
||||
checksum := crc32.NewIEEE()
|
||||
_, _ = checksum.Write(out[4 : 8+len(payload)])
|
||||
binary.BigEndian.PutUint32(out[8+len(payload):], checksum.Sum32())
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
ihdr := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(ihdr[0:4], 64) // width
|
||||
binary.BigEndian.PutUint32(ihdr[4:8], 32) // height
|
||||
ihdr[8] = 8 // bit depth
|
||||
ihdr[9] = 6 // color type RGBA
|
||||
|
||||
data := append([]byte("\x89PNG\r\n\x1a\n"), chunk("IHDR", ihdr)...)
|
||||
data = append(data, chunk("IDAT", []byte("this is not a zlib stream, but the CRC is right"))...)
|
||||
data = append(data, chunk("IEND", nil)...)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsTruncatedJPEG(t *testing.T) {
|
||||
data := encodeJPEG(t, 64, 64)
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000)
|
||||
|
||||
Reference in New Issue
Block a user