Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 16 min read

11 Minutes to Arbitrary File Write: The MONAI Label Zero-Day an AI Agent Found on Its Own

On 20 November 2026 at 17:30 UTC, Amazon's CISO published a threat intelligence report that reads like a single sentence: an operator handed an open-source autonomous penetration-testing framework called Cairn a target l

On 20 November 2026 at 17:30 UTC, Amazon's CISO published a threat intelligence report that reads like a single sentence: an operator handed an open-source autonomous penetration-testing framework called Cairn a target list and one plain-language objective β€” "obtain shell access" β€” and the agents found a zero-day in an open-source medical imaging application, then used it to take full control of a server.

The application was MONAI Label, the labelling server from the MONAI consortium (NVIDIA, Kitware, and academic partners) that research hospitals and university labs use to annotate MRI and CT studies. One path traversal became an arbitrary file write, and that became a root reverse shell. The CVE is CVE-2026-133968, CVSS 3.1 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H). NVD's description ends with the part that matters operationally: "as exploited in the wild starting in September 2026."

This article is not about the narrative. It is about why one upload path in this application hands over filesystem write access, and why, a month after the fix was merged, nobody can install it. The second question is the one a practitioner actually has to act on today.

1. Sixteen hours of failure, eleven minutes of success

Amazon Threat Intelligence found the Cairn instance on 10 September 2026. The operator had left it reachable without authentication, which meant project configuration, operator prompts and agent execution history were readable by anyone on the internet. The prompts were written in Simplified Chinese; timestamps inside executed scripts were set to China Standard Time. The campaign began on 8 September and ran roughly 48 hours against IP addresses belonging to universities in East Asia outside mainland China.

The same framework produced radically different results depending on the target.

Target Effort Outcome
University Redis (unauthenticated) ~16 hours, 148 sequential actions Failed
University GPU server 6+ hours, ~80 real usernames, 30,000+ credential combinations Failed
MONAI Label server API mapping, then parameter probing Arbitrary file write in ~11 minutes

The Redis attempt was elaborate by any standard: abusing replication to load unauthorized code, escaping the scripting sandbox, writing configuration files, corrupting memory, and throwing Log4Shell at another service on the same host. All of it failed. The agents then mapped the internal Docker topology through an SSRF in a co-located Qdrant instance and sprayed credentials at PostgreSQL and SSH. That failed too. The GPU server operation was blunter still: roughly 80 real usernames harvested from faculty directories, lab websites, archived pages and papers, then more than 30,000 combinations against SSH, an admin dashboard, a NAS, a VPN and the campus portal. No working login.

The medical imaging application took eleven minutes. The agents fingerprinted the framework, mapped the API, and probed the upload endpoint's filename parameter with traversal strings. That was enough. Amazon assesses with high confidence that this was a zero-day, based on the absence of any corresponding fix, issue, advisory or vulnerability-database mention at the time.

In a later session the agents used the same flaw to write a Python reverse shell payload into sitecustomize.py β€” a file Python imports automatically at interpreter startup β€” then triggered a training API endpoint to spawn a new Python process. That process imported the payload and established a reverse shell running as root. Afterwards the human operator supplied the agents with a proxy tunnelling into a second university network; the server behind it ran the same vulnerable software, and Amazon infers it had already been compromised the same way. The victim organizations were not disclosed.

2. Where a string becomes a path

MONAI Label is a FastAPI server. Its datastore keeps images and labels on the filesystem and indexes them in datastore.json. The bug lives where the identifier namespace and the path namespace are the same string.

The vulnerable upload endpoint (0.8.5 and earlier):

# monailabel/endpoints/datastore.py:211 (pre-fix, base 0b1ee41)
@router.put("/image", summary=f"{RBAC_ANNOTATOR}Upload new Image")
async def api_add_image(
    background_tasks: BackgroundTasks,
    image: Optional[str] = None,          # query parameter, caller-controlled
    params: str = Form("{}"),
    file: UploadFile = File(...),
    user: User = Depends(RBAC(settings.MONAI_LABEL_AUTH_ROLE_ANNOTATOR)),
):
    return add_image(background_tasks, image, params, file, user.username)


