0xiviel's picture
Add README.md
5052e5e verified
# PoC: Caffe PythonLayer Arbitrary Code Execution (CWE-94)
## Vulnerability
BVLC/caffe's `GetPythonLayer()` in `layer_factory.cpp:295` calls `bp::import()` with an attacker-controlled module name read from a `.prototxt` model file. When a victim loads a crafted `.prototxt`, Python's import mechanism executes all top-level code in the specified module, achieving arbitrary code execution.
```cpp
// layer_factory.cpp:295 β€” no sanitization, no allowlist
bp::object module = bp::import(param.python_param().module().c_str());
bp::object layer = module.attr(param.python_param().layer().c_str())(param);
```
- **CWE-94:** Improper Control of Generation of Code (Code Injection)
- **CVSS:** 8.8 (High)
- **Condition:** Requires `WITH_PYTHON_LAYER=1` compile flag (commonly enabled for custom layers)
- **Repository:** https://github.com/BVLC/caffe (archived, last commit 2020)
## Files
| File | Description |
|------|-------------|
| `evil_layer.py` | Malicious Python module β€” top-level code executes on import |
| `poc_rce.prototxt` | Caffe model config that references the malicious module |
## Reproduction
```bash
# Requires Caffe built with WITH_PYTHON_LAYER=1
cd /path/to/this/directory
caffe test -model poc_rce.prototxt -iterations 1 2>/dev/null
cat /tmp/caffe_rce_proof.txt
```
Or via Python:
```python
import caffe
net = caffe.Net('poc_rce.prototxt', caffe.TEST)
# β†’ evil_layer.py top-level code executes immediately
```
## Attack Scenario
1. Attacker distributes a model package (`.prototxt` + `.py` module)
2. The `.prototxt` contains a Python layer referencing the included module
3. Victim loads the model for inference
4. `bp::import()` triggers Python import β†’ all top-level code in the module executes
5. Full RCE with the victim's privileges
## Root Cause
The `PythonParameter` protobuf message allows arbitrary module and layer names:
```protobuf
message PythonParameter {
optional string module = 1; // β†’ bp::import(module)
optional string layer = 2; // β†’ module.attr(layer)(param)
}
```
No validation, no allowlist, no sandboxing is applied before the import.