[BUG] Unbounded recursion in `read_object` on consecutive `%` comments (raw `RecursionError`)
Environment
$ python -m platform
# Python 3.12, pypdf 6.19.0 (also present in current main)
$ python -c "import pypdf;print(pypdf.__version__)"
6.19.0
Description
When pypdf.generic.read_object is called on a stream whose object position is
followed by N consecutive % comment lines, each comment causes the % branch
(pypdf/generic/_data_structures.py, lines 1577-1582) to recurse:
if tok == b"%":
# comment
skip_over_comment(stream)
tok = read_non_whitespace(stream)
stream.seek(-1, 1)
return read_object(stream, pdf, forced_encoding) # <-- +1 frame
There is no depth counter / limit on this recursion. A crafted input with ~950 or
more such comment lines drives the interpreter past Python's default recursion
limit (1000), and a raw RecursionError propagates up to the caller instead of a
typed pypdf exception (PyPdfError / LimitReachedError).
Contrast: the trailer/xref path in the same area of the codebase caps its scan with a
_MAX_STARTXREF_RECOVERY_LINES = 1000guard (explicitly documented as preventing unbounded scan on crafted files). Theread_objectcomment path lacks the equivalent. Same family as the CMapLimitReachedErrorescape ("crafted input -> raw/untyped exception reaches the user"; tracked separately).
PoC (minimal, deterministic)
Feed read_object a stream of N %pad{i}\n lines (i = 0..N-1) followed by 42\n, where 42 is the
single real object. Verified on pypdf 6.19.0 (also current main):
pypdf 6.19.0 recursion-limit 1000
comments= 0 -> OK NumberObject=42
comments= 1 -> OK NumberObject=42
comments= 10 -> OK NumberObject=42
comments= 100 -> OK NumberObject=42
comments= 500 -> OK NumberObject=42
comments= 900 -> OK NumberObject=42
comments= 950 -> OK NumberObject=42 <-- cliff
comments= 998 -> RecursionError
comments= 999 -> RecursionError
comments= 1000 -> RecursionError
comments= 2000 -> RecursionError
Code
Minimal reproduction (no PDF file needed - pure in-memory stream):
import io, sys, pypdf
from pypdf.generic._data_structures import read_object
def run(n):
p = io.BytesIO()
for i in range(n):
p.write(b"%pad " + str(i).encode() + b"\n") # each => +1 read_object frame
p.write(b"42\n") # the ONE real object
p.seek(0)
try:
obj = read_object(p, None)
return f"OK {type(obj).__name__}={obj}"
except RecursionError:
return "RecursionError"
print("pypdf", pypdf.__version__, "recursion-limit", sys.getrecursionlimit())
for n in (0, 1, 10, 100, 500, 900, 950, 998, 999, 1000, 1001, 1100, 2000):
print(f"comments={n:>5} -> {run(n)}")
Traceback
Traceback (most recent call last):
...
File ".../pypdf/generic/_data_structures.py", line 1582, in read_object
return read_object(stream, pdf, forced_encoding)
[recursion repeated]
RecursionError
Open questions for maintainers
- Cap value: expose via
Configuration, or keep private (align with the_MAX_STARTXREF_RECOVERY_LINESprecedent)? - On cap hit, raise
LimitReachedError(vs anotherPyPdfError)? - Regression test: exactly cap-1 comments parse fine, cap triggers the typed exception (not
RecursionError)?
Cap value: expose via
Configuration, or keep private (align with the_MAX_STARTXREF_RECOVERY_LINESprecedent)?
I would start with a sensible and large enough default limit, without providing a configuration value, as 1000 is the natural upper limit at the moment anyway.
Please note that this does not only affect comments, but all deeply nested objects as far as I remember.
On cap hit, raise
LimitReachedError(vs anotherPyPdfError)?
How do other similar cases in our code handle this?
Regression test: exactly cap-1 comments parse fine, cap triggers the typed exception (not
RecursionError)?
What exactly is to be decided about this here?
Thanks for the guidance. Existing guards use LimitReachedError, for example the Root object recovery limit in _reader.py and the /ToUnicode mapping-size limit in _cmap.py. I followed those precedents in #4150, with a fixed, non-configurable limit of 1000 leading comments.
My test question was just about the boundary, not a separate design decision: the PR allows 1000 comments and raises LimitReachedError on the 1001st, before scanning that extra comment.
Thanks also for pointing out deeply nested objects. This PR only removes recursion from consecutive comment handling; it does not address general object-nesting depth.