def add_image(background_tasks, image=None, params="{}", file=None, user=None):
    file_ext = "".join(pathlib.Path(file.filename).suffixes) if file.filename else ".nii.gz"

    # when image is supplied, it becomes the ID with no basename and no validation
    image_id = image if image else os.path.basename(file.filename).replace(file_ext, "")

Note what os.path.basename applies to: the uploaded file's name. A value passed directly as the image query parameter is never normalized. Down in the datastore:

# monailabel/datastore/local.py:434 (pre-fix)
def add_image(self, image_id: str, image_filename: str, image_info) -> str:
    id, image_ext = self._to_id(os.path.basename(image_filename))
    if not image_id:
        image_id = id

    name = self._filename(image_id, image_ext)        # return id + ext
    dest = os.path.realpath(os.path.join(self._datastore.image_path(), name))

    with FileLock(self._lock_file):
        shutil.copy(image_filename, dest)             # resolved path never checked

os.path.realpath() is not a validation function. It normalizes .. and returns; nobody asks whether the result is still inside the datastore. Pass image=../../../opt/monailabel/sitecustomize and name becomes ../../../opt/monailabel/sitecustomize.nii.gz, and shutil.copy writes wherever the process can write. The extension is caller-controlled too: _to_id() compares the suffix against the datastore's allowed extension list only to decide what to display, while the write path takes the suffix straight from the uploaded filename. Upload something ending in .py and a .py file lands on disk.

Label saving carries the same defect one layer further:

# monailabel/datastore/local.py:476 (pre-fix)
def save_label(self, image_id, label_filename, label_tag, label_info) -> str:
    obj = self._datastore.objects.get(image_id)
    if not obj:
        raise ImageNotFoundException(f"Image {image_id} not found")

    label_path = self._datastore.label_path(label_tag)   # labels_dir + tag
    name = self._filename(image_id, label_ext)
    dest = os.path.join(label_path, name)

    with FileLock(self._lock_file):
        os.makedirs(label_path, exist_ok=True)           # creates attacker-chosen directories
        shutil.copy(label_filename, dest)

label_tag is a query parameter on PUT /datastore/label whose only default is final, and label_path(tag) is os.path.join(labels_dir, tag). Because os.makedirs() runs first, the attacker gets directory creation at an arbitrary location before any file write. The "image must already exist" condition is not a barrier either: a traversal ID from add_image is registered in the objects dictionary as a perfectly normal key, so the same string can come back through save_label. The regression test added with the fix checks exactly this composition.

Then there is the default. In monailabel/config.py:32, MONAI_LABEL_AUTH_ENABLE: bool = False. With authentication off, the RBAC dependency returns without checking roles at all (endpoints/user/auth.py:127-129). Even with authentication on, the ANNOTATOR role is sufficient β€” and that is the role you give the people whose job is uploading images. This is not privilege escalation so much as the intended privilege, applied to a path that was never meant to be part of the input.

Author's note: the Amazon report says "an upload endpoint with a filename parameter" without naming the parameter. image is specified by the advisory and by NVD. The distinction that matters is that it is a query parameter, not the multipart filename field. This is not a body-parsing bug; it reproduces from a single URL.

3. One file write, then root

Arbitrary file write is only interesting because of what you can write. Next to a Python server there is an unusually good target: a file the next Python process will execute on its own.

The standard library's site module tries to import sitecustomize at the end of interpreter initialization. If the file is missing it passes silently. If it exists, it runs, unconditionally. There are three places that file can live and still be found: the current working directory (which becomes sys.path[0] under python -m), any directory on PYTHONPATH, and site-packages.

MONAI Label's training path opens two of those by itself.

# monailabel/main.py:313-314 (server startup)
os.environ["PATH"] += os.pathsep + os.path.join(args.app, "bin")
os.environ["PYTHONPATH"] = os.environ.get("PYTHONPATH", "") + os.pathsep + os.path.join(args.app)

The server pushes its own app directory onto PYTHONPATH. Training then runs as a separate process:

# monailabel/utils/async_tasks/utils.py:34, 55-67
my_env = {**os.environ}                      # PYTHONPATH inherited
cmd = [sys.executable, "-m", "monailabel.interfaces.utils.app",
       "-m", method, "-r", json.dumps(request, separators=(",", ":"))]
process = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                           universal_newlines=True, env=my_env)

The trigger is POST /train/{model}. With authentication off, that endpoint carries only an RBAC_ADMIN label and anyone who can reach the port can call it. One request starts a sys.executable -m ... child, which inherits PYTHONPATH including the app directory, and therefore finds sitecustomize. If a payload is sitting there, the shell opens. The privileges are the server process's privileges, and the official container image has no USER directive in its Dockerfile β€” root by default, which matches the root reverse shell Amazon observed.

PUT /datastore/image?image=../../../opt/monailabel/sitecustomize
  └─ LocalDatastore.add_image()  β†’  shutil.copy(tmp, /opt/monailabel/sitecustomize.py)
                                        (no execute permission needed, just a write)

POST /train/{model}
  └─ AsyncTask.run β†’ subprocess.Popen(sys.executable -m monailabel.interfaces.utils.app ...)
        env: PYTHONPATH=/opt/monailabel:...      ← main.py:314
        └─ site.execsitecustomize() β†’ import sitecustomize β†’ reverse shell (root)

There is one more reason this target fell in eleven minutes, and it is in the code. monailabel/app.py:57-60 builds the FastAPI app with openapi_url="/openapi.json" left on; docs_url is None, but a /docs route is registered against the same schema. The server therefore publishes its endpoint list and every parameter's name, location and type as machine-readable JSON β€” including the fact that image is a query parameter of type string. What Amazon describes as "mapped its API endpoints" may be a single GET /openapi.json.

That is not a vulnerability. It is a framework feature, and usually a good one. But for automated attackers it means enumeration costs nothing: choosing which parameters to throw traversal strings at stops being a heuristic and becomes a schema walk. PUT /datastore/image takes image; PUT /datastore/label takes image and tag; POST /train/{model} takes model. Those three lines are the entire chain.

The technically interesting part is what the chain does not contain: no memory corruption, no kernel exploit, no credential theft. It contains a write permission and a filename that executes itself. Set that against the two targets that resisted for a day β€” services that were unauthenticated yet still hardened β€” and the scoreboard is clear. The agents beat an input parser that validated nothing, and lost to password and permission boundaries.

Item Value
Campaign window Started 2026-09-08, ~48 hours
Cairn instance found 2026-09-10 (unauthenticated, prompts and history exposed)
Fix merged 2026-10-19 13:37:36Z, PR #1915, commit 113527bf
GHSA published 2026-11-18 (GHSA-qc22-rmgc-vg94, Critical, CWE-22)
CVE published 2026-11-20 19:18 UTC (CVSS 9.8, CWE-24)
Zero-day assessment Amazon, high confidence (no prior fix, issue, advisory or DB mention)
Attribution Chinese-nexus, moderate confidence (Simplified Chinese prompts, CST timestamps, targeting)
IoCs 142[.]4.98.145, 142[.]4.107.34 (records dated 2026-09-08 to 09-10)

The confidence qualifiers are worth preserving. Amazon rates the Chinese nexus as moderate and explicitly does not establish government involvement or a named group. Treating the incident purely as state hacking removes the part defenders can use. What defenders can use is not the victims' nationality; it is which class of defect fell in eleven minutes.

4. Merged 19 October, still uninstallable on 22 November

The fix is PR #1915, fix: confine datastore write paths: nine commits, eleven files, +133/βˆ’10. The security-relevant change is 33 lines across two files.

The core is a new static method:

# monailabel/datastore/local.py (post-fix, +25 lines)
@staticmethod
def _confine_path(dest: str, allowed_base: str) -> str:
    dest = os.path.realpath(dest)
    allowed_base = os.path.realpath(allowed_base)
    try:
        inside = os.path.commonpath([dest, allowed_base]) == allowed_base
    except ValueError:
        # e.g. Windows paths on different drives have no common path
        inside = False
    if not inside:
        raise ValueError(f"Invalid path: {dest!r} is not inside {allowed_base!r}")
    return dest

Two call sites changed:

# add_image
- dest = os.path.realpath(os.path.join(self._datastore.image_path(), name))
+ dest = self._confine_path(os.path.join(self._datastore.image_path(), name),
+                           self._datastore.image_path())

# save_label β€” the label directory itself is confined to the labels root
  label_path = self._datastore.label_path(label_tag)
