fix(security): block BLE image decompression bombs at ingest and downsample on render (#1880)

* Validate incoming BLE image dimensions at ingest and downsample at render

* Fix MimeType interpolation and include .jpg alias in ImageContainerValidator
This commit is contained in:
jack authored and GitHub committed 2026-11-25 20:59:45 -10:00
1 parent 8f73cd3757
commit dcac0f5efd
9 files changed
+336 -28

No files matched your search

@@ -0,0 +1,52 @@
import Foundation
import ImageIO
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/// Decodes images via ImageIO thumbnail downsampling after validating header
/// dimensions against `ImageContainerValidator` bounds, preventing OOM crashes
/// from decompression bombs even if an unvalidated file exists on disk.
enum ImageDownsampler {
static let blurredPreviewMaxPixelSize = 64
static let inlineMaxPixelSize = 1_024
static let fullScreenMaxPixelSize = 2_048
#if os(iOS)
typealias PlatformImage = UIImage
#else
typealias PlatformImage = NSImage
#endif
static func loadDownsampledImage(from url: URL, maxPixelSize: Int) -> PlatformImage? {
guard maxPixelSize > 0 else { return nil }
let sourceOptions: CFDictionary = [
kCGImageSourceShouldCache: false
] as CFDictionary
guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) else {
return nil
}
guard ImageContainerValidator.validateDimensions(of: source) == nil else {
return nil
}
let thumbnailOptions: CFDictionary = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
] as CFDictionary
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else {
return nil
}
#if os(iOS)
return UIImage(cgImage: cgImage)
#else
return NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height))
#endif
}
}
@@ -228,6 +228,8 @@ final class BLEFileTransferHandler {
SecureLogger.warning("🚫 MAGIC REJECT: MIME='\(mime)' size=\(bytes)b prefix=[\(prefixHex)] from \(peerID.id.prefix(8))...", category: .security)
case .failure(.invalidAudio(let mime, let bytes, let reason)):
SecureLogger.warning("🚫 AUDIO REJECT: MIME='\(mime)' size=\(bytes)b reason='\(reason)' from \(peerID.id.prefix(8))...", category: .security)
case .failure(.invalidImage(let mime, let bytes, let reason)):
SecureLogger.warning("🚫 IMAGE REJECT: MIME='\(mime)' size=\(bytes)b reason='\(reason)' from \(peerID.id.prefix(8))...", category: .security)
}
return nil
}
@@ -1,6 +1,7 @@
import AudioToolbox
import BitFoundation
import Foundation
import ImageIO
struct BLEFileTransferDeliveryPlan: Equatable {
let isPrivateMessage: Bool
@@ -41,6 +42,7 @@ enum BLEIncomingFileRejection: Error, Equatable {
case unsupportedMime(mimeType: String?, bytes: Int)
case magicMismatch(mime: MimeType, bytes: Int, prefixHex: String)
case invalidAudio(mime: MimeType, bytes: Int, reason: String)
case invalidImage(mime: MimeType, bytes: Int, reason: String)
}
enum BLEIncomingFileValidator {
@@ -77,10 +79,96 @@ enum BLEIncomingFileValidator {
))
}
if mime.category == .image,
let failureReason = ImageContainerValidator.validate(data: filePacket.content, mime: mime) {
return .failure(.invalidImage(
mime: mime,
bytes: filePacket.content.count,
reason: failureReason
))
}
return .success(BLEIncomingFileAcceptance(filePacket: filePacket, mime: mime))
}
}
/// Inspects incoming image headers in memory via ImageIO without decoding pixel
/// buffers. Blocks decompression bombs (tiny compressed payloads claiming huge
/// pixel dimensions or frame counts) and container/UTI spoofing before a file
/// is persisted, tracked for gossip sync, or rendered.
enum ImageContainerValidator {
static let maxDimensionPixels = 4_096
static let maxTotalPixels = 16_777_216 // 4096 x 4096 (~64 MiB RGBA max)
static let maxFrameCount = 120
private static let metadataOptions: CFDictionary = [
kCGImageSourceShouldCache: false
] as CFDictionary
static func validate(data: Data, mime: MimeType) -> String? {
guard let expectedUTI = expectedTypeIdentifier(for: mime) else {
return "unsupported image MIME \(mime)"
}
guard let source = CGImageSourceCreateWithData(data as CFData, metadataOptions) else {
return "unreadable image container"
}
guard let detectedUTI = CGImageSourceGetType(source) as String?,
detectedUTI == expectedUTI else {
let detected = (CGImageSourceGetType(source) as String?) ?? "unknown"
return "image container UTI \(detected) does not match \(mime)"
}
return validateDimensions(of: source)
}
static func validateDimensions(of source: CGImageSource) -> String? {
let frameCount = CGImageSourceGetCount(source)
guard frameCount >= 1 else {
return "image contains no frames"
}
guard frameCount <= maxFrameCount else {
return "image frame count \(frameCount) exceeds limit \(maxFrameCount)"
}
for index in 0..<frameCount {
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, metadataOptions) as? [CFString: Any],
let width = (properties[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
let height = (properties[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue else {
return "missing pixel dimensions at frame \(index)"
}
guard width > 0, height > 0 else {
return "non-positive pixel dimensions \(width)x\(height)"
}
guard width <= maxDimensionPixels, height <= maxDimensionPixels else {
return "pixel dimensions \(width)x\(height) exceed max \(maxDimensionPixels)"
}
let totalPixels = Int64(width) * Int64(height)
guard totalPixels <= Int64(maxTotalPixels) else {
return "pixel count \(totalPixels) exceeds max \(maxTotalPixels)"
}
}
return nil
}
private static func expectedTypeIdentifier(for mime: MimeType) -> String? {
switch mime {
case .jpeg, .jpg:
return "public.jpeg"
case .png:
return "public.png"
case .gif:
return "com.compuserve.gif"
case .webp:
return "org.webmproject.webp"
default:
return nil
}
}
}
/// Inspects incoming audio payloads in memory with CoreAudio before they are
/// persisted or tracked for gossip sync. Blocks container spoofing (e.g., CAF
/// disguised as M4A) and crafted headers claiming absurd durations or frame
@@ -76,12 +76,12 @@ struct ImagePreviewView: View {
}
private func loadImage() {
let imageURL = url
DispatchQueue.global(qos: .userInitiated).async {
#if os(iOS)
guard let image = UIImage(contentsOfFile: url.path) else { return }
#else
guard let image = NSImage(contentsOf: url) else { return }
#endif
guard let image = ImageDownsampler.loadDownsampledImage(
from: imageURL,
maxPixelSize: ImageDownsampler.fullScreenMaxPixelSize
) else { return }
DispatchQueue.main.async {
self.platformImage = image
}
+20 -8
View File
@@ -23,6 +23,8 @@ struct BlockRevealImageView: View {
@State private var isBlurred: Bool = false
@State private var showDeleteConfirmation = false
@State private var loadFailed = false
@State private var loadGeneration: Int = 0
@State private var loadedMaxPixelSize: Int = 0
private enum Strings {
static let tapToReveal = String(localized: "media.image.tap_to_reveal", comment: "Caption on a blurred incoming image inviting a tap to reveal it")
@@ -94,11 +96,17 @@ struct BlockRevealImageView: View {
.simultaneousGesture(hideSwipe)
.onAppear {
isBlurred = initiallyBlurred
loadImage()
loadImage(maxPixelSize: initiallyBlurred ? ImageDownsampler.blurredPreviewMaxPixelSize : ImageDownsampler.inlineMaxPixelSize)
}
.onChange(of: url) { _ in
isBlurred = initiallyBlurred
loadImage()
loadedMaxPixelSize = 0
loadImage(maxPixelSize: initiallyBlurred ? ImageDownsampler.blurredPreviewMaxPixelSize : ImageDownsampler.inlineMaxPixelSize)
}
.onChange(of: isBlurred) { blurred in
if !blurred && loadedMaxPixelSize < ImageDownsampler.inlineMaxPixelSize {
loadImage(maxPixelSize: ImageDownsampler.inlineMaxPixelSize)
}
}
.contextMenu {
if isSending {
@@ -227,20 +235,24 @@ struct BlockRevealImageView: View {
return isBlurred ? Strings.revealHint : Strings.openHint
}
private func loadImage() {
private func loadImage(maxPixelSize: Int) {
loadFailed = false
loadGeneration &+= 1
let generation = loadGeneration
let imageURL = url
DispatchQueue.global(qos: .userInitiated).async {
#if os(iOS)
let image = UIImage(contentsOfFile: url.path)
#else
let image = NSImage(contentsOf: url)
#endif
let image = ImageDownsampler.loadDownsampledImage(
from: imageURL,
maxPixelSize: maxPixelSize
)
DispatchQueue.main.async {
guard self.loadGeneration == generation else { return }
guard let image else {
self.loadFailed = true
return
}
self.platformImage = image
self.loadedMaxPixelSize = maxPixelSize
self.aspectRatio = image.size.height > 0 ? image.size.width / image.size.height : 1
}
}
@@ -1090,9 +1090,9 @@ struct PrivateMediaEndToEndTests {
@Test
func privateJPEGIsOpaqueBeforeFragmentationAndDelivers() async throws {
let marker = Data("JPEG_PRIVATE_MARKER_7f5e5eacb86f4b9a".utf8)
let content = Data([0xFF, 0xD8, 0xFF, 0xE0])
+ marker
+ Data(repeating: 0x4A, count: 6 * 1024)
let content = TestImageFixtures.makeJPEG(
comment: marker + Data(repeating: 0x4A, count: 6 * 1024)
)
try await assertPrivateMediaRoundTrip(
fileName: "img_20260725_120000_11111111-1111-1111-1111-111111111111.jpg",
mimeType: "image/jpeg",
@@ -431,7 +431,7 @@ struct BLEFileTransferHandlerTests {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
let content = TestImageFixtures.makeJPEG()
let fileName = "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
let file = BitchatFilePacket(
fileName: fileName,
@@ -500,7 +500,7 @@ struct BLEFileTransferHandlerTests {
store.finishIncomingFileDelivery(at: $0)
}
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
let content = TestImageFixtures.makeJPEG()
let fileName =
"img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
let file = BitchatFilePacket(
@@ -541,7 +541,7 @@ struct BLEFileTransferHandlerTests {
)]
recorder.signatureVerifies = true
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
let content = TestImageFixtures.makeJPEG()
let packet = try makeFileTransferPacket(
sender: remotePeerID,
mimeType: "image/jpeg",
@@ -572,7 +572,7 @@ struct BLEFileTransferHandlerTests {
let packet = try makeFileTransferPacket(
sender: remotePeerID,
mimeType: "image/jpeg",
content: Data([0xFF, 0xD8, 0xFF, 0xD9]),
content: TestImageFixtures.makeJPEG(),
recipientID: Data(hexString: localPeerID.id),
fileName: "raw-rejected.jpg"
)
@@ -599,7 +599,7 @@ struct BLEFileTransferHandlerTests {
let packet = try makeFileTransferPacket(
sender: remotePeerID,
mimeType: "image/jpeg",
content: Data([0xFF, 0xD8, 0xFF, 0xD9]),
content: TestImageFixtures.makeJPEG(),
recipientID: Data(hexString: localPeerID.id),
fileName: "plain-delegate.jpg"
)
@@ -620,7 +620,7 @@ struct BLEFileTransferHandlerTests {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
let content = TestImageFixtures.makeJPEG()
let file = BitchatFilePacket(
fileName: "photo.jpg",
fileSize: UInt64(content.count),
@@ -650,7 +650,7 @@ struct BLEFileTransferHandlerTests {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
let content = TestImageFixtures.makeJPEG()
let fileName = "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
let file = BitchatFilePacket(
fileName: fileName,
@@ -700,7 +700,7 @@ struct BLEFileTransferHandlerTests {
)
defer { try? FileManager.default.removeItem(at: root) }
let store = BLEIncomingFileStore(baseDirectory: root)
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
let content = TestImageFixtures.makeJPEG()
let file = BitchatFilePacket(
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
fileSize: UInt64(content.count),
@@ -772,7 +772,7 @@ struct BLEFileTransferHandlerTests {
func inFlightStableDuplicateIsNotAcknowledgedAndFailedSaveRemainsRetryable() throws {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
let content = TestImageFixtures.makeJPEG()
let file = BitchatFilePacket(
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
fileSize: UInt64(content.count),
@@ -838,7 +838,7 @@ struct BLEFileTransferHandlerTests {
))
recorder.receiptStates[messageID] = .unavailable
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
let content = TestImageFixtures.makeJPEG()
let payload = try #require(BitchatFilePacket(
fileName: fileName,
fileSize: UInt64(content.count),
@@ -868,7 +868,7 @@ struct BLEFileTransferHandlerTests {
)]
recorder.receiptCommitSucceeds = false
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
let content = TestImageFixtures.makeJPEG()
let payload = try #require(BitchatFilePacket(
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
fileSize: UInt64(content.count),
@@ -895,7 +895,7 @@ struct BLEFileTransferHandlerTests {
recorder.blockedPeers = [remotePeerID]
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
let handler = makeHandler(recorder: recorder)
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
let content = TestImageFixtures.makeJPEG()
let file = BitchatFilePacket(
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
fileSize: UInt64(content.count),
@@ -108,6 +108,65 @@ struct BLEFileTransferPolicyTests {
))
}
@Test
func validatorAcceptsValidPNGAndJPEGWithinBounds() throws {
let pngPayload = try makeFilePayload(mimeType: "image/png", content: TestImageFixtures.makePNG(width: 16, height: 12))
let jpegPayload = try makeFilePayload(mimeType: "image/jpeg", content: TestImageFixtures.makeJPEG(width: 16, height: 12))
if case .failure(let rejection) = BLEIncomingFileValidator.validate(payload: pngPayload) {
Issue.record("Expected valid PNG to pass, got \(rejection)")
}
if case .failure(let rejection) = BLEIncomingFileValidator.validate(payload: jpegPayload) {
Issue.record("Expected valid JPEG to pass, got \(rejection)")
}
}
@Test
func validatorRejectsPNGDecompressionBombExceedingDimensionLimit() throws {
let bomb = TestImageFixtures.makePNGBomb(width: 32_768, height: 32_768)
let payload = try makeFilePayload(mimeType: "image/png", content: bomb)
let result = BLEIncomingFileValidator.validate(payload: payload)
guard case .failure(.invalidImage(let mime, let bytes, _)) = result else {
Issue.record("Expected .invalidImage rejection for 32768x32768 PNG bomb, got \(result)")
return
}
#expect(mime == .png)
#expect(bytes == bomb.count)
}
@Test
func validatorRejectsTruncatedJPEGWithoutDimensions() throws {
let stub = Data([0xFF, 0xD8, 0xFF, 0xD9])
let payload = try makeFilePayload(mimeType: "image/jpeg", content: stub)
let result = BLEIncomingFileValidator.validate(payload: payload)
guard case .failure(.invalidImage(let mime, _, _)) = result else {
Issue.record("Expected .invalidImage rejection for truncated JPEG stub, got \(result)")
return
}
#expect(mime == .jpeg)
}
@Test
func imageDownsamplerRejectsOversizedPNGAndDownsamplesValidImage() throws {
let tempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("ImageDownsamplerTests-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: tempDir) }
let bombURL = tempDir.appendingPathComponent("bomb.png")
try TestImageFixtures.makePNGBomb(width: 16_384, height: 16_384).write(to: bombURL)
#expect(ImageDownsampler.loadDownsampledImage(from: bombURL, maxPixelSize: 64) == nil)
let validURL = tempDir.appendingPathComponent("valid.png")
try TestImageFixtures.makePNG(width: 256, height: 128).write(to: validURL)
let thumbnail = try #require(ImageDownsampler.loadDownsampledImage(from: validURL, maxPixelSize: 64))
#expect(max(thumbnail.size.width, thumbnail.size.height) <= 64)
}
private func makePacket(
sender: PeerID,
ttl: UInt8 = 3,
@@ -0,0 +1,95 @@
import CoreGraphics
import Foundation
import ImageIO
/// Deterministic, spec-compliant image fixtures for media-ingest tests.
enum TestImageFixtures {
static func makeJPEG(width: Int = 1, height: Int = 1, comment: Data? = nil) -> Data {
var encoded = encodeImage(width: width, height: height, uti: "public.jpeg")
if let comment, !comment.isEmpty, encoded.count >= 2, encoded[0] == 0xFF, encoded[1] == 0xD8 {
// Insert a standard JPEG COM (0xFF 0xFE) segment right after SOI.
let maxBody = Int(UInt16.max) - 2
let body = comment.prefix(maxBody)
var segment = Data([0xFF, 0xFE])
var length = UInt16(body.count + 2).bigEndian
withUnsafeBytes(of: &length) { segment.append(contentsOf: $0) }
segment.append(body)
encoded.insert(contentsOf: segment, at: 2)
}
return encoded
}
static func makePNG(width: Int = 1, height: Int = 1) -> Data {
encodeImage(width: width, height: height, uti: "public.png")
}
/// Builds a valid minimal PNG header claiming arbitrary dimensions (e.g.
/// 32768x32768) in under 60 bytes — a classic decompression-bomb header
/// that ImageIO metadata inspection reads without allocating pixel memory.
static func makePNGBomb(width: UInt32, height: UInt32) -> Data {
var data = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
var ihdr = Data()
var w = width.bigEndian
var h = height.bigEndian
withUnsafeBytes(of: &w) { ihdr.append(contentsOf: $0) }
withUnsafeBytes(of: &h) { ihdr.append(contentsOf: $0) }
ihdr.append(contentsOf: [8, 2, 0, 0, 0]) // 8-bit RGB, deflate, standard filter, non-interlaced
appendPNGChunk(type: "IHDR", body: ihdr, to: &data)
appendPNGChunk(type: "IEND", body: Data(), to: &data)
return data
}
private static func encodeImage(width: Int, height: Int, uti: String) -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: bitmapInfo
) else {
return Data()
}
context.setFillColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1.0)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let cgImage = context.makeImage() else { return Data() }
let output = NSMutableData()
guard let dest = CGImageDestinationCreateWithData(output, uti as CFString, 1, nil) else {
return Data()
}
CGImageDestinationAddImage(dest, cgImage, nil)
guard CGImageDestinationFinalize(dest) else { return Data() }
return output as Data
}
private static func appendPNGChunk(type: String, body: Data, to output: inout Data) {
let typeBytes = Data(type.utf8)
var length = UInt32(body.count).bigEndian
withUnsafeBytes(of: &length) { output.append(contentsOf: $0) }
output.append(typeBytes)
output.append(body)
var crc = crc32(typeBytes + body).bigEndian
withUnsafeBytes(of: &crc) { output.append(contentsOf: $0) }
}
private static func crc32(_ data: Data) -> UInt32 {
var crc: UInt32 = 0xFFFF_FFFF
for byte in data {
crc ^= UInt32(byte)
for _ in 0..<8 {
if (crc & 1) != 0 {
crc = (crc >> 1) ^ 0xEDB8_8320
} else {
crc >>= 1
}
}
}
return crc ^ 0xFFFF_FFFF
}
}