ByteCode-Bandit is a security research utility designed to demonstrate the critical importance of file system permissions. It automates Pycache Poisoning—a technique where an attacker hijacks a script's execution by injecting malicious bytecode into the __pycache__ directory.
This tool demonstrates techniques used in real-world scenarios for persistence and lateral movement:
- Technique: T1554 - Compromise Client Software Binary
- Tactic: TA0003 - Persistence
- Tactic: TA0004 - Privilege Escalation
To optimize performance, Python compiles source code (.py) into bytecode (.pyc). On subsequent runs, the interpreter checks the __pycache__ directory. If a .pyc exists and its 16-byte header (Magic Number, Bitfield, Timestamp, and File Size) matches the source file's metadata, Python executes the bytecode directly.
If a low-privileged user has write access to the __pycache__ folder of a high-privileged tool, they can replace the bytecode while cloning the header. This results in the execution of unauthorized code even though the original .py file appears untouched.
Ensure the target script has been run at least once so a valid cache exists for header cloning.
# Using a raw string payload
python3 bandit.py /opt/tools/admin_tool.py --payload 'print("System Compromised!")'
# Using a complex payload from an external file
python3 bandit.py /opt/tools/admin_tool.py --file exploit.py --output malicious.pycLocate the legitimate cache file name and overwrite it: Bash
cp malicious.pyc /opt/tools/__pycache__/admin_tool.cpython-312.pycRun the original script. The poisoned bytecode will execute instead of the original logic.
sudo /opt/tools/admin_tool.py