• Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg
  • Delicious

Anti-Malware Laboratory

Yet Another Malware Blog

About

An informal blog from your friendly neighborhood software security humans.

Blog Archive

  • ►  2015 (5)
    • ►  October (1)
    • ►  August (2)
    • ►  May (1)
    • ►  March (1)
  • ►  2014 (8)
    • ►  October (1)
    • ►  July (1)
    • ►  June (1)
    • ►  May (4)
    • ►  April (1)
  • ▼  2013 (12)
    • ▼  December (3)
      • A Hesperbot Core Analysis
      • PDF CVE-2013-5065 - Dropped BAD Malware
      • New PDF Exploit uses 2 new vuln's + JJencode
    • ►  November (5)
      • Upatre - Zbot downloader in a Spam
      • CryptoLocker - a Ransomware
      • DETAILED ANALYSIS OF Trojan.Win32.Duqu: The Key Lo...
    • ►  August (2)
    • ►  March (2)
  • ►  2012 (35)
    • ►  April (4)
    • ►  March (12)
    • ►  February (17)
    • ►  January (2)

Categories

adobe (1) android (10) android february (1) baksmali (1) Black Hole (2) crimepack (1) disassembler (1) exploit (3) Exploits (4) Fakeav Winrar sfx (1) Fishbowl (1) flash (1) gift certificates (1) Google Authenticator (1) google play (1) hcp (1) java (1) Malware (5) mdac (1) Mobile (24) NSA Mobility Program (1) obfuscated script (1) pdf (1) Reversing (2) rhino (1) skype (1) smali (1) spam (1) test (1) Unpacking (1) vouchers (1) vulnerability (3)

Popular Posts

  • Bank of America spam: An Analysis
    An email claiming to be from Bank of America lures users to open an attachment that shows how to open secure emails from the bank. The mess...
  • [BE CAUTIOUS] Dragon Ball Z: Resurrection of F MALWARE and SCAM
    Be wary of downloading movies in torrent sites.  Executables can also be executed with a file size as huge as a gigabyte...
  • Unpacking MFC Compiled CryptoWall Malware
    Unpacking MFC Compiled CryptoWall Malware Introduction First and foremost, this article does not intend to analyze what CryptoWall malw...

Visitors to this blog

Thursday, December 26, 2013

A Hesperbot Core Analysis

Posted on Thursday, December 26, 2013 by Unknown | No comments


A Hesperbot Core Analysis

Like most malware families, Hesperbot may originate in a spam email. Once executed, it will attempt to download its malicious modules through command-and-control (C&C) servers and monitor the activities of the infected computer. These “monitoring activities” may range from logging of keystrokes, recording of the screen, web browser hijacking and many more.

As I reverse engineer this trojan, I decided to divide it into three layers for easy understanding. These three layers are The Packer, The Injector and The Core.

Three Layers of Hesperbot:



The Packer

The packer makes use of the Thread Information Block (TIB) to retrieve NTDLL.DLL base address. The base address in turn is used in getting the virtual address of the APIs it needs by feeding it to its own hashing algorithm.

This Trojan uses the following hashes of APIs to operate:

For NTDLL.DLL:

  • 0x952A9E4: ZwAllocateVirtualMemory
  • 0xCFF13015: LdrProcessRelocationBlock

It uses ZwAllocateVirtualMemory in order to allot memory space to decrypt 24176hex of data starting from 0x00404438 virtual address where it transfers execution to decrypted data in memory.



Again it traverses TIB, but this time to get the base address of KERNEL32.DLL.

It then checks for the following hashes and saves them for later use.

For KERNEL32.DLL:

  • 0x3A35705F: VirtualFree
  • 0x697A6AFE: VirtualAlloc
  • 0xA9DE6F5A: VirtualProtect
  • 0xC8AC8026: LoadLibraryA
  • 0x1FC0EAEE: GetProcAddress



It allocates another memory space using kernel32.VirtualAlloc and decrypts part of its data (the dropper module). As you can see in the figure below, the encrypted data is on the left and the decrypted data consists of MZ-PE header on the right.



This data is then overwritten to the memory space of the original process in conjunction with the usage of kernel32.VirtualProtect to avoid access violation errors in the committed pages of the original process.



All the necessary APIs are then gathered and stored in its Import Address Table (IAT) using kernel32.LoadLibraryA and kernel32.GetProcAddress.

Code execution is then transferred subsequently to the injector module at 0x0044744F.

The Injector

The Trojan hashes and stores various system information which can be used to identify the infected computer once it connects to a C&C server.

  • computer name
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate
  • system version (like service pack number)
  • processor architecture (x86, AMD64, IA64)
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId
It creates multiple randomly generated mutex and semaphore strings with the following format
<randommutex>.mutex
<randomsemaphore>.semaphore

A system infected with Hesperbot Trojan can be easily distinguished because of this.



It then creates two folders (Sun and a randomly generated directory) in which it store an encrypted copy of itself as <random>.bkp and <random>.dat. The folder location varies from operating systems:

For WinXP:

  • %ALLUSERSPROFILE%\Application Data\Sun\<random>.bkp
  • %ALLUSERSPROFILE%\Application Data\<RandomDirName>\<random>.dat

For Win7 and above:

  • %ALLUSERSPROFILE%\Sun\<random>.bkp
  • %ALLUSERSPROFILE%\ RandomDirName>\<random>.dat



It will then generate a platform-specific loader code, by checking the OS architechture by using GetNativeSystemInfo.



