Kaspersky Securelist

Syndikovat obsah Securelist
Aktualizace: 6 min 43 sek zpět

On the trail of the XMRig miner

5 hodin 35 min zpět

As protection methods improve, the developers of miners have had to enhance their own creations, often turning to non-trivial solutions. Several such solutions (previously unseen by us) were detected during our analysis of the open source miner XMRig.

How it all began: ransominer

Alongside well-known groups that make money from data theft and ransomware (for example, Maze, which is suspected of the recent attacks on SK Hynix and LG Electronics), many would-be attackers are attracted by the high-profile successes of cybercrime. In terms of technical capabilities, such amateurs lag far behind organized groups and therefore use publicly available ransomware, targeting ordinary users instead of the corporate sector.

The outlays on such attacks are often quite small, so the miscreants have to resort to various stratagems to maximize the payout from each infected machine. For example, in August of this year, we noticed a rather curious infection method: on the victim’s machine, a Trojan (a common one detected by our solutions as Trojan.Win32.Generic) was run, which installed administration programs, added a new user, and opened RDP access to the computer. Next, the ransomware Trojan-Ransom.Win32.Crusis started on the same machine, followed by the loader of the XMRig miner, which then set about mining Monero cryptocurrency.

As a result, the computer would already start earning money for the cybercriminals just as the user saw the ransom note. In addition, RDP access allowed the attackers to manually study the victim’s network and, if desired, spread the ransomware to other nodes.

Details about Trojan files:

  • Mssql — PC Hunter x64 (f6a3d38aa0ae08c3294d6ed26266693f)
  • mssql2 — PC Hunter x86 (f7d94750703f0c1ddd1edd36f6d0371d)
  • exe — nmap-like network scanner (597de376b1f80c06d501415dd973dcec)
  • bat — removes shadow copy
  • bat — creates a new user, adds it to the administrators group, opens the port for RDP access, and starts the Telnet server
  • exe — IOBIT Unlocker (5840aa36b70b7c03c25e5e1266c5835b)
  • EVER\SearchHost.exe — Everything software (8add121fa398ebf83e8b5db8f17b45e0)
  • EVER\1saas\1saas.exe — ransomware Trojan-Ransom.Win32.Crusis (0880430c257ce49d7490099d2a8dd01a)
  • EVER\1saas \LogDelete — miner loader (6ca170ece252721ed6cc3cfa3302d6f0, HEUR:Trojan-Downloader.Win32.Generic)

Batch script systembackup.bat adds a user and opens access via RDP

We decided to use KSN to examine how often XMRig and its modifications get bundled with malware. It emerged that in August 2020 there were more than 5,000 attempts to install it on users’ computers. The parties responsible for its distribution turned out to be the Prometei malware family and a new family called Cliptomaner.

Prometei backdoor

The Prometei family has been known since 2016, but spotted together with XMRig for the first time in February 2020. What’s more, the backdoor was distributed in an unusual way: whereas during ordinary attacks the cybercriminals gain server access through various exploits, this time they used brute-force attacks. Having thus obtained usernames and passwords for computers with MS SQL installed, the attackers used the T-SQL function xp_cmdshell to run several PowerShell scripts and elevated the privileges of the current user by exploiting the CVE-2016-0099 vulnerability. After that, Purple Fox Trojan and Prometei itself were installed on the victim’s machine. The whole attack, starting with the brute-forcing of credentials to connect to the SQL server and ending with the installation of Prometei, was carried out in fully automatic mode.

The installation process is of interest: the .NET executable file, packed into an ELF file using standard .NET Core tools (Apphost), sends information about the infected machine to the C&C server, and then downloads the cryptocurrency miner and its configuration. The versions of the loaders for Windows and Linux differ only slightly: the .NET build for different platforms saved the attackers from having to create a separate loader for Linux and allowed cryptocurrency mining on powerful Windows and Linux servers.

Cliptomaner miner

Detected in September 2020, Cliptomaner is very similar to its fellows: like them, it not only mines cryptocurrency, but can also substitute cryptowallet addresses in the clipboard. The miner version is selected according to the computer configuration and downloaded from C&C. The malware is distributed under the guise of software for Realtek audio equipment. On the whole, we saw no new techniques, but interestingly Cliptomaner is written entirely in the AutoIT scripting language. Most of the time, families with similar behavior are written in compiled languages, such as C# or C, but in this case the authors opted for a more creative approach, and wrote a lengthy script that selects the required version of the miner and receives cryptowallet addresses from C&C for substitution.

Substituting cryptowallets in the clipboard

Kaspersky security solutions detect the above malicious programs with the following verdicts: HEUR:Trojan.MSIL.Prometei.gen, HEUR:Trojan.Script.Cliptomaner.gen, HEUR:Trojan-Downloader.Win32.Generic, Trojan-Ransom.Win32.Crusis, Trojan.Win64.Agentb, not-a-virus:RiskTool.Win64.XMRigMiner

Indicators of compromise (IoC) Domains

taskhostw[.]com
svchost[.]xyz
sihost[.]xyz
srhost[.]xyz
2fsdfsdgvsdvzxcwwef-defender[.]xyz

Cryptowallets used for substitution

LTC: LPor3PrQHcQv4obYKEZpnbqQEr8LMZoUuX
BTC: 33yPjjSMGHPp8zj1ZXySNJzSUfVSbpXEuL
ETH: 0x795957d9753e854b62C64cF880Ae22c8Ab14991b
ZEC: t1ZbJBqHQyytNYtCpDWFQzqPQ5xKftePPt8
DODGE: DEUjj7mi5N67b6LYZPApyoV8Ek8hdNL1Vy

MD5

1273d0062a9c0a87e2b53e841b261976
16b9c67bc36957062c17c0eff03b48f3
d202d4a3f832a08cb8122d0154712dd1
6ca170ece252721ed6cc3cfa3302d6f0
1357b42546dc1d202aa9712f7b29aa0d
78f5094fa66a9aa4dc10470d5c3e3155

Life of Maze ransomware

21 Říjen, 2020 - 12:00

In the past year, Maze ransomware has become one of the most notorious malware families threatening businesses and large organizations. Dozens of organizations have fallen victim to this vile malware, including LG, Southwire, and the City of Pensacola.

The history of this ransomware began in the first half of 2019, and back then it didn’t have any distinct branding – the ransom note included the title “0010 System Failure 0010”, and it was referenced by researchers simply as ‘ChaCha ransomware’.

Ransom note of an early version of Maze/ChaCha ransomware

Shortly afterwards, new versions of this Trojan started calling themselves Maze and using a relevantly named website for the victims instead of the generic email address shown in the screenshot above.

Website used by a recent version of Maze ransomware

Infection scenarios Mass campaigns

The distribution tactic of the Maze ransomware initially involved infections via exploit kits (namely, Fallout EK and Spelevo EK), as well as via spam with malicious attachments. Below is an example of one of these malicious spam messages containing an MS Word document with a macro that’s intended to download the Maze ransomware payload.

If the recipient opens the attached document, they will be prompted to enable editing mode and then enable the content. If they fall for it, the malicious macro contained inside the document will execute, which in turn will result in the victim’s PC being infected with Maze ransomware.

Tailored approach

In addition to these typical infection vectors, the threat actors behind Maze ransomware started targeting corporations and municipal organizations in order to maximize the amount of money extorted.

The initial compromise mechanism and subsequent tactics vary. Some incidents involved spear-phishing campaigns that installed Cobalt Strike RAT, while in other cases the network breach was the result of exploiting a vulnerable internet-facing service (e.g. Citrix ADC/Netscaler or Pulse Secure VPN). Weak RDP credentials on machines accessible from the internet also pose a threat as the operators of Maze may use this flaw as well.

Privilege escalation, reconnaissance and lateral movement tactics also tend to differ from case to case. During these stages, the use of the following tools has been observed: mimikatz, procdump, Cobalt Strike, Advanced IP Scanner, Bloodhound, PowerSploit, and others.

During these intermediate stages, the threat actors attempt to identify valuable data stored on the servers and workstations in the compromised network. They will then exfiltrate the victim’s confidential files in order to leverage them when negotiating the size of the ransom.

At the final stage of the intrusion, the malicious operators will install the Maze ransomware executable onto all the machines they can access. This results in the encryption of the victim’s valuable data and finalizes the attack.

Data leaks/doxing

Maze ransomware was one of the first ransomware families that threatened to leak the victims’ confidential data if they refused to cooperate.

In fact, this made Maze something of a trendsetter because this approach turned out to be so lucrative for the criminals that it’s now become standard for several notorious ransomware gangs, including REvil/Sodinokibi, DoppelPaymer, JSWorm/Nemty/Nefilim, RagnarLocker, and Snatch.

The authors of the Maze ransomware maintain a website where they list their recent victims and publish a partial or a full dump of the documents they have managed to exfiltrate following a network compromise.

Website with leaked data published by Maze operators

Ransomware cartel

In June 2020, the criminals behind Maze teamed up with two other threat actor groups, LockBit and RagnarLocker, essentially forming a ‘ransomware cartel’. The data stolen by these groups now gets published on the blog maintained by the Maze operators.

It wasn’t just the hosting of exfiltrated documents where the criminals pooled their efforts – apparently they are also sharing their expertise. Maze now uses execution techniques that were previously only used by RagnarLocker.

Brief technical overview

The Maze ransomware is typically distributed as a PE binary (EXE or DLL depending on the specific scenario) which is developed in C/C++ and obfuscated by a custom protector. It employs various tricks to hinder static analysis, including dynamic API function imports, control flow obfuscation using conditional jumps, replacing RET with JMP dword ptr [esp-4], replacing CALL with PUSH + JMP, and several other techniques.

To counter dynamic analysis, this Trojan will also terminate processes typically used by researchers, e.g. procmon, procexp, ida, x32dbg, etc.

The cryptographic scheme used by Maze consists of several levels:

  • To encrypt the content of the victim’s files, the Trojan securely generates unique keys and nonce values to use with the ChaCha stream cipher;
  • The ChaCha keys and nonce values are encrypted by a session public RSA-2048 key which is generated when the malware is launched;
  • The session private RSA-2048 key is encrypted by the master public RSA-2048 key hardcoded in the Trojan’s body.

This scheme is a variation of a more or less typical approach used by developers of modern ransomware. It allows the operators to keep their master private RSA key secret when selling decryptors for each individual victim, and it also ensures that a decryptor purchased by one victim won’t help others.

When executing on a machine, Maze ransomware will also attempt to determine what kind of PC it has infected. It tries to distinguish between different types of system (‘backup server’, ‘domain controller’, ‘standalone server’, etc.). Using this information in the ransom note, the Trojan aims to further scare the victims into thinking that the criminals know everything about the affected network.

Strings that Maze uses to generate the ransom note

