lab5: закрытие второго ревью

Validate the PNG raster itself: exact Adam7/non-interlaced row layout, scanline filter bytes, palette/PLTE rules, bounded streaming without keeping the raster. Settle an attachment as failed when a newer pipeline fails before any version was published, while keeping a ready serving version intact. Reject unsupported pipeline versions in jobctl before changing state.
This commit is contained in:
Vladislav Kunetskiy
2026-10-31 01:06:43 +03:00
parent b965350cc9
commit 8c0a455aa5
14 changed files with 478 additions and 112 deletions
+152 -45
View File
@@ -1,8 +1,10 @@
// 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.
// raster into an image. A full decode of a 40-megapixel image would allocate
// hundreds of megabytes; attachment uploads must stay bounded. For PNG the
// parser verifies chunk CRCs and streams the zlib image data to check exact
// scanline sizes and filter types without keeping the raster in memory. The
// JPEG parser verifies marker/scan structure. Both catch truncation and
// corruption while using bounded memory.
package imagecheck
import (
@@ -75,13 +77,16 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
}
var (
info Info
seen = make(map[string]bool, 4)
first = true
hasIDAT bool
idat bytes.Buffer
maxInflated int64
maxIDAT int64 = -1
info Info
seen = make(map[string]bool, 4)
first = true
hasIDAT bool
paletteReady bool
colorType byte
idat bytes.Buffer
raster []pngPass
rasterBytes int64
maxIDAT int64 = -1
)
info.ContentType = "image/png"
@@ -147,6 +152,7 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
info.Width = int64(binary.BigEndian.Uint32(data[0:4]))
info.Height = int64(binary.BigEndian.Uint32(data[4:8]))
colorType = data[9]
if info.Width <= 0 || info.Height <= 0 {
return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height)
@@ -158,20 +164,33 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
}
bound, err := pngInflateBound(info, data[8], data[9])
bound, err := pngRasterLayout(info, data[8], data[9], data[10], data[11], data[12])
if err != nil {
return Info{}, err
}
maxInflated = bound
if maxInflated <= 1<<40 {
raster = bound
rasterBytes = pngRasterBytes(bound)
if rasterBytes <= 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
maxIDAT = rasterBytes + rasterBytes/256 + 1<<20
}
case "IDAT":
hasIDAT = true
case "PLTE":
if colorType == 0 || colorType == 4 {
return Info{}, corruptf("png PLTE is invalid for color type %d", colorType)
}
if length == 0 || length%3 != 0 || length > 3*256 {
return Info{}, corruptf("png PLTE length %d", length)
}
if !hasIDAT {
paletteReady = true
}
case "IEND":
if length != 0 {
return Info{}, corruptf("png IEND length %d", length)
@@ -181,11 +200,15 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
return Info{}, corruptf("png has no IDAT chunk")
}
if colorType == 3 && !paletteReady {
return Info{}, corruptf("png palette image has no PLTE before IDAT")
}
// 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 {
// still not be a PNG raster: the zlib payload must inflate to
// exactly the IHDR-declared scanlines with valid filter bytes.
if err := validateRaster(idat.Bytes(), raster); err != nil {
return Info{}, err
}
@@ -198,10 +221,41 @@ 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) {
// pngPass is one consecutive block of scanlines in the inflated image stream.
// Non-interlaced PNGs have a single pass; Adam7 has up to seven.
type pngPass struct {
rowBytes int64
rows int64
}
type pngPassSpec struct {
x0, y0 int64
dx, dy int64
}
var adam7Passes = []pngPassSpec{
{x0: 0, y0: 0, dx: 8, dy: 8},
{x0: 4, y0: 0, dx: 8, dy: 8},
{x0: 0, y0: 4, dx: 4, dy: 8},
{x0: 2, y0: 0, dx: 4, dy: 4},
{x0: 0, y0: 2, dx: 2, dy: 4},
{x0: 1, y0: 0, dx: 2, dy: 2},
{x0: 0, y0: 1, dx: 1, dy: 2},
}
// pngRasterLayout returns the exact inflated size and row layout for the
// IHDR. The Adam7 layout matters: a single non-interlaced formula either
// rejects valid interlaced images or accepts oversized streams.
func pngRasterLayout(
info Info,
bitDepth, colorType, compression, filter, interlace byte,
) ([]pngPass, error) {
if compression != 0 || filter != 0 {
return nil, corruptf(
"png compression/filter method %d/%d", compression, filter,
)
}
var bitsPerPixel int64
switch colorType {
@@ -216,46 +270,99 @@ func pngInflateBound(info Info, bitDepth, colorType byte) (int64, error) {
case 6: // RGBA
bitsPerPixel = 4 * int64(bitDepth)
default:
return 0, corruptf("png invalid color type %d", colorType)
return nil, 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)
return nil, 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)
specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}}
switch interlace {
case 0:
case 1:
specs = adam7Passes
default:
return nil, corruptf("png invalid interlace method %d", interlace)
}
return (rowBytes + 1) * rows, nil
passes := make([]pngPass, 0, len(specs))
for _, spec := range specs {
if info.Width <= spec.x0 || info.Height <= spec.y0 {
continue
}
width := (info.Width - spec.x0 + spec.dx - 1) / spec.dx
rows := (info.Height - spec.y0 + spec.dy - 1) / spec.dy
rowBytes := (width*bitsPerPixel + 7) / 8
// Keep the total overflow-safe. Valid PNGs are additionally bounded
// by the pixel limit checked by the caller.
if rowBytes+1 > (1<<62)/rows {
return nil, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
}
passes = append(passes, pngPass{rowBytes: rowBytes, rows: rows})
}
return passes, 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 {
func pngRasterBytes(passes []pngPass) int64 {
var total int64
for _, pass := range passes {
row := (pass.rowBytes + 1) * pass.rows
if total > (1<<62)-row {
return 1<<62 - 1
}
total += row
}
return total
}
// validateRaster streams the inflated image data, checking every scanline
// filter byte and requiring exactly the IHDR-declared number of rows. It
// catches zlib streams that decompress cleanly but do not describe a valid
// raster (empty payloads, bogus filter bytes) and rejects extra data as a
// decompression bomb.
func validateRaster(compressed []byte, passes []pngPass) 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
for _, pass := range passes {
for range pass.rows {
var filter [1]byte
if _, err := io.ReadFull(reader, filter[:]); err != nil {
return corrupt("png scanline filter", err)
}
return fmt.Errorf("%w: png idat inflates beyond declared dimensions", ErrTooLarge)
if filter[0] > 4 {
return corruptf("png invalid scanline filter %d", filter[0])
}
if _, err := io.CopyN(io.Discard, reader, pass.rowBytes); err != nil {
return corrupt("png scanline data", err)
}
}
}
var extra [1]byte
switch _, err := io.ReadFull(reader, extra[:]); {
case errors.Is(err, io.EOF):
// A clean zlib EOF also verifies the Adler-32 trailer.
return nil
case err == nil:
return fmt.Errorf("%w: png raster exceeds declared dimensions", ErrTooLarge)
default:
return corrupt("png idat zlib trailer", err)
}
}
+139 -16
View File
@@ -2,6 +2,7 @@ package imagecheck_test
import (
"bytes"
"compress/zlib"
"encoding/binary"
"hash/crc32"
"image"
@@ -47,6 +48,30 @@ func encodeJPEG(t *testing.T, width, height int) []byte {
return buffer.Bytes()
}
func pngChunk(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
}
func pngFile(chunks ...[]byte) []byte {
data := []byte(pngSignatureForTest)
for _, chunk := range chunks {
data = append(data, chunk...)
}
return data
}
const pngSignatureForTest = "\x89PNG\r\n\x1a\n"
func TestValidatePNG(t *testing.T) {
info, err := imagecheck.Validate(bytes.NewReader(encodePNG(t, 32, 20)), 40_000_000)
require.NoError(t, err)
@@ -91,33 +116,131 @@ func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
// 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)...)
data := pngFile(
pngChunk("IHDR", ihdr),
pngChunk("IDAT", []byte("this is not a zlib stream, but the CRC is right")),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func craftedPNG(t *testing.T, width, height int, interlace byte, raster []byte) []byte {
t.Helper()
return craftedPNGType(t, width, height, 6, interlace, raster)
}
func craftedPNGType(t *testing.T, width, height int, colorType, interlace byte, raster []byte) []byte {
t.Helper()
var idat bytes.Buffer
writer := zlib.NewWriter(&idat)
_, err := writer.Write(raster)
require.NoError(t, err)
require.NoError(t, writer.Close())
ihdr := make([]byte, 13)
binary.BigEndian.PutUint32(ihdr[0:4], uint32(width))
binary.BigEndian.PutUint32(ihdr[4:8], uint32(height))
ihdr[8] = 8 // bit depth
ihdr[9] = colorType
ihdr[12] = interlace
return pngFile(
pngChunk("IHDR", ihdr),
pngChunk("IDAT", idat.Bytes()),
pngChunk("IEND", nil),
)
}
func TestValidateRejectsPNGEmptyRaster(t *testing.T) {
data := craftedPNG(t, 2, 2, 0, nil)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGInvalidScanlineFilter(t *testing.T) {
raster := []byte{5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
data := craftedPNG(t, 2, 2, 0, raster)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGPaletteWithoutPLTE(t *testing.T) {
raster := []byte{0, 0, 0, 0, 0, 0} // two rows of two 8-bit palette indexes
data := craftedPNGType(t, 2, 2, 3, 0, raster)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateAcceptsPalettePNG(t *testing.T) {
palette := color.Palette{color.RGBA{R: 255, A: 255}, color.RGBA{G: 255, A: 255}, color.RGBA{B: 255, A: 255}}
source := image.NewPaletted(image.Rect(0, 0, 13, 5), palette)
for x := range 13 {
for y := range 5 {
source.SetColorIndex(x, y, uint8((x+y)%len(palette)))
}
}
var buffer bytes.Buffer
require.NoError(t, png.Encode(&buffer, source))
info, err := imagecheck.Validate(bytes.NewReader(buffer.Bytes()), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(13), info.Width)
require.Equal(t, int64(5), info.Height)
}
// A valid Adam7 stream for a tall, narrow image exceeds the old
// (rowBytes+1)*(height+8) guess; the exact pass layout must accept it.
func TestValidateAcceptsAdam7PNG(t *testing.T) {
const width, height = 2, 256
var raster bytes.Buffer
passes := [][4]int{
{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},
}
for _, pass := range passes {
x0, y0, dx, dy := pass[0], pass[1], pass[2], pass[3]
if width <= x0 || height <= y0 {
continue
}
for y := y0; y < height; y += dy {
raster.WriteByte(0) // filter: none
for x := x0; x < width; x += dx {
raster.Write([]byte{byte(x), byte(y), 128, 255})
}
}
}
data := craftedPNG(t, width, height, 1, raster.Bytes())
info, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(width), info.Width)
require.Equal(t, int64(height), info.Height)
}
func TestValidateRejectsTruncatedJPEG(t *testing.T) {
data := encodeJPEG(t, 64, 64)
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000)