package middleware import ( "archive/zip" "bytes" "errors" "io" ) var ( // ErrZipBombDetected indicates a zip bomb (excessive compression ratio) was detected. ErrZipBombDetected = errors.New("zip bomb detected: compression ratio exceeds safe limit") // ErrZipTooManyEntries indicates a ZIP archive contains too many files (zip fragment attack). ErrZipTooManyEntries = errors.New("zip archive contains too many files, possible zip fragment attack") // ErrZipEntryTooLarge indicates a single entry within a ZIP exceeds the uncompressed size limit. ErrZipEntryTooLarge = errors.New("zip entry exceeds maximum uncompressed size limit") ) // inspectZipArchive reads through a ZIP archive to detect zip bombs and zip fragment attacks. // It checks: // - Number of entries (zip fragment / decompression bomb with many small files) // - Compression ratio (zip bomb with extreme compression) // - Individual entry uncompressed size // // The file seek position after this call is indeterminate; callers should not rely on it. func inspectZipArchive(f io.ReadSeeker, compressedSize int64, cfg *UploadSecurityConfig) error { // Seek to beginning so zip.NewReader can scan the whole file if _, err := f.Seek(0, io.SeekStart); err != nil { return errors.New("cannot seek to beginning of zip file") } // Read entire file into memory so we can use zip.NewReader which requires io.ReaderAt // The file size is already validated against MaxFileSize, so this is bounded allBytes, err := io.ReadAll(f) if err != nil { return errors.New("cannot read zip file content") } r, err := zip.NewReader(bytes.NewReader(allBytes), compressedSize) if err != nil { return errors.New("cannot parse zip file") } // Check number of entries if len(r.File) > int(cfg.MaxZipEntries) { return ErrZipTooManyEntries } // Compute total uncompressed size and check compression ratio var totalUncompressed int64 for _, zf := range r.File { totalUncompressed += int64(zf.UncompressedSize64) // Check individual entry size — each entry should not exceed MaxFileSize if int64(zf.UncompressedSize64) > cfg.MaxFileSize { return ErrZipEntryTooLarge } } // Check compression ratio if compressedSize > 0 { ratio := float64(totalUncompressed) / float64(compressedSize) if ratio > cfg.MaxZipCompressionRatio { return ErrZipBombDetected } } return nil }