//! Mandatory test 1: hostile e-books (docs/FORMATS.md ยง3). Each is refused or sanitized; nothing is written //! anywhere (the crate has no file-system or network code: `purity.rs`); no remote URL survives. mod common; use common::*; use liber_format::{DRM_MESSAGE, FormatError, Limits, open}; fn epub_with(extra: Vec) -> Vec { let e = Epub::new("Hostile").chapter("One", "

Hello.

"); let mut entries = vec![ Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), Raw::file("OEBPS/content.opf", e.opf().as_bytes()), Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), Raw::file("OEBPS/text/ch0.xhtml", xhtml("

Hello.

").as_bytes()), ]; entries.extend(extra); raw_zip(&entries) } fn err(bytes: &[u8]) -> FormatError { open(bytes, Some("x.epub"), &Limits::default()).expect_err("must be refused") } #[test] fn baseline_opens() { let d = open(&epub_with(vec![]), None, &Limits::default()).unwrap(); assert_eq!(d.chapters[0].text(), "Hello."); } #[test] fn zip_slip_is_refused_and_nothing_is_written() { let marker = format!("liber-zipslip-{}.txt", std::process::id()); for name in [ format!("../../{marker}"), format!("OEBPS/../../{marker}"), format!("/tmp/{marker}"), format!("C:{marker}"), format!("..\\..\\{marker}"), ] { let bytes = epub_with(vec![Raw::file(&name, b"pwned")]); assert!(matches!(err(&bytes), FormatError::Unsafe(_)), "{name}"); } for dir in [std::env::current_dir().unwrap(), std::env::temp_dir()] { let mut d = dir.clone(); for _ in 0..3 { assert!(!d.join(&marker).exists(), "{} exists", d.join(&marker).display()); d.pop(); } } } #[test] fn symlinks_are_refused() { let link = Raw { unix_mode: 0o120777, deflate: false, ..Raw::file("OEBPS/link.xhtml", b"/etc/passwd") }; assert!(matches!(err(&epub_with(vec![link])), FormatError::Unsafe(_))); } #[test] fn zip_bomb_stops_at_the_ratio_cap() { // 256 MiB of zeros in about 250 kB (about 1000:1), declared as 10 bytes: stopped by the ratio cap. let bomb = miniz_oxide::deflate::compress_to_vec(&vec![0u8; 256 << 20], 6); assert!(bomb.len() < 400_000, "{}", bomb.len()); let bytes = replace_last_entry_body(&[], &bomb, 10); let t = std::time::Instant::now(); let e = err(&bytes); assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}"); assert!(t.elapsed().as_secs() < 5); } #[test] fn zip_bomb_under_the_ratio_stops_at_the_xml_cap() { // 64 MiB of zeros at about 160:1 (fixed Huffman), under the ratio cap: stopped at max_xml for a chapter. let bomb = deflate_zeros(64 << 20); assert!(bomb.len() < 500_000, "{}", bomb.len()); let bytes = replace_last_entry_body(&[], &bomb, 10); let t = std::time::Instant::now(); let e = err(&bytes); assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}"); assert!(t.elapsed().as_secs() < 5); } /// Rebuilds a raw zip whose last entry's deflated body is `body`, declaring `declared` bytes. fn replace_last_entry_body(_old: &[u8], body: &[u8], declared: u32) -> Vec { let e = Epub::new("Bomb").chapter("One", "

x

