With Python getting more and more popular, especially on Microsoft Operating systems, it's common to find malicious Python scripts today. I already covered some of them in previous diaries. I like this language because it is very powerful: You can automate boring tasks in a few lines. It can be used for offensive as well as defensive purposes, and... it has a lot of 3rd party "modules" or libraries that extend its capabilities. For example, if you would like to use Python for forensics purposes, you can easily access the registry and extract data:
This snippet of code starts with an import line. First, I need to load a specific module (in this case
Let's switch back to the "dark side". When an attacker needs to write a piece of code to perform specific tasks, he will search for existing modules and not reinvent the wheel. To search for Python modules, the best place is to visit pypi.org. Let's take another example: injection of code. Python is able to use all the Windows API calls with the help of the
In this example, I'm using the
The suspicious module is
Want more? Let' use now
Other interesting modules? Use
The question is now, from a defender's perspective, how can we detect suspicious Python modules?
If you have access to the host, you can always use the "pip" command (the utility to manage modules):
pip will list the modules that have been installed "manually" (could be done by an attacker). To get a full list of modules, you can use the help() command in the Python interpreter:
As you can see, it's interesting to spot malicious Python code just by having a look at the imported modules! If you would like to hunt, you can create a YARA rule to search for interesting modules inside text files...
Xavier Mertens (@xme)
Jun 11th 2021
|Thread locked Subscribe||
Jun 11th 2021
7 months ago