Fragment of the procedure that generates the ransom note

How to avoid and prevent

Ransomware is evolving day by day, meaning a reactive approach to avoid and prevent infection is not profitable. The best defense against ransomware is proactive prevention because often it is too late to recover data once they have been encrypted.

There are a number of recommendations that may help prevent attacks like these:

  1. Keep your OS and applications patched and up to date.
  2. Train all employees on cybersecurity best practices.
  3. Only use secure technology for remote connection in a company local network.
  4. Use endpoint security with behavior detection and automatic file rollback, such asKaspersky Endpoint Security for Business.
  5. Use the latest threat intelligence information to detect an attack quickly, understand what countermeasures are useful, and prevent it from spreading.
Detection

Kaspersky products protect against this ransomware, detecting it as Trojan-Ransom.Win32.Maze; it is blocked by Behavior-based Protection as PDM:Trojan.Win32.Generic.

We safeguard our customers with the best Ransomware Protection technologies.

TIP Cloud Sandbox report summary and execution map with mapping on MITRE ATT&CK Framework

IOCs

2332f770b014f21bcc63c7bee50d543a
CE3A5898E2B2933FD5216B27FCEACAD0
54C9A5FC6149007E9B727FCCCDAFBBD4
8AFC9F287EF0F3495B259E497B30F39E

GravityRAT: The spy returns

19 Říjen, 2020 - 12:00

In 2018, researchers at Cisco Talos published a post on the spyware GravityRAT, used to target the Indian armed forces. The Indian Computer Emergency Response Team (CERT-IN) first discovered the Trojan in 2017. Its creators are believed to be Pakistani hacker groups. According to our information, the campaign has been active since at least 2015, and previously targeted Windows machines. However, it underwent changes in 2018, with Android devices being added to the list of targets.

Malicious guide

In 2019, on VirusTotal, we encountered a curious piece of Android spyware which, when analyzed, seemed connected to GravityRAT. The cybercriminals had added a spy module to Travel Mate, an Android app for travelers to India, the source code of which is available on Github.

Clean Travel Mate app on Google Play

The attackers used a version of the app published on Github in October 2018, adding malicious code and changing the name to Travel Mate Pro.

The app requests permissions at startup

The Trojan’s manifest file includes Services and Receiver, which are not in the app from Github

List of Trojan classes

The spyware’s functions are fairly standard: it sends device data, contact lists, e-mail addresses, and call and text logs to the C&C server. In addition, the Trojan searches for files in the device memory and on connected media with the extensions .jpg, .jpeg, .log, .png, .txt, .pdf, .xml, .doc, .xls, .xlsx, .ppt, .pptx, .docx, and .opus, and sends these to C&C as well.

The malware does not resemble a “typical” Android spy in that the choice of app is rather specific and the malicious code is not based on that of any known spyware app, as is often the case. As such, we decided to look for connections with known APT families.

C&C addresses hardcoded into the Trojan

The simplest thing to do is to check the C&C addresses used by the Trojan:

  • nortonupdates[.]online:64443
  • nortonupdates[.]online:64443

As it turned out, n3.nortonupdates[.]online:64443 was used by another piece of malware to download data about files found on the computer (.doc, .ppt, .pdf, .xls, .docx, .pptx, .xlsx) together with data about the infected machine. With the aid of Threat Intelligence, we found this malware: a malicious PowerShell script called Enigma.ps1 that executes C# code.

The PowerShell script was run using a VBS script:

Next, we detected a very similar VBS script template with no specifiedpaths under the name iV.dll:

It was located inside the PyInstaller container enigma.exe signed by E-Crea Limited on 09.05.2019. The installer was downloaded from the site enigma.net[.]in under the guise of a secure file sharing app to protect against ransomware Trojans:

Besides the VBS template, inside the container were XML templates for Windows Task Scheduler under the names aeS.dll, rsA.dll, eA.dll, and eS.dll:

 

 

And in the main program, the required paths and names were written into the templates and a scheduled task had been added:

The program communicated with the server at the address download.enigma.net[.]in/90954349.php (note that 90954349A is the start of the MD5 hash of the word “enigma”). It featured a simple graphical interface and encryption and file exchange logic:

The Mac version has a similar functionality and adds a cron job:

Similar in functionality to enigma.exe is the app Titanium (titaniumx.co[.]in), signed on 04.14.2019 by Plano Logic Ltd, certificate revoked on 09.08.2019.

Alongside the Enigma and Titanium payloads were the following spyware Trojans:

  • Wpd.exe, signed 09.17.2018 by Plano Logic Ltd, certificate revoked
  • Taskhostex.exe, signed 02.18.2020 by Theravada Solutions Ltd
  • WCNsvc.exe, signed on 09.17.2018 by Plano Logic Ltd, certificate revoked
  • SMTPHost.exe, signed 12.21.2018 by Plano Logic Ltd, certificate revoked
  • CSRP.exe

Their C&Cs:

  • windowsupdates[.]eu:46769
  • windowsupdates[.]eu:46769
  • mozillaupdates[.]com:46769
  • mozillaupdates[.]com:46769
  • mozillaupdates[.]us

We focused on port 46769, used by the above Trojans. The same port was used by the GravityRAT family.  A further search of nortonupdates[.]online led us to the PE file Xray.exe:

This version collected data and sent it to n1.nortonupdates[.]online and n2.nortonupdates[.]online.

The domains n*.nortonupdates[.]online resolved to the IP address 213.152.161[.]219. We checked our Passive DNS database for other domains previously found at this address, and discovered the suspicious looking u01.msoftserver[.]eu. A search of this domain led us to the app ZW.exe, written in Python and packaged using the same PyInstaller (signed on 04.10.2019 by Plano Logic Ltd, certificate revoked on 09.08.2019).

The C&C addresses called by ZW.exe are decrypted by the AES algorithm from the file Extras\SystemEventBrokerSettings.dat:

  • msoftserver[.]eu:64443
  • msoftserver[.]eu:64443
  • msoftserver[.]eu:64443
  • msoftserver[.]eu:64443

Communication with the server takes place at the relative address /ZULU_SERVER.php.

The spyware receives commands from the server, including to:

  • get information about the system
  • search for files on the computer and removable disks with the extensions .doc, .docx, .ppt, .pptx, .xls, .xlsx, .pdf, .odt, .odp, and .ods, and upload them to the server
  • get a list of running processes
  • intercept keystrokes
  • take screenshots
  • execute arbitrary shell commands
  • record audio (not implemented in this version)
  • scan ports

The code is multiplatform:

The characteristic path also confirms that we are dealing with a new version of GravityRAT:

The newer variants of the malware with similar functionality that we detected using Threat Intelligence — RW.exe and TW.exe — were signed by Theravada Solutions Ltd on 10.01.2019 and 02.20.2020, respectively; the certificates are valid.

RW.exe called the C&C server at the relative address /ROMEO/5d907853.php, and TW.exe at /TANGO/e252a516.php, so we can assume that the first letter in the name of the executable file indicates the version of the C&C server.

C&Cs of this instance:

  • mozillaupdates[.]us
  • mozillaupdates[.]us
  • mozillaupdates[.]us
  • mozillaupdates[.]us
  • microsoftupdate[.]in
  • microsoftupdate[.]in
  • microsoftupdate[.]in
  • microsoftupdate[.]in
Other versions of GravityRAT lolomycin&Co

An older version of GravityRAT, Whisper, in addition to the string “lolomycin2017” (whose byte representation was used as a salt for AES encryption in the component lsass.exe), contained in the component whisper.exe the string “lolomycin&Co” for use as a password to unpack downloaded ZIP archives with the payload:

Through this string, we found newer .NET versions of GravityRAT in the apps:

  • WeShare
  • TrustX
  • Click2Chat
  • Bollywood
New versions of GravityRAT

All sites that distribute malware examined below are hidden behind Cloudflare to make it hard to determine the real IP.

.NET versions
  • Sharify
  • MelodyMate (signed by E-Crea Limited on 11.05.2019)

Python version

GoZap

Another PyInstaller container. Note that the code explicitly mentions the names of the potential payload already familiar to us:

Depending on the specific payload, the destination directory is selected, as well as the name of the task for Windows Task Scheduler:

Payload Name Path Task Name ZW %APPDATA%\Programs WinUpdate SMTPHost %APPDATA%\WinUpdates Disksynchronization WCNsvc %APPDATA%\System Windows_startup_update CSRP %APPDATA%\Applications Antivirus_Update Windows-Portable-Devices %APPDATA%\ System Updates System_Update Electron versions

The following versions are multiplatform for Windows and Mac based on the Electron framework. The logic is as before: the Trojan checks if it is running on a virtual machine, collects information about the computer, downloads the payload from the server, and adds a scheduled task.

  • StrongBox (signed by E-Crea Limited on 11.20.2019)
  • TeraSpace (signed by E-Crea Limited on 11.20.2019)
  • OrangeVault
  • CvStyler (signed by E-Crea Limited 02.20.2020)

Android versions

SavitaBhabi exists for Windows and Android.

The Windows version is based on .NET. The functionality is standard: the Trojan checks if it is running on a virtual machine and if security software is installed on the computer, transmits information about the computer to the server, and receives commands in response. It uses Windows Task Scheduler to launch the payload. Communication with the server is through POST requests to download.savitabhabi.co[.]in/A5739ED5.php.

The second file, downloaded from the same site, is the Android app Savitabhabi.apk, which is an adult comic strip with an embedded spyware module. Unlike the Travel Mate Pro version, this time it seems that the cybercriminals took a bottom-up approach and wrote the app themselves.

The app requests suspicious permissions at startup

The malicious functionality of this Android app is identical to that of Travel Mate Pro; the C&C addresses and code (save for minor details) also coincide:

List of Trojan classes

Conclusion

In 2019, The Times of India published an article about the cybercriminal methods used to distribute GravityRAT during the period 2015-2018. Victims were contacted through a fake Facebook account, and asked to install a malicious app disguised as a secure messenger in order to continue the conversation. Around 100 cases of infection of employees at defense, police, and other departments and organizations were identified.

It is safe to assume that the current GravityRAT campaign uses similar infection methods — targeted individuals are sent links pointing to malicious apps.

The main modification seen in the new GravityRAT campaign is multiplatformity: besides Windows, there are now versions for Android and macOS. The cybercriminals also started using digital signatures to make the apps look more legitimate.

IoCs

MD5

Travel Mate Pro — df6e86d804af7084c569aa809b2e2134

iV.dll — c92a03ba864ff10b8e1ff7f97dc49f68

enigma.exe — b6af1494766fd8d808753c931381a945

Titanium — 7bd970995a1689b0c0333b54dffb49b6

Wpd.exe — 0c26eb2a6672ec9cd5eb76772542eb72

