Member-only story
Silent Python Path Hijacking
Python’s import system allows for the possibility of intercepting the loading process of a module, which can result in unintended code execution. Within the context of a low privileged user this doesn’t mean much, however, it may become very interesting when a high privileged account is running Python code as a scheduled task or with crontab.
Recently, I’ve been writing a lot of Python code for my articles, and it felt appropriate to dedicate one to a potential risk of using Python incorrectly. In this article, we’ll explore how Python handles module imports, examine some examples in action, and discuss ways to mitigate this risk.
Not a member? Read this article for free on my site.

Note that this article is written for educational purposes and is intended only for legal penetration testing and red teaming activities, where explicit permission has been granted. If you wish to test any of the scripts provided, please refer to the disclaimer at the end of this article.
Python Module Search Order
So how does this work? Lets analyze the order in which Python searches for dependencies, directly quoted from the documentation:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default (by convention including a site-packages directory, handled by the site module).
The first two lines are very interesting for what we’re trying to prove:
Directory containing the input script
If directory permissions are not set up correctly, placing a new file may be possible, while editing an existing file is not. I’ve seen this happen a few times, mostly on Windows. Remember to restrict the directory, not only the files!
PYTHONPATH
If the PYTHONPATH contains a location where the attacker has enough permissions to place a file, it may be possible to insert ourselves into the search order.