

Posted by Felix Weyne, March 2017.

Author contact: Twitter | Mail | LinkedIn

Tags: Necurs botnet, Nemucod, Locky ransomware, malware/threat intelligence, rootkit, monitoring, indicators of compromise, SPAM, tshark, ettercap, scripting, Talos LockyDump

I recently came across an interesting paper titled "botwatcher: transparent and generic botnet tracking". The paper discusses ways to track a botnet, a centrally controlled group of computers on which a backdoor is installed. One of the botnets discussed in the paper is called Necurs. Necurs is a group of compromised computers which send spam emails with malicious attachments to a large number of recipients – usually the messages are created to look like a request to check invoice details or to confirm a purchase. The attachments contain packed scripts which install Locky ransomware when ran. The paper enthused me to gather malware intelligence regarding the origin of Locky ransomware. Initially only the spammails and the malicious packed scripts (droppers) spread by the Necurs botnet were in scope of the malware intelligence system. Later on I also added payload (Locky ransomware) intelligence.

In this blog I will discuss the creation and results of the basic self-developed Locky malspam intelligence system. My approach was to run the Necurs rootkit in a virtualized environment (setup displayed below). Running the rootkit made me join the Necurs botnet and gave the Necurs operators control over the virtualised PC. Not long after infecting the virtualised PC with Necurs, it started to send Locky SPAM mails. This behaviour was monitored and controled (restricted) with a firewall. Monitoring the sent malicious mails (with the help of packet captures) was used as input for the intelligence system.



Image one: Setup of the malware intelligence system. The virtual machine is part of the Necurs botnet which sends malicious mails to mail servers. The PCs in the botnet connect to peers and to a centralised C&C server.

The results

The gathered intelligence is stored in a database and displayed via a dashboard (initial dashboard build shown below). Each monitored SPAM wave is an entry in the dashboard. For each SPAM wave, the subject and contents of the mails are stored, as well as the attachments (samples and hashes). The malicious mail attachments (droppers) are detonated in a sandbox. This detonation creates additional threat intell such as the payload hosting location (URL) and the payload itself (Locky ransomware, a packed DLL file). Finally, the payload (Locky) is used to extract additional information such as hardcoded command and control IPs (used to send statistics and encryption key), URL postback pattern and affiliate identifier. All this is intelligence is gathered automatically, no manual interaction is required.



Image two: dashboard with Necurs SPAM mail and Locky dropper/payload intelligence.

Necurs Infection

To become part of the Necurs botnet, I used this Necurs sample to infect a virtual windows 7 machine. Necurs nests itself inside a Windows installer folder and shows a lot of rootkit like behavior. The malware comes with a lot of self-protective measures, a few of them are shown in image three. While Necurs is running, it is not possible to kill the Necurs process (hidden as syshost), to start monitoring tools that make use of drivers (such as memory dumping tools or sysinternals process monitor) or to view the access rights to the executable.



Image three: Necurs self-protective behavior

Necurs sends a heartbeat via HTTP to its C&C server every six minutes on average, communication with peers is done via UDP. The Necurs infected PC sent SPAM waves almost daily; I didn't notice any SPAM waves during the night, nor during weekends.



Image four: Top: Necurs connecting to a C&C server (port 80, HTTP).

Bottom: Necurs sending SPAM mail (port 25, SMTP).

Mail monitoring

The virtual machine infected with Necurs sent plaintext SMTP mails, which makes it easy to monitor. An example mail sent by the infected machine is shown below.



Image five: mail sent by the Necurs botnet

To capture the mails, I created a basic batch script which I ran inside the infected virtual machine. The script runs a loop which captures the network traffic via Wireshark and saves it as a packet capture. At the end of the loop, the packet capture is inspected for presence of SMTP mails with the help of tshark (commandline wireshark). If SMTP traffic is found in the packet capture, the network adapter gets disabled for two hours to prevent the machine sending any additional mails. The packet capture containing the SMTP mails is then processed by another script which extracts the SMTP attachments, this will be explained in the next paragraphs.

