//! Just enough ISO-BMFF (ISO/IEC 14496-12 / 23008-12) to sniff a HEIF brand and read the primary item's size //! from its `ispe` property, so a HEIC bomb is refused before the OS codec sees it. Every read is bounds-checked; //! the walk is iterative and visits a fixed set of box levels. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Brand { Heif, Avif, } /// Brands that name HEVC-coded HEIF. const HEVC_BRANDS: [&[u8; 4]; 8] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs"]; /// Codec-neutral HEIF structural brands (image and sequence). const GENERIC_BRANDS: [&[u8; 4]; 2] = [b"mif1", b"msf1"]; const AVIF_BRANDS: [&[u8; 4]; 2] = [b"avif", b"avis"]; /// The brand family named in a leading `ftyp` box. AVIF files also list `mif1`, so an AV1 brand wins over the /// generic ones; when both an AV1 and an HEVC brand are listed, the major brand decides. pub(crate) fn brand(bytes: &[u8]) -> Option { let (kind, body, _) = next_box(bytes, 0)?; if &kind != b"ftyp" || body.len() < 8 { return None; } let major = &body[0..4]; let brands = || std::iter::once(major).chain(body[8..].as_chunks::<4>().0.iter().map(|c| &c[..])); let any = |set: &[&[u8; 4]]| brands().any(|b| set.iter().any(|s| &s[..] == b)); let avif = any(&AVIF_BRANDS); let hevc = any(&HEVC_BRANDS); match (avif, hevc) { (true, true) if AVIF_BRANDS.iter().any(|s| &s[..] == major) => Some(Brand::Avif), (true, false) => Some(Brand::Avif), (_, true) => Some(Brand::Heif), (false, false) if any(&GENERIC_BRANDS) => Some(Brand::Heif), _ => None, } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct Info { pub width: u32, pub height: u32, pub has_alpha: bool, } /// Size of the primary item (falls back to the largest `ispe` when the item associations are unreadable). pub(crate) fn info(bytes: &[u8]) -> Option { let meta = find_child(bytes, b"meta")?; let meta = meta.get(4..)?; // full box let primary = find_child(meta, b"pitm").and_then(|p| { let version = *p.first()?; if version == 0 { be16(p, 4).map(u32::from) } else { be32(p, 4) } }); let iprp = find_child(meta, b"iprp")?; let ipco = find_child(iprp, b"ipco")?; let mut props: Vec<([u8; 4], &[u8])> = Vec::new(); let mut pos = 0; while let Some((kind, body, next)) = next_box(ipco, pos) { if props.len() >= 4096 { break; } props.push((kind, body)); pos = next; } let ispe_of = |body: &[u8]| -> Option<(u32, u32)> { Some((be32(body, 4)?, be32(body, 8)?)) }; let has_alpha = props.iter().any(|(kind, body)| { &kind[..] == b"auxC" && { let urn = body.get(4..).unwrap_or(&[]); let urn = &urn[..urn.iter().position(|&b| b == 0).unwrap_or(urn.len())]; urn.ends_with(b"auxiliary:alpha") || urn == b"urn:mpeg:hevc:2015:auxid:1" } }); let from_primary = primary.and_then(|item| { let ipma = find_child(iprp, b"ipma")?; primary_props(ipma, item)? .into_iter() .filter_map(|index| props.get(index.checked_sub(1)?)) .find(|(kind, _)| &kind[..] == b"ispe") .and_then(|(_, body)| ispe_of(body)) }); let (width, height) = from_primary.or_else(|| { props .iter() .filter(|(kind, _)| &kind[..] == b"ispe") .filter_map(|(_, body)| ispe_of(body)) .max_by_key(|(w, h)| u64::from(*w) * u64::from(*h)) })?; Some(Info { width, height, has_alpha }) } /// Property indices (1-based into `ipco`) associated with `item` in an `ipma` box. fn primary_props(ipma: &[u8], item: u32) -> Option> { let version = *ipma.first()?; let flags = be32(ipma, 0)? & 0x00FF_FFFF; let count = be32(ipma, 4)?; let mut pos = 8usize; for _ in 0..count.min(1 << 20) { let id = if version < 1 { let v = u32::from(be16(ipma, pos)?); pos += 2; v } else { let v = be32(ipma, pos)?; pos += 4; v }; let n = usize::from(*ipma.get(pos)?); pos += 1; let mut indices = Vec::with_capacity(n); for _ in 0..n { if flags & 1 != 0 { indices.push(usize::from(be16(ipma, pos)? & 0x7FFF)); pos += 2; } else { indices.push(usize::from(*ipma.get(pos)? & 0x7F)); pos += 1; } } if id == item { return Some(indices); } } None } fn find_child<'a>(data: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> { let mut pos = 0; let mut guard = 0; while let Some((kind, body, next)) = next_box(data, pos) { if &kind == want { return Some(body); } guard += 1; if guard > 4096 { return None; } pos = next; } None } /// The box starting at `pos`: (type, body, offset of the next box). fn next_box(data: &[u8], pos: usize) -> Option<([u8; 4], &[u8], usize)> { let size32 = be32(data, pos)?; let kind: [u8; 4] = data.get(pos + 4..pos + 8)?.try_into().ok()?; let (header, size) = match size32 { 0 => (8usize, data.len().checked_sub(pos)?), 1 => (16, usize::try_from(be64(data, pos + 8)?).ok()?), n => (8, usize::try_from(n).ok()?), }; if size < header { return None; } let end = pos.checked_add(size)?; let body = data.get(pos + header..end)?; Some((kind, body, end)) } fn be16(d: &[u8], at: usize) -> Option { Some(u16::from_be_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?)) } fn be32(d: &[u8], at: usize) -> Option { Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?)) } fn be64(d: &[u8], at: usize) -> Option { Some(u64::from_be_bytes(d.get(at..at.checked_add(8)?)?.try_into().ok()?)) } #[cfg(test)] mod tests { use super::*; fn ftyp(major: &[u8; 4], compat: &[&[u8; 4]]) -> Vec { let mut body = major.to_vec(); body.extend_from_slice(&[0; 4]); for c in compat { body.extend_from_slice(&c[..]); } let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec(); out.extend_from_slice(b"ftyp"); out.extend_from_slice(&body); out } #[test] fn brands() { assert_eq!(brand(&ftyp(b"heic", &[b"mif1", b"heic"])), Some(Brand::Heif)); assert_eq!(brand(&ftyp(b"mif1", &[b"heic"])), Some(Brand::Heif)); assert_eq!(brand(&ftyp(b"msf1", &[])), Some(Brand::Heif)); assert_eq!(brand(&ftyp(b"avif", &[b"mif1", b"miaf"])), Some(Brand::Avif)); assert_eq!(brand(&ftyp(b"mif1", &[b"avif"])), Some(Brand::Avif)); assert_eq!(brand(&ftyp(b"isom", &[b"mp41"])), None, "an MP4 is not an image"); assert_eq!(brand(b"\0\0\0\x08ftyp"), None); assert_eq!(brand(b"\xff\xff\xff\xffftypheic"), None); } #[test] fn hostile_box_sizes() { // size 1 with a giant 64-bit size, size smaller than the header, truncated header. assert!(next_box(b"\0\0\0\x01meta\xff\xff\xff\xff\xff\xff\xff\xff", 0).is_none()); assert!(next_box(b"\0\0\0\x04meta", 0).is_none()); assert!(next_box(b"\0\0\0", 0).is_none()); assert!(info(b"\0\0\0\x0cmeta\0\0\0\0").is_none()); } }