+ labels_root = self._datastore.label_path(None)
+ label_path = self._confine_path(label_path, labels_root)
  name = self._filename(image_id, label_ext)
- dest = os.path.join(label_path, name)
+ dest = self._confine_path(os.path.join(label_path, name), label_path)

The second block is the quiet, important half. Fixing only add_image would have left the label tag as an equivalent route. And because the confined label_path is then reused as the allowed_base for the final file path, the directory and the filename are sealed independently.

The endpoint layer also gained normalization:

# monailabel/endpoints/datastore.py (+6 lines)
image_id = image if image else os.path.basename(file.filename).replace(file_ext, "")
if image:
    image_id = os.path.basename(image_id)
    if not image_id or image_id in (".", "..") or image_id.startswith("."):
        raise HTTPException(status_code=400, detail="Invalid image ID")

../../x collapses to x, and a bare .. is a 400. The deprecated PUT /datastore/ alias routes into the same handler, so it is covered too. Regression coverage lives in tests/unit/datastore/test_local_datastore_path_confinement.py (71 lines): image ID escape, label tag escape, and image ID escape at label-save time, plus a check that ordinary uploads still work. The PR body reports the full unit suite at 174 passed, 2 xfailed.

A few engineering observations on the patch itself.

Why endpoint normalization alone is insufficient. LocalDatastore is called from the HTTP layer, from the Python API, from CLI and batch scripts, and from app code. Validation placed in the HTTP layer grows a hole every time a caller is added β€” and save_label's tag receives no normalization at the endpoint at all. _confine_path() in the datastore is the only place that covers every caller.

Properties of realpath plus commonpath. realpath resolves symlinks, so a symlink inside the datastore pointing outward is rejected. Not using a prefix comparison was also the right call: /data/studies_evil starts with the string /data/studies, while commonpath compares path components. What remains is a TOCTOU window between the check and shutil.copy. Exploiting it requires local write access to the datastore directory, so practical risk is low, but the guarantee is only that the path checked and the path written share the same string.

What was left alone. remove_image() still computes os.path.realpath(os.path.join(image_path, name)) and deletes it. It only operates on registered IDs, so it is not arbitrary deletion, but the same string-to-path composition remains. Half of the PR's eleven files are also unrelated CI repair β€” removing the Python 3.9 matrix (#1918), fixing a SimpleITK dependency problem (#1919) that was already failing on main.

Then there is distribution, which is the most practically important part of this incident.

Check Value (queried 2026-11-22 09:00 KST)
GHSA vulnerable_version_range <= 0.8.5
GHSA patched_versions empty β€” "The fix will be included in the next MONAI Label release."
PyPI latest monailabel 0.8.5 (uploaded 2024-11-25)
Latest GitHub release 0.8.5 (2023-10-18)
Default branch continues past the fix (c09d9978, 2026-11-21)

The AWS post says the maintainers "released a fix and a GitHub Security Advisory," and coverage repeated that as a patched release. A source merge and an installable release are not the same thing. Anyone on 0.8.5 or earlier cannot close this with pip install -U monailabel. That distinction disappearing into the phrase "patch available" is how a false sense of remediation spreads.

The maintainers know. On 19 November, PR #1940 (af39c0c1) added a warning at the top of the README:

Security notice: MONAI Label is not intended to be run as an internet-facing application.
There are a number of known, unpatched security issues that make MONAI Label fragile when it is exposed to untrusted networks.

Read the plural. This is not a product that becomes safe when one CVE is closed. Its attack surface assumes an authenticated or unexposed deployment, and deployments that skipped both are the ones this campaign found.

5. If you run this server

MONAI Label deployments usually sit inside a closed research network, but demo, collaboration and remote-reading setups leave ports open more often than the documentation implies. Here is a check order that runs.

pip show monailabel | grep -E '^(Name|Version)'
# If unset, authentication is off and upload plus training APIs are open
grep -rn 'MONAI_LABEL_AUTH_ENABLE' .env 2>/dev/null || echo 'MONAI_LABEL_AUTH_ENABLE unset -> default False'

Three indicators for whether you were already hit:

