DEV Community

Devon Argent
Devon Argent

Posted on

Day 23: Python Import Hijacking & The Writable Directory Trap 🕵️‍♂️

🛠️ Advanced Escalation Vectors

1. Python Import Hijacking

Python looks for modules in a specific order, starting with the current directory. If a root-owned script imports a module like random or os, and I can write to the directory where that script is executed:

  • The Exploit: Create a file named random.py containing a malicious payload (e.g., import os; os.system("/bin/bash")).
  • The Result: When the root script runs import random, it loads my malicious file instead of the system library. Instant Root.

2. The Writable Directory Vulnerability

I learned a critical lesson today: Directory permissions trump file permissions.
Even if a script like /opt/backup.py is owned by root and is read-only, if the /opt folder is world-writable (777), an attacker can simply:

  1. rm /opt/backup.py (Delete the original)
  2. echo "payload" > /opt/backup.py (Create a new malicious version)
  3. Wait for the root process to execute it.

🕵️‍♂️ Refined Pentester Workflow

My initial enumeration now includes a deep-dive into environment context:

  1. Check PYTHONPATH: Are there custom paths where I can drop malicious modules?
  2. Audit Parent Folders: Not just the script, but every folder in its path.
  3. Analyze Imports: What libraries does the root-level script rely on?

Follow my journey: #1HourADayJourney

Top comments (0)