Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(raw): validate DNG default crop bounds (#745)

Alex Gorevskid9a0f3828001
diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs
index 6ae428cde..f4f324dd4 100644
--- a/crates/raw/src/dng.rs
+++ b/crates/raw/src/dng.rs
@@ -113,6 +113,18 @@ fn rect_from(t: &Tiff, ifd: &Ifd, width: usize, height: usize) -> Rect {
}
}
+fn crop_value(value: f64, name: &str) -> Result<usize> {
+ if !value.is_finite() || value < 0.0 {
+ return Err(RawError::malformed(format!("invalid DNG {name}")));
+ }
+ let rounded = value.round();
+ let usize_limit = 2.0_f64.powi(usize::BITS as i32);
+ if rounded >= usize_limit {
+ return Err(RawError::malformed(format!("DNG {name} is not representable")));
+ }
+ Ok(rounded as usize)
+}
+
/// Decodes a DNG file's raw image and metadata.
pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
let ifds = t.all_ifds();
@@ -139,11 +151,29 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
let mut crop = active;
let origin = t.tag_floats(&raw, tag::DEFAULT_CROP_ORIGIN);
let size = t.tag_floats(&raw, tag::DEFAULT_CROP_SIZE);
- if let ([ox, oy], [cw, ch]) = (origin.as_slice(), size.as_slice()) {
- let f = |v: f64| if v.is_finite() && v >= 0.0 { v.round() as usize } else { 0 };
- let r = Rect::new(active.x + f(*ox), active.y + f(*oy), f(*cw), f(*ch)).intersect(&active);
- if !r.is_empty() {
- crop = r;
+ if raw.has(tag::DEFAULT_CROP_ORIGIN) || raw.has(tag::DEFAULT_CROP_SIZE) {
+ if let ([ox, oy], [cw, ch]) = (origin.as_slice(), size.as_slice()) {
+ let (ox, oy, cw, ch) = (
+ crop_value(*ox, "DefaultCropOrigin"),
+ crop_value(*oy, "DefaultCropOrigin"),
+ crop_value(*cw, "DefaultCropSize"),
+ crop_value(*ch, "DefaultCropSize"),
+ );
+ let (ox, oy, cw, ch) = (ox?, oy?, cw?, ch?);
+ let active_right = active.x.checked_add(active.width).ok_or_else(|| RawError::malformed("DNG active-area right edge overflow"))?;
+ let active_bottom = active.y.checked_add(active.height).ok_or_else(|| RawError::malformed("DNG active-area bottom edge overflow"))?;
+ let candidate = active.x.checked_add(ox).zip(active.y.checked_add(oy)).and_then(|(x, y)| {
+ let right = x.checked_add(cw)?;
+ let bottom = y.checked_add(ch)?;
+ (x >= active.x && y >= active.y && right <= active_right && bottom <= active_bottom).then_some(Rect::new(x, y, cw, ch))
+ });
+ if let Some(r) = candidate.filter(|r| !r.is_empty()) {
+ crop = r;
+ } else {
+ warnings.push("out-of-range or empty DNG default crop; active area used".to_string());
+ }
+ } else {
+ warnings.push("incomplete DNG default crop; active area used".to_string());
}
}
let scale = t.tag_floats(&raw, tag::DEFAULT_SCALE);
diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs
index 606a288c4..be8aa5dc0 100644
--- a/crates/raw/src/testgen.rs
+++ b/crates/raw/src/testgen.rs
@@ -178,6 +178,7 @@ pub enum Val {
Ascii(String),
Short(Vec<u16>),
Long(Vec<u32>),
+ Double(Vec<f64>),
Rational(Vec<(u32, u32)>),
SRational(Vec<(i32, i32)>),
Undefined(Vec<u8>),
@@ -219,6 +220,7 @@ impl TiffBuilder {
Val::Ascii(s) => s.len() + 1,
Val::Short(s) => 2 * s.len(),
Val::Long(l) => 4 * l.len(),
+ Val::Double(d) => 8 * d.len(),
Val::Rational(r) => 8 * r.len(),
Val::SRational(r) => 8 * r.len(),
Val::Blobs(b) => 4 * b.len(),
@@ -330,6 +332,7 @@ impl TiffBuilder {
let be = self.big_endian;
let b16 = |v: u16| if be { v.to_be_bytes() } else { v.to_le_bytes() };
let b32 = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() };
+ let b64 = |v: u64| if be { v.to_be_bytes() } else { v.to_le_bytes() };
match v {
Val::Byte(b) => (1, b.len() as u32, b.clone()),
Val::Undefined(b) => (7, b.len() as u32, b.clone()),
@@ -340,6 +343,7 @@ impl TiffBuilder {
}
Val::Short(s) => (3, s.len() as u32, s.iter().flat_map(|&v| b16(v)).collect()),
Val::Long(l) => (4, l.len() as u32, l.iter().flat_map(|&v| b32(v)).collect()),
+ Val::Double(d) => (12, d.len() as u32, d.iter().flat_map(|v| b64(v.to_bits())).collect()),
Val::Rational(r) => (5, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n), b32(d)].concat()).collect()),
Val::SRational(r) => (10, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n as u32), b32(d as u32)].concat()).collect()),
Val::Blobs(b) => (4, b.len() as u32, b.iter().flat_map(|&i| b32(blob_pos[i] as u32)).collect()),
@@ -390,6 +394,8 @@ pub struct DngSpec {
pub active_area: Option<[u32; 4]>,
/// origin (x, y), size (w, h), relative to the active area
pub default_crop: Option<([u32; 2], [u32; 2])>,
+ /// Double-precision origin override for malformed-metadata regression tests.
+ pub default_crop_origin_double: Option<[f64; 2]>,
pub linearization: Option<Vec<u16>>,
/// (illuminant code, ColorMatrix row-major)
pub color_matrix1: Option<(u16, [f64; 9])>,
@@ -422,6 +428,7 @@ impl DngSpec {
white: 65535,
active_area: None,
default_crop: None,
+ default_crop_origin_double: None,
linearization: None,
color_matrix1: None,
color_matrix2: None,
@@ -552,8 +559,11 @@ impl DngSpec {
raw.push((50829, Val::Long(a.to_vec())));
}
if let Some((o, s)) = self.default_crop {
- raw.push((50719, Val::Long(o.to_vec())));
+ let origin = self.default_crop_origin_double.map(|d| Val::Double(d.to_vec())).unwrap_or_else(|| Val::Long(o.to_vec()));
+ raw.push((50719, origin));
raw.push((50720, Val::Long(s.to_vec())));
+ } else if let Some(origin) = self.default_crop_origin_double {
+ raw.push((50719, Val::Double(origin.to_vec())));
}
if let Some(o) = &self.opcode_list2 {
raw.push((51009, Val::Undefined(o.clone())));
diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/dng.rs
index 01db5d5a8..8b2e40144 100644
--- a/crates/raw/tests/dng.rs
+++ b/crates/raw/tests/dng.rs
@@ -105,6 +105,41 @@ fn metadata_is_read() {
assert_eq!((d.width, d.height), (20, 16));
}
+#[test]
+fn enormous_double_crop_origin_is_rejected() {
+ let (w, h) = (16, 12);
+ let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]);
+ spec.active_area = Some([2, 3, 10, 14]);
+ spec.default_crop = Some(([0, 0], [11, 8]));
+ spec.default_crop_origin_double = Some([1e300, 0.0]);
+
+ assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))));
+}
+
+#[test]
+fn out_of_range_default_crop_falls_back_to_active_area_with_warning() {
+ let (w, h) = (16, 12);
+ let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]);
+ spec.active_area = Some([2, 3, 10, 14]);
+ spec.default_crop = Some(([10, 0], [5, 4]));
+
+ let s = sensor(&spec.build());
+ assert_eq!(s.crop, s.active);
+ assert!(s.warnings.iter().any(|warning| warning.contains("out-of-range") && warning.contains("default crop")), "{:?}", s.warnings);
+}
+
+#[test]
+fn incomplete_default_crop_falls_back_to_active_area_with_warning() {
+ let (w, h) = (16, 12);
+ let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]);
+ spec.active_area = Some([2, 3, 10, 14]);
+ spec.default_crop_origin_double = Some([1.0, 1.0]);
+
+ let s = sensor(&spec.build());
+ assert_eq!(s.crop, s.active);
+ assert!(s.warnings.iter().any(|warning| warning.contains("incomplete") && warning.contains("default crop")), "{:?}", s.warnings);
+}
+
/// Linear sRGB (D65) → XYZ, from the sRGB primaries (IEC 61966-2-1).
const SRGB_TO_XYZ: [[f64; 3]; 3] = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]];