sitecustomize / usercustomize auto-import
During Python's standard site initialization at interpreter startup
- Lives in
sitecustomize.py / usercustomize.py on sys.path (usually site-packages)- Attacker needs
- Filesystem write access, Supply-chain foothold
- Lifecycle
- InstallStartupyour codeModule loadRuntimeREPL
Runs while the interpreter boots, before your entrypoint.
How it runs
Same idea as .pth files, different mechanism. Python automatically imports sitecustomize.py and usercustomize.py if they exist on the import path.
sitecustomize.py is meant for system-wide or environment-wide customization, such as org defaults, path tweaks, corporate bootstrapping and debugging hooks. It affects everyone using that environment. usercustomize.py is the per-user version. It only loads if user site-packages are enabled:
python3 -c "import site; print(site.ENABLE_USER_SITE)"
The attack is obvious. Drop a sitecustomize.py into any directory on sys.path and your code runs before main on every Python invocation in that environment. It's less stealthy than a .pth, since the filename draws attention. It's also more powerful, because you get a full Python module instead of single import lines.
Defend
Audit for unexpected sitecustomize/usercustomize modules; disable user site with python -s; run with -S to skip site init in locked-down contexts.