fix: a hostile PDF cannot hold the scanner: bounded DPI reading and a stuck scan is reported
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s

The DPI of a stored PDF is read in a subprocess killed after
PDF_MAX_SECONDS + 5; inside it, only image draws count toward
PDF_MAX_DRAWS (heavy vector art still reads), content streams are parsed
once per object, and the deadline is checked every 1000 operators. A scan
busy for more than SCAN_STUCK_SECONDS marks the scanner unhealthy and logs
one error to Sentry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 10:50:14 -03:00
parent 37d747697a
commit 7e33e6fb1d
4 changed files with 191 additions and 37 deletions

View File

@@ -32,6 +32,14 @@ PDF_VECTOR_DPI = 300
# grade them, so neither does this.
PDF_MAX_BYTES = 150 * 1048576
HEAD_BYTES = 1048576
# How much of a PDF's drawing is walked for its DPI: images and forms drawn
# (Do), however many paths a vector page has. A page whose forms draw other
# forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it
# held the scanner's one thread for hours and every upload behind it
# (security review, 2026-11-27). Past either limit the DPI is unknown, as for
# a format this cannot read, and the order is reviewed by a person.
PDF_MAX_DRAWS = 5000
PDF_MAX_SECONDS = 10
# Rounding in the browser and here can differ by a point on the same file.
TOLERANCE = 2
@@ -84,10 +92,27 @@ def _multiply(a, b):
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
class _TooMuch(Exception):
"""The PDF's drawing is larger than PDF_MAX_DRAWS or PDF_MAX_SECONDS."""
def pdf_dpi(path):
"""The page's area-weighted image DPI, 300 for vectors only, None if the
file is not a one-page PDF this can read."""
file is not a one-page PDF this can read, or draws more than it is worth
walking (PDF_MAX_DRAWS, PDF_MAX_SECONDS)."""
import time
import pikepdf
deadline = time.monotonic() + PDF_MAX_SECONDS
steps = [0]
parsed = {}
def instructions_of(stream):
# A form drawn many times is read once.
key = stream.objgen if stream.objgen != (0, 0) else id(stream)
if key not in parsed:
parsed[key] = pikepdf.parse_content_stream(stream)
return parsed[key]
try:
with pikepdf.open(path) as pdf:
if len(pdf.pages) != 1:
@@ -99,7 +124,9 @@ def pdf_dpi(path):
def walk(resources, instructions, ctm, depth):
stack = []
xobjects = resources.get('/XObject', {}) if resources is not None else {}
for operands, operator in instructions:
for count, (operands, operator) in enumerate(instructions):
if count % 1000 == 0 and time.monotonic() > deadline:
raise _TooMuch
op = str(operator)
if op == 'q':
stack.append(ctm)
@@ -108,6 +135,9 @@ def pdf_dpi(path):
elif op == 'cm':
ctm = _multiply(ctm, [float(v) for v in operands])
elif op == 'Do' and operands:
steps[0] += 1
if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline:
raise _TooMuch
xobject = xobjects.get(str(operands[0]))
if xobject is None:
continue
@@ -120,9 +150,14 @@ def pdf_dpi(path):
elif subtype == '/Form' and depth < 8:
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
walk(xobject.get('/Resources', resources),
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
instructions_of(xobject), _multiply(ctm, matrix), depth + 1)
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
except _TooMuch:
import logging
logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown',
os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS)
return None
except Exception:
return None
found = [(dpi, area) for dpi, area in found if dpi > 0]
@@ -132,14 +167,47 @@ def pdf_dpi(path):
return js_round(sum(dpi * area for dpi, area in found) / total)
def _pdf_dpi_child(result, path):
result.put(pdf_dpi(path))
def bounded_pdf_dpi(path):
"""pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF
library itself can be held by a file (a huge compressed stream), where
pdf_dpi's own limits cannot reach. None when it did not finish."""
import multiprocessing
from queue import Empty
context = multiprocessing.get_context('spawn')
result = context.Queue()
process = context.Process(target=_pdf_dpi_child, args=(result, path))
process.start()
try:
process.join(PDF_MAX_SECONDS + 5)
if process.is_alive():
process.kill()
process.join()
import logging
logging.warning('PDF %s took over %s s to read: its DPI is left unknown',
os.path.basename(path), PDF_MAX_SECONDS + 5)
return None
try:
return result.get(timeout=5)
except Empty:
return None
finally:
result.close()
result.join_thread()
def stored_pdf_dpi(storage, row):
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or
takes too long to read (bounded_pdf_dpi)."""
if row['size'] > PDF_MAX_BYTES:
return None
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
handle.flush()
return pdf_dpi(handle.name)
return bounded_pdf_dpi(handle.name)
class Files:

View File

@@ -124,46 +124,64 @@ def check_large(head, row):
return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome'
# When the scan of the file now in hand began (None between files): the
# worker's health reports a scan held on one file for longer than
# SCAN_STUCK_SECONDS, since every upload waits behind it.
busy_since=None
SCAN_STUCK_SECONDS=900
def stuck():
"""Whether the scan has been on the same file for SCAN_STUCK_SECONDS."""
return busy_since is not None and time.monotonic()-busy_since>SCAN_STUCK_SECONDS
def scan_one(storage, scanner=None):
global busy_since
scanner=scanner or ClamAV()
with connect() as c:
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
if not row:return False
name=row['name']
busy_since=time.monotonic()
try:
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes():
state,reason=check_large(head,row)
else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
# A PDF's resolution is worked out here, once, so checkout never reads
# it (Critical Corrections 2). A failure leaves it for the fallback.
checked,pdf_dpi_value=False,None
if state=='clean' and name.lower().endswith('.pdf'):
try:
pdf_dpi_value=stored_pdf_dpi(storage,row)
checked=True
except Exception:
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
_scan_row(c, storage, scanner, row)
finally:
busy_since=None
return True
def _scan_row(c, storage, scanner, row):
name=row['name']
try:
# Every later decision reads the stored name (the manual charge,
# the JPG refusal, the grade, the print file, the folders), so the
# name is made to say what the file is (D-13).
head=head_of(storage,row)
name=real_name(name,head)
if row['size'] > scan_limit_bytes():
state,reason=check_large(head,row)
else:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
# A PDF's resolution is worked out here, once, so checkout never reads
# it (Critical Corrections 2). A failure leaves it for the fallback.
checked,pdf_dpi_value=False,None
if state=='clean' and name.lower().endswith('.pdf'):
try:
pdf_dpi_value=stored_pdf_dpi(storage,row)
checked=True
except Exception:
logging.exception('Could not work out the PDF DPI of upload %s',row['id'])
c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END,
pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END,
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state, c=c)
def scan_loop(storage):
while True:
try:

View File

@@ -8,7 +8,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
import psycopg
from botocore.exceptions import ClientError
from psycopg.types.json import Jsonb
from . import mail, observability, unpaid
from . import mail, observability, scanning, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -205,13 +205,25 @@ def loop():
delay = 1
time.sleep(1)
scan_stuck_reported = False
class Health(BaseHTTPRequestHandler):
def do_GET(self):
global scan_stuck_reported
scanner = False
try:
scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping())
except Exception:
pass
# Alive but held on one file: every upload waits behind it.
if scanning.stuck():
scanner = False
if not scan_stuck_reported:
scan_stuck_reported = True
logging.error('The upload scan has been on one file for over %s min: every upload waits',
scanning.SCAN_STUCK_SECONDS // 60)
else:
scan_stuck_reported = False
renderer = bool(render_thread and render_thread.is_alive())
healthy = time.monotonic()-last_tick < 15 and scanner and renderer
self.send_response(200 if self.path == '/health' and healthy else 503)