Hesperbot has three ways to inject its core module to explorer.exe and these all depends whether cmdguard.sys or klif.sys exists in the system. Three scenarios are listed below


  • SCENERIO 1: %systemroot%\system32\drivers\cmdguard.sys exists (Comodo Firewall Guard driver)
    • copy procedure to high memory and transfer execution
    • spawn suspended process of explorer.exe using kernel32.CreateProcessW
    • craft bytes in stack that will jump to malware code in memory
    • modify explorer.exe entry-point and insert the crafted bytes from stack using kernel32.VirtualProtectEx and kernel32.WriteProcessMemory
    • resume suspended process using ntdll.ZwResumeThread



  • SCENARIO 2: %systemroot%\system32\drivers\klif.sys exists (Kaspersky Antivirus system driver)
    • copy core procedure to memory
    • spawn suspended process of attrib.exe using kernel32.CreateProcessW
    • craft bytes in stack that will jump to malware code in memory
    • modify attrib.exe entry-point and insert the crafted bytes from stack using kernel32.VirtualProtectEx and kernel32.WriteProcessMemory
    • resume process of attrib.exe using ntdll.ZwResumeThread
    • injected code in attrib.exe uses kernel32.CreateRemoteThread in order to create a new thread that will inject the core module to explorer.exe




  • SCENARIO 3: cmdguard.sys and klif.sys do not exist
    • copy core procedure to memory
    • spawn suspended process of attrib.exe using kernel32.CreateProcessW
    • craft bytes in stack that will jump to malware code in memory
    • modify attrib.exe entry-point and insert the crafted bytes from stack using kernel32.VirtualProtectEx and kernel32.WriteProcessMemory
    • resume process of attrib.exe using ntdll.ZwResumeThread
    • injected code in attrib.exe that spawns explorer.exe in suspended state
    • making use of windows messaging vulnerability to trigger shellcode execution into explorer.exe address space. (This is commonly known as PowerLoader injection http://www.malwaretech.com/2013/08/powerloader-injection-something-truly.html)
    • the shellcode uses CreateThread and VirtualAlloc to pass execution the core module





For debugging purposes, these are the steps on how I got to trace the shell code:

1.       First of all, know which shell code will be executed. For this sample of Hesperbot, the start of its shell code is at 0x0044A77C – E8 29 00 00 00

2. Replace the first byte 0xE8 to 0xCC (int 3). Save this modified copy.
3. In Ollydbg, goto Options->Just-in-time-debugging and click “Make OllyDbg just-in-time debugger” then exit Ollydbg.

4. Now execute your modified copy of the malware and it should crash windows explorer.

5. Hit the “Debug” button and Ollydbg should pop up, just replace back the modified byte from 0xCC to 0xE8 and start tracing that shell code!

These are the hashes of APIs that are used by Hesperbot Trojan in order to protect itself from easy detection by AV vendors.

  • 0xB02814b6 = kernel32.ExpandEnvironmentStringsW
  • 0x002CFE2B = kernel32.CreateFileW
  • 0xB376CE13 = kernel32.lstrlenW
  • 0xA24F346A = kernel32.CreateProcessW
  • 0x107B9483 = kernel32.WriteProcessMemory
  • 0x1A471325 = kernel32.VirtualProtectEx
  • 0xFDEB2A69 = kernel32.IsProcessorFeaturePresent
  • 0x8D70B719 = kernel32.IsWow64Process
  • 0x4B892318 = kernel32.CreateRemoteThread
  • 0x26662FCC = kernel32.CreateThread
  • 0xDF894B12 = kernel32.VirtualAlloc

  • 0x3708EE6B = ntdll.ZwCreateSection
  • 0xC477C525 = ntdll.ZwMapViewofSection
  • 0x2015436B = ntdll.ZwResumeThread
  • 0xB85C56EA = ntdll.ZwTerminateProcess
  • 0x3F66C5FF = ntdll.ZwGetContextThread
  • 0xD1E48C8B = ntdll.ZwSetContextThread
  • 0x4C7D8945 = ntdll.ZwDelayExecution
  • 0x7B005F26 = ntdll._allmul
  • 0x0BD5C7BD = ntdll.ZwQueryInformationProcess
  • 0x87CE75D8 = ntdll.ZwClose
  • 0xE3086B33 = ntdll.ZwOpenProcess
  • 0x35013E23 = ntdll.ZwTerminateThread
  • 0xA2E76D4C= ntdll.ZwOpenThread
  • 0x6DD66096 = ntdll.ZwQueryInformationThread
  • 0x8EAE85FE = ntdll.ZwReadVirtualMemory
  • 0xAAD44E29 = ntdll.ZwOpenSection
  • 0xB7EF35F4 = ntdll.RtlCreateUserThread

  • 0x9CD6615A = user32.FindWindowA
  • 0x4A4627DC = user32.GetWindowThreadProcessId
  • 0x3CC18006 = user32.SendMessageW
  • 0x8252D56B = user32.SetWindowLongW
  • 0x1FFBFCD8 = user32.GetClassName
  • 0x52BD91BC = user32.SystemParametersInfoW
  • 0xD563318F = user32.RegisterClassExW
  • 0x835DB020 = user32.CreateWindowExW
  • 0x8252D56B = user32.GetMessageW
  • 0x8252D56B = user32.TranslateMessage
  • 0x2776DB53 = user32.DispatchMessageW

The Hesperbot Core

Execution is then passed to the core module after injecting it to explorer.exe. Like always, it must gather first all the necessary APIs it needs by using kernel32.LoadLibrary and kernel32.GetProcAdress method.

It will then set its priority level to THREAD_PRIORITY_ABOVE_NORMAL to give more priority to itself than most active threads in explorer.exe.

It will also attempt to set explorer.exe’s integrity level to LOWINTEGRITYLEVEL_FULLACCESS, so that new processes (like other downloaded malicious modules) with higher integrity than explorer.exe can have read/write access to it.




Integrity levels are a new kernel security feature introduced in Windows Vista. You can read more about it in https://en.wikipedia.org/wiki/Mandatory_Integrity_Control.

The core then creates a mutex for itself with the format Global\inst_<randomstring> and Global\<randomstring>.

It then verifies which running process it is injected to. It does this by hashing its current process filename using its own hashing algorithm and comparing to a table of hashes found in its body. So far, these are the hashes of processes which I recovered from its table through trial and error. Understand that recovering these process names is near impossible because of how the hashing algorithm was designed by the malware author.

  • 0x11955DB8: explorer.exe
  • 0XAAF840B5: csrss.exe
  • 0X1FC97071: svchost.exe
  • 0x537B492F: iexplore.exe
  • 0x76379A9A: firefoxe.exe
  • 0XCA846265: chrome.exe
  • 0X6FB8169E: opera.exe
  • 0X9544710B: browser.exe
  • 0X78AB2C5C: webkit2webprocess.exe
  • 0X2771AA06: maxthon.exe
  • 0XB64FEEED: sleipnir.exe
  • 0XE80C41EC: deepnet.exe
  • 0X30B15DB3: seamonkey.exe
  • 0X532A495F: k-meleon.exe



As you can see, most of these hashes are process names of known web browsers. This gives us a hint that it will try to monitor web activity at some point.

The core module is the one responsible for creating a copy of the trojan in %windir%\<randomFolder>\<randomFileName>.exe. This executable is also referenced by a REGRUN entry at HKEY_LOCAL_MACHINE\ SOFTWARE\Microsoft\Windows\CurrentVersion\Run “randomValueName” to ensure auto execution on windows startup.

It will check for a valid internet connection by querying websites like:

  • http://wikipedia.org
  • http://facebook.com
  • http://google.com
  • http://microsoft.com



It then attempts to connect to its control server using https service and port 443. Its control server can be any of the following:

  • whoischeck.biz
  • 192.31.186.116
  • 188.241.112.29
  • 5.63.152.44
  • 96.43.141.186
  • 94.126.178.29






If the default control server (which is whoischeck.biz) did not respond to the request, it continues to check for other control servers listed above using Domain Generator Algorithm (DGA) in which a random domain name is used in order to evade general antivirus detections.



It will then send the following information after a successful connection handshake is established:

  • Computername that will serve as the ID of the infected machine e.g. "WINXP-6F60CDCD2A3429D85B855BF7"
  • Bot name “tr-botnet”
  • Network adapter information like adapter name, ip address, gateway, dhcp server, etc.
  • Installed smart cards by using SCardEstablishContext, SCardListReadersW and SCardConnectW

This Trojan supposedly downloads other malicious modules from its control server like keylogger, screen recorder, Virtual Network Computing (VNC), network traffic interceptor, etc. However; as of this writing, its control servers seems to be taken down already and are not responding.

Conclusion

Reverse engineering hesperbot core is quite fascinating. It demonstrates numerous tricks up its sleeves to elude easy detection by most antivirus vendors like hashing of process names and needed APIs; encrypting and decrypting part of its codes in memory; and generating random domain names when connecting to its command-and-control server.

It also demonstrates three techniques to process injection. These are via (1)CreateProcess-ResumeThread, (2) CreateRemoteThread, (3) and by exploiting window messaging vulnerability using FindWindow-“shell_traywnd” – SetWindowLong trick.

Christopher D. Del Fierro
Read More

Friday, December 6, 2013

PDF CVE-2013-5065 - Dropped BAD Malware

Posted on Friday, December 06, 2013 by Unknown | No comments

This malware is definitely created by a professional as it has an advance method of installing itself. And the malware author knows that what he/she created is BAD.

0x0BAD - Signature of ShellCode for data stealing.

Installation

This malware was dropped by a PDF file that takes advantage of a known vulnerability which results to Privilege Escalation. To maintain its privilege to run as admin, it creates the following autostart key:

Software\Microsoft\Windows NT\Currentversion\Winlogon
Shell="explorer.exe, <malware_path_and_filename>"

This malware inject its code to windows taskbar by searching for Shell_TrayWnd window handle. And also, It uses ZwQuerySystemInformation to get all the running processes in the system wherein it will calculate the hash of the names of running processes. The hashes will then be compared to the hardcoded list of hashes of executable files that will be targeted for code injection. Here are targeted executables and their corresponding hashes:

69CD16BA - iexplore.exe
7B6061F9 - firefox.exe
880F19D2 - chrome.exe
DD87014F - opera.exe
74667F89 - explorer.exe

This malware uses hashes instead of directly providing the API name that it needs. It uses the TIB (FS[0x18]) to get all the loaded dll modules. Below are the list of APIs and their corresponding hashes:

1F8B758A - ntdll.dll
B05FD69A - LdrGetDllHandle
CCE8D5E4 - LdrLoadDll
FBAF20FE - ZwSetInformationThread
F84E6809 - ZwResumeThread
251E0CC9 - ZwDelayExecution
17CF5544 - RtlGetProcessHeaps
9B2E0E85 - RtlAllocateHeap
41324137 - ZwQuerySystemInformation
086A61AC - RtlReAllocateHeap
E4A0A8C0 - RtlFreeHeap
CD74BF79 - ZwOpenProcess
309A4C54 - ZwClose
73ED9B27 - ZwCreateSection
5D859023 - ZwMapViewOfSection
B62E0ECD - _snprintf
6828791B - ZwTerminateThread
0301DA7D - RtlDecompressBuffer
CE8286AD - ZwAllocateVirtualMemory

4F515588 - kernel32.dll
1A08B014 - CreateRemoteThread
C3B42C10 - GetModuleFileNameW
98D29F2E - GetModuleFileNameA
63A4DEA5 - GetShortPathNameW
412E83B3 - GetShortPathNameA
EB771CAF - CreateEventA
F6F15646 - ExpandEnvironmentStringsA
438EED48 - CloseHandle
A01B4F40 - GetFileAttributesA
69FB2CCE - GetFileAttributesW
5568AE6B - CreateFileA
DC0BC10F - WriteFile
534D310F - ExitProcess
2415842C - DeleteFileW
7DC71262 - DeleteFileA
293DF8B5 - GetProcessVersion

5B117232 - advapi32.dll
E4A8B4E0 - OpenProcessToken
3B97B437 - GetTokenInformation
5B1D4476 - EqualSid
1A726DBB - DuplicateTokenEx
F5E6C455 - RegCreateKeyExA
A63ACEB9 - RegSetValueExA
8F2D0F57 - RegCloseKey

5A4B3EDE - user32.dll
8FAFF46C - FindWindowA
D69D869A - PostMessageA
71669709 - SetWindowLongA

69DE0153 - shell32.dll
F955B5FA - ShellExecuteA

69304E4B - ole32.dll
5142539F - CoCreateGuid


Information Stealing

This malware has the following capabilities:

Delete files
Download and execute files
Send stolen data to server
Stop its own process

But the above routines will not get executed if the following network monitoring tools are running:

tcpdump.exe
windump.exe
ethereal.exe  
wireshark.exe
ettercap.exe  
snoop.exe
dsniff.exe

It steals the following information from a compromised machine:

Uptime of the machine
Temp folder
File listing on certain directory
Drive Types
Network Resources
TCP and UDP connection table
List of running processes
List of names of open windows
Machine Information (Manufacturer and Model)
Operating System version
Processor Information
Computer Name
Local Group
Local Users
Language
Timezone
Country
Installed Windows Updates

And then collates and encrypts the above mentioned data before sending them to the following sites via HTTP POST request:

http://{REMOVED}play.com/wp-includes/sitemap/?rank=78964
http://{REMOVED}ree.ir/wp-content/plugins/online-chat/?rank=87758



Read More

Thursday, December 5, 2013

New PDF Exploit uses 2 new vuln's + JJencode

Posted on Thursday, December 05, 2013 by Unknown | No comments
Last week, a new zero-day exploit has been found in the wild. The exploit is a vulnerability that allows attackers to escalate privilege and execute code in kernel or ring0 mode. More details of the CVE-2013-5065 vulnerability can be found in this Microsoft website. After we got a sample of the supposed PDF that was used in the targeted attack,we immediately went to work and here's what we found.


Close inspection of the raw file reveals that it contains a strange looking script at the end of its body. No clue can be obtained as to what this script is doing at initial glance. However, one of our colleague indicated that this obfuscation technique is already widely used by malicious scripts and has been out for some time now. The obfuscation itself is not malicious but since it provides the stealth and complexity that most malicious scripts require, it is favored by more malware authors. This obfuscation is called jjencode. More details about this technique can be found on this blog. De-obfuscating it was a trivial matter, and it can be easily seen that the script contains shellcode that is intended to be executed using an exploit technique ROP (return objected programming).


De-obfuscated script

The thing is, the supposed exploit code that escalates privileges using DeviceIoControl cannot be read on the said script, which probably is contained in the shellcode. And in order to make the shellcode work, it would require another exploit in the PDF. So in theory, this PDF malware needs two exploits in order for it to successfully attack the system. Knowing this, we went ahead and analyzed the PDF, made breakpoints on strategic places to catch its shellcode in action.

ROP in action

The picture above shows the script was able to put its shellcode in memory. It shows that the script has already gained control of the call stack. It will use a technique called ROP (return oriented programming), since normal buffer overflows would not work in this part of memory where security protections are implemented.

 Allocates memory using CreateFileMapping with FFFFFFFF handle

 Copies 0x400 bytes of shellcode in newly allocated memory

It uses a specific DLL where it would implement its API calls, allocates a separate memory region where it would resume the bulk of its shellcode action using CreateFileMapping. Once it successfully copies its shellcode in the new memory, it gets the APIs that it needs using hashes.

Comparison of hashes for needed API


  • ExitProcess
  • VirtualAlloc
  • DeviceIoControl
  • CreateFileA
  • GetCurrentProcessId
  • LoadLibraryA
  • WinExec
  • WriteFile
  • CloseHandle
  • GetTempPathA
  • GetTempFileNameA
  • GetFileSize
  • ReadFile
  • SetFilePointer
The picture below shows the shellcode attempts to invoke CreateFile with the given argument. This buffer should point to a string "\\\\.\\NDProxy", where it should give a handle and calling DeviceIoControl should perform the exploit EoP (Escalation of Privilege). In turn, this would allow the code to execute a dropped executable with a TMP extension in the %TEMP% folder. However, as you may have noticed, the initial code only copied 0x400 bytes of its code in the new memory. And the pointer to the buffer in CreateFileA indicates the string is located at offset 0x40e...

CreateFileA where buffer should point to "\\\\.\\NDProxy"


DeviceIoControl with the right arguments should perform EoP


It will then re-create an executable by decrypting it from the body of the malicious PDF.

Decrypting

Drops a TMP file in TEMP folder


If everything went right, executes a file in kernel mode









Read More

Monday, November 18, 2013

Upatre - Zbot downloader in a Spam

Posted on Monday, November 18, 2013 by Unknown | No comments
This trojan comes as a spam email. Here are sample spam emails:



Like some CryptoLocker samples, this trojan uses a very similar decryption method. It uses VirtualAlloc to allocate memory space where it will decrypt the embedded PE Image, and then calls VirtualProtect so that it can overwrite itself with the newly decrypted PE Image and then passes the control to it.

Here's a visual infection flow of this trojan:


This particular sample that I got to reverse has an interesting anti-debugging technique. It uses RegisterClass and CreateWindowEx as part of its anti-debugging. It will first call RegisterClass to setup the WNDCLASS data structure which contains the address where the next code will go after calling CreateWindowEx.

Once decrypted and pass over the control the new PE Image, it will create a file named "budha.exe" on %TEMP% folder. This file is a copy of the original binary. And then it will execute this newly created file using ShellExecute.

This new process will delete the original binary then it will attempt to download and execute files from compromised sites which are hard-coded in its body. And those files that it downloads are known to be Zbot variants.
Read More

Sunday, November 17, 2013

CryptoLocker - a Ransomware

Posted on Sunday, November 17, 2013 by Unknown | No comments
What is a Ransomware?
A ransomware is a malicious program that encrypts all of document, picture and movie files in a computer. And to be able to decrypt them, the user must pay the malware author for some amount of money.

CryptoLocker
This ransomware, once executed, will search for document files that it targets and encrypt them using an RSA algorithm. And the user may pay USD300 to the malware author to recover the encrypted documents. It gives the user options how to pay the ransom (i.e MoneyPak and Bitcoin). If the user chose not to pay, his/her only practical option is to restore from backup.

Physical File Analysis
The sample that I've come across has a green circular icon with a cross inside it and with the following file properties.



The Fun Part (Code Analysis)
I used the combination of OllyDbg and IDAPro in reversing this malware. The reason being is OllyDBg doesn't have compiler symbols which IDAPro is rich of. OllyDbg 2.0 doesn't resolve the WinMain of this sample but IDAPro is able to do so. But I used OllyDbg throughout the debugging as I am comfortable with its 'look and feel'.

This malware is literally self-modifying as it has an encrypted PE file embedded on itself. The decrypted embedded PE Image will overwrite the original file. OllyDbg is able to detect it:


On the first/original binary, the malware APIs are found in hashes and their matching addresses are traversed to their corresponding DLL. On this case, it only uses kernel32.dll to decrypt itself. This technique is usually seen in packers, encryptors and malwares nowadays to make the life of a malware reverser a little bit harder:


0x000D4E88 - kernel32.dll
0x003560DA - LoadLibraryExA
0x000E3142h - VirtualAlloc
0x0038D13C - VirtualProtect
0x00348BFA - GetProcAddress
0x000068AE - FlsFree

Above are the API needed to map the embedded encrypted PE image in the memory. Once mapped, it will then do its decryption routine to reveal the embedded PE Image. This new PE Image will overwritten to the original binary and pass the control to it. I have dumped this new PE Image using Procdump and found out that this new file has an icon of a yellow key. Here's the code that does the said routine:


Continuing the analysis, it creates a mutex name with the following format:
Global\<random_name1>
Local\<random_name2>


The random_name are basically generated based from the hash of the path where it will be dropped and combining it with a DWORD key. Each generation of name has different DWORD key. It uses Microsoft CryptoAPIs to generate the hash.

This malware sample drops a copy of itself in %APPDATA%\Local\<random_file_name>.exe where random_file_name is generated with the same way as the mutex names.


Once it dropped a copy of itself, it will spawn a process of the newly created copy of itself with the following CommandLine parameter:

%APPDATA%\Local\<random_file_name>.exe -r%PATH_OF_CURRENT_EXECUTION%\<random_file_name>.exe

This command-line will basically remove/delete the file %PATH_OF_CURRENT_EXECUTION%\<random_file_name>.exe

Now, to debug this new child process, you may follow this:

NOTE: Don't Step over yet on the CreateProcess API. Do the following first:
1. Open the newly created file using any binary editor.
2. Go to entry point.
3. Write down the first 2 bytes.
4. change the first 2 bytes to EB FE
5. Save it.
6. Go back to the debugged parent process.
7. Step over to CreateProcess API.
8. Open a new OllyDbg.
9. Attach the new process created to OllyDbg.
10. Go to the Entry Point.
11. modify back the original 2 bytes.
12. Continue debugging the child process.

This newly created process is multi-threaded and will basically do the rest of its malicious deeds. It will create the following registry entry as part of its auto-run mechanism:

HKCU\Software\Microsoft\Windows\CurrentVersion\Run
CryptoLocker="%APPDATA%\Local\<random_file_name>.exe

HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
*CryptoLocker="%APPDATA%\Local\<random_file_name>.exe

On this malware sample, it will attempt to connect to the following hard-coded domain:

xqmrainncxrwho.net

After which, it will start generating domain names. This malware uses Domain Generation Algorithm(DGA). The algorithm is based from current System Date (year, month and day) and some hard-coded constants. It will generate a 14 character long domain name and appends any of the following Top Level Domain(TLD):

.net
.biz
.ru
.org
.co.uk
.info
.com

Once generated it will send the following HTTP Request:

POST /home/ HTTP/1.1
Accept: */*
Host: <random_generated_domain>
Connection: Close

If the server responded OK, it will create a BMP image file on the desktop with a randomly generated name. This image file contains the URL where you can download a copy of CryptoLocker:



And then it displays its GUI that contains the ransom message. The user needs to pay USD300 to recover the encrypted documents. The payment methods that it accept are:

MoneyPak

Bitcoin


This malware encrypts files using RSA algorithm. It encrypts all files that it finds which has the following extension names:

*.odt *.ods *.odp
*.odm *.odc *.odb
*.doc *.docx *.docm
*.wps *.xls *.xlsx
*.xlsm *.xlsb *.xlk
*.ppt *.pptx *.pptm
*.mdb *.accdb *.pst
*.dwg *.dxf *.dxg
*.wpd *.rtf *.wb2
*.pdf *.mdf *.dbf
*.psd *.pdd *.eps
*.ai *.indd *.cdr
*.dng *.3fr *.arw
*.srf *.sr2 *.bay
*.crw *.cr2 *.dcr
*.kdc *.erf *.mef
*.mrw *.nef *.nrw
*.orf *.raf *.raw
*.rwl *.rw2 *.r3d
*.ptx *.pef *.srw
*.x3f





Read More

Thursday, November 14, 2013

DETAILED ANALYSIS OF Trojan.Win32.Duqu: The Key Logger Module

Posted on Thursday, November 14, 2013 by Unknown | No comments
  1. INTRODUCTION
Duqu malware is a collection of malware components that together provide services to attackers. It may arrive as a Microsoft Word (.doc) that exploits Win32k TrueType font parsing engine and allows execution.
This document will be solely focused on the key logger component of Duqu.
  1. SUMMARY
The file in study is the info stealer/key logger component “a part” of what is known as an APT (Advance Persistent Threat) malware Duqu.
The MD5 hash of the file is 9749d38ae9b9ddd81b50aad679ee87ec. Vipre detects this as Trojan.Win32.Duqu.
The detailed analysis will be focused on three parts:

    • 9749d38ae9b9ddd81b50aad679ee87ec – main executable
    • f5ee03fed0133bb06d4cc52b0232fec0 – executable injector module
    • 9a9e77d2b7792fbbddcd7ce05a4eb26e – dll infostealer module

The original executable 9749d38ae9b9ddd81b50aad679ee87ec (exe) has two components, f5ee03fed0133bb06d4cc52b0232fec0 (exe) and 9a9e77d2b7792fbbddcd7ce05a4eb26e (dll) which are originally encrypted within its body.

9749d38ae9b9ddd81b50aad679ee87ec is responsible for setting up the two.  It acts as a command console in which command line arguments are expected to be entered.  The usage is as follows:
9749d38ae9b9ddd81b50aad679ee87ec.exe xxx <optional parameters>
optional parameters are:

      • /delme                                         - deletes the executable.
      • /v                                                    - verbose logging for its own debugging purposes
      • /quit                                              - terminate spawned process (default lsass.exe) with injected .tmp file.
      • /restart                                        - restarts or spawns process (default lsass.exe) with injected .tmp file.
      • /in <config file>                        - config file used for issuing commands on what data to steal and record to its log file, default config is loaded from one of its resource if not specified.
      • /out <filename>       - output file for its encrypted logs, default is ~DQx.tmp in %temp% folder if not specified.

It checks which process to inject its code to; either known antivirus processes or some known windows processes. When a target process is acquired, it spawns a suspended copy of that process in memory and manipulates its entry point to direct to its injector module’s (f5ee03fed0133bb06d4cc52b0232fec0 ) entry point before resuming.

f5ee03fed0133bb06d4cc52b0232fec0 is responsible for injecting  the dll module (9a9e77d2b7792fbbddcd7ce05a4eb26e) to the newly spawned process as a thread. As a sign of infection, a “sortxxxx.nls” thread should be present (where “xxxx” can be any random hex number) within the process.

9a9e77d2b7792fbbddcd7ce05a4eb26e on the other hand steals information about the system and logs them to a tmp file. A total of 9 information stealing routines may be executed and these are the following:

    • 65h: list running processes and get account details
    • 66h: get available drives and information
    • 68h: take a screenshot
    • 69h: get various network information
    • 67h: log keyboard strokes
    • 6Ah: enumerate opened windows
    • 6Bh: enumerate network shares
    • 6Dh: list available files
    • 6Eh: enumerate computers on the domain.


By default, it only executes 8 routines based on its configuration file, routine 6Eh: enumerate computers on the domain, is not executed.

All these data gathered are compressed using bzip2 algorithm and then stored in a temp file ~DQxx.tmp (where xx is any hex number) located in %TEMP% directory.

  1. FLOWCHART
Here is a diagram of the malware’s system infection routine.

  1. INITIAL ANALYSIS
At first glance, the file is a win32 executable with GUI subsystem and runs on an Intel 386 or later processors.

Figure 1: WIN32 executable with GUI subsystem.

PEID does not recognize the file structure of 9749d38ae9b9ddd81b50aad679ee87ec and shows “Nothing found *”.

Figure 2: PEID found nothing!
But based from my past experiences in debugging malwares and research, I find it to be compiled in Microsoft Visual C++ with /GS switch. I actually arrived at this conclusion from what I have seen in its entry point for it uses Cookie Generation Security check to avoid buffer overruns. More about cookie generation security can be found in http://msdn.microsoft.com/en-us/library/aa290051(v=vs.71).aspx.
Figure 3: Cookie Generation Security check by Microsoft

  1. BLACK BOX TESTING
Simply running the malware produces nothing. It is because this infostealer needs to be supplied with the string “xxx” as argument; e.g. “9749d38ae9b9ddd81b50aad679ee87ec.exe xxx”. It also accepts other arguments as well which will be discussed further in the detailed analysis part.
Supplying the string “xxx” we can see that; by default, it creates a bzip2 encrypted file in %TEMP% folder as ~DQxx.tmp (where xx can be any random hex number) and is being used by lsass.exe as seen in Figure 4a.
                     
Figure 4a: A sign of infection, an encrypted log file ~DQ25.tmp is found in lsass.exe

                Another sign of infection is when a thread “sortxxxx.nls” is seen injected to lsass.exe.
                                           
Figure 4b: Another sign of infection, sort9760.nls thread is seen injected to lsass.exe

  1. DETAILED ANALYSIS
9749d38ae9b9ddd81b50aad679ee87ec – The Main Executable a.k.a “The Command Console”
Since this malware is Microsoft Visual C++ compiled, the entry point located at 0x00403C91 is not the actual code start of the malware but instead we have to look for its WinMain entry which is readily available to IDA Pro. (Yay thanks IDA!)
                                  
Figure 5: A Call to WinMain
This executable needs a specific command line argument in order for it to function. The usage is as follows:

malware.exe xxx <optional parameters>
By default, the executable spawns an lsass.exe process in which it injects a ~DQxx.tmp located in %TEMP% directory where “xx” can be any random hex number.
                Other optional command line parameters are also available:
  • /delme                                 - deletes the executable.
Figure 6a: “delme” parameter

  • /v                                            - verbose logging for its own debugging purposes, usage of printf() is visible here.

Figure 6b: “v” parameter, verbose logging using printf() function.

  • /quit                                      - terminates the spawned process (default lsass.exe) with injected .tmp file.
          
Figure 6c: “quit” parameter

  • /restart                                                - restarts or spawns process (default lsass.exe) with injected .tmp file.
         
Figure 6d: “restart” parameter

  • /in <config file>                                - config file used for issuing commands on what data to steal and recorded to its log file, default input is loaded from one of its resource if not specified.
Figure 6e: “in” parameter, a part of its resource is loaded if /in is not specified.

  • /out <filename>               - output file for its encrypted logs, default is ~DQx.tmp in %temp% folder if not specified.
Figure 6f: “out” parameter, a ~DQxx.tmp file in %temp% folder is created if /out is not specified.

                The executable has 2 resources in .rsrc section, #200 and #201. #200 is the encrypted DLL component while #201 is the encrypted configuration file to be used by the malware which specifies which stealing routines to execute later. Both of these resources are mapped in memory.

The executable then proceeds to decrypt its DLL module located in resource section (resource #200) embedded in a JPEG file. This DLL is detected by Vipre as Trojan.Win32.Duqu.d (v) and has a MD5 of 9a9e77d2b7792fbbddcd7ce05a4eb26e.
                              
Figure 7: JPEG File Interchange Format as seen in the malware’s resource section

                The decryption routine is just a simple NOT operator.  You can also use XOR BYTE PTR [EAX],0FF as a substitute in decrypting.
                                                   
Figure 8: Decrypting the DLL module.

                The DLL module is compressed with UPX_LZMA and fakes its file properties to avoid suspicion as seen in Figure 9.
Figure 9: Fake BROWSEUI.DLL disguised to avoid suspicion.



The malware APIs are found in hashes and their matching addresses are traversed to their corresponding DLLs. This is usually seen most in packers, encryptors and malwares nowadays. The hashes and the corresponding APIs are listed below:
  • kernel32.dll
    • 0x88444BE9:       CreateToolhelp32Snapshot
    • 0x92D66FBA:      Process32FirstW
    • 0xD1A588DB:     Process32NextW
    • 0xFCAA0AB8:     OpenProcess
    • 0xAE75A8DB:     CreateProcessW
    • 0xCF5350C5:       GetNativeSystemInfo
    • 0xDCAA4C9F:     IsWow64Process
    • 0x4BBFABB8:     lstrcmpiW
    • 0xA668559E:       VirtualQuery
    • 0x4761BB27:       VirtualProtect
    • 0xD3E360E9:       GetProcAddress
    • 0x6B3749B3:       MapViewOfFile
    • 0xD830E518:       UnmapViewOfFile
    • 0x78C93963:       FlushInstructionCache
    • 0xD83E926D:      LoadLibraryW
    • 0x19BD1298:      FreeLibrary
    • 0x6F8A172D:      CreateThread
    • 0xBF464446:       WaitForSingleObject
    • 0xAE16A0D4:     GetExitCodeThread
    • 0x3242AC18:      GetSystemDirectoryW
    • 0x479DE84E:       CreateFileW
    • 0xB67F8157:       CreateRemoteThread
  • psapi.dll
    • 0xBCC7C0DA:     GetModuleFileNameExW
  • advapi32.dll
    • 0x6012A950:       RegOpenKeyExW
    • 0xC6151DC4:      RegQueryValueExW
    • 0xF03A2554:       RegCloseKey
    • 0x9C6E14F8:       CreateProcessAsUserW
    • 0x702B6244:       DuplicateTokenEx
    • 0x2EDB7947:      OpenProcessToken
    • 0x557DBBB6:      LookupPrivilegeValueW
    • 0xE763A4A3:      AdjustTokenPrivileges
  • version.dll
    • 0xD4DE04DA:     GetFileVersionInfoW
    • 0xCEF01246:       VerQueryValueW
  • userenv.dll
    • 0x3E692063:       CreateEnvironmentBlock
    • 0xAFF5F91F:       DestroyEnvironmentBlock
  • ntdll.dll
    • 0x40C4EC59:       ZwQueryInformationProcess
    • 0x5FC5AD65:      ZwCreateSection
    • 0x1D127D2F:      ZwMapViewOfSection
    • 0x468B8A32:      ZwUnmapViewOfSection
    • 0xDB8CE88C:      ZwClose
    • 0x8C6F89E1:       ZwQuerySection
    • 0x7BCE6E19:       ZwQueryAttributesFile

A code snippet; complete with comments, on how the malware traverses its imported APIs in a specified DLL export table in Figure 10:
Figure 10: Malware API traversing 101.

                It then creates a system snapshot of running processes in memory and verifies if any software security related processes are running. It monitors the following:
  • avp.exe                        - Kaspersky
  • Mcshield.exe            - McAfee
  • avguard.exe               - Avira
  • bdagent.exe              - BitDefender
  • UmxCfg.exe               - CA
  • fsdfwd.exe                 - F-Secure
  • rtvscan.exe                 - Symantec
  • ccSvcHst.exe              - Symantec
  • ekrn.exe                      - Eset
  • tmproxy.exe              - Trend Micro
  • RavMonD.exe           - Rising

If any of the following processes listed above is present, it will attempt to get the complete file path and the file version info of the running security software and will inject its malicious code here. The malware does this in three possible ways:

First is by using GetModuleFileNameExW found in psapi.dll with GetFileVersionInfoW and VerQueryValueW in version.dll. GetModuleFileNameExW returns the complete file path of the targeted file.
Figure 11a: Using GetModuleFileNameExW to extract the complete file path of the matched running process.

                Second is by using WMI querying technique with the format "SELECT ExecutablePath FROM Win32_Process WHERE ProcessID = %u". WMI also known as Windows Management Instrumentation is a core Windows management technology. WMI can give administrators a means to extract information about the operating system; can start a process on remote computer; and many more. More information on WMI can be found in http://technet.microsoft.com/en-us/library/ee692772.aspx.
Figure 11b: Using WMI Query such as "SELECT ExecutablePath FROM Win32_Process WHERE ProcessID = %u"

                Or third is by querying the installation path in registry pertinent to the matched executable process. The problem with this routine is that it can only support avp.exe (Kaspersky), Mcshield.exe (MacAfee) and tmproxy.exe (Trend Micro). The specified registry entries can be any of the following:
  • SOFTWARE\KasperskyLab\protected\AVP80\environment
  • SOFTWARE\KasperskyLab\protected\AVP11\environment
  • SOFTWARE\KasperskyLab\protected\AVP10\environment
  • SOFTWARE\KasperskyLab\protected\AVP9\environment
  • SOFTWARE\KasperskyLab\protected\AVP8\environment
  • SOFTWARE\KasperskyLab\protected\AVP7\environment
  • SOFTWARE\kasperskylab\avp7\environment
  • SOFTWARE\kasperskylab\avp6\environment
  • SOFTWARE\McAfee\VSCore
  • SOFTWARE\TrendMicro\NSC\TmProxy
  • SOFTWARE\Rising\RIS
  • SOFTWARE\Rising\RAV
Figure 11c: Using registry entries to determine the installation path.

                Now if there are no security softwares installed or running in process, the malware will default to of any of the following files:
  • For 32bit operating system:
    • %SystemRoot%\system32\lsass.exe
    • %SystemRoot%\system32\winlogon.exe
    • %SystemRoot%\system32\svchost.exe
  • For 64bit operating system:
    • %SystemRoot%\syswow64\lsass.exe
    • %SystemRoot%\syswow64\winlogon.exe
    • %SystemRoot%\syswow64\svchost.exe

The executable verifies the image of the targeted file if it is Intel 386(32bit) or AMD 64(64bit). What’s interesting is that although the malware author may seem to check for 64bit systems, its procedure is actually empty and returns a NULL. It’s as if there is a plan to support 64bit but forgot to implement it.
Figure 12: 64-Bit support is planned but the procedure only returns NULL.

                It then creates a mutex name based on process ID of the targeted file and continues to decrypt once again another module file (with MD5 of f5ee03fed0133bb06d4cc52b0232fec0). This executable module file is detected by Vipre as Trojan.Win32.Generic!BT.
Figure 13a: Mutex name creation based on PID of target file.

                I have taken the liberty of inserting comments to its decryption routine for the interest of our readers.
Figure 13b: Decrypting the injector module.

                The malware then spawns a suspended process of the targeted file in memory. If the file is running under a 64bit environment, it does nothing and proceeds to terminate itself.
Figure 14: A suspended, no-window, detached process was spawned in memory.

                The malware then proceeds to read the first 0x1000 bytes of the targeted file into memory using ReadProcessMemory function in order to parse the PE header and save the targeted file’s entry point in stack.
Figure 15: ReadProcessMemory in action, first 0x1000 bytes of targeted file is copied into memory.

                The targeted file’s entry point will be replaced with a jump offset to that of the injector module’s entry point (f5ee03fed0133bb06d4cc52b0232fec0) before resuming the suspended process. This is a technique used by the malware in order to pass the execution from targeted file to the malware’s component file. Remember that the targeted file is non-malicious in nature but the code that it jumps to is malicious. This is done to hide the component file and avoid detection by antivirus products. Also take note that NO component files were dropped nor created by the malware, all of these were done in memory.
                                           
Figure 15a: Bytes in targeted file’s entry point are overwritten to pass the execution to malware’s own entry point


f5ee03fed0133bb06d4cc52b0232fec0 – The Executable Module a.k.a. “The Injector”

                 When the code execution is passed to the injector module (f5ee03fed0133bb06d4cc52b0232fec0) in memory, the first thing it will do is to fill and rebuild its Import Address Table.
                                                    
Figure 16: Rebuilding Import Address Table
                
                Next is it will set up a file named “sortxxxx.nls” (where “xxxx” is a string generated by GetTickCount) where modules of the infostealer component (9a9e77d2b7792fbbddcd7ce05a4eb26e) will be copied afterwards.
                                                 
Figure 17: Preparing “sortxxxx.nls”.

                This is followed by decrypting more of its code at target location 0x00401080 using simple XOR EAX, 0x89719922 as key.
                                                     
Figure 18: Decrypting more code, 0x89719922 as decryption key.

                It will then call CreateRemoteThread API to create a thread leading to the execution of the newly decrypted code at 0x00401080. The newly created thread maps a copy of its malicious DLL component (9a9e77d2b7792fbbddcd7ce05a4eb26e) in memory (remember sortxxxx.nls?).
Figure 19: DLL component is copied to memory

                It also demonstrates rootkit capabilities by patching some functions of NTDLL.DLL in memory in order to route execution to the malware itself first before passing to the actual function(s). Some patched functions are:
  • ZwMapViewOfSection
  • ZwCreateSection
  • ZwOpenFile
  • ZwClose
  • ZwQueryAttributesFile
  • ZwQuerySection

Figures below demonstrate how code rerouting is done.
Figure 20a: Overwrites 6 bytes of ntdll.dll .7C90DC55 NtMapViewOfSection to jump to malware code instead.

Figure 20b: This is where the patched NtMapViewOfSection jumps to.

                It will then attempt to load “sortxxxx.nls” in memory using LoadLibraryW function and gets the function address of the 2nd exported function of the dll component using GetProcAddress. It will then pass the execution to export #2 by using call. This is better exemplified by Figure 21.
Figure 21: DLL component export function #2 is now called.

9a9e77d2b7792fbbddcd7ce05a4eb26e – The Dynamic Link Library Module a.k.a. “The InfoStealer”

                The DLL component is the one responsible for stealing data from the infected system. It exports 5 functions which can be seen below:
  • #1 .100026EF - same as #2, a call to entry point
  • #2 .10002701 - main (entry point)
  • #3 .1000276A - same as #2, create thread to entry point
  • #4 .100025BF - infostealer
  • #5 .100025C4 - quit infostealer

This DLL module has nine routines all in all:
  • 65h @ 0x100032E9: List running processes, look up account details
Figure 22a: Routine 65h, list running processes including account id.

  • 66h @ 0x10002F34: List available disk drives including mounted network drives, get drive type (removable, fixed, CD-ROM, RAM disk, or network drive), get volume information (serial number and volume label), and free disk space.
Figure 22b: Routine 66h, list numerous disk information.

  • 68h @ 0x10003ED0: Take a screenshot
Figure 22c: Routine 68h, a screenshot of “take a screenshot function”.

  • 69h @ 0x10005248: Get network parameters (hostname, domain name, dns server, etc.), retrieves the interface–to–IPv4 address mapping table, retrieves the IPv4 routing table, retrieves the MIB-II interface table, retrieves the IPv4 to physical address mapping table, retrieves the IPv4 TCP connection table, retrieves the IPv4 User Datagram Protocol (UDP) listener table, display dns cache and enumerate network connections and resources.
Figure 22d: Routine 69h, retrieve various network information.

  • 67h @ 0x100052C3: Monitor keyboard strokes
Figure 22e: Routine 67h, the keylogger.

  • 6Ah @ 0x100057F5: Enumerate windows
Figure 22f: Routine 6Ah, windows enumeration.

  • 6Bh @ 0x10005D06: Network file, shares and connection enumeration
Figure 22g: Routine 6Bh, network share enumeration.

  • 6Dh @ 0x100069E5: List available files on all drives.
Figure 22h: Routine 6Dh, list all files on all drives.

  • 6Eh @ 0x10006CF5: Lists all servers that are visible in the domain.
Figure 22i: Routine 6Eh, enumerate servers visible in the domain.

Remember resource #201? Resource #201 is then decrypted in memory which serves as the default configuration file as to what stealing routines to be executed. The decryption routine used is clearly seen in Figure 23a.
Figure 23a: Decrypting config file located in resource #201.

                The result of the decrypted configuration file can be seen in Figure 23b. The stealing routines are highlighted in red.
Figure 23b: Decrypted resource #201 which serves as the default config file.

It uses 8 of the listed 9 routines based on its default configuration file. Routines used are 65h, 66h, 68h, 69h, 67h, 6Ah, 6Bh and 6Dh in that sequence. All stolen data are then compressed using bzip2 algorithm before writing to ~DQxx.tmp file. A string “AEh91AY&SY” is seen in the tmp file compared to the original bzip2 marker which is “BZh91AY&SY”.
Figure 24: Modified AEh91AY&SY marker instead of the default BZh91AY&SY by bzip2.

                A sample of the encrypted stolen data and decrypted counterpart is posted below. A list of running processes with corresponding PIDs with account id is seen when fully decrypted.
Figure 25: Left side encrypted bzip2 data, Right side decrypted data.


Analysis and Documentation Prepared By:
Christopher D. Del Fierro
Read More
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)
volute-glacial
volute-glacial
volute-glacial
volute-glacial
Copyright © Anti-Malware Laboratory | Powered by Blogger
Design by Fabthemes | Blogger Template by NewBloggerThemes.com