diff options
Diffstat (limited to 'example')
24 files changed, 0 insertions, 1945 deletions
diff --git a/example/asm_arm.py b/example/asm_arm.py deleted file mode 100755 index 8cd5e303..00000000 --- a/example/asm_arm.py +++ /dev/null @@ -1,68 +0,0 @@ -#! /usr/bin/env python - -from miasm.arch.arm_arch import arm_mn -from miasm.core.bin_stream import bin_stream -from miasm.core import parse_asm -from miasm.core import asmbloc -import struct - -my_mn = arm_mn - - -####filelogger sc#### - -all_bloc, symbol_pool = parse_asm.parse_txt(my_mn,r''' -toto: - STMFD SP!, {R0-R12, LR}^ - MOV R11, LR - MOV R11, R0, ROR 4 - STC P2,C3, [R5, 24]! - MOV R1, R0 - LDR R2, [PC, R0 ROR 0x2] - CMP R2, R3 - BLE tutu - ORR R0, R1, R2 - ORRLE R0, R0, R0 - ORR R0, R0, R0 - LDR R3, [R11, 0x98] - LDR R3, [R11, -0x98] - STMFD SP!, {R4-R6,R11,R12,LR,PC} - STMFD SP!, {R0-R12, SP, LR, PC} - LDMIA R9, {R9, R12} - BLE tutu - LDMFD SP, {R4-R8,R11,SP,PC} - -tutu: - LDMFD SP!, {R0-R12, LR} - BX LR -''') - -g = asmbloc.bloc2graph(all_bloc[0]) -open("graph.txt" , "w").write(g) - - - -for b in all_bloc[0]: - print b -symbol_pool.add_label('base_address', 0x0) -symbol_pool.set_offset(symbol_pool.getby_name("toto"), 0x0) - -resolved_b, patches = asmbloc.asm_resolve_final(my_mn, all_bloc[0], symbol_pool) -print patches - -f = open('uu.bin', 'w') -for p, v in patches.items(): - f.seek(p) - f.write(v) - -f.close() - -print 'DISASSEMBLE FILE' -data = open('uu.bin', 'rb').read() -in_str = bin_stream(data) -job_done = set() -symbol_pool = asmbloc.asm_symbol_pool() -all_bloc = asmbloc.dis_bloc_all(my_mn, in_str, 0, job_done, symbol_pool, follow_call = False, lines_wd = 20) -g = asmbloc.bloc2graph(all_bloc) -open("graph2.txt" , "w").write(g) - diff --git a/example/asm_box.py b/example/asm_box.py deleted file mode 100644 index e610eda1..00000000 --- a/example/asm_box.py +++ /dev/null @@ -1,36 +0,0 @@ -#! /usr/bin/env python - -from miasm.core import parse_asm -from miasm.core import asmbloc -from miasm.arch.ia32_arch import * -from elfesteem import * -e = pe_init.PE() -s_text = e.SHList.add_section(name = "text ", addr = 0x1000, rawsize = 0x100) -s_iat = e.SHList.add_section(name = "iat" , rawsize = 0x100) -new_dll = [({ "name" : "USER32.dll", - "firstthunk" : s_iat.addr}, - ["MessageBoxA"])] -e.DirImport.add_dlldesc(new_dll) -s_myimp = e.SHList.add_section(name = "myimp",rawsize = len(e.DirImport)) -e.DirImport.set_rva(s_myimp.addr) -all_bloc, symbol_pool = parse_asm.parse_txt(x86_mn, r''' -main: - push 0 - push title - push msg - push 0 - call [ MessageBoxA ] - ret -title: -.string "Hello!" -msg: -.string "World!" -''') -symbol_pool.add_label('base_address', 0) -symbol_pool.set_offset(symbol_pool.getby_name("MessageBoxA"),e.DirImport.get_funcvirt('MessageBoxA')) -symbol_pool.set_offset(symbol_pool.getby_name("main"), e.rva2virt(s_text.addr)) -resolved_b, patches = asmbloc.asm_resolve_final(x86_mn, all_bloc[0], symbol_pool) -for p in patches: - e.virt[p] = patches[p] -e.Opthdr.AddressOfEntryPoint = e.virt2rva(symbol_pool.getby_name("main").offset) -open('msg.exe', 'wb').write(str(e)) diff --git a/example/asm_x86.py b/example/asm_x86.py deleted file mode 100755 index d4a621f6..00000000 --- a/example/asm_x86.py +++ /dev/null @@ -1,80 +0,0 @@ -#! /usr/bin/env python - -from miasm.arch.ia32_arch import * -from miasm.core.bin_stream import bin_stream -from miasm.core import parse_asm -from elfesteem import * - -from miasm.core import asmbloc -import struct - -my_mn = x86_mn - -""" -asm a linux shell code in a windows PE -""" - - -my_mn = x86_mn - -e = pe_init.PE() -s_text = e.SHList.add_section(name = "text", addr = 0x1000, rawsize = 0x4000) - -####filelogger sc#### -all_bloc, symbol_pool = parse_asm.parse_txt(my_mn,r''' -main: - jmp end -getstr: - pop ebp - push 0xb - pop eax - cdq - - push edx - mov cx, 0x632d - push cx - mov edi, esp - - push 0xAA68732f - push 0x6e69622f - mov ebx, esp - push edx - - push ebp - mov byte ptr [ebp+eend-mystr], dl - push edi - push ebx - mov byte ptr [ebx+7], dl - mov ecx, esp - int 0x80 -end: - call getstr -mystr: -.string "cat /etc/passwd> /tmp/ooo; ls;" -eend: - nop -''') - -#fix shellcode addr -symbol_pool.add_label('base_address', 0x400000) -symbol_pool.set_offset(symbol_pool.getby_name("main"), 0x401000) -e.Opthdr.AddressOfEntryPoint = s_text.addr - -for b in all_bloc[0]: - print b -####graph sc#### -g = asmbloc.bloc2graph(all_bloc[0]) -open("graph.txt" , "w").write(g) - -print "symbols" -print symbol_pool -#dont erase from start to shell code padading -resolved_b, patches = asmbloc.asm_resolve_final(my_mn, all_bloc[0], symbol_pool, - constrain_pos=True) -print patches - -for offset, raw in patches.items(): - e.virt[offset] = raw - -open('uu.bin', 'wb').write(str(e)) - diff --git a/example/disas_and_graph.py b/example/disas_and_graph.py deleted file mode 100755 index 0a6a3e5d..00000000 --- a/example/disas_and_graph.py +++ /dev/null @@ -1,206 +0,0 @@ -#! /usr/bin/env python -import os -from elfesteem import * -from miasm.tools.pe_helper import * -from miasm.core import bin_stream -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from elfesteem import pe -from miasm.arch import ia32_arch -from miasm.arch import arm_arch -from miasm.arch import ppc_arch -from optparse import OptionParser - -try: - from miasm.arch.java_arch import java_mn -except ImportError: - pass - -import pickle -import sys - -parser = OptionParser(usage = "usage: %prog [options] file") -parser.add_option('-a', "--address", dest="address", metavar="ADDRESS", - help="address to disasemble") -parser.add_option('-m', "--architecture", dest="machine",metavar="MACHINE", - help="architecture to use for disasm: arm, x86, ppc, java") -parser.add_option('-M', "--architecture-options", dest="machine_options", - metavar="MACHINEOPTS", - help="architecture options (u16/u32/u64 bits, ...)") -parser.add_option('-r', "--rawfile", dest="rawfile", action="store_true", - default=False, metavar=None, - help="dont use PE/ELF/CLASS autodetect, disasm raw file") - -parser.add_option('-c', "--followcall", dest="followcall", action="store_true", - default=False, metavar=None, - help="follow call dst") -parser.add_option('-n', "--dontdiscallret", dest="dontdiscallret", action="store_true", - default=False, metavar=None, - help="dont disasssemble call next instruction") -parser.add_option('-l', "--loadstate", dest="load_state_file", default = None, - help="load state file") - - -(options, args) = parser.parse_args(sys.argv[1:]) -if not args: - parser.print_help() - sys.exit(0) -fname = args[0] -ad_to_dis = options.address - - -dll_dyn_funcs = {} -data = open(fname, 'rb').read() - -if options.rawfile: - in_str = bin_stream.bin_stream(data) - if ad_to_dis == None: - ad_to_dis = 0 - else: - ad_to_dis = int(ad_to_dis, 16) - mnemo = ia32_arch.x86_mn -elif data.startswith("MZ"): - e = pe_init.PE(open(fname, 'rb').read()) - if ad_to_dis == None: - ad_to_dis = e.rva2virt(e.Opthdr.AddressOfEntryPoint) - else: - ad_to_dis = int(ad_to_dis, 16) - in_str = bin_stream.bin_stream(e.virt) - try: - dll_dyn_funcs = get_import_address(e) - except: - print 'bug in import parsing' - mnemo = ia32_arch.x86_mn - -elif data.startswith("\x7fELF") : - e = elf_init.ELF(open(fname, 'rb').read()) - if ad_to_dis == None: - ad_to_dis = e.Ehdr.entry - else: - ad_to_dis = int(ad_to_dis, 16) - in_str = bin_stream.bin_stream(e.virt) - try: - dll_dyn_funcs = get_import_address_elf(e) - except: - print 'bug in import parsing' - mnemo = ia32_arch.x86_mn - -elif data.startswith("\xca\xfe\xba\xbe"): - def java_usage(): - print 'usage:' - print '%s methodname methodtype'%sys.argv[0] - print 'possible methods: (use -a N)' - for i, ((c_name, c_type), code) in enumerate(methods): - print i, "->", str(c_name), str(c_type) - sys.exit(-1) - - e = jclass_init.JCLASS(data) - methods = [] - for m in e.description.methods: - name = m.name - descr = m.descriptor - c = filter(lambda x: type(x) is jclass_init.CAttribute_code, m.attributes) - if not c: - continue - code = c[0].code - methods.append(((name, descr), code)) - if ad_to_dis == None: - java_usage() - ad_to_dis = int(ad_to_dis) - if not (0<=ad_to_dis<len(methods)): - java_usage() - in_str = bin_stream.bin_stream(methods[ad_to_dis][1]) - ad_to_dis = 0 - mnemo = java_mn - try: - constants_pool = get_java_constant_pool(e) - except: - print 'bug in constant pool parsing' - constants_pool = {} - - -else: - print 'WARNING cannot autodetect file type, using raw', repr(data[:10]) - in_str = bin_stream.bin_stream(data) - if ad_to_dis == None: - ad_to_dis = 0 - else: - ad_to_dis = int(ad_to_dis, 16) - mnemo = ia32_arch.x86_mn - - -if options.machine: - machine_dct = {"ia32":ia32_arch.x86_mn, - "arm":arm_arch.arm_mn, - "java":java_mn, - "ppc":ppc_arch.ppc_mn, - } - if not options.machine in machine_dct: - raise ValueError('unknown machine', options.machine) - if mnemo: - print "WARNING forcing machine disasm to ", options.machine - - mnemo = machine_dct[options.machine] - -print 'dis', fname, 'at', "0x%.8X"%ad_to_dis, 'using', mnemo - - - -symbol_pool = asmbloc.asm_symbol_pool() -# test qt -from miasm.graph.graph_qt import graph_blocs - - - -#test symbols from ida -for (n,f), ads in dll_dyn_funcs.items(): - for ad in ads: - l = symbol_pool.getby_name_create("%s_%s"%(n, f)) - l.offset = ad - symbol_pool.s_offset[l.offset] = l - - -def my_disasm_callback(ad): - attrib = {} - if mnemo == ia32_arch.x86_mn: - if options.machine_options: - if options.machine_options in ['u16', 'u32']: - admode = opmode = u32 - admode = opmode = options.machine_options - attrib = {"admode":admode, "opmode":admode} - else: - raise ValueError('bad machine options') - - all_bloc = asmbloc.dis_bloc_all(mnemo, in_str, ad, set(), - symbol_pool=symbol_pool, - dontdis_retcall = options.dontdiscallret, - follow_call = options.followcall, - attrib = attrib) - g = asmbloc.bloc2graph(all_bloc) - open('graph.txt', 'w').write(g) - if mnemo == ia32_arch.x86_mn: - for b in all_bloc: - for l in b.lines: - for i, a in enumerate(l.arg): - if not ia32_arch.is_ad_lookup(a): - continue - x = a[ia32_arch.x86_afs.imm] - if x in symbol_pool.s_offset: - l.arg[i][x86_afs.symb] = symbol_pool.s_offset[x] - del(l.arg[i][ia32_arch.x86_afs.imm]) - elif mnemo == java_mn: - o = {} - for k, v in constants_pool.items(): - if hasattr(v, "pp"): - o[k] = v.pp() - else: - o[k] = repr(v) - for b in all_bloc: - for l in b.lines: - l.set_args_symbols(o) - return all_bloc - -graph_blocs(ad_to_dis, symbol_pool, all_bloc = [], - dis_callback = my_disasm_callback, - load_state_file = options.load_state_file) diff --git a/example/emulx86_bin.py b/example/emulx86_bin.py deleted file mode 100755 index eab57408..00000000 --- a/example/emulx86_bin.py +++ /dev/null @@ -1,79 +0,0 @@ -#! /usr/bin/env python -import os -from elfesteem import * -from miasm.core import asmbloc -from miasm.core import parse_asm -from miasm.tools.to_c_helper import * -from miasm.tools import emul_helper -from miasm.arch.ia32_arch import * -import sys - - - -if len(sys.argv) <3: - print 'usage:' - print "%s rawfile address_to_exec"%sys.argv[0] - print 'exemple:' - print "%s x86_sc.bin 0"%sys.argv[0] - - sys.exit(0) -data = open(sys.argv[1], 'rb').read() -ad = sys.argv[2].lower() -if ad.startswith('0x'): - ad = int(ad, 16) -else: - ad = int(ad) - - -vm_init_regs() -init_memory_page_pool_py() -init_code_bloc_pool_py() -in_str = bin_stream_vm() - -codenat_tcc_init() - -code_ad = 0x40000000 -vm_add_memory_page(code_ad, PAGE_READ|PAGE_WRITE|PAGE_EXEC, data) -stack_base_ad = 0x1230000 -stack_size = 0x10000 -vm_add_memory_page(stack_base_ad, PAGE_READ|PAGE_WRITE, "\x00"*stack_size) -dump_memory_page_pool_py() - -regs = vm_get_gpreg() -regs['esp'] = stack_base_ad+stack_size -vm_set_gpreg(regs) -dump_gpregs_py() - - -vm_push_uint32_t(0x1337beef) -symbol_pool = asmbloc.asm_symbol_pool() -known_blocs = {} -code_blocs_mem_range = [] - - - - -log_regs = True -log_mn = log_regs -def run_bin(my_eip, known_blocs, code_blocs_mem_range): - global log_regs, log_mn - while my_eip != 0x1337beef: - - if not my_eip in known_blocs: - updt_bloc_emul(known_blocs, in_str, my_eip, symbol_pool, code_blocs_mem_range, log_regs = log_regs, log_mn = log_mn) - vm_reset_exception() - try: - my_eip = vm_exec_blocs(my_eip, known_blocs) - except KeyboardInterrupt: - break - py_exception = vm_get_exception() - if py_exception: - if py_exception & EXCEPT_CODE_AUTOMOD: - print 'automod code' - dump_gpregs_py() - known_blocs, code_blocs_mem_range = updt_automod_code(known_blocs) - else: - raise ValueError("except at", hex(my_eip)) - -print "start emulation" -run_bin(ad+code_ad, known_blocs, code_blocs_mem_range) diff --git a/example/expression/find_conditions.py b/example/expression/find_conditions.py deleted file mode 100644 index f57a83ad..00000000 --- a/example/expression/find_conditions.py +++ /dev/null @@ -1,123 +0,0 @@ -import sys -from miasm.arch.ia32_arch import * -from miasm.tools.emul_helper import * -from miasm.core.bin_stream import bin_stream -from miasm.tools.to_c_helper import * -from optparse import OptionParser - - - -""" -Symbolic execute a function, and generate conditions list used to -explore whole binary control flow - -python find_conditions.py -a 0 simple_tests -""" - -parser = OptionParser(usage = "usage: %prog [options] file") -parser.add_option('-a', "--address", dest="address", metavar="ADDRESS", - help="address to disasemble", default="0") - - -(options, args) = parser.parse_args(sys.argv[1:]) -if not args: - parser.print_help() - sys.exit(0) -fname = args[0] -ad_to_dis = options.address - -data = (open(fname).read()) -in_str = bin_stream(data) -symbol_pool = asmbloc.asm_symbol_pool() - -def add_bloc_to_disasm(ad, all_blocs, job_done): - b = asmbloc.dis_bloc_all(x86_mn, in_str, ad, set(), - symbol_pool, bloc_wd = 1)[0] - all_blocs[ad] = b - - -def get_bloc(ad, all_blocs, job_done): - if not ad in all_blocs: - add_bloc_to_disasm(ad, all_blocs, job_done) - return all_blocs[ad] - -init_state = x86_machine().pool -def print_state(state): - to_out= [] - for r in [eax, ebx, ecx, edx, esi, edi, esp, ebp]: - if state[r] == init_state[r]: - continue - to_out.append((r, state[r])) - for k, v in state.items(): - if isinstance(k, ExprMem): - to_out.append((k, v)) - for k, v in to_out: - print k, '=', v - -def emul_mn(states_todo, states_done, all_blocs, job_done): - while states_todo: - ad, pool = states_todo.pop() - if (ad, pool) in states_done: - print 'skip', ad - continue - states_done.add((ad, pool)) - machine = x86_machine() - machine.pool = pool.copy() - ad = int(ad.arg) - b = get_bloc(ad, all_blocs, job_done) - ad = emul_bloc(machine, b) - print_state(machine.pool) - if isinstance(ad, ExprCond): - # Create 2 states, each including complementary conditions - p1 = machine.pool.copy() - p2 = machine.pool.copy() - c1 = {ad.cond: ExprInt(uint32(0))} - c2 = {ad.cond: ExprInt(uint32(1))} - p1[ad.cond] = ExprInt(uint32(0)) - p2[ad.cond] = ExprInt(uint32(1)) - ad1 = machine.eval_expr(ad.replace_expr(c1), {}) - ad2 = machine.eval_expr(ad.replace_expr(c2), {}) - if not (isinstance(ad1, ExprInt) and isinstance(ad2, ExprInt)): - print str(ad1), str(ad2) - raise ValueError("zarb condition") - states_todo.add((ad1, p1)) - states_todo.add((ad2, p2)) - elif isinstance(ad, ExprInt): - pass - elif ad == ret_addr: - continue - else: - raise ValueError("zarb eip") - -all_blocs = {} -job_done = set() -machine = x86_machine() - -argc = ExprId('argc') -argv = ExprId('argv') -ret_addr = ExprId('ret_addr') - -machine.eval_instr(push(ia32info(), argv)) -machine.eval_instr(push(ia32info(), argc)) -machine.eval_instr(push(ia32info(), ret_addr)) - -ad = int(ad_to_dis, 16) -print 'disasm', hex(ad) - -states_todo = set() -states_todo.add((ExprInt(uint32(ad)), machine.pool)) -states_done = set() -emul_mn(states_todo, states_done, all_blocs, job_done) - -all_info = set() -print '*'*40, 'conditions to match', '*'*40 -for ad, pool in states_done: - for k, v in pool.items(): - t = (k, v) - # filter conditions which are argc aware - if argc in k: - all_info.add(t) - -machine = x86_machine() -for k, v in list(all_info): - print machine.eval_expr(k.replace_expr({}), {}), "=", v diff --git a/example/expression/manip_expression1.py b/example/expression/manip_expression1.py deleted file mode 100644 index 7c6c8965..00000000 --- a/example/expression/manip_expression1.py +++ /dev/null @@ -1,28 +0,0 @@ -from miasm.expression.expression import * - -print 'simple expression manipulation demo' -# define 2 ID -a = ExprId('eax', 32) -b = ExprId('ebx', 32) -print a, b -# eax ebx - -# add those ID -c = ExprOp('+', a, b) -print c -# (eax + ebx) - -# + automaticaly generates ExprOp('+', a, b) -c = a + b -print c -# (eax + ebx) - -# ax is a slice of eax -ax = a[:16] -print ax -# eax[0:16] - -#memory deref -d = ExprMem(c, 32) -print d -# @32[(eax + ebx)] diff --git a/example/expression/manip_expression2.py b/example/expression/manip_expression2.py deleted file mode 100644 index e8b73a92..00000000 --- a/example/expression/manip_expression2.py +++ /dev/null @@ -1,27 +0,0 @@ -from miasm.arch.ia32_sem import * - -print 'simple expression use demo: get read/written stuff for instruction:' -print 'add eax, [ebx]' -print - -def get_rw(exprs): - o_r = set() - o_w = set() - for e in exprs: - o_r.update(e.get_r(mem_read=True)) - for e in exprs: - o_w.update(e.get_w()) - return o_r, o_w - -a = ExprId('eax') -b = ExprMem(ExprId('ebx'), 32) - -exprs = add(ia32info(), a, b) -o_r, o_w = get_rw(exprs) -# read ID -print 'r:', [str(x) for x in o_r] -# ['eax', '@32[ebx]', 'ebx'] - -# written ID -print 'w:', [str(x) for x in o_w] -# ['eax', 'pf', 'af', 'of', 'zf', 'cf', 'nf'] diff --git a/example/expression/manip_expression3.py b/example/expression/manip_expression3.py deleted file mode 100644 index ed3123bb..00000000 --- a/example/expression/manip_expression3.py +++ /dev/null @@ -1,25 +0,0 @@ -from miasm.arch.ia32_sem import * -from miasm.expression.expression_helper import * - -print 'simple expression simplification demo' -print - -a = ExprId('eax') -b = ExprId('ebx') -c = a + b -d = c - a -print d -# ((eax + ebx) - eax) -print "=>", expr_simp(d) -print -# ebx -e = ExprInt(uint32(0x12)) + ExprInt(uint32(0x30)) - a -print e -# ((0x12 + 0x30) - eax) -print "=>", expr_simp(e) -# (0x42 - eax) - -o = ExprCompose([(a[:8], 0, 8), - (a[8:16], 8, 16)]) -print o -print expr_simp(o) diff --git a/example/expression/manip_expression4.py b/example/expression/manip_expression4.py deleted file mode 100644 index 65f1f2f4..00000000 --- a/example/expression/manip_expression4.py +++ /dev/null @@ -1,107 +0,0 @@ -from miasm.arch.ia32_sem import * -from miasm.arch.ia32_arch import x86_mn -from miasm.core import asmbloc -from miasm.core.bin_stream import bin_stream -from miasm.tools.emul_helper import * - -from elfesteem import pe_init -import sys - -print 'simple expression use for generating dataflow graph' - -def get_rw(exprs): - o_r = set() - o_w = set() - for e in exprs: - o_r.update(e.get_r(mem_read=True)) - if isinstance(e.dst, ExprMem): - o_r.update(e.dst.arg.get_r(mem_read=True)) - for e in exprs: - o_w.update(e.get_w()) - return o_r, o_w - - -def bloc2expr(b): - out = [] - for i, l in enumerate(b.lines): - print i, l - args = [] - ex = get_instr_expr(l, ExprInt(uint32(l.offset)), args) - out.append(ex) - return out - -def node_x_2_id(n, x): - return hash(str(n)+str(x))& 0xffffffffffffffff - -def gen_bloc_data_flow_graph(b): - out_str = """ -digraph asm_graph { -size="80,50"; -node [ -fontsize = "16", -shape = "box" -]; - -""" - all_lines = bloc2expr(b) - current_nodes = {} - out = [] - all_nodes = {} - out_str_2 = "" - for i, exprs in enumerate(all_lines): - n_r, n_w = get_rw(exprs) - src = [] - for n in n_r: - x = current_nodes.get(n, 0) - current_nodes[n] = x - src.append(((n, x), i)) - dst = [] - for n in n_w: - x = current_nodes.get(n, 0) + 1 - current_nodes[n] = x - dst.append((i, (n, x))) - out.append((src, dst)) - for src, dst in out: - #print "---" - print src - print dst - for (n, x), i in src: - #print node_x_2_id(n, x), i - out_str_2 += "%s -> %s\n"%(node_x_2_id(n, x), i) - all_nodes[node_x_2_id(n, x)] = (n, x) - - for i, (n, x) in dst: - out_str_2 += "%s -> %s\n"%(i, node_x_2_id(n, x)) - all_nodes[node_x_2_id(n, x)] = (n, i) - - - for n, v in all_nodes.items(): - out_str += '%s [label=\n"%s"\n];\n'%(n, str(v[1])+"_"+str(v[0])) - for i, l in enumerate(b.lines): - out_str += '%s [fillcolor=lightblue,style=filled,label=\n"%s"\n];\n'%(i, str(i)+" "+str(l)) - out_str += out_str_2 - out_str+="};\n" - open('out.txt', 'w').write(out_str) - -if len(sys.argv) != 2: - print "%s sc_connect_back.bin"%sys.argv[0] - sys.exit(-1) -data = open(sys.argv[1]).read() -in_str = bin_stream(data) - -job_done = set() -symbol_pool = asmbloc.asm_symbol_pool() -l = symbol_pool.add_label('toto') -b = asmbloc.asm_bloc(l) - -ad = 0x2E -asmbloc.dis_bloc(x86_mn, in_str, b, ad, job_done, symbol_pool) -print 'generating dataflow graph for:' -gen_bloc_data_flow_graph(b) - -print """ -Generate ps with pdf: - dot -Tps out.txt -o graph.ps -or: - dotty out.txt -""" diff --git a/example/expression/manip_expression5.py b/example/expression/manip_expression5.py deleted file mode 100644 index 165d9eef..00000000 --- a/example/expression/manip_expression5.py +++ /dev/null @@ -1,82 +0,0 @@ -from miasm.expression.expression import * - -print 'simple expression canonization demo' - -# define 2 ID -a = ExprId('eax', 32) -b = ExprId('ebx', 32) -print a, b -# eax ebx - -# add those ID -c = ExprOp('+', a, b) -print c -# (eax + ebx) - -# + automaticaly generates ExprOp('+', a, b) -c = a + b -print c -# (eax + ebx) - -# ax is a slice of eax -ax = a[:16] -print ax -# eax[0:16] - -#memory deref -d = ExprMem(c, 32) -print d -# @32[(eax + ebx)] - -print (a+b).canonize() -print (b+a).canonize() - -m = ExprMem(a) - -print (a+m).canonize() -print (m+a).canonize() - -s = a[:8] - -print (a+s).canonize() -print (s+a).canonize() - -print (m+s).canonize() -print (s+m).canonize() - -i1 = ExprInt(uint32(0x1)) -i2 = ExprInt(uint32(0x2)) - -print (i1+i2).canonize() -print (i2+i1).canonize() - -print (a+i2).canonize() -print (i2+a).canonize() - -print (m+i2).canonize() -print (i2+m).canonize() - -print (s+i2).canonize() -print (i2+s).canonize() - -cc = ExprCond(a, b, c) - -o = ExprCompose([(a[:8], 8, 16), - (a[8:16], 0, 8)]) -print o -print o.canonize() - -o2 = ExprCompose([(a[8:16], 0, 8), - (a[:8], 8, 16)]) -print o2 -print o2.canonize() - -print ExprMem(o).canonize() - -l = [a, b, c, m, s, i1, i2, o] -print l -print ExprOp('+', *l).canonize() -l.reverse() -print l -print ExprOp('+', *l).canonize() - diff --git a/example/expression/manip_expression6.py b/example/expression/manip_expression6.py deleted file mode 100644 index 7e32da4b..00000000 --- a/example/expression/manip_expression6.py +++ /dev/null @@ -1,138 +0,0 @@ -from miasm.expression.expression import * -from miasm.expression.expression_helper import * -import os - -filename = os.environ.get('PYTHONSTARTUP') -if filename and os.path.isfile(filename): - execfile(filename) - -a = ExprId('a') -b = ExprId('b') -c = ExprId('c') -d = ExprId('d') - - -x = ExprMem(a+b+ExprInt32(0x42)) - -def replace_expr(e): - #print 'visit', e - dct = {c+ExprInt32(0x42):d, - a+b:c,} - if e in dct: - return dct[e] - return e - - -print x -y = x.visit(replace_expr) -print y -print x.copy() -print y.copy() -print y == y.copy() -print repr(y), repr(y.copy()) - - -z = ExprCompose([(a[5:9], 0, 8), (b, 8, 24), (x, 24, 32)]) -print z -print z.copy() -print z[:31].copy().visit(replace_expr) - -print 'replace' -print x.replace_expr({c+ExprInt32(0x42):d, - a+b:c,}) -print z.replace_expr({c+ExprInt32(0x42):d, - a+b:c,}) - - -u = z.copy() -print u -u.args[-1][0].arg.args[1].arg = uint32(0x45) -print u -print z -print u == z - -to_test = [(ExprInt32(1)-ExprInt32(1), ExprInt32(0)), - ((ExprInt32(5)+c+a+b-a+ExprInt32(1)-ExprInt32(5)),b+c+ExprInt32(1)), - (a+b+c-a-b-c+a,a), - (a+a+b+c-(a+(b+c)),a), - (c^b^a^c^b,a), - (a^ExprInt32(0),a), - ((a+b)-b,a), - (-(ExprInt32(0)-((a+b)-b)),a), - - (ExprOp('<<<', a, ExprInt32(32)),a), - (ExprOp('>>>', a, ExprInt32(32)),a), - (ExprOp('>>>', a, ExprInt32(0)),a), - (ExprOp('<<', a, ExprInt32(0)),a), - - (ExprOp('<<<', a, ExprOp('<<<', b, c)), - ExprOp('<<<', a, ExprOp('<<<', b, c))), - (ExprOp('<<<', ExprOp('<<<', a, b), c), - ExprOp('<<<', ExprOp('<<<', a, b), c)), - (ExprOp('<<<', ExprOp('>>>', a, b), c), - ExprOp('<<<', ExprOp('>>>', a, b), c)), - (ExprOp('>>>', ExprOp('<<<', a, b), c), - ExprOp('>>>', ExprOp('<<<', a, b), c)), - (ExprOp('>>>', ExprOp('<<<', a, b), b), - ExprOp('>>>', ExprOp('<<<', a, b), b)), - - - (ExprOp('>>>', ExprOp('<<<', a, ExprInt32(10)), ExprInt32(2)), - ExprOp('<<<', a, ExprInt32(8))), - - (ExprOp('>>>', ExprOp('<<<', a, ExprInt32(10)), ExprInt32(2)) ^ ExprOp('>>>', ExprOp('<<<', a, ExprInt32(10)), ExprInt32(2)), - ExprInt32(0)), - (ExprOp(">>", (a & ExprInt32(0xF)), ExprInt32(0x15)), - ExprInt32(0)), - (ExprOp("==", ExprInt32(12), ExprInt32(10)), ExprInt32(0)), - (ExprOp("==", ExprInt32(12), ExprInt32(12)), ExprInt32(1)), - (ExprOp("==", a|ExprInt32(12), ExprInt32(0)),ExprInt32(0)), - (ExprOp("==", a|ExprInt32(12), ExprInt32(14)), - ExprOp("==", a|ExprInt32(12), ExprInt32(14))), - (ExprOp("parity", ExprInt32(0xf)), ExprInt32(1)), - (ExprOp("parity", ExprInt32(0xe)), ExprInt32(0)), - (ExprInt32(0x4142)[:32],ExprInt32(0x4142)), - (ExprInt32(0x4142)[:8],ExprInt8(0x42)), - (ExprInt32(0x4142)[8:16],ExprInt8(0x41)), - (a[:32], a), - (a[:8][:8],a[:8]), - (a[:16][:8],a[:8]), - (a[8:16][:8],a[8:16]), - (a[8:32][:8],a[8:16]), - (a[:16][8:16],a[8:16]), - (ExprCompose([(a, 0, 32)]),a), - (ExprCompose([(a[:16], 0, 16)]), a[:16]), - (ExprCompose([(a[:16], 0, 16), (a, 16, 32)]), - ExprCompose([(a[:16], 0, 16), (a, 16, 32)]),), - (ExprCompose([(a[:16], 0, 16), (a[16:32], 16, 32)]), a), - - (ExprMem(a)[:32], ExprMem(a)), - (ExprMem(a)[:16], ExprMem(a, size=16)), - - (ExprCond(ExprInt32(1), a, b), a), - (ExprCond(ExprInt32(0), b, a), a), - - (ExprInt32(0x80000000)[31:32], ExprInt32(1)), - (ExprCompose([(ExprInt16(0x1337)[:8], 0, 8),(ExprInt16(0x1337)[8:16], 8, 16)]), - ExprInt16(0x1337)), - - (ExprCompose([(ExprInt32(0x1337beef)[8:16], 8, 16), - (ExprInt32(0x1337beef)[:8], 0, 8), - (ExprInt32(0x1337beef)[16:32], 16, 32)]), - ExprInt32(0x1337BEEF)), - - - ] - - -for e, e_check in to_test[:]: - # - print "#"*80 - e_check = expr_simp(e_check) - print "#"*80 - print str(e), str(e_check) - e_new = expr_simp(e) - print "orig", str(e), "new", str(e_new), "check", str(e_check) - rez = e_new == e_check - if not rez: - fdsfds diff --git a/example/expression/obf.bin b/example/expression/obf.bin deleted file mode 100644 index bdb3c43e..00000000 --- a/example/expression/obf.bin +++ /dev/null Binary files differdiff --git a/example/expression/sc_connect_back.bin b/example/expression/sc_connect_back.bin deleted file mode 100644 index 9e9c80a5..00000000 --- a/example/expression/sc_connect_back.bin +++ /dev/null Binary files differdiff --git a/example/expression/simple_tests b/example/expression/simple_tests deleted file mode 100644 index 96fbdc25..00000000 --- a/example/expression/simple_tests +++ /dev/null Binary files differdiff --git a/example/expression/symbolic_exec.py b/example/expression/symbolic_exec.py deleted file mode 100644 index 40e9dc07..00000000 --- a/example/expression/symbolic_exec.py +++ /dev/null @@ -1,38 +0,0 @@ -import sys -from miasm.arch.ia32_arch import * -from miasm.tools.emul_helper import * -from miasm.core.bin_stream import bin_stream - -print "symbolic execution & simplification demo" - -def loop_emul(ad, machine, all_bloc): - ad = ExprInt(uint32(ad)) - while isinstance(ad, ExprInt): - b = asmbloc.getblocby_offset(all_bloc, ad.arg) - if not b: - raise ValueError('unknown bloc', repr(ad)) - print '*'*20, 'emul bloc:', '*'*20 - print b - ad = emul_bloc(machine, b) - return ad - -if len(sys.argv) != 2: - print "%s obf.bin"%sys.argv[0] - sys.exit(-1) - -data = open(sys.argv[1]).read() -in_str = bin_stream(data) - -symbol_pool = asmbloc.asm_symbol_pool() -ad = 0 - -all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, ad, set(), symbol_pool, dontdis_retcall = True) - -machine = x86_machine() -ad = loop_emul(ad, machine, all_bloc) -print -print "emulation result:" -print dump_reg(machine.pool) -print "eip", ad -print -print dump_mem(machine.pool) diff --git a/example/extract_pe_ressources.py b/example/extract_pe_ressources.py deleted file mode 100644 index 71d8e226..00000000 --- a/example/extract_pe_ressources.py +++ /dev/null @@ -1,44 +0,0 @@ -import sys -import struct -from elfesteem import * -import os -import sys - -# example for extracting all pe ressources - -def extract_res(res, name_o = "", num = 0, lvl=-1): - lvl +=1 - if not res: - return num - for x in res.resentries: - print "\t"*lvl, repr(x) - num += 1 - - if x.name_s: - name = name_o[:]+repr(x.name_s.value[::2]) - else: - name = name_o[:] - - if x.data: - print "\t"*lvl, 'data', len(x.data.s) - open('out/%.3d_%s.bin'%(num, name), 'w').write(str(x.data.s)) - else: - print "\t"*lvl, None - if x.offsettosubdir: - num = extract_res(x.subdir, name, num, lvl+1) - return num - - - -try: - os.stat('out') -except: - os.mkdir('out') - -fname = sys.argv[1] -e = pe_init.PE(open(fname, 'rb').read()) -res = e.DirRes.resdesc - - - -extract_res(res) diff --git a/example/find_rop.py b/example/find_rop.py deleted file mode 100644 index a071cf18..00000000 --- a/example/find_rop.py +++ /dev/null @@ -1,250 +0,0 @@ -import os, sys -from elfesteem import * -from miasm.tools.pe_helper import * -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from elfesteem import pe -from miasm.tools.to_c_helper import * - - -if len(sys.argv) < 2: - print "%s dllfile"%sys.argv[0] - sys.exit(0) -fname = sys.argv[1] -e = pe_init.PE(open(fname, 'rb').read()) -in_str = bin_stream(e.virt) - -# find gadget only in first section -section_code_name = e.SHList.shlist[0].name.strip("\x00") -s_code = e.getsectionbyname(section_code_name) - - -code_start = e.rva2virt(s_code.addr) -code_stop = e.rva2virt(s_code.addr+s_code.size) - - -print "run on", hex(code_start), hex(code_stop) - - -filename = os.environ.get('PYTHONSTARTUP') -if filename and os.path.isfile(filename): - execfile(filename) - - -def whoami(): - return inspect.stack()[1][3] - - - -def mem_read_wrap(evaluator, e): - return e - - -def mem_write_wrap(evaluator, dst, s, src, pool_out): - return ExprTop() - - - -min_addr = code_start -max_addr = code_stop - -print hex(min_addr), hex(max_addr) -arg1 = ExprId('ARG1', 32, True) -arg2 = ExprId('ARG2', 32, True) -ret1 = ExprId('RET1', 32, True) - -data1 = ExprId('DATA1', 32, True) -data2 = ExprId('DATA2', 32, True) -data3 = ExprId('DATA3', 32, True) -data4 = ExprId('DATA4', 32, True) -data5 = ExprId('DATA5', 32, True) -data6 = ExprId('DATA6', 32, True) -data7 = ExprId('DATA7', 32, True) -data8 = ExprId('DATA8', 32, True) -data9 = ExprId('DATA9', 32, True) -data10 = ExprId('DATA10', 32, True) - -machine = eval_abs({esp:init_esp, ebp:init_ebp, eax:init_eax, ebx:init_ebx, ecx:init_ecx, edx:init_edx, esi:init_esi, edi:init_edi, - cs:ExprInt(uint32(9)), - zf : ExprInt(uint32(0)), nf : ExprInt(uint32(0)), pf : ExprInt(uint32(0)), - of : ExprInt(uint32(0)), cf : ExprInt(uint32(0)), tf : ExprInt(uint32(0)), - i_f: ExprInt(uint32(1)), df : ExprInt(uint32(0)), af : ExprInt(uint32(0)), - iopl: ExprInt(uint32(0)), nt : ExprInt(uint32(0)), rf : ExprInt(uint32(0)), - vm : ExprInt(uint32(0)), ac : ExprInt(uint32(0)), vif: ExprInt(uint32(0)), - vip: ExprInt(uint32(0)), i_d: ExprInt(uint32(0)),tsc1: ExprInt(uint32(0)), - tsc2: ExprInt(uint32(0)), - dr7:ExprInt(uint32(0)), - cr0:init_cr0, - - }, - mem_read_wrap, - mem_write_wrap, - ) - - -# add some info for example -from elfesteem import * -from miasm.tools.pe_helper import * -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from elfesteem import pe -from miasm.tools.to_c_helper import * - - -if len(sys.argv) < 2: - print "%s dllfile"%sys.argv[0] - sys.exit(0) -fname = sys.argv[1] -e = pe_init.PE(open(fname, 'rb').read()) -in_str = bin_stream(e.virt) - -# find gadget only in first section -section_code_name = e.SHList.shlist[0].name.strip("\x00") -s_code = e.getsectionbyname(section_code_name) - - -code_start = e.rva2virt(s_code.addr) -code_stop = e.rva2virt(s_code.addr+s_code.size) - - -print "run on", hex(code_start), hex(code_stop) - - -filename = os.environ.get('PYTHONSTARTUP') -if filename and os.path.isfile(filename): - execfile(filename) - - -def whoami(): - return inspect.stack()[1][3] - - - -def mem_read_wrap(evaluator, e): - return e - - -def mem_write_wrap(evaluator, dst, s, src, pool_out): - return ExprTop() - - - -min_addr = code_start -max_addr = code_stop - -print hex(min_addr), hex(max_addr) -arg1 = ExprId('ARG1', 32, True) -arg2 = ExprId('ARG2', 32, True) -ret1 = ExprId('RET1', 32, True) - -data1 = ExprId('DATA1', 32, True) -data2 = ExprId('DATA2', 32, True) -data3 = ExprId('DATA3', 32, True) -data4 = ExprId('DATA4', 32, True) -data5 = ExprId('DATA5', 32, True) -data6 = ExprId('DATA6', 32, True) -data7 = ExprId('DATA7', 32, True) -data8 = ExprId('DATA8', 32, True) -data9 = ExprId('DATA9', 32, True) -data10 = ExprId('DATA10', 32, True) - -machine = eval_abs({esp:init_esp, ebp:init_ebp, eax:init_eax, ebx:init_ebx, ecx:init_ecx, edx:init_edx, esi:init_esi, edi:init_edi, - cs:ExprInt(uint32(9)), - zf : ExprInt(uint32(0)), nf : ExprInt(uint32(0)), pf : ExprInt(uint32(0)), - of : ExprInt(uint32(0)), cf : ExprInt(uint32(0)), tf : ExprInt(uint32(0)), - i_f: ExprInt(uint32(1)), df : ExprInt(uint32(0)), af : ExprInt(uint32(0)), - iopl: ExprInt(uint32(0)), nt : ExprInt(uint32(0)), rf : ExprInt(uint32(0)), - vm : ExprInt(uint32(0)), ac : ExprInt(uint32(0)), vif: ExprInt(uint32(0)), - vip: ExprInt(uint32(0)), i_d: ExprInt(uint32(0)),tsc1: ExprInt(uint32(0)), - tsc2: ExprInt(uint32(0)), - dr7:ExprInt(uint32(0)), - cr0:init_cr0, - - }, - mem_read_wrap, - mem_write_wrap, - ) - - -# add some info for example -machine.eval_instr(push(('u32', 'u32'), arg2)) -machine.eval_instr(push(('u32', 'u32'), arg1)) -machine.eval_instr(push(('u32', 'u32'), ret1)) -machine.eval_instr(push(('u32', 'u32'), ebp)) -machine.eval_instr(mov(('u32', 'u32'), ebp, esp)) -machine.eval_instr(sub(('u32', 'u32'), esp, ExprInt(uint32(0x14)))) -machine.eval_instr(mov(('u32', 'u32'), eax, ExprMem(ebp + ExprInt(uint32(8))))) -machine.eval_instr(mov(('u32', 'u32'), edx, ExprMem(eax + ExprInt(uint32(12))))) -machine.eval_instr(mov(('u32', 'u32'), eax, ExprMem(ebp + ExprInt(uint32(12))))) -machine.eval_instr(mov(('u32', 'u32'), ExprMem(esp), eax)) -machine.eval_instr(push(('u32', 'u32'), ExprInt(uint32(0x1337beef)))) - -for k in machine.pool: - machine.pool[k] = expr_simp(machine.pool[k]) - -print dump_reg(machine.pool) -init_mem = dict(machine.pool) - - -for f_ad in xrange(min_addr, max_addr): - if f_ad %0x100 == 0: - print hex(f_ad) - machine.pool = dict(init_mem) - start_ad = f_ad - my_eip = ExprInt(uint32(f_ad)) - cycles = 0 - - while True: - cycles += 1 - # max 5 instructions chain - if cycles> 5: - break - - #final check - if isinstance(my_eip, ExprCond): - my_eip = my_eip.src1 - elif not isinstance(my_eip, ExprInt): - break - ad = int(my_eip.arg) - #if not e.is_in_virt_address(ad): - if not (min_addr < ad< max_addr): - break - in_str.offset = ad - l = x86_mn.dis(in_str) - # print hex(my_eip.arg), l - if not l: - break - - args = [] - my_eip.arg+=uint32(l.l) - try: - ex = get_instr_expr(l, my_eip, args) - except: - break - try: - my_eip, mem_dst = emul_full_expr(ex, l, my_eip, None, machine) - except: - break - - for k in machine.pool: - machine.pool[k] = expr_simp(machine.pool[k]) - - if isinstance(my_eip, ExprCond): - continue - # we want eip controled by ARG* id or DATA - # here, crappy test on str (not clean expression filtering) - if not ("ARG" in str(my_eip) or "DATA" in str(my_eip)): - continue - - # we want esp controled by ARG* id or DATA - my_esp = machine.pool[esp] - if not ("ARG" in str(my_esp) or "DATA" in str(my_esp)): - continue - - # this should give stack pivot - print "#"*0x80 - print 'constraint solved ad ', hex(start_ad) - print "eip", my_eip - print "esp", my_esp diff --git a/example/md5 b/example/md5 deleted file mode 100755 index a946dada..00000000 --- a/example/md5 +++ /dev/null Binary files differdiff --git a/example/sandbox_elf.py b/example/sandbox_elf.py deleted file mode 100644 index d57adfcf..00000000 --- a/example/sandbox_elf.py +++ /dev/null @@ -1,120 +0,0 @@ -import os -from elfesteem import * -from miasm.tools.pe_helper import * -from miasm.tools import seh_helper -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from miasm.tools.to_c_helper import * -from elfesteem import pe -import cProfile -import code -import sys -from miasm.tools import nux_api - -from miasm.tools.nux_api import * - - -if len(sys.argv) != 2: - print "to test:" - print "python sandbox_elf.py md5" - sys.exit(0) - - - -fname = sys.argv[1] -e = elf_init.ELF(open(fname, 'rb').read()) -in_str = bin_stream_vm() -vm_init_regs() -init_memory_page_pool_py() -init_code_bloc_pool_py() - -codenat_tcc_init() - -filename = os.environ.get('PYTHONSTARTUP') -if filename and os.path.isfile(filename): - execfile(filename) - -vm_load_elf(e) - -runtime_dll, lib_dyn_funcs = preload_elf(e, patch_vm_imp = True, lib_base_ad = 0x77700000) -lib_dyn_ad2name = dict([(x[1], x[0]) for x in lib_dyn_funcs.items()]) -dyn_func = {} - - -stack_base_ad = 0x1230000 -stack_size = 0x10000 -vm_add_memory_page(stack_base_ad, PAGE_READ|PAGE_WRITE, "\x00"*stack_size) -dump_memory_page_pool_py() - - -try: - ep = e.sh.symtab.symbols['main'].value -except: - ep = e.Ehdr.entry - -ptr_esp = stack_base_ad+stack_size-0x1000 -vm_set_mem(ptr_esp, "/home/toto\x00") -ptr_arg0 = ptr_esp -ptr_esp -=0x100 -ptr_args = ptr_esp -vm_set_mem(ptr_args, struct.pack('LL', ptr_arg0, 0)) - -regs = vm_get_gpreg() -regs['eip'] = ep -regs['esp'] = ptr_esp -vm_set_gpreg(regs) -dump_gpregs_py() - -vm_push_uint32_t(ptr_args) -vm_push_uint32_t(1) -vm_push_uint32_t(0x1337beef) - -dump_memory_page_pool_py() - -symbol_pool = asmbloc.asm_symbol_pool() - -my_eip = ep - - -known_blocs = {} -code_blocs_mem_range = [] - - -log_regs = False -log_mn = log_regs -must_stop = False - -ad_oep = None -segm_to_do = {} - - - - -def run_bin(my_eip, known_blocs, code_blocs_mem_range): - global log_regs, log_mn - may_end = None - while my_eip != 0x1337beef: - - if my_eip == ad_oep: - print 'reach ad_oep', hex(ad_oep) - return - #dyn dll funcs - if my_eip in runtime_dll.fad2cname: - my_eip = manage_runtime_func(my_eip, [globals(), nux_api], runtime_dll) - continue - - my_eip, py_exception = do_bloc_emul(known_blocs, in_str, my_eip, - symbol_pool, code_blocs_mem_range, - log_regs = log_regs, log_mn = log_mn, - segm_to_do = segm_to_do, - dump_blocs = False) - - if py_exception: - if py_exception & EXCEPT_CODE_AUTOMOD: - known_blocs, code_blocs_mem_range = updt_automod_code(known_blocs) - else: - raise ValueError("except at", hex(my_eip)) - -print "start run" -run_bin(my_eip, known_blocs, code_blocs_mem_range) diff --git a/example/sandbox_pe.py b/example/sandbox_pe.py deleted file mode 100644 index fe3aa390..00000000 --- a/example/sandbox_pe.py +++ /dev/null @@ -1,126 +0,0 @@ -import os -from elfesteem import * -from miasm.tools.pe_helper import * -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from miasm.tools.to_c_helper import * -from elfesteem import pe -import cProfile -import code -from miasm.tools import emul_helper -import sys -from miasm.tools import win_api -from miasm.arch.ia32_arch import * - - -def whoami(): - return inspect.stack()[1][3] - - -fname = sys.argv[1] -e = pe_init.PE(open(fname, 'rb').read()) - - -# /!\ no seh set for this demo - -vm_init_regs() -init_memory_page_pool_py() -init_code_bloc_pool_py() -in_str = bin_stream_vm() - -codenat_tcc_init() - -vm_load_pe(e) - -filename = os.environ.get('PYTHONSTARTUP') -if filename and os.path.isfile(filename): - execfile(filename) - - -runtime_dll = libimp(0x71111111) -dll_dyn_funcs = preload_lib(e, runtime_dll) -# set winapi to ours -win_api.runtime_dll = runtime_dll -win_api.current_pe = e -dll_dyn_ad2name = dict([(x[1], x[0]) for x in dll_dyn_funcs.items()]) -dyn_func = {} - - -ep = e.rva2virt(e.Opthdr.AddressOfEntryPoint) - -stack_base_ad = 0x1230000 -stack_size = 0x10000 -vm_add_memory_page(stack_base_ad, PAGE_READ|PAGE_WRITE, "\x00"*stack_size) -dump_memory_page_pool_py() - - - - - -regs = vm_get_gpreg() -regs['eip'] = ep -regs['esp'] = stack_base_ad+stack_size -vm_set_gpreg(regs) -dump_gpregs_py() - -vm_push_uint32_t(0) -vm_push_uint32_t(0) -vm_push_uint32_t(0x1337beef) - -symbol_pool = asmbloc.asm_symbol_pool() - -known_blocs = {} -code_blocs_mem_range = [] - - -def dump_raw_e(e): - e.Opthdr.AddressOfEntryPoint = e.virt2rva(vm_get_gpreg()['eip']) - str_e = StrPatchwork(str(e)) - for s in e.SHList: - data = vm_get_str(e.rva2virt(s.addr), s.size) - svad = e.rva2virt(s.addr) - print hex(len(data)) - str_e[s.offset] = data - e.virt[e.off2virt(s.offset)] = data - open('out.bin', 'w').write(str(str_e)) - - -log_regs = True -log_mn = log_regs -def run_bin(my_eip, known_blocs, code_blocs_mem_range): - global log_regs, log_mn - while my_eip != 0x1337beef: - - #dyn dll funcs - if my_eip in runtime_dll.fad2cname: - fname = runtime_dll.fad2cname[my_eip] - if not fname in win_api.__dict__: - print repr(fname) - raise ValueError('unknown api', hex(vm_pop_uint32_t())) - win_api.__dict__[fname]() - regs = vm_get_gpreg() - my_eip = regs['eip'] - continue - - - if not my_eip in known_blocs: - updt_bloc_emul(known_blocs, in_str, my_eip, symbol_pool, code_blocs_mem_range, log_regs = log_regs, log_mn = log_mn) - vm_reset_exception() - - try: - my_eip = vm_exec_blocs(my_eip, known_blocs) - except KeyboardInterrupt: - break - py_exception = vm_get_exception() - if py_exception: - if py_exception & EXCEPT_CODE_AUTOMOD: - print 'automod code' - dump_gpregs_py() - known_blocs, code_blocs_mem_range = updt_automod_code(known_blocs) - else: - raise ValueError("except at", hex(my_eip)) - -print "start emulation" -run_bin(ep, known_blocs, code_blocs_mem_range) -dump_raw_e(e) diff --git a/example/unpack_gen.py b/example/unpack_gen.py deleted file mode 100644 index a81e8247..00000000 --- a/example/unpack_gen.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -from elfesteem import * -from miasm.tools.pe_helper import * -import inspect -from miasm.core import asmbloc -from miasm.core import parse_asm -from miasm.tools.to_c_helper import * -from elfesteem import pe -import cProfile -import code -from miasm.tools import emul_helper -import sys -from miasm.tools import win_api -from miasm.tools import seh_helper - - -def whoami(): - return inspect.stack()[1][3] - -from optparse import OptionParser - -parser = OptionParser(usage = "usage: %prog [options] file") -parser.add_option('-a', "--address", dest="address", metavar="ADDRESS", - help="force eop address", default=None) -parser.add_option('-s', "--segm", dest="usesegm", action="store_true", - help="use segments fs:", default=False) -parser.add_option('-d', "--hdr", dest="loadhdr", action="store_true", - help="load pe hdr", default=False) -parser.add_option('-l', "--loadbasedll", dest="loadbasedll", action="store_true", - help="load base dll", default=False) -parser.add_option('-x', "--dumpall", dest="dumpall", action="store_true", - help="load base dll", default=False) -parser.add_option('-e', "--loadmainpe", dest="loadmainpe", action="store_true", - help="load main pe", default=False) - -(options, args) = parser.parse_args(sys.argv[1:]) -if not args: - parser.print_help() - sys.exit(0) - -e_orig, in_str, runtime_dll, segm_to_do, symbol_pool = load_pe_in_vm(args[0], options) -ad_oep = None -if options.address: - ad_oep = int(options.address, 16) - print "stop at", ad_oep - - -vm_push_uint32_t(0) -vm_push_uint32_t(0) -vm_push_uint32_t(0x1337beef) - -known_blocs = {} -code_blocs_mem_range = [] - - -log_regs = False -log_mn = log_regs -def run_bin(my_eip, known_blocs, code_blocs_mem_range): - global log_regs, log_mn - may_end = None - while my_eip != 0x1337beef: - - if my_eip == ad_oep: - print 'reach ad_oep', hex(ad_oep) - return - #dyn dll funcs - if my_eip in runtime_dll.fad2cname: - my_eip = manage_runtime_func(my_eip, [globals(), win_api], runtime_dll) - continue - - my_eip, py_exception = do_bloc_emul(known_blocs, in_str, my_eip, - symbol_pool, code_blocs_mem_range, - log_regs = log_regs, log_mn = log_mn, - segm_to_do = segm_to_do, - dump_blocs = True) - - if py_exception: - if py_exception & EXCEPT_CODE_AUTOMOD: - known_blocs, code_blocs_mem_range = updt_automod_code(known_blocs) - else: - raise ValueError("except at", hex(my_eip)) - - - -ep = e_orig.rva2virt(e_orig.Opthdr.AddressOfEntryPoint) - -print "start emulation", hex(ep) -run_bin(ep, known_blocs, code_blocs_mem_range) -emul_helper.vm2pe("oo.bin", runtime_dll, e_orig) diff --git a/example/unpack_upx.py b/example/unpack_upx.py deleted file mode 100644 index 34da5ce8..00000000 --- a/example/unpack_upx.py +++ /dev/null @@ -1,279 +0,0 @@ -import sys -import struct -from elfesteem import * -from miasm.tools.pe_helper import * -from elfesteem.strpatchwork import StrPatchwork -from miasm.tools.to_c_helper import * -from miasm.tools.codenat import * -from pdb import pm - - -# example for scrambled upx unpacking - -fname = sys.argv[1] - -e = pe_init.PE(open(fname, 'rb').read()) -in_str = bin_stream(e.virt) - -ep = e.rva2virt(e.Opthdr.AddressOfEntryPoint) -decomp_func = ep - - - - -vm_init_regs() -init_memory_page_pool_py() -init_code_bloc_pool_py() - -codenat_tcc_init() - -print "start emul..." -machine = x86_machine() - - -job_done = set() -symbol_pool = asmbloc.asm_symbol_pool() -if e.Coffhdr.characteristics & (1<<13): - # dll - all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, decomp_func, job_done, symbol_pool, bloc_wd=2) - f_eip = emul_bloc(machine, all_bloc[0]) - f_eip = emul_bloc(machine, all_bloc[1]) - - b = all_bloc[1] -else: - # binary - all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, decomp_func, job_done, symbol_pool, bloc_wd=1) - f_eip = emul_bloc(machine, all_bloc[0]) - - -#f_eip = emul_bloc(machine, b) - -decomp_buf_ad_in = int(machine.pool[esi].arg) -decomp_buf_ad_out = int( machine.pool[edi].arg) - - -decomp_buf_len_in = decomp_func - decomp_buf_ad_in -decomp_buf_len_out = decomp_buf_ad_in - decomp_buf_ad_out -print "in l", hex(decomp_buf_len_in), "out l", hex(decomp_buf_len_out) - -dont_dis = asmbloc.interval([(decomp_buf_ad_out, decomp_buf_ad_in)]) - -g = asmbloc.bloc2graph(all_bloc) -open("graph.txt" , "w").write(g) - - -job_done = set() -symbol_pool = asmbloc.asm_symbol_pool() -all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, decomp_func, job_done, symbol_pool, dont_dis) - - -end_label = None -for b in all_bloc: - if len(b.bto) == 1 and abs(b.label.offset - b.bto[0].label.offset) > 0x1000: - # asmbloc.getblocby_label(all_bloc, b.bto[0].label)== None: - end_label = b.bto[0].label.offset - break -if not end_label: - raise ValueError('cannot find final bloc') - -print 'final label' -print hex(end_label) - - -base_imp = 0 -offset_imp = 0 -libbase_ad = 0x77700000 -def myloadlibexa(): - global base_imp, offset_imp, libbase_ad, runtime_dll - ret_ad = vm_pop_uint32_t() - pname = vm_pop_uint32_t() - print 'loadlib', hex(pname), hex(ret_ad) - - libname = vm_get_str(pname, 0x100) - libname = libname[:libname.find('\x00')] - - print repr(libname) - - ad = runtime_dll.lib_get_add_base(libname) - regs = vm_get_gpreg() - if not base_imp: - base_imp = regs["edi"] - if not offset_imp: - offset_imp = regs['eax'] - - print hex(base_imp), hex(offset_imp) - regs['eip'] = ret_ad - regs['eax'] = ad - vm_set_gpreg(regs) - - -def mygetproc(): - global runtime_dll - ret_ad = vm_pop_uint32_t() - libbase = vm_pop_uint32_t() - fname = vm_pop_uint32_t() - print 'getproc', hex(fname), hex(libbase), hex(ret_ad) - - regs = vm_get_gpreg() - dst_ad = regs['ebx'] - print 'ebx', hex(dst_ad) - - if fname < 0x10000: - fname = fname - else: - fname = vm_get_str(fname, 0x100) - fname = fname[:fname.find('\x00')] - print fname - - - ad = runtime_dll.lib_get_add_func(libbase, fname, dst_ad) - - regs['eip'] = ret_ad - regs['eax'] = ad - vm_set_gpreg(regs) - - -stack_size = 0x10000 -vm_add_memory_page(0x40000000, PAGE_READ|PAGE_WRITE, "\x00"*stack_size) - -vm_load_pe(e) - -runtime_dll = libimp(0x71111111) -dll_dyn_funcs = preload_lib(e, runtime_dll) -dll_dyn_ad2name = dict([(x[1], x[0]) for x in dll_dyn_funcs.items()]) - -from miasm.tools import win_api - - -dyn_func = {} -dyn_func[dll_dyn_funcs['kernel32_LoadLibraryA']] = myloadlibexa -dyn_func[dll_dyn_funcs['kernel32_GetProcAddress']] = mygetproc -if 'kernel32_VirtualProtect' in dll_dyn_funcs: - dyn_func[dll_dyn_funcs['kernel32_VirtualProtect']] = win_api.kernel32_VirtualProtect - - - - -dump_memory_page_pool_py() - - -regs = vm_get_gpreg() -regs['eip'] = decomp_func -regs['esp'] = 0x40000000+stack_size - -vm_set_gpreg(regs) - -vm_push_uint32_t(1) #reason code if dll -vm_push_uint32_t(1) #reason code if dll -vm_push_uint32_t(0x1337beef) - -known_blocs = {} -cpt =0 -code_blocs_mem_range = [] - -def my_run(): - global cpt, my_eip, known_blocs, code_blocs_mem_range - trace_on = {'log_mn':False, 'log_regs':False} - - print 'start' - while True: - cpt+=1 - #print 'eip', hex(my_eip) - if my_eip in [ end_label]: - e.Opthdr.AddressOfEntryPoint = e.virt2rva(my_eip) - print 'updating binary', cpt - for s in e.SHList: - sdata = vm_get_str(e.rva2virt(s.addr), s.rawsize) - e.virt[e.rva2virt(s.addr)] = sdata - in_str = bin_stream(e.virt) - #open('uu.bin', 'wb').write(str(e)) - g = asmbloc.bloc2graph([x.b for x in known_blocs.values()], lines = False) - #open("graph.txt" , "w").write(g) - break - if my_eip in dyn_func: - dyn_func[my_eip]() - print 'call dyn func', hex(my_eip) - regs = vm_get_gpreg() - my_eip = regs['eip'] - continue - if not my_eip in known_blocs: - in_str = updt_pe_from_emul(e) - updt_bloc_emul(known_blocs, in_str, my_eip, symbol_pool, code_blocs_mem_range, **trace_on) - vm_reset_exception() - - my_eip = known_blocs[my_eip].module_c.func() - py_exception = vm_get_exception() - if py_exception: - if py_exception & EXCEPT_CODE_AUTOMOD: - print 'automod code' - dump_gpregs_py() - known_blocs, code_blocs_mem_range = updt_automod_code(known_blocs) - else: - raise ValueError("zarb exception", hex(py_exception)) - - -my_eip = decomp_func - -my_run() - -print "decomp end", hex(base_imp), hex(offset_imp) -regs = vm_get_gpreg() - -for r, v in regs.items(): - print r, hex(v&0xFFFFFFFF) - -oo = vm_get_str(decomp_buf_ad_out, decomp_func-decomp_buf_ad_out) - -#open('uu', 'w').write("A"*0x1000 + oo) -print repr(oo[:0x10]) -print repr(oo[-0x10:]) - - -print hex(len(oo)) - -###rebuild import table########## -print 'assing' -e.virt[decomp_buf_ad_out] = oo -e.SHList.align_sections(0x1000, 0x1000) -print repr(e.SHList) - -ad_base = regs['esi'] - -ad_tmp = base_imp -8 -print "imp addr", hex(ad_tmp) -print 'ad base:', hex(ad_base) -print "base imp", hex(offset_imp) -print 'decomp_buf_ad_out', hex(decomp_buf_ad_out) -new_dll = [] - -offset_imp = offset_imp - decomp_buf_ad_out - struct.unpack('I', e.virt[ad_tmp:ad_tmp+4])[0] -print "read ofset imp", hex(offset_imp) - -#XXXXX -ad_base = decomp_buf_ad_out - -print repr(e.SHList) -st = StrPatchwork() -st[0] = e.content - -# get back data from emulator -for s in e.SHList: - ad1 = e.rva2virt(s.addr) - ad2 =ad1 + len(s.data) - st[s.offset] = e.virt[ad1:ad2] -e.content = str(st) - -e.DirRes = pe.DirRes(e) -#e.DirImport.impdesc = None -print repr(e.DirImport.impdesc) -new_dll = runtime_dll.gen_new_lib(e) -print new_dll -e.DirImport.impdesc = [] -e.DirImport.add_dlldesc(new_dll) -s_myimp = e.SHList.add_section(name = "myimp", rawsize = len(e.DirImport)) -print repr(e.SHList) -e.DirImport.set_rva(s_myimp.addr) - -e.Opthdr.AddressOfEntryPoint = e.virt2rva(end_label) -fname = fname.replace('.', '_') -open(fname+'_unupx.bin','w').write(str(e)) diff --git a/example/x86_sc.bin b/example/x86_sc.bin deleted file mode 100644 index af96aeb2..00000000 --- a/example/x86_sc.bin +++ /dev/null Binary files differ |