Taskhostex.exe — 0c103e5d536fbd945d9eddeae4d46c94

WCNsvc.exe — cceca8bca9874569e398d5dc8716123c

SMTPHost.exe — 7bbf0e96c8893805c32aeffaa998ede4

CSRP.exe — e73b4b2138a67008836cb986ba5cee2f

Chat2Hire.exe — 9d48e9bff90ddcae6952b6539724a8a3

AppUpdater.exe — 285e6ae12e1c13df3c5d33be2721f5cd

Xray.exe — 1f484cdf77ac662f982287fba6ed050d

ZW.exe — c39ed8c194ccf63aab1db28a4f4a38b9

RW.exe — 78506a097d96c630b505bd3d8fa92363

TW.exe — 86c865a0f04b1570d8417187c9e23b74

Whisper — 31f64aa248e7be0be97a34587ec50f67

WeShare —e202b3bbb88b1d32dd034e6c307ceb99

TrustX — 9f6c832fd8ee8d8a78b4c8a75dcbf257

Click2Chat — defcd751054227bc2dd3070e368b697d

Bollywood — c0df894f72fd560c94089f17d45c0d88

Sharify — 2b6e5eefc7c14905c5e8371e82648830

MelodyMate — ee06cfa7dfb6d986eef8e07fb1e95015

GoZap — 6689ecf015e036ccf142415dd5e42385

StrongBox — 3033a1206fcabd439b0d93499d0b57da (Windows), f1e79d4c264238ab9ccd4091d1a248c4 (Mac)

TeraSpace — ee3f0db517f0bb30080a042d3482ceee (Windows), 30026aff23b83a69ebfe5b06c3e5e3fd (Mac)

OrangeVault — f8da7aaefce3134970d542b0e4e34f7b (Windows), 574bd60ab492828fada43e88498e8bd2 (Mac)

CvStyler — df1bf7d30a502e6388e2566ada4fe9c8

SavitaBhabi — 092e4e29e784341785c8ed95023fb5ac (Windows), c7b8e65e5d04d5ffbc43ed7639a42a5f (Android)

URLs

daily.windowsupdates[.]eu

nightly.windowsupdates[.]eu

dailybuild.mozillaupdates[.]com

nightlybuild.mozillaupdates[.]com

u01.msoftserver[.]eu

u02.msoftserver[.]eu

u03.msoftserver[.]eu

u04.msoftserver[.]eu

n1.nortonupdates[.]online

n2.nortonupdates[.]online

n3.nortonupdates[.]online

n4.nortonupdates[.]online

sake.mozillaupdates[.]us

gyzu.mozillaupdates[.]us

chuki.mozillaupdates[.]us

zen.mozillaupdates[.]us

ud01.microsoftupdate[.]in

ud02.microsoftupdate[.]in

ud03.microsoftupdate[.]in

ud04.microsoftupdate[.]in

chat2hire[.]net

wesharex[.]net

click2chat[.]org

x-trust[.]net

bollywoods[.]co[.]in

enigma[.]net[.]in

titaniumx[.]co[.]in

sharify[.]co[.]in

strongbox[.]in

teraspace[.]co[.]in

gozap[.]co[.]in

orangevault[.]net

savitabhabi[.]co[.]in

melodymate[.]co[.]in

cvstyler[.]co[.]in

IAmTheKing and the SlothfulMedia malware family

15 Říjen, 2020 - 12:00

On October 1, 2020, the DHS CISA agency released information about a malware family called SlothfulMedia, which they attribute to a sophisticated threat actor. We have been tracking this set of activity through our private reporting service, and we would like to provide the community with additional context.

In June 2018, we published the first report on a new cluster of activities that we named IAmTheKing, based on malware strings discovered in a malware sample from an unknown family. Amusingly, other strings present inside of it invited “kapasiky antivirus” to “leave [them] alone”.

Over time, we identified three different malware families used by this threat actor, one of which was SlothfulMedia. The aim of this blog post is to introduce all of them and to provide data we have been able to gather about the attackers’ interests.

IAmTheKing’s toolset KingOfHearts

This C++ backdoor, which contains the character strings discussed above, is the first element of this toolset we encountered. It comes in EXE or DLL variants, and we have been able to find traces of this family dating back to 2014. We believe it was distributed through spear-phishing e-mails containing malicious Word documents, but have been unable to obtain samples of these. The infection process relies on a PowerShell script that downloads from a remote server a base64-encoded payload hidden in an image file.

In terms of capabilities, KingOfHearts offers nothing more than the basic features you would expect from a backdoor:

  • Arbitrary command execution
  • File system manipulation: listing drives and files, deleting, uploading and downloading data, etc.
  • Listing of running processes with the option to terminate any of them
  • Capturing screenshots using a custom standalone utility, described below

Rather than developing sophisticated features, the malware developers instead opted to include anti-debugging and virtualization detection routines. Communications with the C2 server take place over HTTP(S), implemented with the wsdlpull open source library. The backdoor looks for new orders every second by sending a heartbeat to the C2 (the “HEART” command, hence the name).

We identified two main development branches: one of them sends url-encoded POST data, and the other one sends JSON objects. Both have been used concurrently and otherwise display the same capabilities: we cannot say what motivates attackers to choose the one or the other.

QueenOfHearts

Following our initial discovery, we identified another, more widespread malware family linked to the same threat actor. While it does not contain the anti-analysis countermeasures of its cousin, the rest of its features and overall design decisions map to King of Hearts almost one to one. QueenOfHearts seems to have appeared somewhere in 2017. It is the family designated as PowerPool by our esteemed colleagues from ESET.

QueenOfHearts also interacts with its C2 server over HTTP. It sends simple GET requests containing a backdoor identifier and optional victim machine information, then reads orders located in the cookie header of the reply. Orders come in the form of two-letter codes (e.g.: “xe” to list drives) which tend to vary between samples. As of today, this family is still in active development, and we have observed code refactoring as well as incremental upgrades over 2020. For instance, earlier backdoor responses were sent as base64-encoded payloads in POST requests. They are now compressed beforehand, and additionally supplied through the cookie header.

QueenOfClubs

In the course of our investigations, we discovered another malware strain that appeared to fill the same role as QueenOfHearts. This C++ backdoor also offers similar features as KingOfHearts, as well as the ability to execute arbitrary Powershell scripts. One minute difference is that in this one, screenshot capture capabilities are embedded directly into the program instead of being handled by a separate utility.

It contains a number of links to QueenOfHearts, namely:

  • Identical hardcoded file names can be found in both malware strains.
  • We observed a number of command and control servers concurrently handling traffic originating from both families.
  • QueenOfHearts and QueenOfClubs were on occasion deployed simultaneously on infected machines.

However, it is also our belief that they originate from two separate codebases, although their authors shared common development practices.

The malware designated as SlothfulMedia by US-CERT is an older variant of this family.

JackOfHearts

Astute readers will notice that we did not discuss persistence mechanisms for any of the two aforementioned families. In fact, both of them expect to run in an environment that has already been prepared for them. JackOfHearts is the dropper associated with QueenOfHearts: its role is to write the malware somewhere on the disk (for instance: %AppData%\mediaplayer.exe) and create a Windows service pointing to it as well as a shortcut in the startup folder that is also used to immediately launch QueenOfHearts. This shortcut is the one that contains references to a “david” user highlighted by the DHS CISA report.

Finally, the dropper creates a self-deletion utility in the %TEMP% folder to remove itself from the filesystem.

As of 2020, JackOfHearts is still used to deploy QueenOfHearts.

Screenshot capture utility

A simple program that captures screenshots and saves them as “MyScreen.jpg”. It is sometimes embedded directly inside QueenOfHearts but has also been seen in conjunction with KingOfHearts.

Powershell backdoor

In addition to these malware families, IAmTheKing also leverages an extensive arsenal of Powershell scripts. Recent infection vectors have involved archives sent over e-mail which contain LNK files masquerading as Word documents. Clicking on these links results in the execution of a Powershell backdoor that hides inside custom Windows event logs and retrieves additional scripts over HTTPS, DNS or even POP3S.

The C2 server provides PNG files, which contain additional Powershell scripts hidden through steganography. The code performing this operation comes from the open-source project Invoke-PSImage. This allows operators to stage components on the victim machine, such as:

  • An information-stealing utility written in Powershell that collects all documents found on the victim’s machine and sends them in password-protected RAR archives. These archives are sent back to the attackers over e-mail.
  • A command execution utility which obtains orders from DNS TXT records. The code to accomplish this is derived from another open-source project, Nishang.
  • An information-gathering utility tasked with collecting running processes, disk drives and installed programs with WMI queries. It may also steal passwords saved by the Chrome browser.
  • A spreader script that lists computers connected to the domain, and tries to open a share on each of them to copy a binary and create a remote scheduled task.
  • A home-made keylogger.
  • QueenOfHearts, one of the malware families described above.
Lateral movement

Once the attackers have gained access to a machine through any of the tools described above, they leverage well-known security testing programs to compromise additional machines on the network. In particular, we found evidence of the following actions on the target:

  • Microsoft’s SysInternals suite: ProcDump to dump the exe process and PsExec to run commands on remote hosts.
  • LaZagne and Mimikatz to collect credentials on infected machines.
  • Built-in networking utilities such as ipconfig.exe, net.exe and ping.exe, etc. for network discovery.
Victimology

Until very recently, IAmTheKing has focused exclusively on collecting intelligence from high-profile Russian entities. Victims include government bodies and defense contractors, public agencies for development, universities and companies in the energy sector. This threat actor’s geographic area of interest is so specific that KingOfHearts, QueenOfHearts and even recent versions of JackOfHearts include code referring specifically to the Russian language character set:

In 2020, we discovered rare incidents involving IAmTheKing in central Asian and Eastern European countries. The DHS CISA also reports activity in Ukraine and Malaysia. Our data however indicates that Russia overwhelmingly remains IAmTheKing’s primary area of operation.

There is currently debate within our team on whether this constitutes a slight shift in this threat actor’s targeting, or if its toolset is now shared with other groups. We are unable to provide a definitive answer to this question at this juncture.

Conclusion

While the public has only recently discovered this set of activity, IAmTheKing has been very active for a few years. Considering the type of organizations that cybercriminals have been targeting, we felt that there was little public interest in raising awareness about this group beyond our trusted circle of industry partners. However, now that researchers have started investigating this threat actor, we want to assist the community as much as possible by providing this brief summary of our knowledge of IAmTheKing.

Based on the type of information IAmTheKing is after, we believe that it is state-sponsored. Its toolset is rapidly evolving, and it is not afraid to experiment with non-standard communications channels. The group is characterized by a mastery of traditional pentesting methodologies and a solid command of Powershell. Data available to us indicates that it has achieved operational success on numerous occasions.

