This is part of a series of posts examining the methods malicious Python code gains execution.
Python allows for so-called customization modules to hook the system executable. These can be applied at either the user or system level and the code in these modules will run with every invocation of Python. This is possible thanks to the site module from the standard library. This module is automatically imported during initialization of the Python interpreter!
The module's documentation does show how the interpreter options -S and -s (or PYTHONNOUSERSITE environment variable) can be specified to disable this technique for the system and user levels, respectively. That is some comfort but how many developers do you know that use those options?
--cta--
This is the basic sequence for how to set the hook for the user-specific site-packages directory:
What happens if site.ENABLE_USER_SITE is not enabled, like when in this virtual environment?
Hakuna matata (it means no worries). We can follow the same sequence but for the global site-packages directory:
It might seem like the obvious choice is to hook the global site-packages directory (or directories) and not even worry about the user-specific site-packages directory. However, there could be permissions issues that limit the ability to set and/or execute the hook at the system level.
Most of the techniques covered so far in this series describe how to get malicious Python code to execute one time. This method is different in that it can serve as a way to gain execution multiple times: infect once, run everywhere. The threat actor's use case here is as a rudimentary backdoor and persistence mechanism. The malicious code would install the hook(s) once, using any of the other techniques already covered. The hook would then contain different malicious code that could check for new secrets or ephemeral environment variables to exfiltrate every time the python executable is run.
Senior Software Engineer, responsible for integrations and author of the "phylum" Python package. Documentation and quality champion, runner, baseball and scout dad, pod-faster, and lover of outdoors.
Subscribe to our research
Keep up with the latest software supply chain attacks