This is part 6 of the series Printing a CRM's PDFs without Chrome.
pdfblaze 1.4.1 shipped a server guide with a pool of long-running workers for Rails, and a worker client for Ruby and Python to copy into an application. Under ordinary load, with no attacker at all, that pool could give one customer's PDF to the next customer. All it took was a request timeout at the wrong moment.
In the audit's proof of concept, a request for "Alice" timed out, and the next request, for "Bob", received 195,932 bytes: Alice's invoice. From then on every answer on that worker was one request behind. It was the second High finding, and it was fixed in 1.4.2. If you copied the worker client or the pool from 1.4.1's docs, copy them again from 1.4.3. Upgrading the binary alone does not fix this: the bug was in code you copied, not in the engine.
The CRM I wrote the guide for was never exposed. It starts one pdfblaze render process per document
and has no pool. That is the reason this bug is worth a post: it lived entirely in documentation and
examples, and the people it would have hurt are the ones who trusted them.
The worker protocol
pdfblaze worker is a process that renders one document after another over its standard input and
output, so fonts stay loaded and caches stay warm. Every message is a frame
(docs/protocol.md):
| Bytes | Content |
|---|---|
| 4 | length of the rest of the frame, little-endian |
| 1 | message type |
| 4 | length of the JSON header, little-endian |
| n | the JSON header |
| … | data blocks, raw bytes, no base64 |
The caller sends R (render) with an id in its header. The worker answers with P (the PDF) or E
(an error), and both carry the same id. A worker handles one request at a time and answers in order.
In between, it may ask the caller for resources, but for a plain render the exchange is one frame out
and one frame back.
That id is the whole defence against a mix-up, and in 1.4.1 nobody read it.
The pool as documented
The guide's pool keeps a queue of workers per Rails process. A request pops one, renders, and pushes it back. The question that matters for every pool is what goes back after a failure. In 1.4.1:
def self.render(html, **options)
worker = POOL.pop
worker ||= PdfblazeWorker.new(*ARGS)
pdf = worker.render(html, base: ROOT, **options)
# … (a worker is recycled after enough documents)
pdf
rescue PdfblazeWorker::WorkerError
worker = nil # it was stopped; the next document starts a new one
raise
ensure
POOL << worker
end
It reads well. If the worker broke, the client raised WorkerError and killed it, so the pool drops it.
Anything else goes back. The flaw is the word "anything". ensure runs for every exception, and only
one class of exception was treated as "this worker's state is unknown".
The client had the matching gap. Its request wrote the frame and returned whatever P came back:
type, answer, data = read_frame
case type
when "P"
@documents += 1
return data.first
It never compared answer["id"] with the id it had just sent.
How one timeout becomes a leak
Rails applications put timeouts around requests: Rack::Timeout, Timeout.timeout, a job runner's own
limit. Those raise an exception in the request's thread, wherever it happens to be. Say it is inside the
client, waiting for a large document:
- Alice's request takes the worker and sends
Rwith id 1. The worker starts rendering. - Rack::Timeout fires in Alice's thread. The exception is not
WorkerError, so nothing kills the worker. - The pool's
ensureputs the worker back. It is still rendering Alice's invoice. - The worker finishes and writes
Pwith id 1. Nobody is reading. - Bob's request takes the same worker and sends
Rwith id 2. - Bob's client reads the next frame on the pipe:
Pwith id 1. It does not check the id. Bob gets Alice's invoice. - The worker renders Bob's document and writes
Pwith id 2, which waits for whoever comes next.
Alice· now
waiting for id 1
worker
rendering Alice's invoice
Bob
idle
pipe: worker → caller
Alice takes the worker. The pool hands her its only worker. Her client sends R, request id 1: a large invoice.
Step 7 is what makes it worse than a single wrong document. The worker is now permanently one answer ahead of its callers. Each person gets the previous person's PDF until the worker happens to be replaced. And an attacker who can make their own renders slow, with a heavy template or a big upload, and can make their own requests time out, can pull other customers' documents out of a shared pool on purpose.
Why the tests did not catch it
The client did handle timeouts. Its own deadline raised WorkerError and killed the worker, and that
path was correct. The bug lived only on the path where something outside the client interrupted it,
and nothing in the examples did that.
Python had the same shape. Its client killed the worker only on answers it did not like. An interrupt
raised while it waited, a TimeoutError from a signal handler or a KeyboardInterrupt, went straight out
through the caller's finally, and the worker went back into the queue. The audit's Python proof of
concept leaked the same way.
There was a smaller cousin, too, which the audit listed separately. The clients put a deadline on the
first byte of a frame, then read the rest with no deadline at all. A worker that wrote half a frame and
stalled would hang the request forever. And on a short read, Ruby's frame.byteslice(1, 4) could return
nil, which raised NoMethodError, not WorkerError: one more way to put a broken worker back.
The fix
The fix is four rules, and each one alone would have stopped this particular leak. I applied all four because each covers a different way the next bug could arrive.
1. Any interruption stops the worker. The only failure that leaves a worker in a known state is a
DocumentError: the worker answered, the document was bad, the pipe is clean. Everything else, including
exceptions the client has never heard of, kills the process before re-raising:
rescue DocumentError
raise
rescue Exception # rubocop:disable Lint/RescueException
# Whatever ended the request (a timeout of the caller too) may leave its answer unread in the
# pipe, where the next request would take it for its own.
kill
raise
end
Rescuing Exception in Ruby is normally a smell. Here it is the point: the rescue does not swallow
anything, it only makes sure the worker cannot outlive an interrupted request. Python does the same with
except BaseException.
2. Every answer's id is checked. An answer to any other request means the worker is out of step, and
the client kills it and raises WorkerError rather than return someone else's document:
type, answer, data = read_frame
@max_rss = answer["maxRss"] if answer["maxRss"]
# An answer to another request means the worker is out of step: never hand it on.
raise WorkerError, answer["message"] if type == "E" && !answer.key?("id")
raise WorkerError, "answer #{answer["id"].inspect} to request #{@id}" unless answer["id"] == @id
This is the rule I trust most, because it does not depend on predicting how a worker gets out of step. Rule 1 closes the path I found. Rule 2 closes the ones I did not.
3. A whole frame has one deadline. Reading a frame is now read_exactly(size, deadline) twice, for the
length and for the body, with the time left recomputed before every partial read. A worker that stalls
mid-frame is killed when the deadline passes, and a short or broken frame becomes WorkerError.
4. The pool keeps only live workers. The client has an alive? method (alive in Python), false once
it was closed or killed, and the pool asks it instead of guessing from the exception class:
ensure
# Only a worker that can take the next document goes back. One that was closed, broke, or
# whose render was cut short (a timeout of the request, too) goes back as nil, and the next
# document starts a new one.
POOL << (worker&.alive? ? worker : nil)
end
A nil in the queue means "start one when needed", so the cost of a timeout is one process start on the
next request, not a leak.
Why kill and not drain
The other way to resynchronise is to read and discard the stale answer, keeping the warm worker. I did not do it. To drain safely you have to know how many answers are outstanding and wait for each, and the one you are waiting for belongs to a document that was slow enough to time out a request. Draining would move the timeout from Alice's request to Bob's. Killing costs a process start and nothing else, and it leaves no state to reason about.
Saying it where people will read it
The fix in code is half of it. The other half is making sure the next person who writes a client, in Node or Go or anything else, does not rebuild the same bug from the protocol docs. So 1.4.2 says it in three places:
- SECURITY.md, under remaining risks: a worker whose render was cut short is stopped, never reused.
- docs/server.md, in bold above the pool: never put back a worker whose render was cut short, and a client of your own must stop the worker, refuse an answer to any request but the one it sent, and not reuse it.
- Both example clients, in their header comment: check
alive?before reusing a worker.
Each example client also checks itself when you run the file on its own. It starts a large render, gives up on it from outside with a very short timeout, and asserts the worker is no longer alive; then it starts a fresh worker and expects a clean PDF. That self-check is the guard for this finding.
Why a docs bug is a real bug
The engine was right. The protocol was right: every answer carried the id of its request. The worker did exactly what it was asked. Every line of the leak was in code that pdfblaze did not run and that I had written as an illustration.
But nobody treats an example in a server guide as an illustration. It is the code that ships, because it is the fastest path to working. The pool snippet was correct on the happy path, which is the only path a reader tries before deploying it. The audit's job was to take the snippet as production code, and as production code it had a cross-tenant data leak.
The general rule I took from it: when a pool hands out stateful connections, the safe default is "put back only what you can prove is idle". The 1.4.1 pool did the opposite, "put back unless you can prove it broke", and every unknown exception fell on the wrong side of that line.
What I'd do differently, and what is still open
- Run the examples in CI. The self-checks run when you run the files. As far as I can see in the workflows, CI does not run them, so a regression in an example client would ship unnoticed. That is the next change.
- Review examples like code. The guide went out in 1.4.1 and the audit found this hours later. I would now hold a guide that shows a pool until the pool has a test that interrupts it.
- Other languages. The guide's one-process examples for Python, Node and Go are fine; any worker client someone writes for those languages must follow the same four rules. The protocol docs say so, but a reference client with tests would say it better.