From 7e33e6fb1d899ae249efc5c7f2d1bae5cc1a7368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 30 Nov 2026 10:50:14 -0300 Subject: [PATCH] fix: a hostile PDF cannot hold the scanner: bounded DPI reading and a stuck scan is reported 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 --- app/grade_check.py | 78 ++++++++++++++++++++++++++++++++++++--- app/scanning.py | 78 ++++++++++++++++++++++++--------------- app/worker.py | 14 ++++++- tests/test_grade_check.py | 58 ++++++++++++++++++++++++++++- 4 files changed, 191 insertions(+), 37 deletions(-) diff --git a/app/grade_check.py b/app/grade_check.py index bdb2ba2..d6359b8 100644 --- a/app/grade_check.py +++ b/app/grade_check.py @@ -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: diff --git a/app/scanning.py b/app/scanning.py index a796bc9..42a9a84 100644 --- a/app/scanning.py +++ b/app/scanning.py @@ -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: diff --git a/app/worker.py b/app/worker.py index be87921..f4bc371 100644 --- a/app/worker.py +++ b/app/worker.py @@ -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) diff --git a/tests/test_grade_check.py b/tests/test_grade_check.py index 174865c..d1aa0e7 100644 --- a/tests/test_grade_check.py +++ b/tests/test_grade_check.py @@ -105,7 +105,7 @@ class GradeCheckTests(unittest.TestCase): storage = CountingStorage({'k.pdf': b'%PDF-1.4 test', 'k.png': encoded('PNG', (100, 50))}) files = grade_check.Files(storage) pdf_row = {'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf'} - with mock.patch.object(grade_check, 'pdf_dpi', return_value=300): + with mock.patch.object(grade_check, 'bounded_pdf_dpi', return_value=300): self.assertEqual(files.pdf_dpi(pdf_row), 300) self.assertEqual(files.pdf_dpi(pdf_row), 300) self.assertEqual(storage.downloads, 1) @@ -158,6 +158,62 @@ class GradeCheckTests(unittest.TestCase): self.assertIn('confirme a ressalva', issue(199.4)) +def nested_forms_pdf(path, fanout=10, levels=8): + """A 2 KB PDF whose page draws form F0 ten times, F0 draws F1 ten times, + eight deep: 10^8 draws for a reader that walks them.""" + pdf = pikepdf.new() + pdf.add_blank_page(page_size=(200, 200)) + forms = [] + for level in reversed(range(levels)): + if forms: + content = b''.join(b'q /F%d Do Q\n' % (level + 1) for _ in range(fanout)) + resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F%d' % (level + 1): forms[0]})) + else: + content, resources = b'0 0 1 1 re f\n', pikepdf.Dictionary() + form = pikepdf.Stream(pdf, content) + form.Type, form.Subtype, form.BBox, form.Resources = (pikepdf.Name.XObject, pikepdf.Name.Form, + [0, 0, 1, 1], resources) + forms.insert(0, pdf.make_indirect(form)) + page = pdf.pages[0] + page.obj.Resources = pikepdf.Dictionary(XObject=pikepdf.Dictionary({'/F0': forms[0]})) + page.obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b''.join(b'q /F0 Do Q\n' for _ in range(fanout)))) + pdf.save(path) + + +class HostilePdfTests(unittest.TestCase): + """A tiny PDF must not hold the scanner's one thread (security review, + 2026-11-27): it held it for hours, and every upload behind it.""" + + def test_nested_forms_end_unknown_in_seconds(self): + import time + with tempfile.NamedTemporaryFile(suffix='.pdf') as handle: + nested_forms_pdf(handle.name) + start = time.monotonic() + self.assertIsNone(grade_check.pdf_dpi(handle.name)) + self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 2) + start = time.monotonic() + self.assertIsNone(grade_check.bounded_pdf_dpi(handle.name)) + self.assertLess(time.monotonic() - start, grade_check.PDF_MAX_SECONDS + 10) + + def test_a_heavy_vector_page_is_still_read(self): + # Vector art has many paths and few draws: only draws are counted. + pdf = pikepdf.new() + pdf.add_blank_page(page_size=(200, 200)) + pdf.pages[0].obj.Contents = pdf.make_indirect(pikepdf.Stream(pdf, b'0 0 1 1 re f\n' * 200000)) + with tempfile.NamedTemporaryFile(suffix='.pdf') as handle: + pdf.save(handle.name) + self.assertEqual(grade_check.pdf_dpi(handle.name), grade_check.PDF_VECTOR_DPI) + + def test_a_scan_held_on_one_file_is_reported(self): + from app import scanning + import time + self.assertFalse(scanning.stuck()) + with mock.patch.object(scanning, 'busy_since', time.monotonic() - scanning.SCAN_STUCK_SECONDS - 1): + self.assertTrue(scanning.stuck()) + with mock.patch.object(scanning, 'busy_since', time.monotonic()): + self.assertFalse(scanning.stuck()) + + class ProportionTests(unittest.TestCase): """A file laid out at proportions it does not have is refused before payment, not found at print time (a 5 m sheet sent as 10 cm)."""