Kaspersky will keep investigating incidents related to this group in the foreseeable future and has gathered a detailed view of their 2020 activity so far. We invite individuals or companies who think they might be – or have been – targeted by IAmTheKing to get in touch with us for additional information, or otherwise request access to our Threat Intelligence Portal for regular updates on this threat actor.

YARA rules

In virtually all our investigations, we write YARA rules to hunt for additional malware samples and get a better idea of each family’s prevalence. In the spirit of sharing knowledge with the community and assisting research efforts on this threat actor, we are happy to release a few of these rules, which will allow defenders to identify recent samples from the families described above. If you are unfamiliar with YARA or would like to learn more about the art of writing rules, please check out the online training written by members of GReAT.

rule apt_IAmTheKing_KingOfHearts { meta: description = "Matches IAmTheKing's KingOfHearts C++ implant" author = "Kaspersky Lab" copyright = "Kaspersky Lab" version = "1.0" type = "APT" filetype = "PE" last_modified = "2020-01-20" strings: $payload_fmt = "cookie=%s;type=%s;length=%s;realdata=%send" ascii $cmd1 = "HEART" ascii $cmd2 = "CMDINFO" ascii $cmd3 = "PROCESSINFO" ascii $cmd4 = "LISTDRIVE" ascii $cmd5 = "LISTFILE" ascii $cmd6 = "DOWNLOAD" ascii condition: uint16(0) == 0x5A4D and filesize < 1MB and ($payload_fmt or all of ($cmd*)) } rule apt_IAmTheKing_KingOfHearts_json { meta: description = "Matches IAmTheKing's KingOfHearts JSON C++ implant" author = "Kaspersky Lab" copyright = "Kaspersky Lab" version = "1.0" type = "APT" filetype = "PE" last_modified = "2020-01-20" strings: $user_agent = "Mozilla/4.0 (compatible; )" ascii $error = "write info fail!!! GetLastError-->%u" ascii $multipart = "Content-Type: multipart/form-data; boundary=--MULTI-PARTS-FORM-DATA-BOUNDARY\x0D\x0A" ascii condition: uint16(0) == 0x5A4D and filesize < 1MB and all of them } rule apt_IAmTheKing_QueenOfHearts_2020 { meta: author = "Kaspersky" copyright = "Kaspersky" version = "1.0" type = "APT" filetype = "PE" description = "Find IAmTheKing's QueenOfHearts 2020 variants" last_modified = "2020-09-29" strings: $s1 = "www.yahoo.com" fullword wide $s2 = "8AAAAHicJY9HDsIwFAXnMmQHIsGULKKIUPZwA0SNqCEIcXwGI+vL781vdknNjR17PvQ48eLKhZKGlsJMwoE7T2nBipSKNQtpy0PSlSSqRr0j1208WVRprNqa6Vs3ju6s" ascii $s3 = "kgAAAHicHYy7DoJAEEXPp2xMKJVEehoKSwsLSqMLCRh5BDTK33vWTHbuzpk7NzLQEMiJ9pmJDy0LK536tA7q1xfYcVJf7Km96jlz5yGJsiCtdN+8XJ1q9yMFR67ySf/M" ascii $s4 = "2gAAAHicHY/JDoJAEAXrZ+SmEUSUAyEueNc/MOBCVFwwxs+3nEw6/V71lilp6Wg48GXEmTc3rpQ86SmsRBy585IWbIlZsqOS9jwkQ0mkeqobct3elwQVh67ayti+WXAX" ascii $s5 = "MyScreen.jpg" fullword wide $s6 = "begin mainthread" fullword wide $s7 = "begin mainthread ok" fullword wide $s8 = "getcommand error" fullword wide $s9 = "querycode error" fullword wide $s10 = "{'session':[{'name':'admin_001','id':21,'time':12836123}],'jpg':" fullword ascii $s11 = "cookie size :%d" fullword wide $s12 = "send request error:%d" fullword wide $s13 = "AABBCCDDEEFFGGHH" fullword wide $s14 = " inflate 1.2.8 Copyright 1995-2013 Mark Adler " fullword ascii $s15 = " Type Descriptor'" fullword ascii $s16 = " constructor or from DllMain." fullword ascii $s17 = " Base Class Descriptor at (" fullword ascii $ex = "ping 127.0.0.1" ascii fullword condition: ( uint16(0) == 0x5A4D ) and ( filesize > 70KB and filesize < 3MB ) and ( 12 of them ) and ( not $ex ) }

Indicators of Compromise

00E415E72A4FC4C8634D4D3815683CE8 KingOfHearts (urlencode variant)
4E2C2E82F076AD0B5D1F257706A5D579 KingOfHearts (JSON variant)
AB956623B3A6C2AC5B192E07B79CBB5B QueenOfHearts
4BBD5869AA39F144FADDAD85B5EECA12 QueenOfHearts
4076DDAF9555031B336B09EBAB402B95 QueenOfHearts
096F7084D274166462D445A7686D1E5C QueenOfHearts
29AA501447E6E20762893A24BFCE05E9 QueenOfClubs
97c6cfa181c849eb87759518e200872f JackOfHearts
7DB4F1547D0E897EF6E6F01ECC484314 Screenshot capture utility
60D78B3E0D7FFE14A50485A19439209B Malicious LNK
90EF53D025E04335F1A71CB9AA6D6592 Keylogger

MontysThree: Industrial espionage with steganography and a Russian accent on both sides

8 Říjen, 2020 - 12:00

In summer 2020 we uncovered a previously unknown multi-module C++ toolset used in highly targeted industrial espionage attacks dating back to 2018. Initially the reason for our interest in this malware was its rarity, the obviously targeted nature of the campaign and the fact that there are no obvious similarities with already known campaigns at the level of code, infrastructure or TTPs. To date, we consider this toolset and the actor behind it to be new. The malware authors named the toolset “MT3”; following this abbreviation we have named the toolset “MontysThree”.

Following the MT3 abbreviation we named the toolset MontysThree

The malware includes a set of C++ modules used for persistence, obtaining data from a bitmap with steganography, decryption of configuration tasks (making screenshots, fingerprinting the target, getting the file, etc.) and their execution, and network communications with major legitimate public cloud services such as Google, Microsoft and Dropbox. MontysThree is configured to search for specific Microsoft Office and Adobe Acrobat documents stored in current documents directories and on removable media. The malware uses custom steganography and several encryption schemes: besides custom XOR-based encryption, the modules rely on 3DES and RSA algorithms for configuration decryption and communications.

MontysThree contains natural language artifacts of proper Russian language and configuration that seek directories that exist only on Cyrilic localised Windows versions. While most external public cloud communications use token-based authorisation, some samples contain email-based accounts for them, which pretend to be a Chinese lookalike. We consider these names to be false flags. Many more artifacts suggest that the malware was developed by a Russian-speaking actor and is targeting Cyrillic Windows versions.

How the malware spreads

The initial loader module is spread inside RAR self-extracting archives (SFX) with names related to employees’ phones list, technical documentation and medical test results. There are no lures, only PE files (masquerading a .pdf or .doc file), but such titles are now a typical trick used in spear-phishing – “corporate info update” or “medical analysis results”. One of the loaders (MD5 da49fea229dd2dedab2b909f24fb24ab) has the name “Список телефонов сотрудников 2019.doc” (“Employee phone list”, in Russian). Other loaders have the names “Tech task.pdf” and “invitro-106650152-1.pdf”. The latter is the name of a medical laboratory in Russia. All of them seem like typical spear-phishing tricks. The SFX script is as follows:

Path=%TEMP%\
SavePath
Setup=rundll32.exe "invitro-106650152-1.pdf",Open
Silent=1
Overwrite=1
Update=U
Delete=invitro-106650152-1.pdf

On execution, the SFX script calls the Open() function (we’ll return to this exported name) of the decompressed loader executable in the %TEMP% directory and deletes it. Judging by the filename, it most likely imitates medical analysis results, given that “Invitro” is a prominent medical laboratory in Russia. This initial PE32 is the first loader module.

How modules work and communicate

Execution flow of MontysThree’s modules

The diagram above shows the overall execution flow of the MontysThree modules. Four modules and their features are listed in the table below. The modules share common communication conventions. When dealing with shared data, such as the configuration and detailed execution log, the malware initializes the structure in thread local storage (TLS), which in its turn refers to heap structures. Interestingly, besides RAM, the execution log is stored on disk in a file, encrypted with a one-byte XOR.

The entry point DllEntryPoint() works just like a construtor, which allocates the structure with TlsAlloc() and saves it in a global variable. Modules must export a function named Open(), which takes no parameters (but could parse the command line) and returns a four-byte error code.

Module name Features Loader This anti-detection module is in charge of custom steganography, kernel module decryption. Kernel This kernel (main) module is in charge of decrypting the config XML, then parsing and executing the corresponding tasks in it. HttpTransport Network module to communicate with Google, Microsoft, Dropbox legitimate public cloud services, as well as with WebDAV sources. The module is able to make requests through RDP and Citrix in a naive way using legitimate clients. LinkUpdate Persistence module is a Windows Quick Launch .lnk modifier. With this naive persistence method users would run the Loader module by themselves every time along with the browsers from the Windows Quick Launch toolbar.

Now let’s take a look how the developers mixed strong modern cryptography standards with custom XOR-based ones.

Task Encryption in use Steganography To decrypt the kernel module the initial loader uses a custom algorithm. Logs encryption The malware logs exist in memory as well as in encrypted files on disk at the same time. In RAM the developers store the logs in plaintext, on disk they use one-byte XOR. Config encryption Kernel module uses strong encryption algorithms. Configuration data is encrypted with 3DES and the key is encrypted using RSA. All the keys – RSA public/private as well as encrypted 3DES – are stored inside the module’s .data section. Network module encryption Initially encrypted HttpTransport is made of four binary blobs stored in the kernel module. The kernel concatenates them and decrypts them with a custom XOR-based algorithm. A round key of four bytes length is used Communications encryption The encryption algorithm is RSA using the same public and private keys stored inside the kernel module .data section.

 

Loader module: Bitmap decryptor and next stage launcher

If the filename of the bitmap containing the steganography-encrypted data is provided to the loader as an argument, the loader decrypts the next stager from the pixel array. In the first iteration, it extracts the steganography parameter data. To do so, the algorithm takes the last bits of the bytes.

The IID, IParam and ISize parameters are kept in the first 384 bytes of the pixel array, meaning that only the last bit of every pixel array’s byte is needed. As a result, the module gathers 48 bytes of steganography configuration structure with the fields, determining the next decryption stages.

Field Offset Features IID 0x00 Determines one or two decryption layers would apply to the following pixel array. IParam 0x04 Determines which bits from pixel arrays bytes would form the next kernel module. ISize 0x28 The decrypted kernel module’s resulting size.

