From 8c5c90ebaca005f081cf97a7e5add55d18bcbb78 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 20:58:55 +0530 Subject: [PATCH] craft-zip: reject zip-slip path traversal vectors during entry enumeration --- crates/zip/src/archive.rs | 75 +++++++++++++++++-- crates/zip/src/entry.rs | 140 ++++++++++++++++++++++++++++++++++++ crates/zip/src/lib.rs | 2 + crates/zip/src/seekable.rs | 116 ++++++++++++++++++++++++++++-- crates/zip/src/write.rs | 9 +++ crates/zip/tests/archive.rs | 100 +++++++++++++++++++++++++- 6 files changed, 428 insertions(+), 14 deletions(-) create mode 100644 crates/zip/src/entry.rs diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 0f26267c12..2bfaa08085 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -4,6 +4,7 @@ use std::borrow::Cow; use std::io::{Cursor, Read}; use std::sync::Arc; +use crate::entry::has_traversal_component; use crate::preflight::{ReadError, read_entry}; use crate::{Budget, Error, check_entry_count}; @@ -89,8 +90,22 @@ impl<'a> Archive<'a> { } /// The name at `index`, copied on demand so callers can process hostile directories without - /// retaining a second copy of every potentially large name. + /// retaining a second copy of every potentially large name. Names containing path-traversal + /// components (`..`, absolute paths, Windows drive prefixes, null bytes) return `None`. pub fn entry_name(&mut self, index: usize) -> Result, 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 name = file.name().map_err(|error| Error::NotZip(error.to_string()))?; + if has_traversal_component(&name) { + return Ok(None); + } + Ok(Some(name.into_owned())) + } + + /// The name at `index`, copied on demand without path validation. + pub fn raw_entry_name(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { return Ok(None); } @@ -105,6 +120,11 @@ impl<'a> Archive<'a> { return Ok(None); } let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + if let Ok(name) = file.name() + && has_traversal_component(&name) + { + return Ok(None); + } Ok(Some(file.is_dir())) } @@ -114,6 +134,11 @@ impl<'a> Archive<'a> { return Ok(None); } let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + if let Ok(name) = file.name() + && has_traversal_component(&name) + { + return Ok(None); + } Ok(Some(file.unix_mode().is_some_and(|mode| mode & 0o170000 == 0o120000))) } @@ -123,6 +148,11 @@ impl<'a> Archive<'a> { return Ok(None); } let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + if let Ok(name) = file.name() + && has_traversal_component(&name) + { + return Ok(None); + } Ok(Some((file.size(), file.compressed_size()))) } @@ -132,25 +162,38 @@ impl<'a> Archive<'a> { self.duplicates } + /// Whether any entry in the archive contains path-traversal components (`..`, absolute paths, + /// Windows drive prefixes, null bytes). + pub fn has_traversal_component(&self) -> bool { + self.zip.file_names().any(|r| r.is_ok_and(|name| has_traversal_component(&name))) + } + /// Do two entries' compressed data ranges overlap? A format that stores many files in one /// archive can refuse aliases so one payload cannot be expanded and retained repeatedly. pub fn has_overlapping_files(&mut self) -> Result { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. A name that is not text is - /// left out. + /// The entry names in the archive's order, folders included. Names that are not text or + /// that contain path-traversal components are left out. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok) + self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) } - /// Is there an entry `name` (exactly as stored)? + /// Is there an entry `name` (exactly as stored)? Paths containing traversal components + /// return `false`. pub fn contains(&self, name: &str) -> bool { + if has_traversal_component(name) { + return false; + } self.zip.index_for_name(name).is_some() } /// The size entry `name` declares. It is a claim, not a measurement. pub fn declared_size(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.size()) } @@ -158,6 +201,9 @@ impl<'a> Archive<'a> { /// The size entry `name` takes in the archive, compressed. With [`Archive::declared_size`] it /// gives the compression ratio the entry claims. pub fn compressed_size(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.compressed_size()) } @@ -165,6 +211,9 @@ impl<'a> Archive<'a> { /// Is `name` stored without compression? The answer lets a format with in-memory source bytes /// apply an output-size cap to compressed entries while bounding stored reads by source size. pub fn is_stored(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.compression() == zip::CompressionMethod::Stored) } @@ -175,6 +224,9 @@ impl<'a> Archive<'a> { /// /// The entry's checksum is not checked: it covers the whole entry. pub fn read_head(&mut self, name: &str, n: usize) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; 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()))?; @@ -195,21 +247,30 @@ impl<'a> Archive<'a> { /// [`Limits::max_total_bytes`]. An entry that expands past the size it declares is refused. /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; self.read_index_named(index, name, max) } /// Read the entry at `index` under the same size, checksum and aggregate budget - /// rules as [`Self::read`], without repeating a decoded-name lookup. + /// rules as [`Self::read`], without repeating a decoded-name lookup. Entries containing + /// path-traversal components return `None`. pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { if index >= self.zip.len() { return Ok(None); } - let name = self.entry_name(index)?.unwrap_or_default(); + let Some(name) = self.entry_name(index)? else { + return Ok(None); + }; self.read_index_named(index, &name, max) } fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } 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(); diff --git a/crates/zip/src/entry.rs b/crates/zip/src/entry.rs new file mode 100644 index 0000000000..33be92d80e --- /dev/null +++ b/crates/zip/src/entry.rs @@ -0,0 +1,140 @@ +//! Validation and sanitization of ZIP archive entry paths. +//! +//! Rejects zip-slip path traversal vectors: +//! - Parent traversal components (`..`) +//! - Leading directory separators (`/` or `\`), indicating absolute paths +//! - Windows drive prefixes (`C:`, `D:`, etc.) at the start or within components +//! - Null bytes (`\0`) +//! +//! Checks slice tokens directly without allocating memory. + +/// Whether `path` contains any path-traversal components or zip-slip vectors. +/// +/// Rejects: +/// - Parent directory traversal (`..`) in any path segment +/// - Null bytes (`\0`) +/// - Leading separators (`/` or `\`) +/// - Windows drive letters (`C:`, etc.) at the start or in any component +/// +/// This check inspects slice tokens directly without allocating heap memory. +pub fn has_traversal_component(path: &str) -> bool { + has_traversal_component_bytes(path.as_bytes()) +} + +/// Byte-level check for path-traversal components without allocating heap memory. +pub fn has_traversal_component_bytes(bytes: &[u8]) -> bool { + if bytes.is_empty() { + return false; + } + if bytes.contains(&0) { + return true; + } + // Reject leading separators: '/' or '\' + if bytes.starts_with(b"/") || bytes.starts_with(b"\\") { + return true; + } + // Tokenize by '/' and '\' directly on byte slices + let mut rest = bytes; + while !rest.is_empty() { + let pos = rest.iter().position(|&b| b == b'/' || b == b'\\').unwrap_or(rest.len()); + let token = &rest[..pos]; + + // Parent traversal component + if token == b".." { + return true; + } + + // Windows drive prefix: e.g. "C:" or "C:test.txt" or in any component + if token.len() >= 2 && token[0].is_ascii_alphabetic() && token[1] == b':' { + return true; + } + + if pos == rest.len() { + break; + } + rest = &rest[pos + 1..]; + } + false +} + +/// Sanitize and validate an entry path, rejecting any zip-slip traversal vectors. +/// +/// Returns `None` if `path` is empty or contains parent traversal components (`..`), +/// null bytes, leading separators (`/` or `\`), or Windows drive prefixes (`C:`). +/// Returns `Some(path)` if the path is safe. +pub fn sanitize_path(path: &str) -> Option<&str> { + if path.is_empty() || has_traversal_component(path) { None } else { Some(path) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_parent_traversal() { + assert!(has_traversal_component("..")); + assert!(has_traversal_component("../")); + assert!(has_traversal_component("..\\")); + assert!(has_traversal_component("../../etc/passwd")); + assert!(has_traversal_component(r"..\..\windows\system32")); + assert!(has_traversal_component("foo/../bar")); + assert!(has_traversal_component(r"foo\..\bar")); + assert!(has_traversal_component("foo/bar/..")); + assert!(has_traversal_component("foo/bar/../")); + assert!(has_traversal_component("a/b/../../c")); + } + + #[test] + fn detects_absolute_and_leading_separators() { + assert!(has_traversal_component("/etc/passwd")); + assert!(has_traversal_component(r"\windows\system32")); + assert!(has_traversal_component("//server/share")); + assert!(has_traversal_component(r"\\server\share")); + assert!(has_traversal_component("/")); + assert!(has_traversal_component("\\")); + } + + #[test] + fn detects_windows_drive_letters() { + assert!(has_traversal_component("C:/test.txt")); + assert!(has_traversal_component(r"C:\test.txt")); + assert!(has_traversal_component("c:/test.txt")); + assert!(has_traversal_component(r"c:\windows\system32")); + assert!(has_traversal_component("D:test.txt")); + assert!(has_traversal_component("foo/C:/bar")); + assert!(has_traversal_component(r"foo\D:\bar")); + } + + #[test] + fn detects_null_bytes() { + assert!(has_traversal_component("foo\0bar")); + assert!(has_traversal_component("\0")); + assert!(has_traversal_component_bytes(b"foo/bar\x00baz")); + } + + #[test] + fn accepts_safe_relative_paths() { + assert!(!has_traversal_component("mimetype")); + assert!(!has_traversal_component("dir/file.txt")); + assert!(!has_traversal_component(r"dir\file.txt")); + assert!(!has_traversal_component("dir/")); + assert!(!has_traversal_component("a/b/c/d.bin")); + assert!(!has_traversal_component(".")); + assert!(!has_traversal_component("./file.txt")); + assert!(!has_traversal_component("foo..bar")); + assert!(!has_traversal_component("..foo")); + assert!(!has_traversal_component("foo..")); + assert!(!has_traversal_component("")); + } + + #[test] + fn sanitize_path_validation() { + assert_eq!(sanitize_path("../../etc/passwd"), None); + assert_eq!(sanitize_path(r"..\..\windows\system32"), None); + assert_eq!(sanitize_path("C:/test.txt"), None); + assert_eq!(sanitize_path("/etc/shadow"), None); + assert_eq!(sanitize_path(""), None); + assert_eq!(sanitize_path("safe/path.txt"), Some("safe/path.txt")); + assert_eq!(sanitize_path("mimetype"), Some("mimetype")); + } +} diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index e8f8764dea..b5bd083be4 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -25,6 +25,7 @@ struct ReadmeExamples; mod archive; +pub mod entry; mod guard; #[cfg(feature = "lenient")] pub mod lenient; @@ -34,6 +35,7 @@ mod seekable; mod write; pub use archive::{Archive, Limits}; +pub use entry::{has_traversal_component, has_traversal_component_bytes, sanitize_path}; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; pub use guard::{check_entry_count, check_entry_count_seekable}; diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index 354177d9d5..a38bbf72c0 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -4,6 +4,7 @@ use std::borrow::Cow; use std::collections::HashMap; use std::io::{self, Read, Seek, SeekFrom}; +use crate::entry::has_traversal_component; use crate::{Budget, Error, MetadataReader, check_entry_count_seekable}; /// Why an indexed seekable archive exceeded its caller's limits. @@ -158,14 +159,34 @@ impl SeekableArchive { self.duplicate_names.iter().map(String::as_str) } + /// Whether any entry in the archive contains path-traversal components (`..`, absolute paths, + /// Windows drive prefixes, null bytes). + pub fn has_traversal_component(&self) -> bool { + self.zip.file_names().any(|r| r.is_ok_and(|name| has_traversal_component(&name))) + } + /// Locate a surviving entry by the absolute offset of its central directory record, /// without decoding its name or reading the local entry header. pub fn index_for_central_record(&self, offset: u64) -> Option { (0..self.zip.len()).find(|&i| self.zip.by_index_data(i).is_ok_and(|e| e.central_header_start() == offset)) } - /// The name at `index`, copied on demand. + /// The name at `index`, copied on demand. Names containing path-traversal components (`..`, + /// absolute paths, Windows drive prefixes, null bytes) return `None`. pub fn entry_name(&mut self, index: usize) -> Result, 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 name = file.name().map_err(|error| Error::NotZip(error.to_string()))?; + if has_traversal_component(&name) { + return Ok(None); + } + Ok(Some(name.into_owned())) + } + + /// The name at `index`, copied on demand without path validation. + pub fn raw_entry_name(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { return Ok(None); } @@ -180,6 +201,11 @@ impl SeekableArchive { return Ok(None); } let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + if let Ok(name) = file.name() + && has_traversal_component(&name) + { + return Ok(None); + } Ok(Some(file.is_dir())) } @@ -189,6 +215,11 @@ impl SeekableArchive { return Ok(None); } let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + if let Ok(name) = file.name() + && has_traversal_component(&name) + { + return Ok(None); + } Ok(Some((file.size(), file.compressed_size()))) } @@ -197,30 +228,44 @@ impl SeekableArchive { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted. + /// The entry names in the archive's order, folders included. Non-UTF-8 names and names + /// containing path-traversal components are omitted. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok) + self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) } - /// Is there an entry `name` (exactly as stored)? + /// Is there an entry `name` (exactly as stored)? Paths containing traversal components + /// return `false`. pub fn contains(&self, name: &str) -> bool { + if has_traversal_component(name) { + return false; + } self.zip.index_for_name(name).is_some() } /// The size entry `name` declares. It is a claim, not a measurement. pub fn declared_size(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.size()) } /// The size entry `name` takes in the archive, compressed. pub fn compressed_size(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.compressed_size()) } /// Is `name` stored without compression? pub fn is_stored(&mut self, name: &str) -> Option { + if has_traversal_component(name) { + return None; + } let index = self.zip.index_for_name(name)?; self.zip.by_index_raw(index).ok().map(|f| f.compression() == zip::CompressionMethod::Stored) } @@ -231,6 +276,9 @@ impl SeekableArchive { /// [`SeekableLimits::max_total_bytes`]. The returned [`EntryReader`] enforces the size cap and /// verifies the CRC-32 on EOF, charging [`Self::budget`] only when the full entry is read. pub fn open_entry(&mut self, name: &str, max: u64) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; self.open_entry_index_named(index, name, max) } @@ -240,11 +288,16 @@ impl SeekableArchive { if index >= self.zip.len() { return Ok(None); } - let name = self.entry_name(index)?.unwrap_or_default(); + let Some(name) = self.entry_name(index)? else { + return Ok(None); + }; self.open_entry_index_named(index, &name, max) } fn open_entry_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } let file = self.zip.by_index(index).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?; let declared = file.size(); if declared > max { @@ -258,6 +311,9 @@ impl SeekableArchive { /// Read all bytes of entry `name` into memory, or `None` when there is no such entry. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { + if has_traversal_component(name) { + return Ok(None); + } let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; self.read_index_named(index, name, max) } @@ -267,7 +323,9 @@ impl SeekableArchive { if index >= self.zip.len() { return Ok(None); } - let name = self.entry_name(index)?.unwrap_or_default(); + let Some(name) = self.entry_name(index)? else { + return Ok(None); + }; self.read_index_named(index, &name, max) } @@ -475,4 +533,50 @@ mod tests { assert!(archive.has_duplicate_names_matching(|n| n == "notes.txt")); assert_eq!(archive.read("Cat.lrcat", 100).unwrap().as_deref(), Some(b"catalog".as_slice())); } + + #[test] + fn seekable_archive_rejects_path_traversal_components() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + writer.start_file("../../etc/passwd", options).unwrap(); + writer.write_all(b"hostile").unwrap(); + writer.start_file(r"..\..\windows\system32", options).unwrap(); + writer.write_all(b"hostile").unwrap(); + writer.start_file("C:/test.txt", options).unwrap(); + writer.write_all(b"hostile").unwrap(); + writer.start_file("valid.txt", options).unwrap(); + writer.write_all(b"valid content").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + let limits = SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 4096 }; + let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap(); + assert!(archive.has_traversal_component()); + + // Names iterator filters out traversal vectors + let names = archive.names().collect::>(); + assert_eq!(names, vec!["valid.txt"]); + + // Virtual lookups reject traversal + assert!(!archive.contains("../../etc/passwd")); + assert!(!archive.contains(r"..\..\windows\system32")); + assert!(!archive.contains("C:/test.txt")); + assert!(archive.contains("valid.txt")); + assert_eq!(archive.declared_size("../../etc/passwd"), None); + assert_eq!(archive.compressed_size(r"..\..\windows\system32"), None); + assert_eq!(archive.is_stored("C:/test.txt"), None); + + // Entry reads reject traversal + assert!(archive.open_entry("../../etc/passwd", 100).unwrap().is_none()); + assert!(archive.open_entry(r"..\..\windows\system32", 100).unwrap().is_none()); + assert!(archive.open_entry("C:/test.txt", 100).unwrap().is_none()); + assert_eq!(archive.read("../../etc/passwd", 100).unwrap(), None); + assert_eq!(archive.read(r"..\..\windows\system32", 100).unwrap(), None); + assert_eq!(archive.read("C:/test.txt", 100).unwrap(), None); + assert_eq!(archive.read_index(0, 100).unwrap(), None); + assert_eq!(archive.read_index(1, 100).unwrap(), None); + assert_eq!(archive.read_index(2, 100).unwrap(), None); + + // Safe entry reads normally + assert_eq!(archive.read("valid.txt", 100).unwrap().as_deref(), Some(b"valid content".as_slice())); + } } diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 76bf753a62..1a1b7237ef 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -61,6 +61,9 @@ impl Writer { /// Adds a directory entry with the deterministic 1980 timestamp. pub fn add_directory(&mut self, name: &str) -> Result<(), Error> { + if crate::entry::has_traversal_component(name) { + return Err(Error::Write(format!("{name}: path traversal components are not permitted"))); + } let options = zip::write::SimpleFileOptions::default().last_modified_time(zip::DateTime::default()); self.zip.add_directory(name, options).map_err(|e| Error::Write(format!("{name}: {e}"))) } @@ -87,6 +90,9 @@ impl Writer { } fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16, large_file: bool) -> Result<(), Error> { + if crate::entry::has_traversal_component(name) { + return Err(Error::Write(format!("{name}: path traversal components are not permitted"))); + } let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), @@ -106,6 +112,9 @@ impl Writer { /// Adds an entry by streaming it into the compressor, so large generated entries need not /// first be buffered in memory. A name the archive already has is an error. pub fn add_with(&mut self, name: &str, compression: Compression, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<(), Error> { + if crate::entry::has_traversal_component(name) { + return Err(Error::Write(format!("{name}: path traversal components are not permitted"))); + } let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), diff --git a/crates/zip/tests/archive.rs b/crates/zip/tests/archive.rs index d3b135a9c2..481adaf370 100644 --- a/crates/zip/tests/archive.rs +++ b/crates/zip/tests/archive.rs @@ -1,7 +1,7 @@ //! Reading archives within limits, duplicate names, and the writer. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use craft_zip::{Archive, Compression, Error, Limits, Writer, check_entry_count, zip64_entry_count_sample}; +use craft_zip::{Archive, Compression, Error, Limits, Writer, check_entry_count, has_traversal_component, sanitize_path, zip64_entry_count_sample}; const ROOMY: Limits = Limits { max_entries: 1000, max_total_bytes: 1 << 20 }; @@ -205,3 +205,101 @@ fn owned_archive_applies_directory_guards() { assert!(Archive::open_owned(bytes, ROOMY).unwrap().has_duplicate_names()); assert!(Archive::open_owned(b"invalid".to_vec(), ROOMY).is_err()); } + +#[test] +fn path_traversal_detection_flags_hostile_vectors() { + // Parent directory traversal + assert!(has_traversal_component("../../etc/passwd")); + assert!(has_traversal_component(r"..\..\windows\system32")); + assert!(has_traversal_component("foo/../bar")); + assert!(has_traversal_component(r"foo\..\bar")); + assert!(has_traversal_component("..")); + + // Absolute and drive-letter prefixes + assert!(has_traversal_component("C:/test.txt")); + assert!(has_traversal_component(r"C:\test.txt")); + assert!(has_traversal_component("c:/test.txt")); + assert!(has_traversal_component(r"c:\windows\system32")); + assert!(has_traversal_component("/etc/passwd")); + assert!(has_traversal_component(r"\windows\system32")); + + // Null bytes + assert!(has_traversal_component("foo\0bar")); + + // Sanitization flags them safely + assert_eq!(sanitize_path("../../etc/passwd"), None); + assert_eq!(sanitize_path(r"..\..\windows\system32"), None); + assert_eq!(sanitize_path("C:/test.txt"), None); + assert_eq!(sanitize_path("/etc/passwd"), None); + assert_eq!(sanitize_path("foo\0bar"), None); + + // Safe relative paths are allowed + assert!(!has_traversal_component("safe/path.txt")); + assert!(!has_traversal_component("mimetype")); + assert_eq!(sanitize_path("safe/path.txt"), Some("safe/path.txt")); + assert_eq!(sanitize_path("mimetype"), Some("mimetype")); +} + +#[test] +fn synthetic_hostile_zip_headers_are_safely_flagged_and_rejected() { + 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); + zip.start_file("../../etc/passwd", opts).unwrap(); + zip.write_all(b"root:x:0:0").unwrap(); + zip.start_file(r"..\..\windows\system32", opts).unwrap(); + zip.write_all(b"system32").unwrap(); + zip.start_file("C:/test.txt", opts).unwrap(); + zip.write_all(b"drive").unwrap(); + zip.start_file("safe/file.txt", opts).unwrap(); + zip.write_all(b"safe").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + + // Archive level checks + let mut archive = Archive::open(&bytes, ROOMY).unwrap(); + assert!(archive.has_traversal_component()); + + // Enumeration omits traversal components + let names = archive.names().collect::>(); + assert_eq!(names, vec!["safe/file.txt"]); + assert_eq!(archive.entry_name(3).unwrap().as_deref(), Some("safe/file.txt")); + assert_eq!(archive.entry_name(0).unwrap(), None); + assert_eq!(archive.entry_name(1).unwrap(), None); + assert_eq!(archive.entry_name(2).unwrap(), None); + + // Raw entry name is still available for inspection + assert_eq!(archive.raw_entry_name(0).unwrap().as_deref(), Some("../../etc/passwd")); + assert_eq!(archive.raw_entry_name(1).unwrap().as_deref(), Some(r"..\..\windows\system32")); + assert_eq!(archive.raw_entry_name(2).unwrap().as_deref(), Some("C:/test.txt")); + + // Virtual lookups reject traversal components + assert!(!archive.contains("../../etc/passwd")); + assert!(!archive.contains(r"..\..\windows\system32")); + assert!(!archive.contains("C:/test.txt")); + assert!(archive.contains("safe/file.txt")); + assert_eq!(archive.declared_size("../../etc/passwd"), None); + assert_eq!(archive.compressed_size(r"..\..\windows\system32"), None); + assert_eq!(archive.is_stored("C:/test.txt"), None); + assert_eq!(archive.declared_size("safe/file.txt"), Some(4)); + + // Extractions reject traversal components + assert_eq!(archive.read("../../etc/passwd", 100).unwrap(), None); + assert_eq!(archive.read(r"..\..\windows\system32", 100).unwrap(), None); + assert_eq!(archive.read("C:/test.txt", 100).unwrap(), None); + assert_eq!(archive.read_head("../../etc/passwd", 10).unwrap(), None); + assert_eq!(archive.read_index(0, 100).unwrap(), None); + assert_eq!(archive.read_index(1, 100).unwrap(), None); + assert_eq!(archive.read_index(2, 100).unwrap(), None); + assert_eq!(archive.read("safe/file.txt", 100).unwrap().as_deref(), Some(&b"safe"[..])); + assert_eq!(archive.read_index(3, 100).unwrap().as_deref(), Some(&b"safe"[..])); +} + +#[test] +fn writer_rejects_path_traversal_components() { + let mut writer = Writer::new(); + assert!(matches!(writer.add("../../etc/passwd", b"bad", Compression::Stored), Err(Error::Write(msg)) if msg.contains("path traversal"))); + assert!(matches!(writer.add(r"..\..\windows\system32", b"bad", Compression::Stored), Err(Error::Write(msg)) if msg.contains("path traversal"))); + assert!(matches!(writer.add("C:/test.txt", b"bad", Compression::Stored), Err(Error::Write(msg)) if msg.contains("path traversal"))); + assert!(matches!(writer.add_directory("../../etc/"), Err(Error::Write(msg)) if msg.contains("path traversal"))); +}