Researchers at Phylum have discovered a collection of Python packages stored in the popular PyPI repository that use an attack method called “typosquatting,” in which a threat actor will create resources like domains, or in this case package names, that are very similar in name. Typosquatting is used in the hope that users will misspell commonly requested packages when attempting to install them, thus installing the malicious package instead. For example, there is a legitimate package in python named “urllib” and a malicious “pyurllib” typosquat package.
These malicious packages can be copies of legitimate packages, but with extra code injected by malicious “__import__” statements that perform all of the illegitimate actions. Most often the malicious import code is simply added into the standard setup.py or __init__.py files. Phylum observed that threat group tactics changed as these malicious packages were taken down. In a clever tactic, threat actors began simply adding hundreds of spaces before their import code so that it would be pushed far off to the right in a standard display, making the additional code challenging to notice. In a handful of malicious PyPI packages, a “pip install” statement was added to setup.py, pointing to one of the other malicious packages.
Code that is delivered in these ways attempts to download a second stage payload from a threat group’s remote infrastructure. Once the second stage is retrieved, it is executed with pythonw.exe which, as opposed to python.exe, will not open a console window as it runs. The second stage contains multiple layers of obfuscated and compressed bytecode which eventually result in delivering the W4SP stealer malware.
PyPI is often treated as a very trustworthy source of packages; in reality, anyone can upload a package to be distributed by PyPI. It is recommended to install python libraries using built-in operating system package managers where possible. For example, on Debian based Linux systems using apt(8), it is recommend to use: apt install python3-. Repositories maintained by Linux operating system developers typically have more stringent requirements for new packages.
In the event that using an operating systems package manager is not possible, or in the event that the package hasn’t been added to upstream repositories for a particular OS, it is advised to verify the spelling of the required package. Finding documentation online that matches the desired package can assist in verification. Users can also check https://pypi.org and search for the package that they need, and do a cursory check to see if the name of the package matches the contents of the project description.