After extracting the steganography parameters, the next stager is decrypted using a two-step algorithm. Firstly, the IParam algorithm chooses the bits from the pixel array’s bytes. Then, if IID equals 2, a custom dexoring operation using a four-byte round key is applied on the gathered bytes. The initial key for the first four-byte decryption has the hardcoded value 0x23041920. Then the formula for the round XOR key for the next bytes is:
key ^= 8 * (key ^ (key << 20))

We consider this steganography algorithm to be custom made and not taken from some open source third-party repository. Surprisingly, the decryption result is not injected into some process’s memory, but dropped to disk as a file named msgslang32.dll. The loader then simply uses the Windows API functions LoadLibraryW() and GetProcAddress() to run the next stager’s Open() function, as we previously saw with the loader module.

Kernel module: Config decryptor and tasks dispatcher

The kernel module contains three encryption keys used for configuration decryption and C2 communications. Public and private RSA keys are stored in the .data section as PUBLICKEYBLOB and PRIVATEKEYBLOB respectively. These are used to encrypt C2 communications and to decrypt the 3DES key as well. The third 3DES key is also stored in the .data section in its encrypted form; this key is used to decrypt an embedded .cab archive containing the XML config. To decompress the .cab archive the module uses Window’s standard system utility, “expand.exe”. We’ll see another common software usage in the HttpTransport module.

The XML configuration contains valuable data that helps us understand the campaign operator’s interest. It is structured using various “tasks” for the malware, such as fingerprinting the target using its OS version, process list and capturing screenshots; but also grabs the list of users’ recent documents with any of the extensions .doc, .docx, .xls, .xlsx, .rtf, .pdf, .odt, .psw, .pwd from the several recent documents directories in %USERPROFILE% and %APPDATA%, including %APPDATA%\Microsoft\Office\Последние файлы. This folder name translates to “Recent files” in Russian, suggesting that the malware is aimed at Cyrillic localised Windows versions.

Config holds the tasks scheduling (screenshot top), access tokens (here Dropbox, redacted), directories and extensions of interest. One directory exists only on Cyrillic Windows localized versions

We observed several Cyrillic text strings such as “Снимок рабочего стола” (desktop snapshot), “Системная информация” (system information), “Время выхода” (exit time).

Config tasks description starts with MT3D and contains proper short phrases in Russian

The decrypted config structure is as follows:

Field Size Content Magic 4 bytes MT3D. All parsed files must have this as a prefix to be valid Creation time 4 bytes Timestamp, task config creation time stored as Epoch time Header size 4 bytes Header size has to be greater than 18. Observed value is e.g. 0x7E XML size 4 bytes XML task description has to be greater than zero. Observed value is e.g. 0x662D XML body XML size The task’s description and schedule in XML format

While the samples we looked at didn’t contain RTTI information, the execution logs allowed us to recover the C++ class names. After the kernel module parses the tasks from the configuration into memory, the main class that processes the instruction is CTask. CTask’s IoControl() method is in charge of handling the corresponding tasks and in turn runs the following methods:

CTask method Features MainIoControl() Handler of “Main” task in XML. In case of a RESET command the file, serving as a “pipe”, will be deleted. Any other command here will be logged, but not executed FileIoControl() Handler of “File” task with PUT, DEL, FIND, WATCH, WATCH_REMOVABLE, RUN and LOGS subcommands SysInfoIoControl() Handler of “SysInfo” task with SCREENSHOT, INFO and TASKLIST subcommands HttpIoControl() Handler of “Http” task with SENDRECV subcommand GDriveIoControl() Handler of “GDrive” task with SENDRECV subcommand DropboxIoControl() Handler of “Dropbox” task with SENDRECV subcommand

All methods used for external communications first decrypt the HttpTransport module and use it to transmit the corresponding data RSA-encrypted. The RSA keys in use are the same aforementioned keys used to decrypt the 3DES config key. In a separate Window procedure, the malware monitors if a USB device is plugged in, searching for files of interest.

HttpTransport module: network tasks

The HttpTransport module exists as four encrypted chunks of data inside the .text section of the kernel module. When the kernel needs to communicate, it decrypts this module and, as usual for MontysThree, runs the Open() function, passing command line arguments.

Depending on the arguments transmitted from the kernel module, the module may upload or download content using RDP, WebDAV, Citrix and HTTP protocols. Downloading data from Google and Dropbox public services using user tokens is implemented in HttpTransport as well. In case of HTTP GET/POST requests, the malware would receive a steganography bitmap picture using Windows API HTTP-related functions from a corresponding URL.

The aforementioned communication protocols themselves aren’t implemented inside the module. The malware authors make use of legitimate Windows programs like RDP, Citrix clients and Internet Explorer already installed on the target’s machine. For example, the module executes a task to send some data to a URL and receive the reply through an RDP connection as follows: edit the .rdp file to silently run Internet Explorer on the remote machine; paste the URL to the browser via the clipboard; wait and paste the contents to the opened web page via the clipboard as well; wait and receive the result through the clipboard again.

To copy data, the malware literally sends Ctrl+C, Ctrl+V and Ctrl+A. Perhaps it’s the first time we have seen such a method of “RDP communication”. The Citrix communication is done using a similar procedure: the malware doesn’t implement the protocol but rather searches for Windows Quick Launch .lnk for XenApp pnagent.exe, runs Internet Explorer remotely and communicates with it through the clipboard using special keyboard shortcuts.

Dropbox and Google data upload and download relies on another principle: its implementation uses the custom class CSimpleHttp to authenticate and send HTTP requests. For WebDAV communication, the developers simply use the “net use” Windows command.

LinkUpdate

This auxiliary module is in charge of achieving persistence on the host. It changes the .lnk files in the Windows Quick Launch panel to run the loader along with legitimate applications such as browsers when the user executes them using the modified link.

Who is behind this malware

As we mentioned at the beginning, to date we have observed no similarities or overlaps with known campaigns in terms of TTPs, infrastructure or malware code. So far, we attribute this activity and the use of MontysThree to a new actor. Some samples contain account details used for communicating with public cloud services, which pretend to be of Chinese origin. Taking into consideration all the aforementioned Cyrilic artefacts, we consider these account names to be false flags.

We assume that the actor behind MontysThree is both Russian-speaking and is going after Russian-speaking targets. Some of the filenames of the RAR SFX archives used for spreading the malware were written in Russian and referenced a Russian medical laboratory, used to entice the user to open the file. The XML configuration showcased data fields and Windows titles written in Russian, as well as specific folder paths that exist on Cyrilic localised versions of Windows. We also saw some grammatical errors in the malware’s English log message strings.

Let’s sum up

Typically we see targeted malware that is mostly going after governmental entities, diplomats and telecom operators, which are fruitful for state-sponsored actors. Industrial espionage cases like MontysThree are far more rare.

The overall campaign sophistication doesn’t compare to top notch APT actors in terms of spreading, persistence method. And some aspects of the malware – logging in RAM and files at the same time, keeping the encryption keys in the same file, running an invisible browser on the remote RDP host – seem immature and amateurish in terms of malware development.

On the other hand, the amount of code and therefore effort invested, in MontysThree is significant. The toolset demonstrates some tech-savvy decisions: Storing 3DES key under RSA encryption, custom steganography to avoid IDS and the use of legitimate cloud storage providers to hide the C2 traffic.

File Hashes

Loader
1B0EE014DD2D29476DF31BA078A3FF48
0976C442A06D2D8A34E9B6D38D45AE42
A2AA414B30934893864A961B71F91D98

Kernel
A221671ED8C3956E0B9AF2A5E04BDEE3
3A885062DAA36AE3227F16718A5B2BDB
3AFA43E1BC578460BE002EB58FA7C2DE

HttpTransport
017539B3D744F7B6C62C94CE4BCA444F
501E91BA1CE1532D9790FCD1229CBBDA
D6FB78D16DFE73E6DD416483A32E1D72

Domains and IPs

autosport-club.tekcities[.]com
dl10-web-stock[.]ru
dl16-web-eticket[.]ru
dl166-web-eticket[.]ru
dl55-web-yachtbooking[.]xyz

MosaicRegressor: Lurking in the Shadows of UEFI

5 Říjen, 2020 - 12:00

 Part II. Technical details (PDF)

UEFI (or Unified Extensible Firmware Interface) has become a prominent technology that is embedded within designated chips on modern day computer systems. Replacing the legacy BIOS, it is typically used to facilitate the machine’s boot sequence and load the operating system, while using a feature-rich environment to do so. At the same time, it has become the target of threat actors to carry out exceptionally persistent attacks.

One such attack has become the subject of our research, where we found a compromised UEFI firmware image that contained a malicious implant. This implant served as means to deploy additional malware on the victim computers, one that we haven’t come across thus far. To the best of our knowledge, this is the second known public case where malicious UEFI firmware in use by a threat actor was found in the wild.

Throughout this blog we will elaborate on the following key findings:

  • We discovered rogue UEFI firmware images that were modified from their benign counterpart to incorporate several malicious modules;
  • The modules were used to drop malware on the victim machines. This malware was part of a wider malicious framework that we dubbed MosaicRegressor;
  • Components from that framework were discovered in a series of targeted attacks pointed towards diplomats and members of an NGO from Africa, Asia and Europe, all showing ties in their activity to North Korea;
  • Code artefacts in some of the framework’s components and overlaps in C&C infrastructure used during the campaign suggest that a Chinese-speaking actor is behind these attacks, possibly having connections to groups using the Winnti backdoor;

The attack was found with the help of Firmware Scanner, which has been integrated into Kaspersky products since the beginning of 2019. This technology was developed to specifically detect threats hiding in the ROM BIOS, including UEFI firmware images.

Current State of the Art

Before we dive deep into our findings, let us have a quick recap of what UEFI is and how it was leveraged for attacks thus far. In a nutshell, UEFI is a specification that constitutes the structure and operation of low-level platform firmware, so as to allow the operating system to interact with it at various stages of its activity.

This interaction happens most notably during the boot phase, where UEFI firmware facilitates the loading of the operating system itself. That said, it can also occur when the OS is already up and running, for example in order to update the firmware through a well-defined software interface.

Considering the above, UEFI firmware makes for a perfect mechanism of persistent malware storage. A sophisticated attacker can modify the firmware in order to have it deploy malicious code that will be run after the operating system is loaded. Moreover, since it is typically shipped within SPI flash storage that is soldered to the computer’s motherboard, such implanted malware will be resistant to OS reinstallation or replacement of the hard drive.
This type of attack has occurred in several instances in the past few years. A prominent example is the LowJax implant discovered by our friends at ESET in 2018, in which patched UEFI modules of the LoJack anti-theft software (also known as Computrace) were used to deploy a malicious user mode agent in a number of Sofacy \ Fancy Bear victim machines. The dangers of Computrace itself were described by our colleagues from the Global Research and Analysis Team (GReAT) back in 2014.

