315 lines
7.5 KiB
Go
315 lines
7.5 KiB
Go
package media
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"hash/crc32"
|
|
"image"
|
|
"image/jpeg"
|
|
"image/png"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
ErrPayloadTooLarge = errors.New("payload too large")
|
|
ErrUnsupportedMediaType = errors.New("unsupported or corrupted media")
|
|
ErrBadFilename = errors.New("invalid filename")
|
|
)
|
|
|
|
var pngSignature = []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}
|
|
|
|
type ValidatedImage struct {
|
|
File *os.File
|
|
SizeBytes int64
|
|
SHA256 string
|
|
ContentType string
|
|
Width int
|
|
Height int
|
|
}
|
|
|
|
func (v *ValidatedImage) Cleanup() {
|
|
if v != nil && v.File != nil {
|
|
name := v.File.Name()
|
|
_ = v.File.Close()
|
|
_ = os.Remove(name)
|
|
v.File = nil
|
|
}
|
|
}
|
|
|
|
func ParseAllowedContentType(headerVal string) (string, error) {
|
|
mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(headerVal))
|
|
if err != nil {
|
|
return "", ErrUnsupportedMediaType
|
|
}
|
|
mediaType = strings.ToLower(mediaType)
|
|
if mediaType != "image/png" && mediaType != "image/jpeg" {
|
|
return "", ErrUnsupportedMediaType
|
|
}
|
|
return mediaType, nil
|
|
}
|
|
|
|
// ValidateAndSpoolImage streams upload bytes into an ephemeral temp file while enforcing
|
|
// maxBytes, verifying magic bytes against declared Content-Type, checking pixel limits
|
|
// before bitmap allocation, and checking PNG/JPEG container integrity in bounded RAM.
|
|
func ValidateAndSpoolImage(r io.Reader, declaredContentType string, maxBytes int64, maxPixels int64) (*ValidatedImage, error) {
|
|
ct, err := ParseAllowedContentType(declaredContentType)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if maxBytes <= 0 {
|
|
maxBytes = 10 * 1024 * 1024
|
|
}
|
|
if maxPixels <= 0 {
|
|
maxPixels = 40_000_000
|
|
}
|
|
|
|
tmpFile, err := os.CreateTemp("", "lab4-upload-*")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create temp spool file: %w", err)
|
|
}
|
|
cleanupTmp := true
|
|
defer func() {
|
|
if cleanupTmp && tmpFile != nil {
|
|
name := tmpFile.Name()
|
|
_ = tmpFile.Close()
|
|
_ = os.Remove(name)
|
|
}
|
|
}()
|
|
|
|
hasher := sha256.New()
|
|
buf := make([]byte, 32*1024)
|
|
n, err := io.CopyBuffer(io.MultiWriter(tmpFile, hasher), io.LimitReader(r, maxBytes+1), buf)
|
|
if err != nil {
|
|
return nil, ErrBadFilename
|
|
}
|
|
if n == 0 {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if n > maxBytes {
|
|
return nil, ErrPayloadTooLarge
|
|
}
|
|
|
|
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Verify content magic bytes match declared Content-Type (prevents MIME spoofing).
|
|
head := make([]byte, 512)
|
|
headLen, _ := io.ReadFull(tmpFile, head)
|
|
if headLen == 0 {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
sniffed := http.DetectContentType(head[:headLen])
|
|
if ct == "image/png" {
|
|
if headLen < len(pngSignature) || !bytes.Equal(head[:8], pngSignature) || sniffed != "image/png" {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
} else {
|
|
if headLen < 3 || head[0] != 0xff || head[1] != 0xd8 || head[2] != 0xff || sniffed != "image/jpeg" {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
}
|
|
|
|
// Parse image header BEFORE full pixel decode to prevent decompression-bomb OOMs.
|
|
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
cfg, format, err := image.DecodeConfig(tmpFile)
|
|
if err != nil {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if (ct == "image/png" && format != "png") || (ct == "image/jpeg" && format != "jpeg") {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if cfg.Width <= 0 || cfg.Height <= 0 {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if int64(cfg.Width) > maxPixels/int64(cfg.Height) {
|
|
return nil, ErrPayloadTooLarge
|
|
}
|
|
|
|
// Verify structural integrity in bounded memory.
|
|
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
if ct == "image/png" {
|
|
if err := verifyPNGChunks(tmpFile); err != nil {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if int64(cfg.Width)*int64(cfg.Height) <= 2_000_000 {
|
|
_, _ = tmpFile.Seek(0, io.SeekStart)
|
|
if _, err := png.Decode(tmpFile); err != nil {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
}
|
|
} else {
|
|
if err := verifyJPEGStructure(tmpFile); err != nil {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
if int64(cfg.Width)*int64(cfg.Height) <= 2_000_000 {
|
|
_, _ = tmpFile.Seek(0, io.SeekStart)
|
|
if _, err := jpeg.Decode(tmpFile); err != nil {
|
|
return nil, ErrUnsupportedMediaType
|
|
}
|
|
}
|
|
}
|
|
|
|
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cleanupTmp = false
|
|
return &ValidatedImage{
|
|
File: tmpFile,
|
|
SizeBytes: n,
|
|
SHA256: hex.EncodeToString(hasher.Sum(nil)),
|
|
ContentType: ct,
|
|
Width: cfg.Width,
|
|
Height: cfg.Height,
|
|
}, nil
|
|
}
|
|
|
|
func verifyPNGChunks(r io.Reader) error {
|
|
sig := make([]byte, 8)
|
|
if _, err := io.ReadFull(r, sig); err != nil || !bytes.Equal(sig, pngSignature) {
|
|
return errors.New("invalid PNG signature")
|
|
}
|
|
|
|
header := make([]byte, 8)
|
|
crcBuf := make([]byte, 4)
|
|
scratch := make([]byte, 32*1024)
|
|
seenIHDR := false
|
|
seenIEND := false
|
|
|
|
for {
|
|
_, err := io.ReadFull(r, header)
|
|
if err != nil {
|
|
return errors.New("truncated PNG chunk")
|
|
}
|
|
chunkLen := binary.BigEndian.Uint32(header[0:4])
|
|
if chunkLen > 10*1024*1024 {
|
|
return errors.New("PNG chunk too large")
|
|
}
|
|
chunkType := string(header[4:8])
|
|
if !seenIHDR && chunkType != "IHDR" {
|
|
return errors.New("first PNG chunk must be IHDR")
|
|
}
|
|
if chunkType == "IHDR" {
|
|
seenIHDR = true
|
|
}
|
|
|
|
crc := crc32.NewIEEE()
|
|
_, _ = crc.Write(header[4:8])
|
|
|
|
remaining := int64(chunkLen)
|
|
for remaining > 0 {
|
|
toRead := int64(len(scratch))
|
|
if remaining < toRead {
|
|
toRead = remaining
|
|
}
|
|
m, rErr := io.ReadFull(r, scratch[:toRead])
|
|
if rErr != nil {
|
|
return errors.New("truncated PNG chunk data")
|
|
}
|
|
_, _ = crc.Write(scratch[:m])
|
|
remaining -= int64(m)
|
|
}
|
|
|
|
if _, err := io.ReadFull(r, crcBuf); err != nil {
|
|
return errors.New("missing PNG CRC")
|
|
}
|
|
expectedCRC := binary.BigEndian.Uint32(crcBuf)
|
|
if crc.Sum32() != expectedCRC {
|
|
return errors.New("PNG CRC mismatch")
|
|
}
|
|
|
|
if chunkType == "IEND" {
|
|
seenIEND = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !seenIHDR || !seenIEND {
|
|
return errors.New("incomplete PNG structure")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func verifyJPEGStructure(r io.Reader) error {
|
|
br := bufio.NewReaderSize(r, 32*1024)
|
|
b0, err := br.ReadByte()
|
|
b1, err2 := br.ReadByte()
|
|
if err != nil || err2 != nil || b0 != 0xff || b1 != 0xd8 {
|
|
return errors.New("missing JPEG SOI")
|
|
}
|
|
|
|
seenSOF := false
|
|
seenSOS := false
|
|
seenEOI := false
|
|
|
|
for {
|
|
b, err := br.ReadByte()
|
|
if err != nil {
|
|
break
|
|
}
|
|
if b != 0xff {
|
|
if !seenSOS {
|
|
return errors.New("unexpected bytes before JPEG SOS")
|
|
}
|
|
continue
|
|
}
|
|
for {
|
|
b, err = br.ReadByte()
|
|
if err != nil {
|
|
return errors.New("truncated JPEG marker")
|
|
}
|
|
if b != 0xff {
|
|
break
|
|
}
|
|
}
|
|
marker := b
|
|
if marker == 0x00 || (marker >= 0xd0 && marker <= 0xd7) {
|
|
continue
|
|
}
|
|
if marker == 0xd9 {
|
|
seenEOI = true
|
|
break
|
|
}
|
|
if marker == 0x01 || marker == 0xd8 {
|
|
continue
|
|
}
|
|
|
|
var lenBuf [2]byte
|
|
if _, err := io.ReadFull(br, lenBuf[:]); err != nil {
|
|
return errors.New("truncated JPEG segment length")
|
|
}
|
|
segLen := int(binary.BigEndian.Uint16(lenBuf[:]))
|
|
if segLen < 2 {
|
|
return errors.New("invalid JPEG segment length")
|
|
}
|
|
if _, err := io.CopyN(io.Discard, br, int64(segLen-2)); err != nil {
|
|
return errors.New("truncated JPEG segment payload")
|
|
}
|
|
if (marker >= 0xc0 && marker <= 0xc3) || (marker >= 0xc5 && marker <= 0xc7) || (marker >= 0xc9 && marker <= 0xcb) || (marker >= 0xcd && marker <= 0xcf) {
|
|
seenSOF = true
|
|
}
|
|
if marker == 0xda {
|
|
seenSOS = true
|
|
}
|
|
}
|
|
|
|
if !seenSOF || !seenSOS || !seenEOI {
|
|
return errors.New("incomplete JPEG structure")
|
|
}
|
|
return nil
|
|
}
|