setlocal EnableDelayedExpansion :loop echo Loop start Time: %time% set timenozero = %TIME: =0 % set hour = %timenozero:~0 , 2 % set min = %timenozero:~3 , 2 % For /f "tokens=2,3,4,5 delims=/. " %%a in ( 'date/T' ) do set CDate = %%a - %%b - %%c set datetime = %hour% - %min% _ %CDate% echo Starting Wireshark cd "C:\Program Files\Wireshark" start wireshark -i "Local Area Connection" -k -Y "(http && tcp) || smtp" -w %userprofile% \Desktop\pcaps\packets_ %datetime% .cap PING 1 . 1 . 1 . 1 -n 1 -w 30000 >NUL tskill wireshark for /f "delims=" %%a in ( 'tshark.exe -r %userprofile%\Desktop\pcaps\packets_%datetime%.cap -T fields -e tcp.stream -Y mime_multipart.header.content-type' ) do @ set myResult = %%a set "safeCompare=%myResult%" if "!safeCompare!" == "" ( echo No SMTP attachments found, keep going! goto loop ) else ( echo SMTP attachment found, aborting mission! netsh interface set interface name = "Local Area Connection" admin = disabled ) echo Started sleeping two hours ( %time% ) set /a x =120 :waitqueue if %x% gtr 5 ( echo Sleeping %x% more minutes PING 127 . 0 . 0 . 1 -n 60 >NUL set /a x- =1 goto waitqueue ) netsh interface set interface name = "Local Area Connection" admin = enabled PING 127 . 0 . 0 . 1 -n 10 >NUL goto loop

Mail containment

Script one: Bath script which creates packet captures (pcaps) until SMTP mail traffic is detected. When SMTP traffic is detected, the ethernet adapter gets disabled.

The script shown in the previous paragraph prevents the Necurs infected machine from sending spam mails any longer than thirty seconds. A lot of additional countermeasures were taken to prevent that any malicious mail was actually received by a mail server. Discussing all these countermeasures is out of the scope of this blog, however I will discuss one easy to implement countermeasure, namely content filtering with ettercap.

I used a second virtual machine running Kali Linux to run ettercap, and I routed the internet traffic from the infected Windows machine trough the Kali machine. With the help of ettercap, the internet connection of the Necurs infected machine was sniffed and filtered. Filtering included replacing strings of the malicious attachment with harmless strings. An example replacement is to replace the 'zip' attachment extension with a 'txt' extension.

To test the filtering setup, I first tried to filter the browser user agent from the infected machine. I used a simple ettercap rule which replaced the string "Firefox" with "LiteFox". The rule was compiled and the virtual Windows machine was put on the target list of ettercap, as shown on image six.



Image six: ettercap setup on the Kali Linux virtual machine.

When visiting a website with a Firefox browser on the infected Windows machine, the user agent got changed. This replacement is transparent to the virtual Windows machine: i.e. when inspecting the sent requests inside the machine, we still see a "Firefox" string. The receiver of the request (e.g. the whoishostingthis.com website) however receives a modified user agent, as shown on image seven.



Image seven: visible results of the ettercap filtering in the browser of the virtual Windows machine.

Mail attachment (dropper) extraction (tshark)

In the mail monitoring paragraph, I explained how packet captures containing the SMTP mails were automatically generated. In this paragraph, I will briefly explain how the mail attachments are extracted from those packet captures. I created a quick-and-dirty powershellscript to extract the (base64 encoded) mail attachments. The script uses a tshark functionality to dump the contents of a specific TCP (conversation) stream. Tshark can only dump a TCP stream for which a specific numerical index is defined, so the script needs to provide a list of indices which correspond to TCP streams containing SMTP mail attachments. Each TCP stream is dumped in hex format, so the script needs to convert the hex format to an ASCII format. Finally, the conversion result (base64 encoded mail attachments, mostly zip files) needs to be stored in a text file.