"); let mut out = raw_zip(&[ Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), Raw::file("OEBPS/content.opf", e.opf().as_bytes()), Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), ]); // Strip the EOCD and central directory of that archive, then append our own entry and directories. let z = liber_format::zip::Zip::parse(&out, &Limits::default()).unwrap(); let n = z.entries().len(); drop(z); let eocd = out.len() - 22; let cd_off = u32::from_le_bytes(out[eocd + 16..eocd + 20].try_into().unwrap()) as usize; let central = out[cd_off..eocd].to_vec(); out.truncate(cd_off); let name = b"OEBPS/text/ch0.xhtml"; let off = out.len() as u32; let crc = 0u32; // never reached: inflation stops at the cap first out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]); out.extend_from_slice(&crc.to_le_bytes()); out.extend_from_slice(&(body.len() as u32).to_le_bytes()); out.extend_from_slice(&declared.to_le_bytes()); out.extend_from_slice(&(name.len() as u16).to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(name); out.extend_from_slice(body); let mut cd = central; cd.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); cd.extend_from_slice(&[0x14, 0x03, 20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]); cd.extend_from_slice(&crc.to_le_bytes()); cd.extend_from_slice(&(body.len() as u32).to_le_bytes()); cd.extend_from_slice(&declared.to_le_bytes()); cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); cd.extend_from_slice(&[0; 8]); cd.extend_from_slice(&(0o100644u32 << 16).to_le_bytes()); cd.extend_from_slice(&off.to_le_bytes()); cd.extend_from_slice(name); let new_cd = out.len() as u32; out.extend_from_slice(&cd); out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); out.extend_from_slice(&[0; 4]); out.extend_from_slice(&((n + 1) as u16).to_le_bytes()); out.extend_from_slice(&((n + 1) as u16).to_le_bytes()); out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); out.extend_from_slice(&new_cd.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out } #[test] fn many_small_entries_stop_at_the_total_cap() { let big = vec![b'a'; 900 * 1024]; let mut extra = Vec::new(); for i in 0..12 { extra.push(Raw::file(&format!("OEBPS/img{i}.png"), &big)); } let mut epub = Epub::new("Total").chapter("One", ""); let mut body = String::new(); for i in 0..12 { body.push_str(&format!("")); } epub.chapters[0].1 = body.clone(); let mut entries = vec![ Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), Raw::file("OEBPS/content.opf", epub.opf().as_bytes()), Raw::file("OEBPS/nav.xhtml", epub.nav().as_bytes()), Raw::file("OEBPS/text/ch0.xhtml", xhtml(&format!("

x

{body}")).as_bytes()), ]; entries.extend(extra); let bytes = raw_zip(&entries); let limits = Limits { max_total: 4 << 20, ..Limits::default() }; // Images over the total cap are not loaded (and are not raster anyway); the book still opens, bounded. let d = open(&bytes, None, &limits).unwrap(); assert_eq!(d.images.len(), 0); // A chapter over the total cap refuses the book. let limits = Limits { max_total: 1024, ..Limits::default() }; assert!(matches!(open(&bytes, None, &limits).unwrap_err(), FormatError::TooLarge(_))); } #[test] fn too_many_entries() { let mut extra = Vec::new(); for i in 0..50 { extra.push(Raw::file(&format!("f{i}"), b"x")); } let limits = Limits { max_entries: 20, ..Limits::default() }; assert!(matches!(open(&epub_with(extra), None, &limits).unwrap_err(), FormatError::TooLarge(_))); } #[test] fn xxe_and_billion_laughs_are_refused() { let xxe_opf = r#"]> &xxe; "#; let mut e = Epub::new("x").chapter("One", "

Hi

"); e.opf_override = Some(xxe_opf.into()); assert!(matches!(err(&e.build()), FormatError::Unsafe(_))); let laughs = "\ ]>

&c;

"; let mut e = Epub::new("x").chapter("One", ""); let mut entries = vec![ Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), Raw::file("OEBPS/content.opf", e.opf().as_bytes()), Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), ]; entries.push(Raw::file("OEBPS/text/ch0.xhtml", laughs.as_bytes())); e.extra.clear(); assert!(matches!(err(&raw_zip(&entries)), FormatError::Unsafe(_))); // A plain external DTD reference is harmless: nothing is ever fetched, the book opens. let dtd = "

Fine text

"; entries.pop(); entries.push(Raw::file("OEBPS/text/ch0.xhtml", dtd.as_bytes())); let d = open(&raw_zip(&entries), None, &Limits::default()).unwrap(); assert_eq!(d.chapters[0].text(), "Fine\u{a0}text"); } const NASTY: &str = r#"

Text js link and web.

Styled

in svg

x

Safe emphasis stays.