Another example is source code of a UEFI bootkit named VectorEDK which was discovered in the Hacking Team leaks from 2015. This code consisted of a set of UEFI modules that could be incorporated into the platform firmware in order to have it deploy a backdoor to the system which will be run when the OS loads, or redeploy it if it was wiped. Despite the fact that VectorEDK’s code was made public and can be found in Github nowadays, we hadn’t witnessed actual evidence of it in the wild, before our latest finding.

Our Discovery

During an investigation, we came across several suspicious UEFI firmware images. A deeper inspection revealed that they contained four components that had an unusual proximity in their assigned GUID values, those were two DXE drivers and two UEFI applications. After further analysis we were able to determine that they were based on the leaked source code of HackingTeam’s VectorEDK bootkit, with minor customizations.

Rogue components found within the compromised UEFI firmware

The goal of these added modules is to invoke a chain of events that would result in writing a malicious executable named ‘IntelUpdate.exe’ to the victim’s Startup folder. Thus, when Windows is started the written malware would be invoked as well. Apart from that, the modules would ensure that if the malware file is removed from the disk, it will be rewritten. Since this logic is executed from the SPI flash, there is no way to avoid this process other than eliminating the malicious firmware.

Following is an outline of the components that we revealed:

  • SmmInterfaceBase: a DXE driver that is based on Hacking Team’s ‘rkloader’ component and intended to deploy further components of the bootkit for later execution. This is done by registering a callback that will be invoked upon an event of type EFI_EVENT_GROUP_READY_TO_BOOT. The event occurs at a point when control can be passed to the operating system’s bootloader, effectively allowing the callback to take effect before it. The callback will in turn load and invoke the ‘SmmAccessSub’ component.
  • Ntfs: a driver written by Hacking Team that is used to detect and parse the NTFS file system in order to allow conducting file and directory operations on the disk.
  • SmmReset: a UEFI application intended to mark the firmware image as infected. This is done by setting the value of a variable named ‘fTA’ to a hard-coded GUID. The application is based on a component from the original Vector-EDK code base that is named ‘ReSetfTA’.

 Setting of the fTA variable with a predefined GUID to mark the execution of the bootkit

  • SmmAccessSub: the main bootkit component that serves as a persistent dropper for a user-mode malware. It is executed by the callback registered during the execution of ‘SmmInterfaceBase’, and takes care of writing a binary embedded within it as a file named ‘IntelUpdate.exe’ to the startup directory on disk. This allows the binary to execute when Windows is up and running.
    This is the only proprietary component amongst the ones we inspected, which was mostly written from scratch and makes only slight use of code from a Vector-EDK application named ‘fsbg’. It conducts the following actions to drop the intended file to disk:

    • Bootstraps pointers for the SystemTable, BootServices and RuntimeServices global structures.
    • Tries to get a handle to the currently loaded image by invoking the HandleProtocol method with the EFI_LOADED_IMAGE_PROTOCOL_GUID argument.
    • If the handle to the current image is obtained, the module attempts to find the root drive in which Windows is installed by enumerating all drives and checking that the ‘\Windows\System32’ directory exists on them. A global EFI_FILE_PROTOCOL object that corresponds to the drive will be created at this point and referenced to open any further directories or files in this drive.
    • If the root drive is found in the previous stage, the module looks for a marker file named ‘setupinf.log’ under the Windows directory and proceeds only if it doesn’t exist. In the absence of this file, it is created.
    • If the creation of ‘setupinf.log’ succeeds, the module goes on to check if the ‘Users’ directory exists under the same drive.
    • If the ‘Users’ directory exists, it writes the ‘IntelUpdate.exe’ file (embedded in the UEFI application’s binary) under the ‘ProgramData\Microsoft\Windows\Start Menu\Programs\Startup’ directory in the root drive.

Code from ‘SmmAccessSub’ used to write the embedded ‘IntelUpdate.exe’ binary to the Windows Startup directory

Unfortunately, we were not able to determine the exact infection vector that allowed the attackers to overwrite the original UEFI firmware. Our detection logs show that the firmware itself was found to be malicious, but no suspicious events preceded it. Due to this, we can only speculate how the infection could have happened.

One option is through physical access to the victim’s machine. This could be partially based on Hacking Team’s leaked material, according to which the installation of firmware infected with VectorEDK requires booting the target machine from a USB key. Such a USB would contain a special update utility that can be generated with a designated builder provided by the company. We found a Q-flash update utility in our inspected firmware, which could have been used for such a purpose as well.

Furthermore, the leaks reveal that the UEFI infection capability (which is referred to by Hacking Team as ‘persistent installation’) was tested on ASUS X550C laptops. These make use of UEFI firmware by AMI which is very similar to the one we inspected. For this reason we can assume that Hacking Team’s method of patching the firmware would work in our case as well.

Excerpt from a Hacking Team manual for deployment of infected UEFI firmware, also known as ‘persistent installation’

Of course, we cannot exclude other possibilities whereby rogue firmware was pushed remotely, perhaps through a compromised update mechanism. Such a scenario would typically require exploiting vulnerabilities in the BIOS update authentication process. While this could be the case, we don’t have any evidence to support it.

The Bigger Picture: Enter MosaicRegressor Framework

While Hacking Team’s original bootkit was used to write one of the company’s backdoors to disk, known as ‘Soldier’, ‘Scout’ or ‘Elite’, the UEFI implant we investigated deployed a new piece of malware that we haven’t seen thus far. We decided to look for similar samples that share strings and implementation traits with the dropped binary. Consequently, the samples that we found suggested that the dropped malware was only one variant derived from a wider framework that we named MosaicRegressor.

MosaicRegressor is a multi-stage and modular framework aimed at espionage and data gathering. It consists of downloaders, and occasionally multiple intermediate loaders, that are intended to fetch and execute payload on victim machines. The fact that the framework consists of multiple modules assists the attackers to conceal the wider framework from analysis, and deploy components to target machines only on demand. Indeed, we were able to obtain only a handful of payload components during our investigation.

The downloader components of MosaicRegressor are composed of common business logic, whereby the implants contact a C&C, download further DLLs from it and then load and invoke specific export functions from them. The execution of the downloaded modules usually results in output that can be in turn issued back to the C&C.

Having said that, the various downloaders we observed made use of different communication mechanisms when contacting their C&Cs:

  • CURL library (HTTP/HTTPS)
  • BITS transfer interface
  • WinHTTP API
  • POP3S/SMTPS/IMAPS, payloads transferred in e-mail messages

The last variant in the list is distinct for its use of e-mail boxes to host the requested payload. The payload  intended to run by this implant can also generate an output upon invocation, which can be later forwarded to a ‘feedback’ mail address, where it will likely be collected by the attackers.

The mail boxes used for this purpose reside on the ‘mail.ru’ domain, and are accessed using credentials that are hard-coded in the malware’s binary. To fetch the requested file from the target inbox, MailReg enters an infinite loop where it tries to connect to the “pop.mail.ru” server every 20 minutes, and makes use of the first pair of credentials that allow a successful connection. The e-mails used for login (without their passwords) and corresponding feedback mail are specified in the table below:

Login mail Feedback mail thtgoolnc@mail.ru thgetmmun@mail.ru thbububugyhb85@mail.ru thyhujubnmtt67@mail.ru

The downloaders can also be split in two distinct types, the “plain” one just fetching the payload, and the “extended” version that also collects system information:

Structure of the log file written by BitsRegEx, strings marked in red are the original fields that appear in that file

We were able to obtain only one variant of the subsequent stage, that installs in the autorun registry values and acts as another loader for the components that are supposed to be fetched by the initial downloader. These components are also just intermediate loaders for the next stage DLLs. Ultimately, there is no concrete business logic in the persistent components, as it is provided by the C&C server in a form of DLL files, most of them temporary.

We have observed one such library, “load.rem“, that is a basic document stealer, fetching files from the “Recent Documents” directory and archiving them with a password, likely as a preliminary step before exfiltrating the result to the C&C by another component.

The following figure describes the full flow and connection between the components that we know about. The colored elements are the components that we obtained and gray ones are the ones we didn’t:

Flow from BitsRegEx to execution of intermediate loaders and final payload

 

Who were the Targets?

According to our telemetry, there were several dozen victims who received components from the MosaicRegressor framework between 2017 and 2019. These victims included diplomatic entities and NGOs in Africa, Asia and Europe. Only two of them were also infected with the UEFI bootkit in 2019, predating the deployment of the BitsReg component.

Based on the affiliation of the discovered victims, we could determine that all had some connection to the DPRK, be it non-profit activity related to the country or actual presence within it. This common theme  can be reinforced through one of the infection vectors used to deliver the malware to some of the victims, which was SFX archives pretending to be documents discussing various subjects related to North Korea. Those were bundled with both an actual document and MosaicRegressor variants, having both executed when the archive is opened. Examples for the lure documents can be seen below.

Examples of lure documents bundled to malicious SFX archives sent to MosaicRegressor victims, discussing DPRK related topics

 

Who is behind the attack?

When analyzing MosaicRegressor’s variants, we noticed several interesting artefacts that provided us with clues on the identity of the actor behind the framework. As far as we can tell, the attacks were conducted by a Chinese-speaking actor, who may have previously used the Winnti backdoor. We found the following evidence to support this:

  • We spotted many strings used in the system information log generated by the BitsRegEx variant that contain the character sequence ‘0xA3, 0xBA’. This is an invalid sequence for a UTF8 string and the LATIN1 encoding translates these symbols to a pound sign followed by a “masculine ordinal indicator” (“£º”). An attempt to iterate over all available iconv symbol tables, trying to convert the sequence to UTF-8, produces possible candidates that give a more meaningful interpretation. Given the context of the string preceding the symbol and line feed symbols following it, the best match is the “FULL-WIDTH COLON” Unicode character translated from either the Chinese or Korean code pages (i.e. CP936 and CP949).

Figure: The BitsRegEx system information log making use of the character sequence 0xA3, 0xBA, likely used to represent a full-width colon, according to code pages CP936 and CP949.

  • Another artefact that we found was a file resource found in CurlReg samples that contained a language identifier set to 2052 (“zh-CN”)

Chinese language artefact in the resource section of a CurlReg sample

  • We detected an OLE2 object taken out of a document armed with the CVE-2018-0802 vulnerability, which was produced by the so-called ‘Royal Road’ / ‘8.t’ document builder and used to drop a CurlReg variant. To the best of our knowledge, this builder is commonly used by Chinese-speaking threat actors.

