Files
Liber-public/crates/liber-format/tests/hostile.rs
T

390 lines
17 KiB
Rust

//! 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<Raw>) -> Vec<u8> {
let e = Epub::new("Hostile").chapter("One", "<p>Hello.</p>");
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("<p>Hello.</p>").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<u8> {
let e = Epub::new("Bomb").chapter("One", "<p>x</p>");
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!("<img src=\"../img{i}.png\"/>"));
}
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!("<p>x</p>{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#"<?xml version="1.0"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata><dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">&xxe;</dc:title></metadata>
<manifest><item id="c0" href="text/ch0.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c0"/></spine></package>"#;
let mut e = Epub::new("x").chapter("One", "<p>Hi</p>");
e.opf_override = Some(xxe_opf.into());
assert!(matches!(err(&e.build()), FormatError::Unsafe(_)));
let laughs = "<?xml version=\"1.0\"?><!DOCTYPE html [<!ENTITY a \"aaaaaaaaaa\"><!ENTITY b \"&a;&a;&a;&a;&a;&a;&a;&a;\">\
<!ENTITY c \"&b;&b;&b;&b;&b;&b;&b;&b;\">]><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>&c;</p></body></html>";
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 = "<?xml version=\"1.0\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \
\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>Fine&nbsp;text</p></body></html>";
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#"
<p onclick="steal()">Text <a href="javascript:alert(1)">js link</a> and <a href="https://evil.example/track">web</a>.</p>
<script>alert('x')</script><script src="https://evil.example/x.js"></script>
<img src="https://evil.example/pixel.png" onerror="alert(2)"/><img src="//evil.example/p.png"/>
<img src="data:image/png;base64,iVBORw0KGgo="/>
<iframe src="https://evil.example"></iframe><frame src="x"/><object data="x.swf"></object><embed src="x.swf"/>
<form action="https://evil.example"><input name="q"/><button>Go</button><textarea>t</textarea></form>
<style>@font-face { src: url(https://evil.example/f.woff) } body { background: url(https://evil.example/b.png) }</style>
<div style="background:url(https://evil.example/bg.png)" class="x" onmouseover="alert(3)">Styled</div>
<link rel="stylesheet" href="https://evil.example/s.css"/><base href="https://evil.example/"/>
<meta http-equiv="refresh" content="0;url=https://evil.example"/>
<svg xmlns="http://www.w3.org/2000/svg"><script>alert(4)</script><foreignObject><p>in svg</p></foreignObject></svg>
<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>
<video src="https://evil.example/v.mp4"></video><audio src="a.mp3"></audio><template><p>t</p></template>
<p>Safe <em>emphasis</em> stays.</p>
"#;
#[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("<div xmlns=\"http://www.w3.org/1999/xhtml\">", "<div>", 1);
for bad in [
"<script",
"alert",
"onclick",
"onerror",
"onmouseover",
"javascript",
"<iframe",
"<frame",
"<object",
"<embed",
"<form",
"<input",
"<button",
"<textarea",
"<style",
"style=",
"class=",
"<link",
"<base",
"<meta",
"<svg",
"<math",
"<video",
"<audio",
"<template",
"http",
"//",
"src=",
"href=",
"url(",
"data:",
] {
assert!(!x.contains(bad), "{bad:?} survived in {x}");
}
assert!(x.contains("<em>emphasis</em>"));
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", "<p>Hello there.</p>").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("<script")));
}
#[test]
fn malformed_packages() {
let mut e = Epub::new("Bad").chapter("One", "<p>x</p>");
e.opf_override = Some("<package><metadata><dc:title>unclosed</metadata></package>".into());
assert!(matches!(err(&e.build()), FormatError::Malformed(_)));
e.opf_override = Some("<package xmlns=\"http://www.idpf.org/2007/opf\"><metadata/><manifest/></package>".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(), "<p>x</p>".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{}", "<div>".repeat(depth), "</div>".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<p>unclosed", "<div><span>".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"<adept:rights xmlns:adept=\"http://ns.adobe.com/adept\"/>")]);
let lcp = epub_with(vec![Raw::file("META-INF/license.lcpl", b"{}")]);
let fairplay = epub_with(vec![Raw::file("META-INF/sinf.xml", b"<fairplay/>")]);
let aes = epub_with(vec![Raw::file(
"META-INF/encryption.xml",
br#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/>
<enc:CipherData><enc:CipherReference URI="OEBPS/text/ch0.xhtml"/></enc:CipherData></enc:EncryptedData></encryption>"#,
)]);
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#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.idpf.org/2008/embedding"/>
<enc:CipherData><enc:CipherReference URI="OEBPS/fonts/a.otf"/></enc:CipherData></enc:EncryptedData></encryption>"#,
)]);
assert!(open(&fonts, None, &Limits::default()).is_ok());
// MOBI with Mobipocket DRM, KFX, Topaz.
let mut m = Mobi::new("<html><body><p>secret</p></body></html>");
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("<html><body><p>Hello mobi.</p></body></html>").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());
}