PYTHONPATH / PYTHONHOME module shadowing
Affects every import statement, starting from interpreter initialization
- Lives in
PYTHONPATH / PYTHONHOME environment variables- Attacker needs
- Environment control
- Lifecycle
- InstallStartupyour codeModule loadRuntimeREPL
Runs on import or require, for every module the app loads.
How it runs
Classic module shadowing. PYTHONPATH prepends directories to sys.path, so any module you place there gets imported before the real one.
mkdir /tmp/evil
echo 'print("You are hacked"); raise SystemExit()' > /tmp/evil/json.py
PYTHONPATH=/tmp/evil python -c "import json"
That shadows the entire json standard-library module. The real json never loads, and your version runs instead.
PYTHONHOME goes further. It changes where Python looks for the standard library. Set it carefully and you can replace core modules wholesale. The attacker needs control of the environment. Think CI/CD pipelines, shared servers, Docker containers with inherited env vars, and .env files checked into repos. If you can inject an environment variable, you can hijack Python's module resolution.
Defend
Scrub inherited env vars in CI/CD and containers; never commit .env files with path vars; pin interpreter and stdlib location explicitly.