Excerpt from the OLE2 object found within a ‘Royal Road’ weaponized document, delivering the CurlReg variant

  • A C&C address (103.82.52[.]18) which was found in one of MosaicRegressor’s variants (MD5:3B58E122D9E17121416B146DAAB4DB9D) was observed in use by the ‘Winnti umbrella and linked groups’, according to a publicly available report. Since this is the only link between our findings and any of the groups using the Winnti backdoor, we estimate with low confidence that it is indeed responsible for the attacks.
Conclusion

The attacks described in this blog post demonstrate the length an actor can go in order to gain the highest level of persistence on a victim machine. It is highly uncommon to see compromised UEFI firmware in the wild, usually due to the low visibility into attacks on firmware, the advanced measures required to deploy it on a target’s SPI flash chip, and the high stakes of burning sensitive toolset or assets when doing so.

With this in mind, we see that UEFI continues to be a point of interest to APT actors, while at large being overlooked by security vendors. The combination of our technology and understanding of the current and past campaigns leveraging infected firmware, helps us monitor and report on future attacks against such targets.

The full details of this research, as well as future updates on the underlying threat actor, are available to customers of the APT reporting service through our Threat Intelligence Portal.

IoCs

The followings IoC list is not complete. If you want more information about the APT discussed here, a full IoC list and YARA rules are available to customers of Kaspersky Threat Intelligence Reports. Contact: intelreports@kaspersky.com

UEFI Modules

F5B320F7E87CC6F9D02E28350BB87DE6 (SmmInterfaceBase)
0C136186858FD36080A7066657DE81F5 (SmmAccessSub)
91A473D3711C28C3C563284DFAFE926B (SmmReset)
DD8D3718197A10097CD72A94ED223238 (Ntfs)

RAR SFX droppers

0EFB785C75C3030C438698C77F6E960E
12B5FED367DB92475B071B6D622E44CD
3B3BC0A2772641D2FC2E7CBC6DDA33EC
3B58E122D9E17121416B146DAAB4DB9D
70DEF87D180616406E010051ED773749
7908B9935479081A6E0F681CCEF2FDD9
AE66ED2276336668E793B167B6950040
B23E1FE87AE049F46180091D643C0201
CFB072D1B50425FF162F02846ED263F9

Decoy documents

0D386EBBA1CCF1758A19FB0B25451AFE
233B300A58D5236C355AFD373DABC48B
449BE89F939F5F909734C0E74A0B9751
67CF741E627986E97293A8F38DE492A7
6E949601EBDD5D50707C0AF7D3F3C7A5
92F6C00DA977110200B5A3359F5E1462
A69205984849744C39CFB421D8E97B1F
D197648A3FB0D8FF6318DB922552E49E

BitsReg

B53880397D331C6FE3493A9EF81CD76E
AFC09DEB7B205EADAE4268F954444984 (64-bit)

BitsRegEx

DC14EE862DDA3BCC0D2445FDCB3EE5AE
88750B4A3C5E80FD82CF0DD534903FC0
C63D3C25ABD49EE131004E6401AF856C
D273CD2B96E78DEF437D9C1E37155E00
72C514C0B96E3A31F6F1A85D8F28403C

CurlReg

9E182D30B070BB14A8922CFF4837B94D
61B4E0B1F14D93D7B176981964388291
3D2835C35BA789BD86620F98CBFBF08B

CurlRegEx

328AD6468F6EDB80B3ABF97AC39A0721
7B213A6CE7AB30A62E84D81D455B4DEA

MailReg

E2F4914E38BB632E975CFF14C39D8DCD

WinHTTP Based Downloaders

08ECD8068617C86D7E3A3E810B106DCE
1732357D3A0081A87D56EE1AE8B4D205
74DB88B890054259D2F16FF22C79144D
7C3C4C4E7273C10DBBAB628F6B2336D8

BitsReg Payload (FileA.z)

89527F932188BD73572E2974F4344D46

2nd Stage Loaders

36B51D2C0D8F48A7DC834F4B9E477238 (mapisp.dll)
1C5377A54CBAA1B86279F63EE226B1DF (cryptui.sep)
9F13636D5861066835ED5A79819AAC28 (cryptui.sep)

3rd Stage Payload

FA0A874926453E452E3B6CED045D2206 (load.rem)

File paths

%APPDATA%\Microsoft\Credentials\MSI36C2.dat
%APPDATA%\Microsoft\Internet Explorer\%Computername%.dat
%APPDATA%\Microsoft\Internet Explorer\FileA.dll
%APPDATA%\Microsoft\Internet Explorer\FileB.dll
%APPDATA%\Microsoft\Internet Explorer\FileC.dll
%APPDATA%\Microsoft\Internet Explorer\FileD.dll
%APPDATA%\Microsoft\Internet Explorer\FileOutA.dat
%APPDATA%\Microsoft\Network\DFileA.dll
%APPDATA%\Microsoft\Network\DFileC.dll
%APPDATA%\Microsoft\Network\DFileD.dll
%APPDATA%\Microsoft\Network\subst.sep
%APPDATA%\Microsoft\WebA.dll
%APPDATA%\Microsoft\WebB.dll
%APPDATA%\Microsoft\WebC.dll
%APPDATA%\Microsoft\Windows\LnkClass.dat
%APPDATA%\Microsoft\Windows\SendTo\cryptui.sep
%APPDATA%\Microsoft\Windows\SendTo\load.dll %APPDATA%\Microsoft\Windows\load.rem
%APPDATA%\Microsoft\Windows\mapisp.dll
%APPDATA%\Microsoft\exitUI.rs
%APPDATA%\Microsoft\sppsvc.tbl
%APPDATA%\Microsoft\subst.tbl
%APPDATA%\newplgs.dll
%APPDATA%\rfvtgb.dll
%APPDATA%\sdfcvb.dll
%APPDATA%\msreg.dll
%APPDATA\Microsoft\dfsadu.dll
%COMMON_APPDATA%\Microsoft\Windows\user.rem
%TEMP%\BeFileA.dll
%TEMP%\BeFileC.dll
%TEMP%\RepairA.dll
%TEMP%\RepairB.dll
%TEMP%\RepairC.dll
%TEMP%\RepairD.dll
%TEMP%\wrtreg_32.dll
%TEMP%\wrtreg_64.dll
%appdata%\dwhost.exe
%appdata%\msreg.exe
%appdata%\return.exe
%appdata%\winword.exe

Domains and IPs

103.195.150[.]106
103.229.1[.]26
103.243.24[.]171
103.243.26[.]211
103.30.40[.]116
103.30.40[.]39
103.39.109[.]239
103.39.109[.]252
103.39.110[.]193
103.56.115[.]69
103.82.52[.]18
117.18.4[.]6
144.48.241[.]167
144.48.241[.]32
150.129.81[.]21
43.252.228[.]179
43.252.228[.]252
43.252.228[.]75
43.252.228[.]84
43.252.230[.]180
menjitghyukl.myfirewall[.]org

Additional Suspected C&Cs

43.252.230[.]173
185.216.117[.]91
103.215.82[.]161
103.96.72[.]148
122.10.82[.]30

Mutexes

FindFirstFile Message Bi
set instance state
foregrounduu state
single UI
Office Module
process attach Module

SAS@Home is back this fall

30 Září, 2020 - 17:15

The world during the pandemic prepares many surprises for us. Most of them are certainly unpleasant: health risks, inability to travel or meet old friends. One of these unpleasant surprises awaited us in the early spring, when the organizing team of the beloved SAS conference were forced to announce that the event would be postponed to the fall. Later, another difficult but correct decision was made: to cancel the SAS conference altogether this year.

At the same time, it was the pandemic that gave us the opportunity to invite an unprecedented number of people to the online version of the conference, which we called SAS@Home: more than 2,000 people participated at its peak. All of them had the opportunity to touch the unique atmosphere of the SAS: to see the coolest IT security experts in the company of their colleagues with whom they have warm and friendly relationships.

Now, this unique year presents us with a new surprise: the second SAS in one calendar year! Once again, everyone can visit this online event. Our listeners will plunge into the friendly atmosphere of our cozy online conference to listen to new stories from leading experts and threat hunters from around the world, from the comfort of their own couch.

The speakers are experts at Kaspersky Lab:

  • Denis Legezo will tell a fascinating story about espionage in industrial companies worthy of the James Bond series.
  • Tatyana Shishkova will talk about long-running spyware that has been on the radar of analysts for a while but still continues to change and be of interest.
  • Costin Raiu will take the stage to untangle the issue of location tracking and explain how applications collect our data covertly.
  • Last but not least, Igor Kuznetsov and Mark Lechtik will share their fresh research disclosing something entirely new and unexpected.

Well-known industry experts from other companies will also join us:

  • Katie Moussouris, CEO & Founder of Luta Security who has been featured in two Forbes lists: The World’s Top 50 Women in Tech and America’s Top 50 Women in Tech, will talk about Vulnerability Disclosure Programs (VDPs) across many government sectors, and what could possibly go wrong with them.
  • John Lambert, the Vice President of the Microsoft Threat Intelligence Center, will talk about “githubification” of InfoSec.
  • Kris McConkey from PwC will present a highly technical demonstration of ways to find victims and C2 servers associated with rare implants from multiple APT actors in situations where it is really hard to obtain any viable samples.
  • In addition, Ohad Zaidenberg, Marc Rogers, Nate Warfield and Patrick Wardle will share their stories.

Just like during the first SAS@home, the last two days of the conference will be largely devoted to workshops, which will help to pump skills from different areas of digital security:

  • Vitaly Kamluk will teach how to use professional solutions for remote digital forensics.
  • Pavel Cheremushkin will share the secrets of his incredible success in searching for vulnerabilities in his workshop on automated discovery of memory corruption vulnerabilities.
  • SAS@home participants will also have the opportunity to listen to a Virus Total workshop conducted by our friends Vicente Diaz and Juan Infantes Diaz. This workshop will be of interest to any threat hunter who has not yet discovered all the capabilities offered by Virus Total.
  • A good friend of the SAS conference, Joe Fitzpatrick of Securing Hardware, will share his extensive knowledge of IoT security.

As always, the SAS is preparing a lot of fun activities and gifts for attendees:

  • Easter egg challenge for the most attentive listeners.
  • Mini CTF that will be announced this week. Three winners will get full access to Kaspersky training course for experts, “Hunt APTs with Yara like a GReAT Ninja“, for free.
  • All SAS@home participants will receive a discount code for the course that will be valid for the duration of the conference.

All these activities, workshops and presentations will take place on October 6 through 8:

11:00 AM – 2:00 PM Eastern
8:00 AM – 11:00 AM PST
4:00 PM – 7:00 PM London
6:00 PM – 9:00 PM Moscow

You will find the full SAS@Home agenda here: https://thesascon.com/Online

All you need to do to join this awesome conference is register here: https://kas.pr/3e7o

Why master YARA: from routine to extreme threat hunting cases. Follow-up

29 Září, 2020 - 16:00

