[BUG] `LimitReachedError` escapes from `extract_text()` when a `/ToUnicode` `beginbfchar` source token exceeds the 16-hex cap
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
In pypdf/_cmap.py, process_cm_line treats a malformed CMap
mapping line as skippable with a warning. For beginbfchar the
guard is:
elif process_char:
try:
parse_bfchar(line, map_dict, int_entry)
except ValueError as error:
logger_warning("Skipping broken line %(line)r: %(error)s", source=__name__, line=line, error=error)
However, parse_bfchar also validates the source token with
_check_token_length, which raises LimitReachedError (a
PyPdfError subclass) when the <hex> code is longer than
MAX_CMAP_CODE_BYTES_LIMIT (16 hex chars = 8 bytes). Because
LimitReachedError is not a ValueError, that
except ValueError clause does not catch it, so the exception
escapes process_cm_line → _parse_to_unicode → get_encoding →
Font.from_font_resource and ultimately surfaces as an uncaught
LimitReachedError from the public PdfReader.extract_text().
The same except (ValueError, IndexError) on the beginbfrange branch
has the identical gap if an oversized token is encountered there.
Family: same class as the
read_objectcomment-recursion bug — "crafted /ToUnicode CMap → a pypdf internalLimitReachedErrorreaches the user as an uncaught exception instead of a handled/logged skip".
PoC
Minimal in-memory Type0 font with a /ToUnicode CMap whose
beginbfchar source token is 18 hex chars (9 bytes) — just over
the 16-hex (8-byte) cap. Calling get_encoding(font) (the
extract_text() entry) raises the uncaught LimitReachedError.
Verified on pypdf 6.19.0 (current main). A normal 4-hex source (<0041>) in
the identical CMap parses cleanly, confirming the trigger is the
oversized source token, not the CMap structure.
Code
import sys, pypdf
from pypdf._cmap import get_encoding, MAX_CMAP_CODE_BYTES_LIMIT
from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject
from pypdf.errors import LimitReachedError
print(f"MAX_CMAP_CODE_BYTES_LIMIT = {MAX_CMAP_CODE_BYTES_LIMIT} hex chars")
# Source is 9 bytes (18 hex) -> exceeds the 8-byte/16-hex cap.
source = b"01" * 9
body = (
b"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n"
b"/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n"
b"1 beginbfchar\n<" + source + b"> <0041>\nendbfchar\nendcmap\n"
b"CMapName currentdict /CMap defineresource pop\nend\nend"
)
tu = DecodedStreamObject()
tu.set_data(body)
ft = DictionaryObject()
ft[NameObject("/Type")] = NameObject("/Font")
ft[NameObject("/Subtype")] = NameObject("/Type0")
ft[NameObject("/BaseFont")] = NameObject("/SomeFont")
ft[NameObject("/Encoding")] = NameObject("/Identity-H")
ft[NameObject("/ToUnicode")] = tu
try:
get_encoding(ft) # extract_text() entry
print("parsed cleanly")
except LimitReachedError as e:
print("ESCAPED LimitReachedError:", e)
except BaseException as e:
print("other exception:", type(e).__name__, e)
Run inside a pypdf checkout (or adjust imports for an installed version). Output observed:
MAX_CMAP_CODE_BYTES_LIMIT = 16 hex chars
ESCAPED LimitReachedError: Maximum /ToUnicode code length exceeded: 18 > 16.
Traceback
Traceback (most recent call last):
File "cmap_oversize_source_e2e.py", line 73, in <module>
encoding, map_dict = get_encoding(ft)
File "pypdf/_cmap.py", line 51, in get_encoding
map_dict, int_entry = _parse_to_unicode(ft)
File "pypdf/_cmap.py", line 215, in _parse_to_unicode
process_rg, process_char, multiline_rg = process_cm_line(
File "pypdf/_cmap.py", line 296, in process_cm_line
parse_bfchar(line, map_dict, int_entry)
File "pypdf/_cmap.py", line 425, in parse_bfchar
_check_token_length(source, limit=MAX_CMAP_CODE_BYTES_LIMIT)
File "pypdf/_cmap.py", line 327, in _check_token_length
raise LimitReachedError(
pypdf.errors.LimitReachedError: Maximum /ToUnicode code length exceeded: 18 > 16.
Open questions for maintainers
- Should the
beginbfcharguard broaden toexcept (ValueError, LimitReachedError)(and thebeginbfrangearm likewise), making oversize tokens a skipped-with-warning line rather than a fatal escape? - Alternatively, should the size guard in
_check_token_length/parse_bfcharconvert the oversize condition into aValueErrorso the existing catch already handles it?
Should the
beginbfcharguard broaden toexcept (ValueError, LimitReachedError)(and thebeginbfrangearm likewise), making oversize tokens a skipped-with-warning line rather than a fatal escape?
Which effects would this have? Reaching such limits tends to indicate some broken or possibly malicious file, thus they are denied at the moment. Are you able to provide a real-world example triggering this behavior?
Alternatively, should the size guard in
_check_token_length/parse_bfcharconvert the oversize condition into aValueErrorso the existing catch already handles it?
LimitReachedError is a security-related exception and should not be a subclass of a ValueError, unless there a explicit reasons to use a ValueError instead of a LimitReachedError at the specific location.
I don't have any real malicious file for testing at the moment, and I think the reason for the security restrictions you mentioned is legitimate, so I won't proceed with this change for now