# 1) traversal-shaped IDs in the datastore index
python3 - <<'EOF'
import json, glob
for f in glob.glob('/path/to/studies/datastore.json'):
    d = json.load(open(f))
    for k in d.get('objects', {}):
        if '/' in k or '\\' in k or '..' in k or k.startswith('.'):
            print('SUSPICIOUS ID:', f, repr(k))
EOF

# 2) startup files that execute themselves inside the app directory
find /opt/monailabel /path/to/app -maxdepth 2 \( -name 'sitecustomize.py' -o -name 'usercustomize.py' \)

# 3) traversal strings in upload requests (uvicorn access log or proxy log)
grep -E 'PUT /datastore/(image|label)' app.log | grep -E 'image=.*(%2e%2e|\.\.)|tag=.*(%2e%2e|\.\.)'

The third check depends on log format. uvicorn's default access log records the path without the query string, so you need a reverse proxy or middleware that keeps queries. If nothing keeps them, turning that on is the first incident-response step, not the last.

Mitigations are the advisory's three, plus an install path.

Control Action Limit
Authentication MONAI_LABEL_AUTH_ENABLE=True, ANNOTATOR only for trusted users ANNOTATOR still reaches the same code path
Network No exposure to the internet or untrusted networks, proxies included A remote-reading workflow is itself an exposed surface
Least privilege Dedicated account, no write access outside the datastore If the app directory is writable, the sitecustomize route survives
Patched source Pin the merge commit, as below Move back to a release once one exists
pip install "monailabel @ git+https://github.com/Project-MONAI/MONAILabel@113527bf638585ee5de6a1839b985829331ea272"

Pinning buys reproducibility. Following the default branch means running an unknown future state; when a release tag appears, returning to pip install -U monailabel is the better maintenance posture.

A detection rule needs two axes, not one: traversal components in upload parameters, and the server process spawning a child interpreter of itself. The second is normal during training, so the signal is a new sitecustomize appearing in a directory that is on PYTHONPATH. Watching file creation in the app directory (inotify, auditd) breaks this chain before execution. And if your training processes run as root, the prior question is why they run as root at all.

6. What stays

Reading this as "AI replaced a human" prepares nobody for the next incident. Two things were actually observed. First, the failures stayed failures. An unauthenticated Redis instance and thirty thousand credential combinations did not get in, despite nearly a day of tireless adaptation; the targets were merely slightly hardened. Second, the success came from the laziest layer: an upload parameter that became a filename and then a path, and an authentication default of off.

What remains for defenders is speed. Eleven minutes from API mapping to file write is shorter than most SOCs take to triage one alert. Amazon closes on the same note: attach automated response to high-confidence detections and have humans supervise outcomes rather than review each action. Applied here, "traversal string in the MONAI Label upload parameter" is a rule-level block, not a human decision.

The tool's dual use is worth stating plainly. Cairn was built as a research and problem-solving engine for defenders; give it a target list and a plain-language objective and its agents plan, execute and adjust. That ease is the offensive ease. Amazon cites an earlier Gambit Security report in which a different operator used the same framework for at least 105 attacks and compromised 27 companies to varying degrees (per press coverage). Espionage and financial crime now diverge above a shared tool. The boundary is not the tool; it is the set of targets the tool can reach.

Finally, what is verified and what is not. The victim universities were not disclosed. The zero-day assessment is Amazon's own, high confidence. The Chinese-nexus attribution is moderate confidence. And right now this vulnerability has a CVE, an advisory and a merge commit, but no installable package. The question worth asking this morning is not whether a patch exists, but whether the thing you are running contains that commit.

Primary sources: Amazon Security Blog, "Chinese-nexus actor's Cairn AI agents found a zero-day on their own" (CJ Moses, 2026-11-20 17:30 UTC) Β· GitHub Security Advisory GHSA-qc22-rmgc-vg94 (2026-11-18) Β· fix PR #1915, merge commit 113527bf638585ee5de6a1839b985829331ea272 (2026-10-19) Β· NVD CVE-2026-133968 (2026-11-20) Β· PyPI and GitHub Releases queried 2026-11-22. Code excerpts are from pre-fix base commit 0b1ee41 and the merge commit; the makedirs behaviour in the label path was read directly from that source.

Originally published in Korean at dohyeontech.github.io.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.