importsysimportpefilefromcapstoneimport*defdisassemble(file_path):# pefile info: https://github.com/erocarrera/pefile/blob/wiki/UsageExamples.md# load pe file or pefile.PE(use data=str_object_with_pe_file_data) to load string bufferpe=pefile.PE(file_path)imports={}# get all imports forentryinpe.DIRECTORY_ENTRY_IMPORT:# uncomment to print dll name # print entry.dllforimpinentry.imports:imports[hex(imp.address)]=imp.name# get entry point of PEeop=pe.OPTIONAL_HEADER.AddressOfEntryPointcode_section=pe.get_section_by_rva(eop)# get code data code_dump=code_section.get_data()# allocate correct memory address code_addr=pe.OPTIONAL_HEADER.ImageBase+code_section.VirtualAddress# Capstone engine info http://www.capstone-engine.org/lang_python.html# Initialize capstone class, arguments for class hardware architecture & the hardware mode# for 64bit change CS_MODE_32 to CS_MODE_64md=Cs(CS_ARCH_X86,CS_MODE_32)# detail must be enabled to get the operand values/details md.detail=True# disassemble memory in code_dump at address code_addrforiinmd.disasm(code_dump,code_addr):# dir(i) for more details op_str=i.op_str# compare mnemonicifi.mnemonic=="call"ori.mnemonic=="jmp":# get the displacement within the operandtemp_str=hex(i.operands[0].mem.disp)# hack to remove the L from Pythons Longiftemp_str[-1]=="L":temp_str=temp_str[:-1]ifimports.has_key(temp_str):# replace address with import nameapi_name=imports[temp_str]op_str=api_name# print address, mnemonic and operand string. See line 36 on accessing more # details in the operand(s) print("0x%x:\t%s\t%s"%(i.address,i.mnemonic,op_str))disassemble(sys.argv[1])
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.