362 lines
15 KiB
Rust
362 lines
15 KiB
Rust
//! A small zip reader and writer, written for hostile input (docs/FORMATS.md §3): the central directory is checked
|
|
//! entry by entry before anything is read, names are refused rather than cleaned, and inflation stops at a cap that
|
|
//! never trusts the sizes the archive declares. Stored and deflate only; no ZIP64, no encryption.
|
|
|
|
use crate::{FormatError, Limits, Result};
|
|
use std::cell::Cell;
|
|
use std::io::{self, Read, Write};
|
|
|
|
const EOCD: u32 = 0x0605_4b50;
|
|
const CENTRAL: u32 = 0x0201_4b50;
|
|
const LOCAL: u32 = 0x0403_4b50;
|
|
const DESCRIPTOR: u32 = 0x0807_4b50;
|
|
const MIB: u64 = 1024 * 1024;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Entry {
|
|
pub name: String,
|
|
method: u16,
|
|
crc: u32,
|
|
csize: u64,
|
|
usize: u64,
|
|
local: u64,
|
|
}
|
|
|
|
impl Entry {
|
|
pub fn is_dir(&self) -> bool {
|
|
self.name.ends_with('/')
|
|
}
|
|
/// The size the archive declares (never trusted for allocation).
|
|
pub fn declared_size(&self) -> u64 {
|
|
self.usize
|
|
}
|
|
}
|
|
|
|
/// A parsed archive over borrowed bytes.
|
|
pub struct Zip<'a> {
|
|
data: &'a [u8],
|
|
entries: Vec<Entry>,
|
|
limits: Limits,
|
|
inflated: Cell<u64>,
|
|
}
|
|
|
|
fn u16_at(d: &[u8], o: usize) -> Option<u16> {
|
|
Some(u16::from_le_bytes(d.get(o..o + 2)?.try_into().ok()?))
|
|
}
|
|
fn u32_at(d: &[u8], o: usize) -> Option<u32> {
|
|
Some(u32::from_le_bytes(d.get(o..o + 4)?.try_into().ok()?))
|
|
}
|
|
fn bad(w: &str) -> FormatError {
|
|
FormatError::Malformed(format!("the archive is broken ({w})"))
|
|
}
|
|
|
|
/// Whether a name may appear in an archive Liber reads: relative, no `..`, no backslash, no drive, no controls.
|
|
pub fn safe_name(name: &str) -> bool {
|
|
if name.is_empty() || name.len() > 1024 {
|
|
return false;
|
|
}
|
|
if name.starts_with('/') || name.contains('\\') || name.chars().any(|c| c.is_control()) {
|
|
return false;
|
|
}
|
|
let b = name.as_bytes();
|
|
if b.len() >= 2 && b[1] == b':' {
|
|
return false;
|
|
}
|
|
!name.split('/').any(|seg| seg == "..")
|
|
}
|
|
|
|
impl<'a> Zip<'a> {
|
|
pub fn parse(data: &'a [u8], limits: &Limits) -> Result<Zip<'a>> {
|
|
if data.len() < 22 {
|
|
return Err(bad("too short"));
|
|
}
|
|
let from = data.len().saturating_sub(22 + 65_535);
|
|
let eocd = (from..=data.len() - 22)
|
|
.rev()
|
|
.find(|&i| u32_at(data, i) == Some(EOCD))
|
|
.ok_or_else(|| bad("no end of central directory: the file is truncated or not a zip"))?;
|
|
let count = u16_at(data, eocd + 10).ok_or_else(|| bad("eocd"))? as usize;
|
|
let cd_size = u32_at(data, eocd + 12).ok_or_else(|| bad("eocd"))? as u64;
|
|
let cd_off = u32_at(data, eocd + 16).ok_or_else(|| bad("eocd"))? as u64;
|
|
if count == 0xFFFF || cd_size == 0xFFFF_FFFF || cd_off == 0xFFFF_FFFF {
|
|
return Err(FormatError::Unsupported("ZIP64 archives".into()));
|
|
}
|
|
if u16_at(data, eocd + 4) != Some(0) || u16_at(data, eocd + 6) != Some(0) {
|
|
return Err(FormatError::Unsupported("multi-part archives".into()));
|
|
}
|
|
if count > limits.max_entries {
|
|
return Err(FormatError::TooLarge(format!("more than {} files in the archive", limits.max_entries)));
|
|
}
|
|
if cd_off + cd_size > eocd as u64 {
|
|
return Err(bad("the central directory points past its end"));
|
|
}
|
|
let mut entries = Vec::with_capacity(count);
|
|
let mut p = cd_off as usize;
|
|
for _ in 0..count {
|
|
if u32_at(data, p) != Some(CENTRAL) {
|
|
return Err(bad("a central directory entry"));
|
|
}
|
|
let made_by = u16_at(data, p + 4).ok_or_else(|| bad("entry"))?;
|
|
let flags = u16_at(data, p + 8).ok_or_else(|| bad("entry"))?;
|
|
let method = u16_at(data, p + 10).ok_or_else(|| bad("entry"))?;
|
|
let crc = u32_at(data, p + 16).ok_or_else(|| bad("entry"))?;
|
|
let csize = u32_at(data, p + 20).ok_or_else(|| bad("entry"))? as u64;
|
|
let usize = u32_at(data, p + 24).ok_or_else(|| bad("entry"))? as u64;
|
|
let nlen = u16_at(data, p + 28).ok_or_else(|| bad("entry"))? as usize;
|
|
let elen = u16_at(data, p + 30).ok_or_else(|| bad("entry"))? as usize;
|
|
let clen = u16_at(data, p + 32).ok_or_else(|| bad("entry"))? as usize;
|
|
let external = u32_at(data, p + 38).ok_or_else(|| bad("entry"))?;
|
|
let local = u32_at(data, p + 42).ok_or_else(|| bad("entry"))? as u64;
|
|
let raw = data.get(p + 46..p + 46 + nlen).ok_or_else(|| bad("an entry name"))?;
|
|
let name = String::from_utf8_lossy(raw).into_owned();
|
|
if !safe_name(&name) {
|
|
return Err(FormatError::Unsafe(format!("the archive contains the path {name:?}")));
|
|
}
|
|
if made_by >> 8 == 3 && (external >> 16) & 0o170000 == 0o120000 {
|
|
return Err(FormatError::Unsafe(format!("the archive contains a symbolic link ({name})")));
|
|
}
|
|
if flags & 1 != 0 {
|
|
return Err(FormatError::Unsupported("password-protected archives".into()));
|
|
}
|
|
if csize == 0xFFFF_FFFF || usize == 0xFFFF_FFFF || local == 0xFFFF_FFFF {
|
|
return Err(FormatError::Unsupported("ZIP64 archives".into()));
|
|
}
|
|
if local + 30 > data.len() as u64 || local + csize > data.len() as u64 {
|
|
return Err(bad("an entry points past the end: the file is truncated"));
|
|
}
|
|
entries.push(Entry { name, method, crc, csize, usize, local });
|
|
p += 46 + nlen + elen + clen;
|
|
}
|
|
Ok(Zip { data, entries, limits: limits.clone(), inflated: Cell::new(0) })
|
|
}
|
|
|
|
pub fn entries(&self) -> &[Entry] {
|
|
&self.entries
|
|
}
|
|
|
|
/// An entry by exact name, else ignoring ASCII case.
|
|
pub fn find(&self, name: &str) -> Option<&Entry> {
|
|
self.entries
|
|
.iter()
|
|
.find(|e| e.name == name)
|
|
.or_else(|| self.entries.iter().find(|e| e.name.eq_ignore_ascii_case(name)))
|
|
}
|
|
|
|
/// Reads one entry, inflating at most up to the caps.
|
|
pub fn read(&self, e: &Entry) -> Result<Vec<u8>> {
|
|
self.read_capped(e, u64::MAX)
|
|
}
|
|
|
|
/// Reads one entry with an extra cap for this kind of file (an XML document: `max_xml`).
|
|
pub fn read_capped(&self, e: &Entry, extra: u64) -> Result<Vec<u8>> {
|
|
let d = self.data;
|
|
let l = e.local as usize;
|
|
if u32_at(d, l) != Some(LOCAL) {
|
|
return Err(bad("a local header"));
|
|
}
|
|
let nlen = u16_at(d, l + 26).ok_or_else(|| bad("local"))? as usize;
|
|
let elen = u16_at(d, l + 28).ok_or_else(|| bad("local"))? as usize;
|
|
let start = l + 30 + nlen + elen;
|
|
let body = d.get(start..start + e.csize as usize).ok_or_else(|| bad("an entry is cut off"))?;
|
|
let used = self.inflated.get();
|
|
let left = self.limits.max_total.saturating_sub(used);
|
|
let mut cap = self.limits.max_entry.min(left).min(extra);
|
|
if e.csize > 0 {
|
|
cap = cap.min((e.csize.saturating_mul(self.limits.max_ratio)).max(MIB));
|
|
}
|
|
let out = match e.method {
|
|
0 => {
|
|
if body.len() as u64 > cap {
|
|
return Err(FormatError::TooLarge(format!("{} is larger than the limit", e.name)));
|
|
}
|
|
body.to_vec()
|
|
}
|
|
8 => miniz_oxide::inflate::decompress_to_vec_with_limit(body, cap as usize).map_err(|err| {
|
|
if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput {
|
|
FormatError::TooLarge(format!(
|
|
"{} inflates beyond the limit (a zip bomb, or a book over the size cap)",
|
|
e.name
|
|
))
|
|
} else {
|
|
bad(&format!("{} does not inflate", e.name))
|
|
}
|
|
})?,
|
|
m => return Err(FormatError::Unsupported(format!("compression method {m}"))),
|
|
};
|
|
if crc32fast::hash(&out) != e.crc {
|
|
return Err(bad(&format!("{} fails its checksum", e.name)));
|
|
}
|
|
self.inflated.set(used + out.len() as u64);
|
|
Ok(out)
|
|
}
|
|
|
|
pub fn read_name(&self, name: &str) -> Result<Option<Vec<u8>>> {
|
|
self.read_name_capped(name, u64::MAX)
|
|
}
|
|
|
|
pub fn read_name_capped(&self, name: &str, extra: u64) -> Result<Option<Vec<u8>>> {
|
|
match self.find(name) {
|
|
Some(e) => self.read_capped(e, extra).map(Some),
|
|
None => Ok(None),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A streaming zip writer: deflated in-memory entries, and stored streams with a data descriptor (no seeking).
|
|
pub struct ZipWriter<W: Write> {
|
|
w: W,
|
|
at: u64,
|
|
central: Vec<u8>,
|
|
count: u16,
|
|
}
|
|
|
|
impl<W: Write> ZipWriter<W> {
|
|
pub fn new(w: W) -> ZipWriter<W> {
|
|
ZipWriter { w, at: 0, central: Vec::new(), count: 0 }
|
|
}
|
|
|
|
fn put(&mut self, b: &[u8]) -> io::Result<()> {
|
|
self.w.write_all(b)?;
|
|
self.at += b.len() as u64;
|
|
Ok(())
|
|
}
|
|
|
|
fn check(&self, name: &str) -> io::Result<()> {
|
|
if !safe_name(name) {
|
|
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsafe name {name:?}")));
|
|
}
|
|
if self.count == u16::MAX - 1 {
|
|
return Err(io::Error::other("too many entries for a zip without ZIP64"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn header(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32) -> io::Result<u32> {
|
|
let off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?;
|
|
let mut h = Vec::with_capacity(30 + name.len());
|
|
h.extend_from_slice(&LOCAL.to_le_bytes());
|
|
h.extend_from_slice(&20u16.to_le_bytes());
|
|
h.extend_from_slice(&(flags | 0x0800).to_le_bytes());
|
|
h.extend_from_slice(&method.to_le_bytes());
|
|
h.extend_from_slice(&0u16.to_le_bytes()); // time
|
|
h.extend_from_slice(&0x21u16.to_le_bytes()); // date 1980-01-01
|
|
h.extend_from_slice(&crc.to_le_bytes());
|
|
h.extend_from_slice(&csize.to_le_bytes());
|
|
h.extend_from_slice(&usize.to_le_bytes());
|
|
h.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
|
h.extend_from_slice(&0u16.to_le_bytes());
|
|
h.extend_from_slice(name.as_bytes());
|
|
self.put(&h)?;
|
|
Ok(off)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn record(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32, off: u32) {
|
|
let c = &mut self.central;
|
|
c.extend_from_slice(&CENTRAL.to_le_bytes());
|
|
c.extend_from_slice(&0x0314u16.to_le_bytes()); // made by Unix, 2.0
|
|
c.extend_from_slice(&20u16.to_le_bytes());
|
|
c.extend_from_slice(&(flags | 0x0800).to_le_bytes());
|
|
c.extend_from_slice(&method.to_le_bytes());
|
|
c.extend_from_slice(&0u16.to_le_bytes());
|
|
c.extend_from_slice(&0x21u16.to_le_bytes());
|
|
c.extend_from_slice(&crc.to_le_bytes());
|
|
c.extend_from_slice(&csize.to_le_bytes());
|
|
c.extend_from_slice(&usize.to_le_bytes());
|
|
c.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
|
c.extend_from_slice(&[0; 8]); // extra, comment, disk, internal
|
|
c.extend_from_slice(&(0o100644u32 << 16).to_le_bytes());
|
|
c.extend_from_slice(&off.to_le_bytes());
|
|
c.extend_from_slice(name.as_bytes());
|
|
self.count += 1;
|
|
}
|
|
|
|
/// Adds an in-memory file; `deflate` compresses it.
|
|
pub fn add(&mut self, name: &str, data: &[u8], deflate: bool) -> io::Result<()> {
|
|
self.check(name)?;
|
|
let crc = crc32fast::hash(data);
|
|
let usize = u32::try_from(data.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
|
|
let (method, body) =
|
|
if deflate { (8, miniz_oxide::deflate::compress_to_vec(data, 6)) } else { (0, data.to_vec()) };
|
|
let csize = u32::try_from(body.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
|
|
let off = self.header(name, 0, method, crc, csize, usize)?;
|
|
self.put(&body)?;
|
|
self.record(name, 0, method, crc, csize, usize, off);
|
|
Ok(())
|
|
}
|
|
|
|
/// Adds a file streamed from `r`, stored (book files are compressed already), with a data descriptor.
|
|
pub fn add_stream(&mut self, name: &str, r: &mut dyn Read) -> io::Result<()> {
|
|
self.check(name)?;
|
|
let off = self.header(name, 0x0008, 0, 0, 0, 0)?;
|
|
let mut hasher = crc32fast::Hasher::new();
|
|
let mut n: u64 = 0;
|
|
let mut buf = vec![0u8; 64 * 1024];
|
|
loop {
|
|
let k = r.read(&mut buf)?;
|
|
if k == 0 {
|
|
break;
|
|
}
|
|
hasher.update(&buf[..k]);
|
|
self.put(&buf[..k])?;
|
|
n += k as u64;
|
|
}
|
|
let size = u32::try_from(n).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
|
|
let crc = hasher.finalize();
|
|
let mut d = Vec::with_capacity(16);
|
|
d.extend_from_slice(&DESCRIPTOR.to_le_bytes());
|
|
d.extend_from_slice(&crc.to_le_bytes());
|
|
d.extend_from_slice(&size.to_le_bytes());
|
|
d.extend_from_slice(&size.to_le_bytes());
|
|
self.put(&d)?;
|
|
self.record(name, 0x0008, 0, crc, size, size, off);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn finish(mut self) -> io::Result<W> {
|
|
let cd_off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?;
|
|
let central = std::mem::take(&mut self.central);
|
|
self.put(¢ral)?;
|
|
let mut e = Vec::with_capacity(22);
|
|
e.extend_from_slice(&EOCD.to_le_bytes());
|
|
e.extend_from_slice(&[0; 4]);
|
|
e.extend_from_slice(&self.count.to_le_bytes());
|
|
e.extend_from_slice(&self.count.to_le_bytes());
|
|
e.extend_from_slice(&(central.len() as u32).to_le_bytes());
|
|
e.extend_from_slice(&cd_off.to_le_bytes());
|
|
e.extend_from_slice(&0u16.to_le_bytes());
|
|
self.put(&e)?;
|
|
self.w.flush()?;
|
|
Ok(self.w)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn round_trip() {
|
|
let mut w = ZipWriter::new(Vec::new());
|
|
w.add("mimetype", b"application/epub+zip", false).unwrap();
|
|
w.add("a/b.txt", "žluťoučký kůň".repeat(100).as_bytes(), true).unwrap();
|
|
w.add_stream("c.bin", &mut &b"streamed"[..]).unwrap();
|
|
let bytes = w.finish().unwrap();
|
|
let z = Zip::parse(&bytes, &Limits::default()).unwrap();
|
|
assert_eq!(z.entries().len(), 3);
|
|
assert_eq!(z.read_name("mimetype").unwrap().unwrap(), b"application/epub+zip");
|
|
assert_eq!(z.read_name("a/b.txt").unwrap().unwrap(), "žluťoučký kůň".repeat(100).as_bytes());
|
|
assert_eq!(z.read_name("c.bin").unwrap().unwrap(), b"streamed");
|
|
}
|
|
|
|
#[test]
|
|
fn names() {
|
|
for n in ["../x", "a/../../x", "/etc/passwd", "C:x", "c:/x", "a\\b", "a\0b", ""] {
|
|
assert!(!safe_name(n), "{n:?}");
|
|
}
|
|
for n in ["OEBPS/content.opf", "a..b/c", "..a", "META-INF/"] {
|
|
assert!(safe_name(n), "{n:?}");
|
|
}
|
|
}
|
|
}
|