Merge pull request #10600 from dotCooCoo/fix/pdf13-transparency-scan

Tests: the PDF 1.3 transparency check reads dictionaries only
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-02 15:30:26 -08:00
commit 923fd71b89
1 file changed
+232 -2
+232 -2
View File
@@ -71,9 +71,163 @@ fn export(s: &mut Session, p: Value) -> (Vec<u8>, Vec<String>) {
(bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect())
}
/// The transparency `pdf` has, in its dictionaries.
/// Whether `b` ends a PDF token: white space or a delimiter.
fn ends_token(b: u8) -> bool {
b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b)
}
/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the
/// `startxref` at `startxref` and following `/Prev`.
fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option<usize> {
let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::<usize>().ok()?;
let mut visited = vec![];
loop {
if visited.contains(&offset) {
return None;
}
visited.push(offset);
let table = String::from_utf8_lossy(pdf.get(offset..)?);
let mut words = table.split_ascii_whitespace();
if words.next()? != "xref" {
return None;
}
loop {
let first = words.next()?;
if first == "trailer" {
break;
}
let first = first.parse::<usize>().ok()?;
let count = words.next()?.parse::<usize>().ok()?;
for index in 0..count {
let at = words.next()?.parse::<usize>().ok()?;
let entry_generation = words.next()?.parse::<usize>().ok()?;
let status = words.next()?;
if first.checked_add(index)? == number {
return (status == "n" && entry_generation == generation).then_some(at);
}
}
}
let trailer = table.split_once("trailer")?.1.split_once(">>")?.0;
let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty());
words.find(|&w| w == "Prev")?;
offset = words.next()?.parse().ok()?;
}
}
/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary
/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white
/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its
/// object in `pdf`. `None` when it is missing or cannot be read.
fn stream_length(text: &[u8], pdf: &[u8]) -> Option<usize> {
let from = text
.windows(3)
.enumerate()
.rev()
.find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')))
.map_or(0, |(at, _)| at + 3);
let dict = &text[from..];
let mut i = dict.windows(2).position(|w| w == b"<<")? + 2;
let mut depth = 1usize;
let mut length = None;
while i < dict.len() && depth > 0 {
let rest = &dict[i..];
if rest.starts_with(b"<<") {
depth += 1;
i += 2;
} else if rest.starts_with(b">>") {
depth -= 1;
i += 2;
} else if rest[0] == b'<' {
// A hex string.
i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1);
} else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) {
let value = String::from_utf8_lossy(&rest[7..]);
let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect();
length = match words[..] {
// `n g R` is an indirect length: the integer in object `n g`.
[n, g, "R", ..] => {
let header = format!("{n} {g} obj");
let read_length = |at: usize| {
let body = String::from_utf8_lossy(&pdf[at + header.len()..]);
match body.split_ascii_whitespace().take(2).collect::<Vec<_>>()[..] {
[n, "endobj"] => n.parse::<usize>().ok(),
_ => None,
}
};
if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") {
let at =
xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref");
let object = pdf.get(at..).expect("stream /Length xref offset is outside the file");
assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object");
read_length(at)
} else {
pdf.windows(header.len())
.enumerate()
// An object header starts a line, and the length object holds one integer.
.filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n')))
.find_map(|(at, _)| read_length(at))
}
}
[n, ..] => n.parse::<usize>().ok(),
[] => None,
};
i += 7;
} else {
i += 1;
}
}
length
}
/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out:
/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time
/// and can spell `/BM`.
fn transparency(pdf: &[u8]) -> Vec<&'static str> {
let text = String::from_utf8_lossy(pdf);
let mut text = Vec::with_capacity(pdf.len());
let mut i = 0;
while i < pdf.len() {
let rest = &pdf[i..];
// A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name.
let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>';
if keyword_start && rest.starts_with(b"endstream") {
text.extend_from_slice(b"endstream");
i += b"endstream".len();
} else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) {
// Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to
// `endstream`); its bytes are not PDF syntax.
let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 };
i = match stream_length(&text, pdf) {
Some(n) => {
let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream");
while matches!(pdf.get(end), Some(b'\r' | b'\n')) {
end += 1;
}
assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream");
end
}
None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"),
};
} else if rest[0] == b'(' {
// A literal string: balanced parentheses, with `\` escaping the next byte.
let mut depth = 0usize;
while i < pdf.len() {
match pdf[i] {
b'\\' => i += 1,
b'(' => depth += 1,
b')' => depth -= 1,
_ => {}
}
i += 1;
if depth == 0 {
break;
}
}
} else {
text.push(rest[0]);
i += 1;
}
}
let text = String::from_utf8_lossy(&text);
let mut found = vec![];
for (what, there) in [
("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")),
@@ -193,3 +347,79 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err()
);
}
/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check
/// reads the file's dictionaries only, not its strings or its XMP packet.
#[test]
fn the_transparency_check_skips_strings_and_metadata() {
let pdf = b"%PDF-1.3\n5 0 obj\n<</Title(a/BM/SMask/CA 0.5)>>\nendobj\n6 0 obj\n<</Type/Metadata>>\nstream\n<?xpacket begin=\"\"?><x>q/BMx/S/Transparency</x><?xpacket end=\"r\"?>\nendstream\nendobj\ntrailer\n<</ID[(hIX/BMcE)(hIX/BMcE)]>>\n";
assert_eq!(transparency(pdf), Vec::<&str>::new());
assert_eq!(transparency(b"<</ExtGState<</G<</BM/Multiply/CA 0.5>>>>>>"), vec!["blend modes", "opacity"]);
// A `(` in image data starts no string, and nested and escaped parentheses end where the
// string does.
let pdf = b"<</Length 3>>\nstream\n(\x00(\nendstream\n<</T(a(b)c\\)d)/SMask 9 0 R>>\n<</S/Transparency>>";
assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]);
// Stream data is skipped by its length, even when it holds `endstream` itself.
let pdf = b"1 0 obj\n<</Length 15>>\nstream\nendstream (/BM\nendstream\nendobj\n<</BM/Multiply>>";
assert_eq!(transparency(pdf), vec!["blend modes"]);
let pdf = b"1 0 obj\n<</Length 13>>\nstream\nendstream /BM\nendstream\nendobj\n";
assert_eq!(transparency(pdf), Vec::<&str>::new());
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabc\r\nendstream\nendobj\n<</SMask 9 0 R>>";
assert_eq!(transparency(pdf), vec!["soft masks"]);
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabcendstream\nendobj\n<</BM/Multiply>>";
assert_eq!(transparency(pdf), vec!["blend modes"]);
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R>>";
assert_eq!(transparency(pdf), vec!["soft masks"]);
// Only the stream dictionary's own `/Length` counts, not one in a nested dictionary.
let pdf = b"1 0 obj\n<</Length 4/DecodeParms<</Length 1>>>>\nstream\n/BM \nendstream\nendobj\n";
assert_eq!(transparency(pdf), Vec::<&str>::new());
// `stream` inside a name is not the keyword.
let pdf = b"1 0 obj\n<</Type/Upstream\n/BM/Multiply>>\nendobj\n";
assert_eq!(transparency(pdf), vec!["blend modes"]);
let pdf = b"1 0 obj\n<</Type/stream\n/SMask 9 0 R>>\nendobj\n";
assert_eq!(transparency(pdf), vec!["soft masks"]);
// An indirect length is read from its object, so `endstream` in the data does not end it.
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n";
assert_eq!(transparency(pdf), Vec::<&str>::new());
let payload = b"2 0 obj\n13\nendobj\nendstream /BM";
let mut pdf = b"%PDF-1.3\n".to_vec();
let stream_at = pdf.len();
pdf.extend_from_slice(b"1 0 obj\n<</Length 2 0 R>>\nstream\n");
pdf.extend_from_slice(payload);
pdf.extend_from_slice(b"\nendstream\nendobj\n");
let length_at = pdf.len();
pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes());
let catalog_at = pdf.len();
pdf.extend_from_slice(b"3 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n");
let pages_at = pdf.len();
pdf.extend_from_slice(b"4 0 obj\n<</Type/Pages/Kids[]/Count 0>>\nendobj\n");
let xref_at = pdf.len();
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
for at in [stream_at, length_at, catalog_at, pages_at] {
pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes());
}
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 3 0 R>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
assert_eq!(transparency(&pdf), Vec::<&str>::new());
// A stream with no length and no `endstream` fails rather than hiding the rest of the file.
let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<</SMask 9 0 R>>";
assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err());
for length in [2, 20, 999, usize::MAX] {
let pdf = format!("1 0 obj\n<</Length {length}>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R/BM/Multiply>>");
let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic");
let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}");
}
}
/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the
/// stream's `/Length` is still read from the outer dictionary.
#[test]
fn the_stream_length_skips_names_that_end_in_obj() {
let text = b"1 0 obj\n<</Length 5/Tag/obj>>\nstream\n";
assert_eq!(stream_length(text, text), Some(5));
// NUL is PDF white space, so it may separate the generation number from `obj`.
let text = b"1 0 obj\n<</Length 9>>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<</Length 5>>\nstream\n";
assert_eq!(stream_length(text, text), Some(5));
let pdf = b"1 0 obj\n<</Length 13/Tag/obj>>\nstream\nendstream /BM\nendstream\nendobj\n";
assert_eq!(transparency(pdf), Vec::<&str>::new());
}