Remote Code Execution via Malicious Safetensors File in Hugging Face Transformers
Overview
A critical remote code execution (RCE) vulnerability was discovered in the popular `safetensors` library, affecting versions prior to 0.5.1. The `safetensors` format was designed as a secure alternative to Python's `pickle` for serializing and sharing machine learning model weights. However, researchers found a flaw in the metadata parsing logic that could be exploited to trigger a deserialization-of-untrusted-data-style attack. An attacker could craft a malicious `.safetensors` model file and distribute it on platforms like the Hugging Face Hub. When a victim downloads and attempts to load this model using the `transformers` library's `from_pretrained()` method, the vulnerable parsing code can be tricked into executing arbitrary Python code embedded within the file's header. The impact is severe, as it grants the attacker full control over the machine loading the model. This could be used to steal sensitive data, such as API keys and SSH credentials, install persistent backdoors, or use the victim's computational resources (including valuable GPUs) for malicious purposes like cryptocurrency mining. The vulnerability underscores the importance of rigorous security validation even for libraries designed with security as a primary goal.
Affected Systems
Testing Guide
1. Check the installed versions of `safetensors` and `transformers`: ```bash pip show safetensors transformers ``` 2. If `safetensors` version is below `0.5.1` or `transformers` is below `4.42.0`, your environment is vulnerable. 3. **Do not** attempt to acquire or load a proof-of-concept malicious model file on a production or sensitive system. Use a dedicated, isolated, and non-critical machine for any such testing.
Mitigation Steps
1. **Upgrade Immediately:** Update the `safetensors` and `transformers` libraries to the latest patched versions: ```bash pip install --upgrade safetensors transformers ``` 2. **Scan Model Files:** Before loading any new or untrusted model, use a model scanning tool like `protectai/modelscan` to check for known malicious patterns or exploits. 3. **Use Sandboxed Environments:** Run model loading and inference workloads in isolated environments (e.g., Docker containers with no network access or limited permissions) to contain the impact of a potential RCE. 4. **Verify Model Provenance:** Only use models from trusted, verified creators on platforms like Hugging Face. Check for digital signatures or other signs of authenticity if available.
Patch Details
Patched in safetensors version 0.5.1 and incorporated into transformers 4.42.0.