On 3rd of September, we were hosting our “Experts Talk. Why master YARA: from routine to extreme threat hunting cases“, in which several experts from our Global Research and Analysis Team and invited speakers shared their best practices on YARA usage. At the same time, we also presented our new online training covering some ninja secrets of using YARA to hunt for targeted attacks and APTs.

Here is a brief summary of the agenda from that webinar:

  • Tips and insights on efficient threat hunting with YARA
  • A detailed demo of our renowned training
  • A threat hunting panel discussion with a lot of real-life yara-rules examples

Due to timing restrictions we were not able to answer all the questions, therefore we’re trying to answer them below. Thanks to everyone who participated and we appreciate all the feedback and ideas!

Questions about usage of YARA rules
  1. How practical (and what is the ROI), in your opinion, is it to develop in-house (in-company/custom) YARA rules (e.g. for e-mail / web-proxy filtering system), for mid-size and mid-mature (in security aspects) company, when there are already market-popular e-mail filtering/anti-virus solutions in use (with BIG security departments working on the same topic)?
  2. In the case of mid-size companies, they can benefit a lot from three things connected to YARA, because YARA gives you some flexibility to tailor security for your environment.
    First is the usage of YARA during incident response. Even if you don’t have an EDR Endpoint Detection and Response) solution, you can easily roll-out YARA and collect results through the network using PowerShell or bash. And it’s often the case that someone in a company should have experience developing YARA rules.
    Second is the usage of third-party YARA rules. It’s an effective way to  have one more layer of protection. On the other hand, you need to maintain hunting and detection sets and fix rules and remove false positives anyway. Which once again means that someone needs experience in writing YARA rules.
    Third is that, as mentioned earlier, it might be really useful to have rules to look for organization-specific information or IT assets. It can be a hunting rule that triggers on specific project names, servers, domains, people, etc.So the short answer is yes, but it is important to invest time wisely, so as not to become overwhelmed with unrelated detections.

  3. What is the biggest challenge in your daily YARA rule writing/management process? Is it a particular malware family, actor, or perhaps a specific anti-detection technique?
  4. In our experience, certain file formats make writing YARA rules more difficult. For instance, malware stored in the Office Open XML file format is generally more tricky to detect than the OLE2 compound storage, because of the additional layer of ZIP compression. Since YARA itself doesn’t support ZIP decompression natively, you need to handle that with external tools. Other examples include HLL (high level language) malware, notably Python or Golang malware. Such executables can be several megabytes in size and contain many legitimate libraries. Finding good strings for detection of malicious code in such programs can be very tricky.

  5. Some malware uses YouTube or Twitter or other social media network comments for Command-and-Control. In that regard, where there are no C2 IPs, is it currently hard to detect these?
  6. Yes and no. Yes, it’s hard to get the real C2, because you need to reverse engineer or dynamically run malware to get the final C2. No, it’s relatively easy to detect, because from a ML   point of view  it’s a pure anomaly when very unpopular software goes to a popular website.

  7. So what is the size of the publicly available collections for people to use YARA against? What are some good ways to access a set of benign files, if you don’t have access to retrohunts/VTI?
  8. You can use YARA on clean files and malware samples. Creating a comprehensive clean collection is a challenge, but in general, to avoid false positives, we recommend grabbing OS  distributions and popular software. For this purpose, a good starting point could be sites like:
    https://www.microsoft.com/en-us/download
    https://sourceforge.net/
    ftp://ftp.elf.stuba.sk/pub/pc/

    For malware collection it’s a bit tricker. In an organization it’s easier, since you can collect executables from your own infrastructure. There are also websites with the collection of bad files for research purpose in Lenni Zeltser blogpost there is a good list of references:
    https://zeltser.com/malware-sample-sources/

    The final size of such a collection could be several terabytes or even more.

  9. Can YARA be used to parse custom packers?
  10. Yes, but not out-of-the-box. YARA has a modular architecture, so you can write a module that will first unpack the custom packer and then scan the resulting binary.
    A more common option is to run YARA against already unpacked objects, e.g. results of unpacking tools like Kaspersky Deep Unpack or sandbox and emulator dumps.

  11. What is the trade-off when we want to hunt for new malware using YARA rules? How many FPs should we accept when we need rules that detect new variants
  12. It depends what you want to catch. In general, from a research perspective, it’s ok to have an average FP rate up to 30%. On the other hand, production rules should have no FPs whatsoever!

  13. Could YARA help us to detect a fileless attack (malware)?
  14. Yes, YARA can scan memory dumps and different data containers. Also, you can run YARA against telemetry, but it may take some additional steps to achieve it and properly modify the ruleset.

  15. We can use YARA, together with network monitoring tools like Zeek, to scan files like malicious documents. Can YARA be used against an encrypted protocol?
  16. Only if you do a MITM (Man-in-the-Middle) and decrypt the traffic, since YARA rules most likely expect to run on decrypted content.

  17. What open source solution do you recommend in order to scan a network with YARA rules?
  18. YARA itself plus PowerShell or bash scripts; or, as an alternative, you can use an incident response framework and monitoring agent like OSquery, Google Rapid Response, etc. Other options are based on EDR solutions which are mostly proprietary.

  19. Which is better, YARA or Snort, for looking at the resource utilization for detection in live environments?
  20. YARA and Snort are different tools providing different abilities. Snort is designed specifically as a network traffic scanner, while YARA is for scanning files and/or memory. The best approach is to combine usage of YARA and Snort rules together!

Questions about creating yara rules and training course questions
  1. Are we able to keep any of the materials after the course is finished?
  2. Yes, Kaspersky YARA cheat-sheets or training slides which include Kaspersky solutions to exercises are some of the things that are available for you to download and use even after the training session has finished.

  3. Is knowledge about string extraction or hashing sufficient to create solid YARA rules? Are there other things to learn as prerequisites?
  4. This depends on case-by-case knowledge. Strings and hashing are basic building blocks for creating YARA rules. Other important things are PE structure and preferences and anomalies in headers, entropy, etc. Also, to create rules for a specific file format, you need some knowledge of the architecture of the corresponding platform and file types.

  5. Can we add a tag to the rule that says it is elegant, efficient or effective, such as the tag on the exploit (in the metasploit): excellent, great, or normal?
  6. Sounds like a good idea. Actually, YARA rules also support tags in the name:
    https://yara.readthedocs.io/en/stable/writingrules.html

  7. Maybe you can explain more about the fact that metadata strings don’t have a direct impact on the actual rule.

    As we described before, a YARA rule can consist of meta, strings and conditions. While the condition is a mandatory element, the meta section is used only for providing more info about that specific YARA rule. and it is not at all used by the YARA scanning engine.

  8. ASCII is the default, so why do you need to put ASCII in the rule?
  9. Without ASCII, say ‘$a1 = “string” wide’, only the Unicode representation of the string would be searched. To search both ASCII and Unicode, we need ‘$a1= “string” ascii wide’.

  10. Can we use RegEx in YARA? Is nesting possible in YARA?
  11. Yes, it’s possible to use RegEx patterns in YARA. Be aware that RegEx patterns usually affect performance and can be rewritten in the  form of lists. But in some cases you just cannot avoid using them and the YARA engine fully supports them.
    Nesting is also possible in YARA. You can write private rules that will be used as a condition or as a pre-filter for your other rules.

  12.  Is there a limit on the number of statements in a YARA rule?
  13. We created several systems that create YARA rules automatically; and over time these have reached tens of megabytes in size. While these still work fine for us, having a very large number of strings in one rule can lead to issues. In many cases, setting a large stack size (see the yara -k option) helps.

  14. Can we say that YARA can be a double-edged sword? So a hacker can develop malware and then check with YARA if there’s anything similar out there and enhance it accordingly?
  15. Sure, although they would need access to your private stash of YARA rules. In essence, YARA offers organizations a way to add extra defenses by creating custom, proprietary YARA rules for malware that could be used against them. Malware developers can always test their creations with antivirus products they can just download or purchase. However, it would be harder to get access to private sets of YARArules.

  16. This is a philosophical question: Juan said YARA has democratized hunting for malware. How have APTs and malware authors responded to this? Do they have anti-YARA techniques?
  17. A few years ago we observed a certain threat actor constantly avoiding our private YARA rules for one to two months after we published a report. Although the YARA rules were very strong, the changes the threat actor made to the malware kind of suggested they knew specifically what to change. For instance, in the early days they would use only a few encryption keys across different samples, which we, of course, used in our YARA rules. Later, they switched to a unique key per sample.

  18. Would be possible to create a YARA rule to find Morphy’s games among a large set of chess games?
  19. Probably! Morphy was one of the most famous players from the so-called romantic chess period, characterised by aggressive openings, gambits and risky play. Some of the openings that Morphy loved, such as the Evans Gambit or the King’s Gambit accepted, together with playing with odds (Morphy would sometimes play without a rook against a weaker opponent), might yield some interesting games. Or, you could just search for ‘$a1 = “Morphy, Paul” ascii wide nocase’, perhaps together with’ $a2 = “1. e4″‘  ????

  20. Would you recommend YARA for Territorial Dispute checks?
  21. Yes, of course. In essence, “Territorial Dispute” references a set of IoCs for various threat actors, identified through “SIGS”. While some of them have been identified, for instance in Boldi’s paper, many are still unknown. With YARA, you can search for unique filenames or other artifacts and try to find malware that matches those IoCs. Most recently, Juan Andres Guerrero-Saade was able to identify SIG37 as “Nazar”: check out his research here:
    https://www.epicturla.com/blog/the-lost-nazar

Pro tips and tricks from the audience
  • Using YARA programmatically (e.g. via py/c) allows you to use hit callbacks to get individual string matches. This enables you to check for partial rule coverage (k of n strings matched but without triggering the condition), which is great for aiding rule maintenance.
  • On the top white list (clean stuff), known exploits and payloads should be also populated in our YARArule sets.
  • I always find it easier to maintain code by grouping the strings together.
  • As a dedicated/offline comment to JAG-S: The “weird” strings from the rule discussed most likely come from the reloc section (thus locking on encoded offsets), which would make the rule highly specific to a given build, even with a soft 15/22 strings required. That would still probably work well if the samples originate from a builder (i.e. configured stub) but should not generalize well. And for the IDA-extracted functions: consider wildcarding offsets to have better generalizing rules.
  • When it comes to strings – besides the strings from disk, mem, network dump, etc., bringing context and offset should be a best practice. Then rank the strings in the context of the malware. And this requires human expertise but can be easily adapted into the YARA rule building process.
  • Сombining, in a flexible way, the YARA rules build process with the enrichment of the recently announced Kaspersky Threat Attribution Engine, will be also GReAT ????

Feel free to follow us on Twitter and other social networks for updates, and feel free to reach out to us to discuss interesting topics.
On Twitter: