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 (
rw
for 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) orrwx
with root ownership.Check if the imported library has global write permissions: Look for
rw
for all users (rw-r--rw-
).
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-xrwx
permissions.Verify the installation location of the target library: Ensure the original library is in a lower-priority path.
Scenario 3: PYTHONPATH Environment Variable
PYTHONPATH
specifies directories Python searches for modules.You have sudo permissions to execute Python with
SETENV
enabled.You can set
PYTHONPATH
to a directory you control.
Exploitation:
Create a fake library file with the same name and function.
Set
PYTHONPATH
to point to the directory containing your malicious module.
Check if you have permissions to set environment variables with
sudo
:Command:Look forSETENV
permission for the Python binary.Confirm you can create a library in a controlled directory.
Test setting
PYTHONPATH
to 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
PYTHONPATH
usingsudo
andSETENV
.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