VAITP Dataset

← Back to the dataset

CVE-2024-5452

RCE vulnerability in pytorch-lightning due to improper deserialization handling.

  • CVSS 9.8
  • CWE-913
  • Input Validation and Sanitization
  • Remote

A remote code execution (RCE) vulnerability exists in the lightning-ai/pytorch-lightning library version 2.2.1 due to improper handling of deserialized user input and mismanagement of dunder attributes by the `deepdiff` library. The library uses `deepdiff.Delta` objects to modify application state based on frontend actions. However, it is possible to bypass the intended restrictions on modifying dunder attributes, allowing an attacker to construct a serialized delta that passes the deserializer whitelist and contains dunder attributes. When processed, this can be exploited to access other modules, classes, and instances, leading to arbitrary attribute write and total RCE on any self-hosted pytorch-lightning application in its default configuration, as the delta endpoint is enabled by default.

CVSS base score
9.8
Published
2024-06-06
OWASP
A01 Broken Access Control
Orthogonal defect classification
Function
Code defect classification
Incorrect Check
Category
Input Validation and Sanitization
Subcategory
Insecure Parsing or Deserialization
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
lightning-ai
Fixed by upgrading
Yes

Solution

Upgrade to lightning-ai/pytorch-lightning version 2.2.2 or later.

Vulnerable code sample

from deepdiff import Delta
import os

def deserialize(delta_serialized):
    """Vulnerable function that demonstrates the security issue."""
    delta = Delta.from_dict(delta_serialized)
    return delta

    delta_serialized = {
    'some_attribute': 'new_value',
    '__setattr__': 'os.system("touch /tmp/pwned")'
    }

    delta = deserialize(delta_serialized)

    class Target:
        def __init__(self):
            """Vulnerable function that demonstrates the security issue."""
            self.some_attribute = 'original_value'
            self.__dunder_attribute__ = 'original_dunder_value'

            def __setattr__(self, name, value):
                """Vulnerable function that demonstrates the security issue."""
                if name == '__setattr__':
                    try:
                        exec(value)
                        except Exception as e:
                            print(f"Error executing __setattr__: {e}")
                        else:
                            super().__setattr__(name, value)

                            target_instance = Target()
                            print("Before:", target_instance.some_attribute, target_instance.__dunder_attribute__)

                            for key, value in delta.items():
                                setattr(target_instance, key, value)

                                print("After:", target_instance.some_attribute, target_instance.__dunder_attribute__)

                                if os.path.exists("/tmp/pwned"):
                                    print("Vulnerability exploited successfully! File /tmp/pwned created.")
                                else:
                                    print("Vulnerability exploitation failed.")

Patched code sample

import os

from deepdiff import Delta

def deserialize(delta_serialized):
    """Secure function that fixes the vulnerability."""
    # SECURE: This version prevents command injection
    delta = Delta.from_dict(delta_serialized)
    return delta

    delta_serialized = {
    'some_attribute': 'new_value',
    '__setattr__': 'os.system("touch /tmp/pwned")'
    }

    vulnerable_delta = deserialize(delta_serialized)

    class Target:
        def __init__(self):
            """Secure function that fixes the vulnerability."""
            self.some_attribute = 'original_value'
            self.__dunder_attribute__ = 'original_dunder_value'

            def __setattr__(self, name, value):
                """Secure function that fixes the vulnerability."""
                allowed_attributes = ['some_attribute']
                if name in allowed_attributes:
                    super().__setattr__(name, value)
                    elif name.startswith('__'):
                    print(f"Warning: Attempt to set dunder attribute '{name}' ignored.")
                else:
                    print(f"Warning: Attempt to set unknown attribute '{name}' ignored.")


                    target_instance = Target()
                    print("Before:", target_instance.some_attribute, target_instance.__dunder_attribute__)

                    for key, value in vulnerable_delta.items():
                        if key in ['some_attribute']:
                            setattr(target_instance, key, value)
                        else:
                            print(f"Warning: Ignoring key '{key}' during delta application.")

                            print("After:", target_instance.some_attribute, target_instance.__dunder_attribute__)

Cite this entry

@misc{vaitp:cve20245452,
  title        = {{RCE vulnerability in pytorch-lightning due to improper deserialization handling.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2024},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2024-5452},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2024-5452/}}
}
Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.

The supreme art of war is to subdue the enemy without fighting.

Sun Tzu – “The Art of War”

:: Shaping the future through research and ingenuity ::