use std::fs::{self, File};
use std::io::{self, BufReader, Read};
use std::path::Path;
use ::image::{GenericImageView, ImageFormat, ImageReader, Limits};
use crc32fast::Hasher as Crc32;
use crate::{MAX_RETAINED_IMAGE_BYTES, PhotoForgeError, Result};
const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
const MAX_DECODE_DIMENSION: u32 = 32_768;
const MAX_DECODE_PIXELS: u64 = 100_000_000;
const MAX_DECODE_ALLOCATION: u64 = 512 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PhotoFormat {
Jpeg,
Png,
}
impl PhotoFormat {
pub(crate) fn from_mime(mime: &str) -> Result<Self> {
match mime {
"image/jpeg" => Ok(Self::Jpeg),
"image/png" => Ok(Self::Png),
_ => Err(PhotoForgeError::VerificationFailed {
path: mime.to_string(),
message: "unsupported photo MIME type in PhotoForge 0.1".to_string(),
}),
}
}
pub(crate) const fn extension(self) -> &'static str {
match self {
Self::Jpeg => "jpg",
Self::Png => "png",
}
}
pub(crate) fn relative_name(self) -> String {
format!("photo.{}", self.extension())
}
}
pub(crate) fn validate_image_file(
path: &Path,
mime: &str,
expected_width: u32,
expected_height: u32,
) -> Result<()> {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || !metadata.is_file() {
return verification(path, "image is not a regular non-symlink file");
}
if metadata.len() == 0 {
return verification(path, "image is empty");
}
if metadata.len() > MAX_RETAINED_IMAGE_BYTES {
return verification(path, "image exceeds the hard retained-image limit");
}
if expected_width == 0
|| expected_height == 0
|| expected_width > MAX_DECODE_DIMENSION
|| expected_height > MAX_DECODE_DIMENSION
|| u64::from(expected_width)
.checked_mul(u64::from(expected_height))
.is_none_or(|pixels| pixels > MAX_DECODE_PIXELS)
{
return verification(path, "expected image dimensions exceed decode limits");
}
let format = PhotoFormat::from_mime(mime)?;
match format {
PhotoFormat::Jpeg => validate_jpeg(path, expected_width, expected_height),
PhotoFormat::Png => validate_png(path, expected_width, expected_height),
}?;
fully_decode_image(path, format, expected_width, expected_height)
}
fn fully_decode_image(
path: &Path,
format: PhotoFormat,
expected_width: u32,
expected_height: u32,
) -> Result<()> {
let expected_format = match format {
PhotoFormat::Jpeg => ImageFormat::Jpeg,
PhotoFormat::Png => ImageFormat::Png,
};
let mut reader = ImageReader::new(BufReader::new(File::open(path)?))
.with_guessed_format()
.map_err(|error| PhotoForgeError::VerificationFailed {
path: path.display().to_string(),
message: format!("image format detection failed: {error}"),
})?;
if reader.format() != Some(expected_format) {
return verification(path, "decoder format does not match the declared MIME type");
}
let mut limits = Limits::default();
limits.max_image_width = Some(MAX_DECODE_DIMENSION);
limits.max_image_height = Some(MAX_DECODE_DIMENSION);
limits.max_alloc = Some(MAX_DECODE_ALLOCATION);
reader.limits(limits);
let decoded = reader
.decode()
.map_err(|error| PhotoForgeError::VerificationFailed {
path: path.display().to_string(),
message: format!("full bounded image decode failed: {error}"),
})?;
let (width, height) = decoded.dimensions();
if width != expected_width || height != expected_height {
return verification(path, "decoded dimensions do not match Commons metadata");
}
Ok(())
}
fn validate_png(path: &Path, expected_width: u32, expected_height: u32) -> Result<()> {
let file = File::open(path)?;
let file_len = file.metadata()?.len();
let mut reader = BufReader::new(file);
let mut signature = [0_u8; 8];
read_exact_image(&mut reader, &mut signature, path, "truncated PNG signature")?;
if &signature != PNG_SIGNATURE {
return verification(path, "PNG signature is invalid");
}
let mut position = 8_u64;
let mut chunk_index = 0_u64;
let mut saw_idat = false;
let mut idat_ended = false;
loop {
if position == file_len {
return verification(path, "PNG is missing IEND");
}
if file_len.saturating_sub(position) < 12 {
return verification(path, "PNG has a truncated chunk header");
}
let mut header = [0_u8; 8];
read_exact_image(&mut reader, &mut header, path, "truncated PNG chunk header")?;
position = position.saturating_add(8);
let length = u32::from_be_bytes(header[..4].try_into().expect("four-byte slice"));
let chunk_type: [u8; 4] = header[4..].try_into().expect("four-byte slice");
if !chunk_type.iter().all(u8::is_ascii_alphabetic) {
return verification(path, "PNG chunk type is invalid");
}
let remaining = u64::from(length).checked_add(4).ok_or_else(|| {
PhotoForgeError::VerificationFailed {
path: path.display().to_string(),
message: "PNG chunk length overflowed".to_string(),
}
})?;
if remaining > file_len.saturating_sub(position) {
return verification(path, "PNG chunk length exceeds the remaining file");
}
if chunk_index == 0 && (chunk_type != *b"IHDR" || length != 13) {
return verification(path, "PNG IHDR must be the first 13-byte chunk");
}
if chunk_index != 0 && chunk_type == *b"IHDR" {
return verification(path, "PNG contains more than one IHDR chunk");
}
if matches!(&chunk_type, b"acTL" | b"fcTL" | b"fdAT") {
return verification(path, "APNG animation chunks are not accepted");
}
if chunk_type == *b"IDAT" {
if idat_ended {
return verification(path, "PNG IDAT chunks are not consecutive");
}
saw_idat = true;
} else if saw_idat && chunk_type != *b"IEND" {
idat_ended = true;
}
let mut crc = Crc32::new();
crc.update(&chunk_type);
let mut retained = Vec::new();
let mut left = u64::from(length);
let mut buffer = [0_u8; 64 * 1024];
while left > 0 {
let wanted = usize::try_from(left.min(buffer.len() as u64)).expect("bounded buffer");
read_exact_image(
&mut reader,
&mut buffer[..wanted],
path,
"truncated PNG chunk data",
)?;
crc.update(&buffer[..wanted]);
if chunk_type == *b"IHDR" {
retained.extend_from_slice(&buffer[..wanted]);
}
left -= wanted as u64;
position = position.saturating_add(wanted as u64);
}
let mut expected_crc = [0_u8; 4];
read_exact_image(
&mut reader,
&mut expected_crc,
path,
"truncated PNG chunk CRC",
)?;
position = position.saturating_add(4);
if crc.finalize() != u32::from_be_bytes(expected_crc) {
return verification(path, "PNG chunk CRC does not match");
}
if chunk_type == *b"IHDR" {
validate_ihdr(path, &retained, expected_width, expected_height)?;
}
if chunk_type == *b"IEND" {
if length != 0 || !saw_idat {
return verification(path, "PNG IEND is invalid or precedes IDAT");
}
if position != file_len {
return verification(path, "PNG has trailing bytes after IEND");
}
return Ok(());
}
chunk_index = chunk_index.saturating_add(1);
}
}
fn validate_ihdr(
path: &Path,
data: &[u8],
expected_width: u32,
expected_height: u32,
) -> Result<()> {
if data.len() != 13 {
return verification(path, "PNG IHDR length is not 13 bytes");
}
let width = u32::from_be_bytes(data[..4].try_into().expect("four-byte slice"));
let height = u32::from_be_bytes(data[4..8].try_into().expect("four-byte slice"));
let bit_depth = data[8];
let color_type = data[9];
let valid_depth = match color_type {
0 => matches!(bit_depth, 1 | 2 | 4 | 8 | 16),
2 | 4 | 6 => matches!(bit_depth, 8 | 16),
3 => matches!(bit_depth, 1 | 2 | 4 | 8),
_ => false,
};
if width == 0
|| height == 0
|| width != expected_width
|| height != expected_height
|| !valid_depth
|| data[10] != 0
|| data[11] != 0
|| !matches!(data[12], 0 | 1)
{
return verification(
path,
"PNG IHDR dimensions or encoding fields do not match metadata",
);
}
Ok(())
}
fn validate_jpeg(path: &Path, expected_width: u32, expected_height: u32) -> Result<()> {
let mut reader = BufReader::new(File::open(path)?);
let mut soi = [0_u8; 2];
read_exact_image(&mut reader, &mut soi, path, "truncated JPEG SOI")?;
if soi != [0xff, 0xd8] {
return verification(path, "JPEG does not begin with FF D8");
}
let prefix = read_byte(&mut reader, path, "JPEG ends after SOI")?;
if prefix != 0xff {
return verification(path, "JPEG does not begin with FF D8 FF");
}
let mut marker = marker_after_prefix(&mut reader, path)?;
let mut saw_sof = false;
let mut saw_sos = false;
let mut scan_mode = false;
loop {
if marker == 0xd9 {
if !saw_sof || !saw_sos {
return verification(path, "JPEG EOI appears before a valid SOF and scan");
}
let mut trailing = [0_u8; 64 * 1024];
loop {
let count = reader.read(&mut trailing)?;
if count == 0 {
return Ok(());
}
if trailing[..count]
.iter()
.any(|byte| !matches!(byte, 0x00 | 0xff))
{
return verification(path, "JPEG has non-padding bytes after EOI");
}
}
}
if matches!(marker, 0xd8) {
return verification(path, "JPEG contains an unexpected second SOI");
}
if matches!(marker, 0x01 | 0xd0..=0xd7) {
marker = next_jpeg_marker(&mut reader, path, scan_mode)?;
continue;
}
let mut length_bytes = [0_u8; 2];
read_exact_image(
&mut reader,
&mut length_bytes,
path,
"truncated JPEG segment length",
)?;
let length = usize::from(u16::from_be_bytes(length_bytes));
if length < 2 {
return verification(path, "JPEG segment length is smaller than two");
}
let payload_len = length - 2;
if is_sof_marker(marker) {
if saw_sof {
return verification(path, "JPEG contains multiple frame headers");
}
let mut payload = vec![0_u8; payload_len];
read_exact_image(
&mut reader,
&mut payload,
path,
"truncated JPEG frame header",
)?;
validate_sof(path, &payload, expected_width, expected_height)?;
saw_sof = true;
scan_mode = false;
} else if marker == 0xda {
let mut payload = vec![0_u8; payload_len];
read_exact_image(
&mut reader,
&mut payload,
path,
"truncated JPEG scan header",
)?;
validate_sos(path, &payload)?;
if !saw_sof {
return verification(path, "JPEG scan precedes its frame header");
}
saw_sos = true;
scan_mode = true;
} else {
skip_exact(&mut reader, payload_len, path, "truncated JPEG segment")?;
scan_mode = false;
}
marker = next_jpeg_marker(&mut reader, path, scan_mode)?;
if !matches!(marker, 0xd0..=0xd7 | 0x01) {
scan_mode = false;
}
}
}
fn validate_sof(
path: &Path,
payload: &[u8],
expected_width: u32,
expected_height: u32,
) -> Result<()> {
if payload.len() < 6 {
return verification(path, "JPEG frame header is too short");
}
let precision = payload[0];
let height = u32::from(u16::from_be_bytes([payload[1], payload[2]]));
let width = u32::from(u16::from_be_bytes([payload[3], payload[4]]));
let components = usize::from(payload[5]);
if !matches!(precision, 8 | 12)
|| width == 0
|| height == 0
|| width != expected_width
|| height != expected_height
|| !(1..=4).contains(&components)
|| payload.len() != 6 + components * 3
{
return verification(
path,
"JPEG frame dimensions or component structure do not match metadata",
);
}
Ok(())
}
fn validate_sos(path: &Path, payload: &[u8]) -> Result<()> {
let Some(&components) = payload.first() else {
return verification(path, "JPEG scan header is empty");
};
let components = usize::from(components);
if !(1..=4).contains(&components) || payload.len() != 1 + components * 2 + 3 {
return verification(path, "JPEG scan header has an invalid component structure");
}
Ok(())
}
fn is_sof_marker(marker: u8) -> bool {
matches!(
marker,
0xc0 | 0xc1 | 0xc2 | 0xc3 | 0xc5 | 0xc6 | 0xc7 | 0xc9 | 0xca | 0xcb | 0xcd | 0xce | 0xcf
)
}
fn next_jpeg_marker<R: Read>(reader: &mut R, path: &Path, scan_mode: bool) -> Result<u8> {
if !scan_mode {
let prefix = read_byte(reader, path, "JPEG is missing a following marker")?;
if prefix != 0xff {
return verification(path, "JPEG segment is not followed by a marker");
}
return marker_after_prefix(reader, path);
}
loop {
if read_byte(reader, path, "JPEG scan is truncated before EOI")? != 0xff {
continue;
}
let marker = marker_after_prefix(reader, path)?;
if marker == 0x00 || matches!(marker, 0xd0..=0xd7 | 0x01) {
continue;
}
return Ok(marker);
}
}
fn marker_after_prefix<R: Read>(reader: &mut R, path: &Path) -> Result<u8> {
loop {
let marker = read_byte(reader, path, "truncated JPEG marker")?;
if marker == 0xff {
continue;
}
return Ok(marker);
}
}
fn read_byte<R: Read>(reader: &mut R, path: &Path, message: &str) -> Result<u8> {
let mut byte = [0_u8; 1];
read_exact_image(reader, &mut byte, path, message)?;
Ok(byte[0])
}
fn read_exact_image<R: Read>(
reader: &mut R,
bytes: &mut [u8],
path: &Path,
message: &str,
) -> Result<()> {
reader.read_exact(bytes).map_err(|error| {
if error.kind() == io::ErrorKind::UnexpectedEof {
PhotoForgeError::VerificationFailed {
path: path.display().to_string(),
message: message.to_string(),
}
} else {
PhotoForgeError::Io(error)
}
})
}
fn skip_exact<R: Read>(reader: &mut R, mut count: usize, path: &Path, message: &str) -> Result<()> {
let mut buffer = [0_u8; 64 * 1024];
while count > 0 {
let wanted = count.min(buffer.len());
read_exact_image(reader, &mut buffer[..wanted], path, message)?;
count -= wanted;
}
Ok(())
}
fn verification<T>(path: &Path, message: &str) -> Result<T> {
Err(PhotoForgeError::VerificationFailed {
path: path.display().to_string(),
message: message.to_string(),
})
}
#[cfg(test)]
pub(crate) fn test_png(width: u32, height: u32) -> Vec<u8> {
use ::image::ImageEncoder;
let pixels = vec![0x6a; width as usize * height as usize * 3];
let mut bytes = Vec::new();
::image::codecs::png::PngEncoder::new(&mut bytes)
.write_image(&pixels, width, height, ::image::ExtendedColorType::Rgb8)
.expect("tiny generated PNG encodes");
bytes
}
#[cfg(test)]
pub(crate) fn test_jpeg(width: u16, height: u16) -> Vec<u8> {
let pixels = vec![0x79; width as usize * height as usize * 3];
let mut bytes = Vec::new();
::image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90)
.encode(
&pixels,
u32::from(width),
u32::from(height),
::image::ExtendedColorType::Rgb8,
)
.expect("tiny generated JPEG encodes");
bytes
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn write_fixture(bytes: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("image.bin");
let mut file = File::create(&path).unwrap();
file.write_all(bytes).unwrap();
(temp, path)
}
fn corrupt_png_deflate_with_valid_crc(bytes: &mut [u8]) {
let mut offset = PNG_SIGNATURE.len();
while offset + 12 <= bytes.len() {
let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize;
let kind_start = offset + 4;
let data_start = offset + 8;
let data_end = data_start + length;
if &bytes[kind_start..kind_start + 4] == b"IDAT" {
bytes[data_start] ^= 0x7f;
let mut crc = Crc32::new();
crc.update(&bytes[kind_start..data_end]);
bytes[data_end..data_end + 4].copy_from_slice(&crc.finalize().to_be_bytes());
return;
}
offset = data_end + 4;
}
panic!("generated PNG had no IDAT");
}
fn structurally_valid_but_undecodable_jpeg(width: u16, height: u16) -> Vec<u8> {
let mut bytes = vec![0xff, 0xd8];
let sof = [
8,
(height >> 8) as u8,
height as u8,
(width >> 8) as u8,
width as u8,
1,
1,
0x11,
0,
];
bytes.extend_from_slice(&[0xff, 0xc0]);
bytes.extend_from_slice(&((sof.len() + 2) as u16).to_be_bytes());
bytes.extend_from_slice(&sof);
let sos = [1, 1, 0, 0, 63, 0];
bytes.extend_from_slice(&[0xff, 0xda]);
bytes.extend_from_slice(&((sos.len() + 2) as u16).to_be_bytes());
bytes.extend_from_slice(&sos);
bytes.extend_from_slice(&[0x12, 0xff, 0x00, 0x34, 0xff, 0xd9]);
bytes
}
#[test]
fn validates_generated_static_png_and_jpeg() {
let (_temp, png) = write_fixture(&test_png(3, 2));
validate_image_file(&png, "image/png", 3, 2).unwrap();
let (_temp, jpeg) = write_fixture(&test_jpeg(3, 2));
validate_image_file(&jpeg, "image/jpeg", 3, 2).unwrap();
}
#[test]
fn png_rejects_bad_signature_crc_truncation_and_dimension_mismatch() {
let mut bytes = test_png(3, 2);
bytes[0] = 0;
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/png", 3, 2).is_err());
let mut bytes = test_png(3, 2);
bytes[29] ^= 1;
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/png", 3, 2).is_err());
let mut bytes = test_png(3, 2);
bytes.truncate(bytes.len() - 2);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/png", 3, 2).is_err());
let (_temp, path) = write_fixture(&test_png(3, 2));
assert!(validate_image_file(&path, "image/png", 4, 2).is_err());
}
#[test]
fn png_rejects_apng_and_trailing_data() {
let mut bytes = test_png(1, 1);
let iend = bytes.split_off(bytes.len() - 12);
let data = [0_u8; 8];
bytes.extend_from_slice(&(data.len() as u32).to_be_bytes());
bytes.extend_from_slice(b"acTL");
bytes.extend_from_slice(&data);
let mut crc = Crc32::new();
crc.update(b"acTL");
crc.update(&data);
bytes.extend_from_slice(&crc.finalize().to_be_bytes());
bytes.extend_from_slice(&iend);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/png", 1, 1).is_err());
let mut bytes = test_png(1, 1);
bytes.push(0);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/png", 1, 1).is_err());
}
#[test]
fn full_decode_rejects_malformed_png_deflate_and_jpeg_entropy_tables() {
let mut png = test_png(2, 1);
corrupt_png_deflate_with_valid_crc(&mut png);
let (_temp, path) = write_fixture(&png);
validate_png(&path, 2, 1).unwrap();
assert!(validate_image_file(&path, "image/png", 2, 1).is_err());
let jpeg = structurally_valid_but_undecodable_jpeg(2, 1);
let (_temp, path) = write_fixture(&jpeg);
validate_jpeg(&path, 2, 1).unwrap();
assert!(validate_image_file(&path, "image/jpeg", 2, 1).is_err());
}
#[test]
fn jpeg_rejects_bad_soi_segment_lengths_truncation_and_mismatch() {
let mut bytes = test_jpeg(3, 2);
bytes[1] = 0;
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());
let mut bytes = test_jpeg(3, 2);
bytes[4] = 0;
bytes[5] = 1;
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());
let mut bytes = test_jpeg(3, 2);
bytes.truncate(bytes.len() - 1);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());
let (_temp, path) = write_fixture(&test_jpeg(3, 2));
assert!(validate_image_file(&path, "image/jpeg", 2, 2).is_err());
}
#[test]
fn jpeg_requires_eoi_and_rejects_nonpadding_trailer() {
let mut bytes = test_jpeg(1, 1);
bytes.truncate(bytes.len() - 2);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/jpeg", 1, 1).is_err());
let mut bytes = test_jpeg(1, 1);
bytes.extend_from_slice(&[0, 0xff]);
let (_temp, path) = write_fixture(&bytes);
validate_image_file(&path, "image/jpeg", 1, 1).unwrap();
let mut bytes = test_jpeg(1, 1);
bytes.push(1);
let (_temp, path) = write_fixture(&bytes);
assert!(validate_image_file(&path, "image/jpeg", 1, 1).is_err());
}
#[test]
fn rejects_every_unsupported_initial_mime() {
let (_temp, path) = write_fixture(b"GIF89a");
for mime in [
"image/gif",
"image/svg+xml",
"image/webp",
"image/tiff",
"image/avif",
"image/bigtiff",
] {
assert!(validate_image_file(&path, mime, 1, 1).is_err());
}
}
#[test]
fn hard_file_and_decode_dimension_limits_apply_before_allocation() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("oversized.png");
let file = File::create(&path).unwrap();
file.set_len(MAX_RETAINED_IMAGE_BYTES + 1).unwrap();
assert!(validate_image_file(&path, "image/png", 1, 1).is_err());
let (_temp, path) = write_fixture(&test_png(1, 1));
assert!(validate_image_file(&path, "image/png", MAX_DECODE_DIMENSION + 1, 1).is_err());
}
}