python 通过 capstone 反汇编
作者:互联网
Capstone是一个轻量级的多平台、多架构的反汇编框架,该模块支持目前所有通用操作系统,反汇编架构几乎全部支持。
capstone使用起来非常简单,如果只需要静态反汇编,则几行代码即可完成该功能了。
from capstone import *
# powerby LyShark
def Disassembly(path,BaseAddr,FileOffset,ReadByte):
with open(path,"rb") as fp:
fp.seek(int(FileOffset))
opcode = fp.read(int(ReadByte))
md = Cs(CS_ARCH_X86, CS_MODE_32)
for item in md.disasm(opcode, 0):
addr = int(BaseAddr) + item.address
dic = {"Addr": str(addr) , "OpCode": item.mnemonic + " " + item.op_str}
print(dic)
if __name__ == "__main__":
# 文件名 内存地址 开始位置 长度
Disassembly("d://Win32Project.exe",401000,0,1024)
如果需要针对.text节进行反汇编,则需要通过pefile模块找到该节所对应到文件中的位置,并从该位置开始向下反编译即可,代码如下:
from capstone import *
import pefile
# 遍历整个可执行文件并返回汇编代码,有一个小Bug
# powerby LyShark
def FOA_Disassembly(FilePath):
opcode_list = []
pe = pefile.PE(FilePath)
ImageBase = pe.OPTIONAL_HEADER.ImageBase
for item in pe.sections:
if str(item.Name.decode('UTF-8').strip(b'\x00'.decode())) == ".text":
# print("虚拟地址: 0x%.8X 虚拟大小: 0x%.8X" %(item.VirtualAddress,item.Misc_VirtualSize))
VirtualAddress = item.VirtualAddress
VirtualSize = item.Misc_VirtualSize
ActualOffset = item.PointerToRawData
StartVA = ImageBase + VirtualAddress
StopVA = ImageBase + VirtualAddress + VirtualSize
with open(FilePath,"rb") as fp:
fp.seek(ActualOffset)
HexCode = fp.read(VirtualSize)
md = Cs(CS_ARCH_X86, CS_MODE_32)
for item in md.disasm(HexCode, 0):
addr = hex(int(StartVA) + item.address)
dic = {"Addr": str(addr) , "OpCode": item.mnemonic + " " + item.op_str}
print("[+] 反汇编地址: {} 参数: {}".format(addr,dic))
opcode_list.append(dic)
return opcode_list
if __name__ == "__main__":
ref = FOA_Disassembly("d://Win32Project.exe")
print(ref)
标签:fp,__,addr,python,dic,item,反汇编,capstone 来源: https://www.cnblogs.com/LyShark/p/16099380.html