Python利用capstone实现反汇编

2022-07-15,,,

capstone是kali linux自带的一款轻量级反汇编引擎。它可以支持多种硬件构架,如arm、arm64、mips、x86。该框架使用c语言实现,但支持c++、python、ruby、ocaml、c#、java和go语言,具有很好的扩展性。因此,该框架被256种工具所集成,如cuckoo、binwalk、intellij idea。渗透测试人员一额可以通过python、ruby语言编写脚本,引入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)

到此这篇关于python利用capstone实现反汇编的文章就介绍到这了,更多相关python capstone反汇编内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Python利用capstone实现反汇编.doc》

下载本文的Word格式文档,以方便收藏与打印。