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.

  1. Check if the script has SUID/SGID set and executes as a privileged user: Look for rws (SUID) or rwx with root ownership.

    ls -l <script_name>
  2. Check if the imported library has global write permissions: Look for rw for 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.

  1. View the search order of Python libraries::

    python3 -c 'import sys; print("\\n".join(sys.path))'
  2. Identify if any higher-priority paths are writable: Look for drwxr-xrwx permissions.

    ls -la <path>
  3. Verify the installation location of the target library: Ensure the original library is in a lower-priority path.

    pip3 show <module_name>

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.

  1. Check if you have permissions to set environment variables with sudo:Command:Look for SETENV permission for the Python binary.

    sudo -l
  2. Confirm you can create a library in a controlled directory.

  3. Test setting PYTHONPATH to redirect the module search:

    sudo PYTHONPATH=/tmp/ /usr/bin/python3 <script_name>

General Checklist for Python Library Hijacking

  1. Verify the script has SUID/SGID privileges or runs as root.

  2. Identify the libraries imported in the script.

  3. Check for global write permissions on the imported libraries.

  4. Inspect the Python search path (sys.path) for writable directories.

  5. Confirm if you can set PYTHONPATH using sudo and SETENV.

  6. Create a malicious library file with:

    • The same name as the imported library.

    • A function matching the original library's function signature.

  7. Test the exploitation by running the script.

Last updated