Skip to main content

Overview

If a script runs as root and imports a Python module, you can hijack that import by placing a malicious module earlier in the search path.

Python Module Search Order

Check search path:

Find Target Scripts

Scripts Running as Root

Check Imports


Same Directory Hijack

If root script at /opt/script.py imports utils:
And /opt/ is writable:
Create malicious module:
Wait for execution → /tmp/rootbash -p.

Writable Library Path

Check if any directory in Python path is writable:
If writable → drop malicious module with same name as imported module:

PYTHONPATH Injection

If sudo preserves PYTHONPATH:
Create hijack module:

Writable .py File (Direct Edit)

If the imported module itself is writable:
Inject at the top:

.pth File Injection

.pth files in site-packages directories add paths to sys.path. Lines starting with import are executed. Check if writable:
If writable dir exists, create:
Executes on any Python invocation.

pip Install Hijack

If user can run pip install as root or root runs pip automatically:

Malicious setup.py


Quick Reference