#extract mails with zip attachment from PCAP #use TSHARK to dump the mail in hex $tcpStreamsWithAttachedZip = & "C:\Program Files\Wireshark\tshark.exe" -r necurs.cap -T fields -e tcp.stream -Y "mime_multipart.header.content-type" | Sort-Object -Unique for ( $i =0; $i -le $tcpStreamsWithAttachedZip .Length; $i ++){ $streamIndex = $tcpStreamsWithAttachedZip [ $i ] echo $streamIndex $tsharkOutput = & "C:\Program Files\Wireshark\tshark.exe" -r necurs.cap -q -z "follow,tcp,raw,$streamIndex" for ( $j =6 $j -le $tsharkOutput .length-2; $j ++){ #Tshark puts a new line for each packet. #Tshark appends a tap in a response packet. [string]$result = $tsharkOutput [ $j ].Split( "`t" ).Split( "\r

" ); $trimmed = $result .Trim() #convert string of hexcharacters to asciistring -join ( $trimmed -split '(..)' | ? { $_ } | % { [char][convert] :: ToUInt32( $_ ,16) }) | Out-File mailDump.txt -Append } } #extract attachments from mail txt file $mailInput = cat mailDump.txt $oneLinerMails = $mailInput -join "" #base64 encoded zip starts and ends with same characters $regex = '\bUEsDBB[A-Za-z0-9+/]*AAAA\b' $findAttachment = ( $oneLinerMails | Select-String -Pattern $regex -AllMatches | % { $_ .Matches } | % { $_ .Value } ) #export unique attachments $uniqueAttachments = [System.Collections.ArrayList] @ () foreach ( $value in $findAttachment ) { if (! $uniqueAttachments .contains( $value )) { $uniqueAttachments .Add( $value ) echo $value | Out-File attachmentDump.txt -Append } }

Script two: Powershell script which extracts zip attachments from SMTP mails in packet captures (pcaps)

The first part of the above script dumps mails in ASCII format. The second part of the script looks for unique base64 encoded zip files. Each SPAM wave generated at least twenty unique zip files, each zip file contains a malicious script with an extension such as "js" or "wsf". The zip files are decoded, extracted and sent to a sandbox, where they will be executed (not shown in script). Their execution will provide additional threatintell, this will be explained in the last paragraph.

Payload extraction and intelligence

The final part in the basic Locky malspam intelligence system is responsible for gathering some intelligence regarding what the cybercriminals actually try to achieve by sending their spam mails: deliver ransomware to the end user. The previous paragraph explained how the droppers (mail attachments) were extracted. Automated static inspection of these droppers with the goal of finding additional indicators of compromise (IOCs) is hard because of the high obfuscation grade of the embedded scripts. It is much easier to automatically extract the scripts from the zip archive, and to dynamically run and analyze them in a sandbox. Running a Locky dropper script always generates the same pattern: an encrypted file is downloaded from a website. This encrypted file is decrypted and saved as a dynamic link library (DLL). This DLL is the Locky ransomware payload and is executed via the 'rundll32' Windows executable. The ransomware does not immediately start encrypting the files, it sleeps a certain amount of time to avoid sandbox detection. This behaviour gives us the opportunity to run the malicious dropper in a sandbox, and to wait until the rundll32 process is started. If we terminate the started rundll32 process immediately, no harmful changes will be made to the sandbox. The started rundll32 process will contain the location of the downloaded, decrypted payload (the DLL file) in its commandline argument.

The payload hosting URL can be extracted from packed captures, the payload itself can automatically be archived in the intelligence system. The archived payload (Locky) contains a lot of additional interesting information, which is also usefull to put in the intelligence system. Examples are: hardcoded command and control servers, URI patterns and an affiliate identifier. This information can easily be extracted from the DLL with a fantastic tool called 'LockyDump', developed by Talos. Below an example of the output of the payload extraction and intelligence script is shown.



Image eight: automated collection of payload intell by running the dropper inside a sandbox

References

Transparent and Generic Botnet Tracking, T. Barabosch et al.

Necurs analysis, CERT Poland

Angler exploit kit delevering Necurs, B. Duncan (SANS ISC)

Necurs – the Heavyweight Malware Spammer, TrustWave

The curse of Necurs (blacklisting drivers), Virus Bulletin

Analysis of Necurs botnet in 2012 (French), Malekal.com

Tutorial on how to use ettercap on Kali Linux, YouTube

TCP flow, Wikipedia

Extracting Locky config with LockyDump, Talos