mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
fix(opc): keep legacy leading-slash part names readable under zip hardening
OPC part names are a virtual namespace that is never joined to a filesystem path, so a legacy writer's `/docProps/core.xml` must stay a readable part even though craft-zip's named APIs now refuse leading separators. craft-zip gains an explicit index-based virtual-name API (`virtual_entry_name`, `virtual_entry_size`, `read_virtual_index`): leading `/` and `\` are stripped, while `..`, drive prefixes, NUL and empty names are still refused. The named APIs (`names`, `entry_name`, `read`, ...) are unchanged. Both the eager `Package` and the lazy `LazyPackage` readers, and `declared_oversized`, enumerate and read through it. The `backslash_zip_entry_names_are_found` case regains its `/docProps/core.xml` entry (patched into the headers, since the writer refuses it) and asserts it in both readers; new tests assert traversal and drive-prefix entries are not parts in either reader, and that the virtual API does not open the named one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fd5267b498
commit
be002ddcde
4 files changed
+132
-18
No files matched your search
+31
-15
@@ -25,6 +25,20 @@ fn open_zip<'a>(bytes: &'a [u8], limits: &Limits, max_total: u64) -> Result<Zip<
|
||||
Ok(zip)
|
||||
}
|
||||
|
||||
/// Every entry that can be a part, as (index, name). Part names are a virtual namespace, never
|
||||
/// joined to a filesystem path, so a legacy writer's leading `/` is no hazard and its part stays
|
||||
/// readable; names with traversal components (`..`, a drive prefix, a NUL) are left out
|
||||
/// ([`craft_zip::Archive::virtual_entry_name`]).
|
||||
fn entries(zip: &mut Zip<'_>) -> Result<Vec<(usize, String)>, Error> {
|
||||
let mut out = Vec::new();
|
||||
for index in 0..zip.len() {
|
||||
if let Some(name) = zip.virtual_entry_name(index).map_err(crate::zip_error)? {
|
||||
out.push((index, name));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A part name as stored: `\` as `/` (code that splits paths on `/` must not meet a `\`), no
|
||||
/// leading `/`.
|
||||
fn stored_name(name: &str) -> String {
|
||||
@@ -59,8 +73,8 @@ impl Package {
|
||||
let mut files = BTreeMap::new();
|
||||
let mut skipped = Vec::new();
|
||||
let (mut total, mut work) = (0u64, 0u64);
|
||||
let entries: Vec<String> = zip.names().map(|n| n.into_owned()).collect();
|
||||
for (i, entry) in entries.iter().enumerate() {
|
||||
let entries = entries(&mut zip)?;
|
||||
for (i, (index, entry)) in entries.iter().enumerate() {
|
||||
if skip && work >= limits.max_work {
|
||||
log::warn!("opc: decompression budget spent; skipping the remaining {} entries", entries.len().saturating_sub(i));
|
||||
break;
|
||||
@@ -69,7 +83,7 @@ impl Package {
|
||||
continue;
|
||||
}
|
||||
let name = stored_name(entry);
|
||||
let size = zip.declared_size(entry).unwrap_or(0);
|
||||
let size = zip.virtual_entry_size(*index).ok().flatten().unwrap_or(0);
|
||||
if size > limits.max_part {
|
||||
if skip {
|
||||
log::warn!("opc: skipping oversized part {name} ({size} bytes)");
|
||||
@@ -87,7 +101,7 @@ impl Package {
|
||||
}
|
||||
return Err(Error::PackageTooLarge { limit: limits.max_total.min(limits.max_work) });
|
||||
}
|
||||
match zip.read(entry, room) {
|
||||
match zip.read_virtual_index(*index, room) {
|
||||
Ok(Some(buf)) => {
|
||||
work = work.saturating_add(buf.len() as u64);
|
||||
total = total.saturating_add(buf.len() as u64);
|
||||
@@ -207,8 +221,8 @@ impl Package {
|
||||
/// reader that needs a few parts of a large file, or one part at a time.
|
||||
pub struct LazyPackage<'a> {
|
||||
zip: Zip<'a>,
|
||||
/// Normalized part name → entry name (the first entry of a name).
|
||||
names: HashMap<String, String>,
|
||||
/// Normalized part name → entry index and name (the first entry of a name).
|
||||
names: HashMap<String, (usize, String)>,
|
||||
total: u64,
|
||||
limits: Limits,
|
||||
}
|
||||
@@ -218,10 +232,10 @@ impl<'a> LazyPackage<'a> {
|
||||
/// [`Limits::oversized`] are not used.
|
||||
pub fn open(bytes: &'a [u8], limits: &Limits) -> Result<LazyPackage<'a>, Error> {
|
||||
// This reader keeps its own count, which a failed read spends (see `read_limited`).
|
||||
let zip = open_zip(bytes, limits, u64::MAX)?;
|
||||
let mut zip = open_zip(bytes, limits, u64::MAX)?;
|
||||
let mut names = HashMap::new();
|
||||
for n in zip.names() {
|
||||
names.entry(normalize(&n)).or_insert_with(|| n.into_owned());
|
||||
for (index, n) in entries(&mut zip)? {
|
||||
names.entry(normalize(&n)).or_insert((index, n));
|
||||
}
|
||||
Ok(LazyPackage { zip, names, total: 0, limits: *limits })
|
||||
}
|
||||
@@ -240,7 +254,7 @@ impl<'a> LazyPackage<'a> {
|
||||
/// The stored spelling of part `name` (leading `/` ignored; case-insensitive), as
|
||||
/// [`Package::canonical`] gives it: for a writer that keeps the package's part names.
|
||||
pub fn canonical(&self, name: &str) -> Option<String> {
|
||||
self.names.get(&normalize(name)).map(|n| n.trim_start_matches('/').replace('\\', "/"))
|
||||
self.names.get(&normalize(name)).map(|(_, n)| n.trim_start_matches('/').replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// Bytes charged to [`Limits::max_total`] so far. It is the whole of it once a read has
|
||||
@@ -275,10 +289,10 @@ impl<'a> LazyPackage<'a> {
|
||||
/// pay it again and again. Every later read is then a cheap error.
|
||||
pub fn read_limited(&mut self, part: &str, maximum: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
let maximum = maximum.min(self.limits.max_part);
|
||||
let Some(entry) = self.names.get(&normalize(part)) else {
|
||||
let Some(&(index, _)) = self.names.get(&normalize(part)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let size = self.zip.declared_size(entry).unwrap_or(0);
|
||||
let size = self.zip.virtual_entry_size(index).ok().flatten().unwrap_or(0);
|
||||
if size > maximum {
|
||||
return Err(Error::PartTooLarge { part: part.to_string(), limit: maximum });
|
||||
}
|
||||
@@ -287,7 +301,7 @@ impl<'a> LazyPackage<'a> {
|
||||
self.total = self.limits.max_total;
|
||||
return Err(Error::PackageTooLarge { limit: self.limits.max_total });
|
||||
}
|
||||
match self.zip.read(entry, maximum.min(remaining)) {
|
||||
match self.zip.read_virtual_index(index, maximum.min(remaining)) {
|
||||
Ok(Some(out)) => {
|
||||
self.total = self.total.saturating_add(out.len() as u64);
|
||||
Ok(Some(out))
|
||||
@@ -321,8 +335,10 @@ impl<'a> LazyPackage<'a> {
|
||||
/// the user which part made a package too large.
|
||||
pub fn declared_oversized(bytes: &[u8], limits: &Limits) -> Option<(String, u64)> {
|
||||
let mut zip = open_zip(bytes, limits, u64::MAX).ok()?;
|
||||
let names: Vec<String> = zip.names().map(|n| n.into_owned()).collect();
|
||||
names.into_iter().find_map(|n| zip.declared_size(&n).filter(|size| *size > limits.max_part).map(|size| (n, size)))
|
||||
entries(&mut zip)
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.find_map(|(index, n)| zip.virtual_entry_size(index).ok().flatten().filter(|size| *size > limits.max_part).map(|size| (n, size)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -182,10 +182,24 @@ fn skipped_parts_count_against_the_inflate_budget() {
|
||||
assert_eq!(Package::open(&z, &refuse).err(), Some(Error::PackageTooLarge { limit: 100 }));
|
||||
}
|
||||
|
||||
/// Renames every entry spelled `from` to `to`, a name of the same length, in its local and
|
||||
/// central headers: for names the writer refuses to store.
|
||||
fn rename_entries(z: &mut [u8], from: &[u8], to: &[u8]) {
|
||||
assert_eq!(from.len(), to.len());
|
||||
let found: Vec<usize> = z.windows(from.len()).enumerate().filter(|(_, w)| *w == from).map(|(i, _)| i).collect();
|
||||
assert_eq!(found.len(), 2, "one local and one central header");
|
||||
for at in found {
|
||||
z[at..at + to.len()].copy_from_slice(to);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backslash_zip_entry_names_are_found() {
|
||||
let z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"<a/>".to_vec()), ("docProps/core.xml", b"<b/>".to_vec())]);
|
||||
// A legacy writer's leading `/` stays a readable part: part names are never filesystem paths.
|
||||
let mut z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"<a/>".to_vec()), ("xdocProps/core.xml", b"<b/>".to_vec())]);
|
||||
rename_entries(&mut z, b"xdocProps/core.xml", b"/docProps/core.xml");
|
||||
let p = Package::open(&z, &LIMITS).unwrap();
|
||||
assert_eq!(p.get("docProps/core.xml"), Some(&b"<b/>"[..]));
|
||||
assert!(p.get("ppt/slides/slide1.xml").is_some());
|
||||
assert_eq!(p.canonical("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml"));
|
||||
assert_eq!(p.canonical("docprops/core.xml"), Some("docProps/core.xml"));
|
||||
@@ -195,6 +209,20 @@ fn backslash_zip_entry_names_are_found() {
|
||||
assert_eq!(lazy.canonical("/DOCPROPS/core.xml").as_deref(), Some("docProps/core.xml"));
|
||||
assert_eq!(lazy.canonical("nothing"), None);
|
||||
assert_eq!(lazy.read("PPT/slides/slide1.xml").unwrap().as_deref(), Some(&b"<a/>"[..]));
|
||||
assert_eq!(lazy.read("docProps/core.xml").unwrap().as_deref(), Some(&b"<b/>"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_zip_entry_names_are_not_parts() {
|
||||
let mut z = zip_of(&[("a.xml", b"<a/>".to_vec()), ("xx/evil.xml", b"<e/>".to_vec()), ("C_/evil2.xml", b"<f/>".to_vec())]);
|
||||
rename_entries(&mut z, b"xx/evil.xml", b"../evil.xml");
|
||||
rename_entries(&mut z, b"C_/evil2.xml", b"C:/evil2.xml");
|
||||
let p = Package::open(&z, &LIMITS).unwrap();
|
||||
assert_eq!(p.names().collect::<Vec<_>>(), ["a.xml"]);
|
||||
let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap();
|
||||
assert_eq!(lazy.names(), ["a.xml"]);
|
||||
assert_eq!(lazy.read("../evil.xml").unwrap(), None);
|
||||
assert_eq!(lazy.read("evil.xml").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::borrow::Cow;
|
||||
use std::io::{Cursor, Read};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::entry::{has_traversal_component, has_traversal_component_bytes};
|
||||
use crate::entry::{has_traversal_component, has_traversal_component_bytes, sanitize_path};
|
||||
use crate::preflight::{ReadError, read_entry};
|
||||
use crate::{Budget, Error, check_entry_count};
|
||||
|
||||
@@ -117,6 +117,34 @@ impl<'a> Archive<'a> {
|
||||
Ok(Some(name.into_owned()))
|
||||
}
|
||||
|
||||
/// The name at `index` in a virtual namespace, for a format whose entry names are never
|
||||
/// joined to a filesystem path (OPC part names, for one): leading `/` and `\` removed, so a
|
||||
/// legacy writer's `/docProps/core.xml` is `docProps/core.xml`. Names that still contain
|
||||
/// traversal components (`..`, a drive prefix, a NUL) after that, and names that are not
|
||||
/// UTF-8, return `None`. A caller that extracts entries to disk uses [`Self::entry_name`].
|
||||
pub fn virtual_entry_name(&mut self, index: usize) -> Result<Option<String>, Error> {
|
||||
if index >= self.zip.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?;
|
||||
let raw = file.name_raw();
|
||||
let start = raw.iter().position(|b| *b != b'/' && *b != b'\\').unwrap_or(raw.len());
|
||||
if raw[start..].is_empty() || has_traversal_component_bytes(&raw[start..]) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(name) = file.name() else { return Ok(None) };
|
||||
Ok(sanitize_path(&name).map(str::to_string))
|
||||
}
|
||||
|
||||
/// The size the entry at `index` declares, when it has a [`Self::virtual_entry_name`].
|
||||
pub fn virtual_entry_size(&mut self, index: usize) -> Result<Option<u64>, Error> {
|
||||
if self.virtual_entry_name(index)?.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?;
|
||||
Ok(Some(file.size()))
|
||||
}
|
||||
|
||||
/// Whether the entry at `index` is a directory according to ZIP filename conventions.
|
||||
pub fn entry_is_dir(&mut self, index: usize) -> Result<Option<bool>, Error> {
|
||||
if index >= self.zip.len() {
|
||||
@@ -264,15 +292,29 @@ impl<'a> Archive<'a> {
|
||||
self.read_index_named(index, &name, max)
|
||||
}
|
||||
|
||||
/// Read the entry at `index` under the same size, checksum and budget rules as [`Self::read`],
|
||||
/// when it has a [`Self::virtual_entry_name`]; `None` otherwise.
|
||||
pub fn read_virtual_index(&mut self, index: usize, max: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
let Some(name) = self.virtual_entry_name(index)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.read_at(index, &name, max).map(Some)
|
||||
}
|
||||
|
||||
fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
if has_traversal_component(name) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.read_at(index, name, max).map(Some)
|
||||
}
|
||||
|
||||
/// The entry at `index`, whose name the caller has already checked; `name` is for errors.
|
||||
fn read_at(&mut self, index: usize, name: &str, max: u64) -> Result<Vec<u8>, Error> {
|
||||
let entry = |msg: String| Error::Entry { name: name.to_string(), msg };
|
||||
let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?;
|
||||
let declared = f.size();
|
||||
match read_entry(f, declared, max, &mut self.budget) {
|
||||
Ok(data) => Ok(Some(data)),
|
||||
Ok(data) => Ok(data),
|
||||
Err(ReadError::DeclaredTooLarge { limit, .. }) | Err(ReadError::Overrun { limit }) => {
|
||||
Err(Error::EntryTooLarge { name: name.to_string(), limit })
|
||||
}
|
||||
|
||||
@@ -340,3 +340,31 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() {
|
||||
assert_eq!(seekable.entry_sizes(0).unwrap(), None);
|
||||
assert_eq!(seekable.read_index(0, 10).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_names_strip_a_leading_separator_and_still_refuse_traversal() {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
for (name, data) in [("/docProps/core.xml", &b"core"[..]), ("../evil.xml", b"evil"), ("C:/drive.xml", b"drive"), ("/", b"")] {
|
||||
zip.start_file(name, opts).unwrap();
|
||||
zip.write_all(data).unwrap();
|
||||
}
|
||||
let bytes = zip.finish().unwrap().into_inner();
|
||||
let mut archive = Archive::open(&bytes, ROOMY).unwrap();
|
||||
|
||||
// The named API stays closed to a leading separator; the virtual one reads it without it.
|
||||
assert_eq!(archive.entry_name(0).unwrap(), None);
|
||||
assert_eq!(archive.read("/docProps/core.xml", 100).unwrap(), None);
|
||||
assert_eq!(archive.virtual_entry_name(0).unwrap().as_deref(), Some("docProps/core.xml"));
|
||||
assert_eq!(archive.virtual_entry_size(0).unwrap(), Some(4));
|
||||
assert_eq!(archive.read_virtual_index(0, 100).unwrap().as_deref(), Some(&b"core"[..]));
|
||||
|
||||
// Traversal, drive prefixes and an empty name stay unreadable either way.
|
||||
for index in 1..archive.len() {
|
||||
assert_eq!(archive.virtual_entry_name(index).unwrap(), None, "entry {index}");
|
||||
assert_eq!(archive.virtual_entry_size(index).unwrap(), None, "entry {index}");
|
||||
assert_eq!(archive.read_virtual_index(index, 100).unwrap(), None, "entry {index}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user