Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Bound decompressed size and entry count of native and IDML ZIP imports

NetterSilver4626c4b0846d
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index 1c8910747..86393f803 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -87,22 +87,51 @@ pub fn load(bytes: &[u8]) -> Result<Document, FormatError> {
load_legacy_json(bytes)
}
+/// Most entries a `.designcraft` archive may hold.
+const MAX_ENTRIES: usize = 100_000;
+/// Most bytes `meta.json` or `document.json` may expand to.
+const MAX_JSON_BYTES: u64 = 256 << 20;
+/// Most bytes one embedded asset may expand to.
+const MAX_ASSET_BYTES: u64 = 1 << 30;
+/// Most bytes all the entries read from one archive may expand to together.
+const MAX_TOTAL_BYTES: u64 = 4 << 30;
+
+/// Read entry `name` of `z`, or `None` when it is missing or unreadable. Refuses an entry that
+/// expands past `limit` bytes or past what is `left` of the archive's budget, without
+/// decompressing more than that: the sizes the archive claims are not trusted.
+fn read_entry(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, limit: u64, left: &mut u64) -> Result<Option<Vec<u8>>, FormatError> {
+ let too_big = || FormatError::Io(format!("{name} is larger than the {limit}-byte limit (or the archive is larger than {MAX_TOTAL_BYTES} bytes)"));
+ let Ok(f) = z.by_name(name) else { return Ok(None) };
+ let limit = limit.min(*left);
+ if f.size() > limit {
+ return Err(too_big());
+ }
+ let mut v = Vec::new();
+ if f.take(limit.saturating_add(1)).read_to_end(&mut v).is_err() {
+ return Ok(None);
+ }
+ let n = v.len() as u64;
+ if n > limit {
+ return Err(too_big());
+ }
+ *left = left.saturating_sub(n);
+ Ok(Some(v))
+}
+
fn load_zip(bytes: &[u8]) -> Result<Document, FormatError> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::NotOurs(e.to_string()))?;
- let read = |z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str| -> Option<Vec<u8>> {
- let mut f = z.by_name(name).ok()?;
- let mut v = Vec::new();
- f.read_to_end(&mut v).ok()?;
- Some(v)
- };
- let version = read(&mut z, "meta.json")
+ if z.len() > MAX_ENTRIES {
+ return Err(FormatError::NotOurs(format!("{} entries (at most {MAX_ENTRIES})", z.len())));
+ }
+ let mut left = MAX_TOTAL_BYTES;
+ let version = read_entry(&mut z, "meta.json", MAX_JSON_BYTES, &mut left)?
.and_then(|meta| serde_json::from_slice::<Value>(&meta).ok())
.and_then(|m| m.get("version").and_then(Value::as_u64))
.map_or(1, |v| u32::try_from(v).unwrap_or(u32::MAX));
if version > VERSION {
return Err(FormatError::TooNew(version));
}
- let json = read(&mut z, "document.json").ok_or_else(|| FormatError::NotOurs("missing document.json".into()))?;
+ let json = read_entry(&mut z, "document.json", MAX_JSON_BYTES, &mut left)?.ok_or_else(|| FormatError::NotOurs("missing document.json".into()))?;
let mut v: Value = serde_json::from_slice(&json).map_err(|e| FormatError::NotOurs(e.to_string()))?;
upgrade_json(&mut v);
let mut doc: Document = serde_json::from_value(v).map_err(|e| FormatError::NotOurs(e.to_string()))?;
@@ -114,7 +143,11 @@ fn load_zip(bytes: &[u8]) -> Result<Document, FormatError> {
for name in names {
let Some(stem) = name.strip_prefix("assets/") else { continue };
let Some(id) = stem.split('.').next().and_then(|s| s.parse::<u64>().ok()) else { continue };
- if let (Some(data), Some(a)) = (read(&mut z, &name), doc.assets.get_mut(&AssetId(id))) {
+ // Entries for assets the document doesn't have are never decompressed.
+ if !doc.assets.contains_key(&AssetId(id)) {
+ continue;
+ }
+ if let (Some(data), Some(a)) = (read_entry(&mut z, &name, MAX_ASSET_BYTES, &mut left)?, doc.assets.get_mut(&AssetId(id))) {
let same = loaded.entry(fingerprint.hash_one(data.as_slice())).or_default();
let data = match same.iter().find(|d| ***d == data) {
Some(d) => d.clone(),
@@ -613,4 +646,79 @@ mod tests {
}
assert!(matches!(load(&buf.into_inner()), Err(FormatError::TooNew(99))));
}
+
+ /// Write `len` bytes of `fill` to the current entry of `z`.
+ fn write_fill(z: &mut zip::ZipWriter<Cursor<Vec<u8>>>, len: usize, fill: u8) {
+ let chunk = vec![fill; 1 << 20];
+ let mut left = len;
+ while left > 0 {
+ let n = left.min(chunk.len());
+ z.write_all(&chunk[..n]).unwrap();
+ left -= n;
+ }
+ }
+
+ /// Make the archive claim that entry `name` expands to `size` bytes, in both its local header
+ /// and its central directory record (the archive has no ZIP64 fields or data descriptors).
+ fn claim_size(bytes: &mut [u8], name: &str, size: u32) {
+ let mut patched = 0;
+ for i in 0..bytes.len().saturating_sub(46) {
+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {
+ b"PK\x03\x04" => (22, 26, 30),
+ b"PK\x01\x02" => (24, 28, 46),
+ _ => continue,
+ };
+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;
+ if bytes.get(i + name_at..i + name_at + len) == Some(name.as_bytes()) {
+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&size.to_le_bytes());
+ patched += 1;
+ }
+ }
+ assert_eq!(patched, 2, "{name} not found in both headers");
+ }
+
+ /// A small archive whose `document.json` expands past the 256 MiB limit while claiming to
+ /// hold one byte is refused once the limit is reached, with an error that says so, instead of
+ /// being read whole into memory.
+ #[test]
+ fn oversized_document_json_is_refused() {
+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();
+ write_fill(&mut z, (256 << 20) + 1, b' ');
+ let mut bytes = z.finish().unwrap().into_inner();
+ assert!(bytes.len() < 4 << 20, "{}", bytes.len());
+ claim_size(&mut bytes, "document.json", 1);
+ let Err(err) = load(&bytes) else { panic!("an oversized document.json loaded") };
+ assert!(err.to_string().contains("limit"), "{err}");
+ }
+
+ /// An embedded file that expands past the 1 GiB limit (and says so) is refused too.
+ #[test]
+ fn oversized_asset_is_refused() {
+ let mut d = Document::new(&NewDocument::default());
+ let aid = png_asset(&mut d, &[1]);
+ place(&mut d, aid, 0.0);
+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();
+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();
+ z.start_file(format!("assets/{}.png", aid.0), zip::write::SimpleFileOptions::default()).unwrap();
+ write_fill(&mut z, (1 << 30) + 1, 0);
+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an oversized asset loaded") };
+ assert!(err.to_string().contains("limit"), "{err}");
+ }
+
+ /// An archive with more entries than any document needs is refused before any is read.
+ #[test]
+ fn too_many_entries_are_refused() {
+ let d = Document::new(&NewDocument::default());
+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
+ let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ z.start_file("document.json", stored).unwrap();
+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();
+ for i in 0..100_000 {
+ z.start_file(format!("junk/{i}"), stored).unwrap();
+ }
+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an archive with 100 001 entries loaded") };
+ assert!(err.to_string().contains("entries"), "{err}");
+ }
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 51dc66d84..54e1da5db 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -62,30 +62,14 @@ pub struct Imported {
/// Import with a custom reader for linked files, reporting the problems that did not stop it.
pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Imported> {
- let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
- let mut files: HashMap<String, Vec<u8>> = HashMap::new();
- // Normalised part name → entry name, first entry wins (zip order, so the choice is stable).
- let mut lenient: HashMap<String, String> = HashMap::new();
- for i in 0..zip.len() {
- let mut f = zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
- if f.is_dir() {
- continue;
- }
- let name = f.name().to_string();
- // The size is what the archive claims: don't reserve more than a sane part up front.
- let mut buf = Vec::with_capacity((f.size() as usize).min(1 << 24));
- f.read_to_end(&mut buf).map_err(|e| IdmlError::Part { part: name.clone(), msg: e.to_string() })?;
- lenient.entry(normalize_part_name(&name)).or_insert_with(|| name.clone());
- files.insert(name, buf);
- }
- let part = |name: &str| files.get(name).or_else(|| lenient.get(&normalize_part_name(name)).and_then(|n| files.get(n)));
- if let Some(m) = part("mimetype")
- && String::from_utf8_lossy(m).trim() != MIMETYPE
+ let mut pkg = Package::open(bytes)?;
+ if let Some(m) = pkg.part("mimetype")?
+ && String::from_utf8_lossy(&m).trim() != MIMETYPE
{
- return Err(IdmlError::NotIdml(format!("unexpected mimetype `{}`", String::from_utf8_lossy(m).trim())));
+ return Err(IdmlError::NotIdml(format!("unexpected mimetype `{}`", String::from_utf8_lossy(&m).trim())));
}
- let dm = part("designmap.xml").ok_or_else(|| IdmlError::NotIdml("missing designmap.xml".into()))?;
- let root = parse(dm).map_err(|msg| IdmlError::Part { part: "designmap.xml".into(), msg })?;
+ let dm = pkg.part("designmap.xml")?.ok_or_else(|| IdmlError::NotIdml("missing designmap.xml".into()))?;
+ let root = parse(&dm).map_err(|msg| IdmlError::Part { part: "designmap.xml".into(), msg })?;
if root.local() != "Document" {
return Err(IdmlError::NotIdml(format!("designmap root is <{}>", root.name)));
}
@@ -95,11 +79,11 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u
for c in root.elements() {
if c.name.starts_with("idPkg:") {
let Some(src) = c.get("src") else { continue };
- let Some(data) = part(src) else {
+ let Some(data) = pkg.part(src)? else {
warnings.push(format!("{src}: listed in designmap.xml but missing from the package; its contents were not imported"));
continue;
};
- let el = parse(data).map_err(|msg| IdmlError::Part { part: src.into(), msg })?;
+ let el = parse(&data).map_err(|msg| IdmlError::Part { part: src.into(), msg })?;
top.extend(el.elements().cloned());
} else {
top.push(c.clone());
@@ -116,6 +100,68 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u
Ok(Imported { document, warnings })
}
+/// Most entries an IDML package may hold.
+const MAX_ENTRIES: usize = 100_000;
+/// Most bytes one package part may expand to.
+const MAX_PART_BYTES: u64 = 512 << 20;
+/// Most bytes all the parts read from one package may expand to together.
+const MAX_TOTAL_BYTES: u64 = 2 << 30;
+
+/// An IDML package whose parts are decompressed only when the import asks for them, within
+/// byte budgets that don't trust the sizes the archive claims.
+struct Package<'a> {
+ zip: zip::ZipArchive<std::io::Cursor<&'a [u8]>>,
+ /// Normalised part name → entry name, first entry wins (zip order, so the choice is stable).
+ lenient: HashMap<String, String>,
+ /// Bytes the parts still to be read may expand to.
+ left: u64,
+}
+
+impl<'a> Package<'a> {
+ fn open(bytes: &'a [u8]) -> Result<Self> {
+ let zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
+ if zip.len() > MAX_ENTRIES {
+ return Err(IdmlError::NotIdml(format!("{} entries (at most {MAX_ENTRIES})", zip.len())));
+ }
+ let mut lenient: HashMap<String, String> = HashMap::new();
+ for i in 0..zip.len() {
+ let Some(name) = zip.name_for_index(i) else { continue };
+ if name.ends_with('/') {
+ continue;
+ }
+ lenient.entry(normalize_part_name(name)).or_insert_with(|| name.to_string());
+ }
+ Ok(Package { zip, lenient, left: MAX_TOTAL_BYTES })
+ }
+
+ /// The bytes of part `name` (matched exactly, then leniently), or `None` if the package has
+ /// no such part.
+ fn part(&mut self, name: &str) -> Result<Option<Vec<u8>>> {
+ let exact = self.zip.index_for_name(name).filter(|_| !name.ends_with('/'));
+ let Some(i) = exact.or_else(|| self.lenient.get(&normalize_part_name(name)).and_then(|n| self.zip.index_for_name(n))) else {
+ return Ok(None);
+ };
+ let f = self.zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
+ let part = f.name().to_string();
+ let limit = MAX_PART_BYTES.min(self.left);
+ let too_big = || IdmlError::Part {
+ part: part.clone(),
+ msg: format!("larger than the {MAX_PART_BYTES}-byte part limit (or the package is larger than {MAX_TOTAL_BYTES} bytes)"),
+ };
+ if f.size() > limit {
+ return Err(too_big());
+ }
+ let mut buf = Vec::new();
+ f.take(limit.saturating_add(1)).read_to_end(&mut buf).map_err(|e| IdmlError::Part { part: part.clone(), msg: e.to_string() })?;
+ let n = buf.len() as u64;
+ if n > limit {
+ return Err(too_big());
+ }
+ self.left = self.left.saturating_sub(n);
+ Ok(Some(buf))
+ }
+}
+
/// A package part name in the form the lookup compares: InDesign and other IDML writers differ
/// in percent-encoding, case, path separators and a leading `./` or `/`.
fn normalize_part_name(name: &str) -> String {
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 57801e34f..4cc273ca1 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -2169,3 +2169,89 @@ fn frame_preference_property_color_resolves_for_frames_and_object_styles() {
assert_eq!(colors, vec!["Near", "Near", "Far", designcraft_color::swatch::NONE]);
assert_eq!(d.styles.object_style("Child").unwrap().text_frame.as_ref().unwrap().column_rule_color, "Near");
}
+
+/// A package entry nothing in `designmap.xml` refers to is never decompressed: a damaged one
+/// (its checksum no longer matches) does not stop the import.
+#[test]
+fn unreferenced_entries_are_not_read() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for (n, c) in [
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", STORY),
+ ] {
+ w.start_file(n, SimpleFileOptions::default()).unwrap();
+ w.write_all(c.as_bytes()).unwrap();
+ }
+ w.start_file("junk/irrelevant.bin", stored).unwrap();
+ w.write_all(b"<<payload-of-an-unused-entry>>").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ let at = bytes.windows(9).position(|w| w == b"<<payload").unwrap();
+ bytes[at] = b'X';
+ let d = import_idml(&bytes).unwrap();
+ assert_eq!(d.spreads.len(), 1);
+}
+
+/// A part that expands past the 512 MiB limit while claiming to hold one byte is refused once the
+/// limit is reached, with an error that says so, instead of being read whole into memory.
+#[test]
+fn oversized_part_is_refused() {
+ use zip::write::SimpleFileOptions;
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Story src="Stories/Story_big.xml"/>
+ </Document>"#;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ w.start_file("mimetype", SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ w.start_file("designmap.xml", SimpleFileOptions::default()).unwrap();
+ w.write_all(designmap.as_bytes()).unwrap();
+ w.start_file("Stories/Story_big.xml", SimpleFileOptions::default()).unwrap();
+ let chunk = vec![b' '; 1 << 20];
+ for _ in 0..512 {
+ w.write_all(&chunk).unwrap();
+ }
+ w.write_all(b" ").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ assert!(bytes.len() < 8 << 20, "{}", bytes.len());
+ // Claim one byte in the local header and the central directory record (no ZIP64 fields or
+ // data descriptors here), so only the bytes actually decompressed can show the part is too big.
+ let mut patched = 0;
+ for i in 0..bytes.len().saturating_sub(46) {
+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {
+ b"PK\x03\x04" => (22, 26, 30),
+ b"PK\x01\x02" => (24, 28, 46),
+ _ => continue,
+ };
+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;
+ if bytes.get(i + name_at..i + name_at + len) == Some(b"Stories/Story_big.xml".as_slice()) {
+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&1u32.to_le_bytes());
+ patched += 1;
+ }
+ }
+ assert_eq!(patched, 2);
+ let Err(err) = import_idml(&bytes) else { panic!("an oversized part imported") };
+ assert!(err.to_string().contains("limit"), "{err}");
+}
+
+/// A package with more entries than any document needs is refused before any is read.
+#[test]
+fn too_many_entries_are_refused() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for i in 0..100_000 {
+ w.start_file(format!("junk/{i}"), stored).unwrap();
+ }
+ let Err(err) = import_idml(&w.finish().unwrap().into_inner()) else { panic!("a package with 100 001 entries imported") };
+ assert!(err.to_string().contains("entries"), "{err}");
+}