This is part 5 of the series Printing a CRM's PDFs without Chrome.
A CRM prints its customers' logos on their quotes. In pdfblaze 1.4.1, a customer could upload a
10,312-byte file as logo.png and every quote that used it would kill the renderer: not an error,
not a blank image, but a stack overflow that aborts the whole process with exit code 134. In a
worker, every render it was running went with it.
It was the first High finding of the audit, and it was
fixed the same day in 1.4.2: objects
nested deeper than 64 levels are refused, and the image is drawn without them. Upgrade to 1.4.3 or
later, and if you use pdfblaze as a Rust library, add the [patch.crates-io] entry shown below:
without it, your build does not get the fix.
This post is how a logo becomes a PDF, why one object can exhaust the stack, why two separate defences missed it, and why the fix is a vendored copy of someone else's crate.
How a logo becomes a PDF
pdfblaze decides what an image is from its bytes, not its name or its URL. That is the right call
for a renderer: customers name files whatever they like, and a data:image/png URL can hold
anything. One of the formats it accepts is PDF. If %PDF- appears near the start of the data, the
image is a PDF, and its first page is drawn as vector graphics. That is a real feature: a vector logo
exported as PDF prints sharper than a PNG.
So <img src="logo.png"> with PDF bytes inside sends those bytes to a PDF parser. pdfblaze uses
hayro-syntax for that, the parser that krilla, the PDF writer pdfblaze builds on, also depends on. hayro-syntax reads
the cross-reference table, the objects and the page tree as it opens the file, and pdfblaze copies the
page it needs into the output.
The project's SECURITY.md said of that opening step that "the file's size bounds that work". For plain bytes, it does. For compressed bytes, it does not.
One object, five million levels
A PDF object can be an array, and an array can hold arrays. [[[[ ]]]] is a legal object four levels
deep. hayro-syntax reads lazily: to know where an array ends, it skips over each element, and to skip
an element that is itself an array, it calls the same skip function again. One level of nesting is one
call, and one call is one stack frame. In 0.7.2 nothing counted the levels:
Array::skip → skip(element) → Array::skip → skip(element) → …
The audit's file holds one such array, 5,000,000 levels deep. Written out, that is five million opening brackets and five million closing ones, far more than 10 KB. But PDF lets objects live inside an object stream, and object streams can be Flate-compressed. A run of identical bytes is the best case for any compressor, so the whole array fits in a file of 10,312 bytes. The page dictionary then refers to it from an entry nobody looks at for drawing, and the opening and copying steps resolve it anyway.
So the parser starts skipping, and keeps calling itself, and the stack runs out long before level 5,000,000.
call stack (innermost on top)
- Array::skip
- depth
- 0
- file nests
- 5,000,000
The page points at an object in a compressed object stream. Skipping it, the parser sees an opening bracket and calls itself for the first element.
Why it aborts instead of failing
Most failures in a Rust program can be turned into an error. A panic can be caught at a thread boundary, and pdfblaze does exactly that around third-party parsers. A stack overflow is different. The thread hits the guard page below its stack, and the runtime prints "has overflowed its stack" and aborts. There is no unwinding to catch; the process ends with SIGABRT.
What that meant for each way of running pdfblaze:
| How it runs | What the file did |
|---|---|
pdfblaze render, one process per document | the process died, exit 134 |
pdfblaze worker | the worker died with its warm caches and every render it held; the client saw WorkerError. Repeat the logo and every quote kills a worker: a cheap way to starve the pool |
pdfblaze merge | the same abort. Here even an uncompressed array 200,000 levels deep, about 400 KB, overflows the 8 MiB main stack |
| the C library | it renders inside the caller's process, so the abort would take the host process down. This follows from the CLI result; I could not build the library on the audit machine to show it |
The renderer runs documents on its own threads, with a much larger stack than the main thread, because style, layout and painting walk the document recursively. A larger stack only moves the threshold. The file's depth is a choice of the attacker, and five million is far past any stack size.
The guard that was looking the other way
The engine already guarded hayro-syntax against a deep page tree: a PDF whose page tree refers to
itself, or nests deeply, so that the parser recurses through it. The guard is neat. pdfblaze hands the
parser its data through a small wrapper, and the parser calls that wrapper's as_ref every time it
reads an object from the file. The wrapper measures how far the stack has moved since the opening
began, and stops the opening if it has moved too far:
impl AsRef<[u8]> for Watched {
fn as_ref(&self) -> &[u8] {
OPENING.with(|opening| {
// …
let depth = state.base.abs_diff(stack_position());
state.bytes = state.bytes.saturating_add(READ_BYTES + depth as u64 / 8);
if depth > MAX_STACK || state.bytes > MAX_BYTES {
state.too_large = true;
opening.set(Some(state));
resume_unwind(Box::new(Unopened::PageTree));
}
// …
});
&self.0
}
}
That catches recursion between objects, because each step of a page tree is a new read from the
file. It cannot see recursion inside one object. The parser reads the decompressed object once,
gets its bytes, and then recurses through them without reading anything else from the file. as_ref
is never called again until the stack is already gone. The guard was correct for the attack it was
written for, and blind to this one by construction.
The fuzzers that could not reach it
pdfblaze has fuzz targets for PDF images and for merge. They did not find this, and the reason is in one line of fuzz/run.sh: both cap their input at 64 KiB.
To overflow the stack with plain bytes you need a lot of them: 200,000 levels, about 400 KB, already overflow the 8 MiB main stack, and the render threads need more. Either way, well past 64 KiB. To do it within 64 KiB you need the compressed form, which means a fuzzer has to produce a valid Flate stream, inside a valid object stream, referenced from a valid cross-reference table, that happens to inflate to a deep array. Coverage-guided fuzzing is good at finding the branch that mishandles a byte; it is poor at constructing a compressed structure whose danger is only visible after decompression. The input cap made the plain form unreachable, and the structure made the compressed form improbable.
The lesson I took is not "fuzz harder". It is that a size cap on fuzz input is also an assumption about the attack, and this attack lives exactly where that assumption is wrong: in data that grows after the cap is applied.
The fix: a depth limit, from the parser's next version
The audit listed several options. A linear pre-scan of every object stream for bracket depth before handing it to the parser. Parsing PDFs in a child process, so an abort costs a process and not a worker. Or a fix in hayro-syntax itself.
The third had already happened upstream. hayro-syntax 0.8 skips nested objects with a depth counter and
gives up at 64 levels. pdfblaze could not simply upgrade: krilla pins hayro-syntax 0.7 and does its PDF
reading through it, so raising pdfblaze's own dependency would not change the parser that runs. So 1.4.2 carries a copy of hayro-syntax 0.7.2 in
vendor/hayro-syntax with that one change backported, and tells Cargo to use it in place of the
published crate:
# hayro-syntax 0.7.2 with the object nesting limit of 0.8 backported (vendor/README.md): krilla
# still pins 0.7, which overflows the stack on a deeply nested object in a PDF image or merge.
[patch.crates-io]
hayro-syntax = { path = "vendor/hayro-syntax" }
The change itself is small. Every skip function takes the depth it is at, passes depth + 1 to the
next call, and returns None at the limit:
fn skip_with_depth(r: &mut Reader<'_>, is_content_stream: bool, depth: usize) -> Option<()> {
if depth >= super::MAX_OBJECT_NESTING_DEPTH {
return None;
}
r.forward_tag(b"[")?;
loop {
r.skip_white_spaces_and_comments();
if let Some(()) = r.forward_tag(b"]") {
return Some(());
} else if is_content_stream {
r.skip_with_depth::<Object<'_>>(true, depth + 1)?;
} else {
r.skip_with_depth::<MaybeRef<Object<'_>>>(false, depth + 1)?;
}
}
}
Dictionaries get the same treatment. None is how this parser already says "I cannot read this
object", so everything above it already knew what to do: the deep object is unreadable, the PDF image
is drawn without it, and the process keeps running. A page whose own dictionary nests too deeply
cannot be read at all, and merge refuses that file with an error instead of aborting.
vendor/README.md says what was
changed, that nothing else differs from the published 0.7.2, and how to check that with one diff -r
against Cargo's registry copy. It also says when to delete the whole thing: once krilla moves to
hayro-syntax 0.8 or newer.
I chose the backport over the pre-scan because it puts the limit where the recursion is. A pre-scan is a second parser that has to agree with the first about strings, comments and streams; the day they disagree, the scan says "shallow" and the parser recurses anyway.
What it costs Rust users
There is a sharp edge here, and it belongs in the open. Cargo applies [patch.crates-io] only from the
top-level project being built. pdfblaze's own patch fixes the binaries and the C library, which are built
from pdfblaze's workspace. It does not reach a Rust project that depends on the pdfblaze crate. That
project resolves hayro-syntax 0.7.2 from crates.io and gets the unbounded recursion back.
So docs/rust.md now asks Rust users to add the patch themselves:
[dependencies]
pdfblaze = { git = "https://github.com/sundarshahi/pdfblaze", tag = "v1.4.3" }
# Needed for PDFs that come from users (images, merge).
[patch.crates-io]
hayro-syntax = { git = "https://github.com/sundarshahi/pdfblaze", tag = "v1.4.3" }
A security fix that each user must opt into by copying two lines is a weak fix for that audience, and
I would rather say so than let the release notes imply otherwise. The same applied inside the repository:
the fuzz targets are their own Cargo workspace, so fuzz/Cargo.toml needed the same patch, or the fuzzers
would have kept testing the old parser.
The guard tests
Two tests carry the audit's file. The repository keeps it as a test fixture; I am describing it here
rather than linking it, and the shape above is all a reader needs. The first renders it both as a
logo.png and as a PDF image, and expects a clean render with no diagnostics:
#[test]
fn survives_pdf_files_with_deeply_nested_objects() {
for src in ["logo.png", "t.pdf"] {
let output = render(
&format!("<img src={src}>"),
&[(src, fixture("pdf/deep-object.pdf"))],
);
assert_eq!(codes(&output), Vec::<&str>::new(), "{src}");
Pdf::new(output.pdf).expect("a PDF hayro reads");
}
}
The second, merges_pdfs_with_deeply_nested_objects, merges two files: one whose page dictionary holds a
200,000-level uncompressed array, which must be refused with an error, and the audit's file, which must
merge to one page without the deep object. It runs once with links and tags kept and once without.
Beyond the tests, the audit's proof of concept was run against the released binaries: the logo file exits 134 on 1.4.1, and renders on 1.4.2 and 1.4.3.
A second line, outside the engine
The CRM that prompted the audit does not rely on the engine alone. Before a customer's logo reaches a template, it checks the file's first bytes and accepts only PNG, JPEG or WebP. That was the stopgap the audit recommended before the fix existed, and it stays after: a logo has no reason to be a PDF in that product, so there is no reason to accept one. If your product does not need vector logos, do the same.
What I'd do differently, and what is still open
- Treat compression as a size multiplier everywhere. "The file's size bounds the work" is the sentence that let this through. It is true of raw bytes and false of anything that inflates. Every place that promises a bound in terms of input size should say which size: before or after decompression.
- Fuzz with a deep-nesting seed and a larger input cap. Not done yet. The fuzzers now test the patched parser, but they still cannot produce this input on their own.
- The exact call site. The audit attributed the overflow to the skip path by reading the code; a debugger backtrace of a five-million-frame overflow did not finish. The fix limits every skip, so the attribution does not change the fix, but I would like the backtrace.
- The C library crash was inferred, not run. Its build failed on the audit machine.
- Delete the vendor copy. When krilla moves to hayro-syntax 0.8 or newer, the vendored crate and both patches go, and Rust users can drop their two lines.
- Blast radius. A depth limit fixes this input. A parser bug I have not found yet could abort the process the same way. Opening untrusted PDFs in a short-lived child process would turn the next one into an error instead of a dead worker; that is worth measuring.