Python Library Hijacking
Scenario 1: Incorrect Write Permissions
A Python script with SUID/SGID privileges imports a vulnerable library.
The script can execute as a privileged user (e.g., root).
The imported library file has global write permissions (
rwfor all users).
Exploitation:
Modify the library by adding malicious code (e.g., reverse shell).
Execute the script to trigger the payload.
Check if the script has SUID/SGID set and executes as a privileged user: Look for
rws(SUID) orrwxwith root ownership.ls -l <script_name>Check if the imported library has global write permissions: Look for
rwfor all users (rw-r--rw-).ls -l /usr/local/lib/python3.X/dist-packages/<module_name>
Scenario 2: Library Path Misconfiguration
Python loads libraries based on a priority order defined in its
sys.path.Conditions:The imported library resides in a lower-priority path.
A higher-priority path is writable by your user.
Exploitation:
Create a malicious library file in the writable, higher-priority path.
Python will load the malicious version before the original library.
View the search order of Python libraries::
Identify if any higher-priority paths are writable: Look for
drwxr-xrwxpermissions.Verify the installation location of the target library: Ensure the original library is in a lower-priority path.
Scenario 3: PYTHONPATH Environment Variable
PYTHONPATHspecifies directories Python searches for modules.You have sudo permissions to execute Python with
SETENVenabled.You can set
PYTHONPATHto a directory you control.
Exploitation:
Create a fake library file with the same name and function.
Set
PYTHONPATHto point to the directory containing your malicious module.
Check if you have permissions to set environment variables with
sudo:Command:Look forSETENVpermission for the Python binary.Confirm you can create a library in a controlled directory.
Test setting
PYTHONPATHto redirect the module search:
General Checklist for Python Library Hijacking
Verify the script has SUID/SGID privileges or runs as root.
Identify the libraries imported in the script.
Check for global write permissions on the imported libraries.
Inspect the Python search path (
sys.path) for writable directories.Confirm if you can set
PYTHONPATHusingsudoandSETENV.Create a malicious library file with:
The same name as the imported library.
A function matching the original library's function signature.
Test the exploitation by running the script.
Last updated