"#; #[test] fn scripts_handlers_forms_and_remote_urls_are_stripped() { let bytes = Epub::new("Nasty") .chapter("One", NASTY) .file("OEBPS/style.css", b"@import url(https://evil.example/i.css);") .build(); let d = open(&bytes, None, &Limits::default()).unwrap(); let x = d.chapters[0].xhtml.replacen("
", "
", 1); for bad in [ "emphasis")); assert!(x.contains("js link") && x.contains("web"), "link text stays: {x}"); assert!(d.images.is_empty()); for f in d.footnotes.values() { assert!(!f.contains("http")); } } #[test] fn truncated_archives() { let good = Epub::new("Cut").chapter("One", "

Hello there.

").build(); for cut in [good.len() / 2, good.len() - 10, 30, 0] { let e = err(&good[..cut]); assert!(matches!(e, FormatError::Malformed(_)), "cut at {cut}: {e:?}"); } // A flipped byte in a deflated body fails its checksum or inflation, never yields garbage silently. let mut flipped = good.clone(); let at = good.len() / 2; flipped[at] ^= 0xff; let r = open(&flipped, None, &Limits::default()); assert!(r.is_err() || r.as_ref().unwrap().chapters.iter().all(|c| !c.xhtml.contains("x

"); e.opf_override = Some("unclosed".into()); assert!(matches!(err(&e.build()), FormatError::Malformed(_))); e.opf_override = Some("".into()); assert!(matches!(err(&e.build()), FormatError::Malformed(_))); let no_opf = raw_zip(&[ Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), ]); assert!(matches!(err(&no_opf), FormatError::Malformed(_))); // A spine pointing at a missing chapter: the book opens without it only if another chapter has text. e.opf_override = None; let mut bytes_e = Epub::new("Missing"); bytes_e.chapters.push(("One".into(), "

x

".into())); let ok = bytes_e.build(); assert!(open(&ok, None, &Limits::default()).is_ok()); } #[test] fn deep_nesting_does_not_overflow() { let depth = 100_000; let body = format!("{}deep{}", "
".repeat(depth), "
".repeat(depth)); // So repetitive it compresses past the ratio cap: allow it here, depth is what is tested. let l = Limits { max_ratio: 100_000, ..Limits::default() }; let d = open(&Epub::new("Deep").chapter("One", &body).build(), None, &l).unwrap(); assert!(d.chapters[0].text().contains("deep")); // Tag soup (not well-formed): through html5ever, still capped. let soup = format!("{}soup

unclosed", "

".repeat(20_000)); let d = open(&Epub::new("Soup").chapter("One", &soup).build(), None, &l).unwrap(); assert!(d.chapters[0].text().contains("soup")); } #[test] fn drm_is_refused_with_the_one_sentence() { let rights = epub_with(vec![Raw::file("META-INF/rights.xml", b"")]); let lcp = epub_with(vec![Raw::file("META-INF/license.lcpl", b"{}")]); let fairplay = epub_with(vec![Raw::file("META-INF/sinf.xml", b"")]); let aes = epub_with(vec![Raw::file( "META-INF/encryption.xml", br#" "#, )]); for (what, b) in [("rights", rights), ("lcp", lcp), ("fairplay", fairplay), ("aes", aes)] { let e = err(&b); assert_eq!(e, FormatError::Drm, "{what}"); assert_eq!(e.message(), DRM_MESSAGE); } // Font obfuscation only: not DRM. let fonts = epub_with(vec![Raw::file( "META-INF/encryption.xml", br#" "#, )]); assert!(open(&fonts, None, &Limits::default()).is_ok()); // MOBI with Mobipocket DRM, KFX, Topaz. let mut m = Mobi::new("

secret

"); m.encryption = 2; assert_eq!(err(&m.build()), FormatError::Drm); let mut kfx = b"\xeaDRMION\xee".to_vec(); kfx.extend_from_slice(&[0; 100]); assert_eq!(err(&kfx), FormatError::Drm); assert_eq!(err(b"TPZ0\x00\x00garbage"), FormatError::Drm); } #[test] fn hostile_mobi() { let good = Mobi::new("

Hello mobi.

").build(); assert!(open(&good, None, &Limits::default()).is_ok()); // A record offset past the end. let mut b = good.clone(); b[78..82].copy_from_slice(&u32::MAX.to_be_bytes()); assert!(matches!(err(&b), FormatError::Malformed(_))); // More text records than records. let mut b = good.clone(); let r0 = u32::from_be_bytes(good[78..82].try_into().unwrap()) as usize; b[r0 + 8..r0 + 10].copy_from_slice(&500u16.to_be_bytes()); assert!(matches!(err(&b), FormatError::Malformed(_))); // A PalmDOC back-reference before the start of the record. let mut m = Mobi::new("x"); m.compression = 1; let mut b = m.build(); b[r0..r0 + 2].copy_from_slice(&2u16.to_be_bytes()); let r1 = u32::from_be_bytes(b[86..90].try_into().unwrap()) as usize; b[r1] = 0x80; b.push(0xff); let _ = open(&b, None, &Limits::default()); // HUFF/CDIC compression with no HUFF records: refused cleanly. let mut b = good.clone(); b[r0..r0 + 2].copy_from_slice(&17480u16.to_be_bytes()); assert!(matches!(err(&b), FormatError::Malformed(_))); // Absurd text length is capped by max_text, not allocated. let mut b = good.clone(); b[r0 + 4..r0 + 8].copy_from_slice(&u32::MAX.to_be_bytes()); assert!(open(&b, None, &Limits::default()).is_ok()); }