4.7 x64dbg 应用层的钩子扫描( 二 )


执行如上所示代码,则可输出当前程序内存中的反汇编指令集,并以字典的方式输出,效果图如下所示;
这两项功能实现之后,那么实现内存与磁盘之间的比对工作将变得很容易实现,如下代码中首先通过ly获取到内存反汇编指令,然后通过获取磁盘反汇编指令,并将两者[index] != [index]最比较,以此来判断特定内存是否被挂钩;
import binascii,os,sysimport pefilefrom capstone import *from LyScript32 import MyDebug# 得到内存反汇编代码def get_memory_disassembly(address,offset,len):# 反汇编列表dasm_memory_dict = []# 内存列表ref_memory_list = bytearray()# 读取数据for index in range(offset,len):char = dbg.read_memory_byte(address + index)ref_memory_list.append(char)# 执行反汇编md = Cs(CS_ARCH_X86,CS_MODE_32)for item in md.disasm(ref_memory_list,0x1):addr = int(pe_base) + item.addressdic = {"address": str(addr), "opcode": item.mnemonic + " " + item.op_str}dasm_memory_dict.append(dic)return dasm_memory_dict# 反汇编文件中的机器码def get_file_disassembly(path):opcode_list = []pe = pefile.PE(path)ImageBase = pe.OPTIONAL_HEADER.ImageBasefor 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.VirtualAddressVirtualSize = item.Misc_VirtualSizeActualOffset = item.PointerToRawDataStartVA = ImageBase + VirtualAddressStopVA = ImageBase + VirtualAddress + VirtualSizewith open(path,"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 = {"address": str(addr) , "opcode": item.mnemonic + " " + item.op_str}# print("{}".format(dic))opcode_list.append(dic)return opcode_listif __name__ == "__main__":dbg = MyDebug()dbg.connect()pe_base = dbg.get_local_base()pe_size = dbg.get_local_size()print("模块基地址: {}".format(hex(pe_base)))print("模块大小: {}".format(hex(pe_size)))# 得到内存反汇编代码dasm_memory_list = get_memory_disassembly(pe_base,0,pe_size)dasm_file_list = get_file_disassembly("d://lyshark.exe")# 循环对比内存与文件中的机器码for index in range(0,len(dasm_file_list)):if dasm_memory_list[index] != dasm_file_list[index]:print("地址: {:8} --> 内存反汇编: {:32} --> 磁盘反汇编: {:32}".format(dasm_memory_list[index].get("address"),dasm_memory_list[index].get("opcode"),dasm_file_list[index].get("opcode")))dbg.close()
运行上方代码片段,耐性等待一段时间,则可输出内存与磁盘反汇编指令集列表,输出效果图如下所示;