如何使用Python进行汇编、反汇编和仿真?

2021年11月16日18:06:05 发表评论 2,187 次浏览

本文带你了解如何使用 Keystone 引擎、Capstone 引擎和 Unicorn 引擎在 Python 中汇编、反汇编和模拟机器代码(ARM、x86-64 等)。

Python汇编、反汇编和仿真:处理器执行汇编代码,这是一种在本机可执行文件中直接使用寄存器和内存的低级编程语言。汇编代码以其汇编形式存储,作为二进制数据,有处理器手册指定如何将每条指令编码为数据字节。

Python如何反汇编反汇编汇编的逆过程,数据字节被解析并翻译成汇编指令(对用户来说更具可读性)。

不同的处理器架构可以有不同的指令集,一个处理器只能在自己的指令集中执行汇编指令,为了运行针对不同架构的代码,我们需要使用一个模拟器,它是一个为不支持的程序翻译代码的程序将架构转换为可以在主机系统上运行的代码。

Python如何汇编代码?在许多场景中,为不同架构汇编、反汇编或模拟代码是有用的,主要兴趣之一是学习(大多数大学教授 MIPS 汇编)以运行和测试为路由器等不同设备编写的程序(模糊测试等) ,以及逆向工程。

在本教程中,我们将使用Keystone 引擎Capstone 引擎Unicorn 引擎对为 ARM 编写的汇编代码进行汇编、反汇编和仿真,这些框架提供方便的 Python 绑定来操作汇编代码,它们支持不同的体系结构(x86ARMMIPSSPARC等),并且它们对主要操作系统(包括 Linux、Windows 和 MacOS)具有本机支持。

首先,让我们安装这三个框架:

pip3 install keystone-engine capstone unicorn

对于本教程的演示,我们将采用在 ARM 汇编中实现的阶乘函数、汇编代码并对其进行仿真。

我们还将反汇编一个 x86 函数(以展示如何轻松处理多个架构)。

汇编ARM

Python如何汇编代码?我们首先导入我们需要的 ARM 程序集:

# We need to emulate ARM
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_ARM, UcError
# for accessing the R0 and R1 registers
from unicorn.arm_const import UC_ARM_REG_R0, UC_ARM_REG_R1
# We need to assemble ARM code
from keystone import Ks, KS_ARCH_ARM, KS_MODE_ARM, KsError

Python汇编、反汇编和仿真 - 让我们编写我们的 ARM 汇编代码,它计算 factorial( r0),其中r0是一个输入寄存器:

ARM_CODE = """
// n is r0, we will pass it from python, ans is r1
mov r1, 1       	// ans = 1
loop:
cmp r0, 0       	// while n >= 0:
mulgt r1, r1, r0	//   ans *= n
subgt r0, r0, 1 	//   n = n - 1
bgt loop        	// 
                	// answer is in r1
"""

让我们汇编上面的汇编代码(将其转换为字节码):

print("Assembling the ARM code")
try:
    # initialize the keystone object with the ARM architecture
    ks = Ks(KS_ARCH_ARM, KS_MODE_ARM)
    # Assemble the ARM code
    ARM_BYTECODE, _ = ks.asm(ARM_CODE)
	# convert the array of integers into bytes
    ARM_BYTECODE = bytes(ARM_BYTECODE)
    print(f"Code successfully assembled (length = {len(ARM_BYTECODE)})")
    print("ARM bytecode:", ARM_BYTECODE)
except KsError as e:
    print("Keystone Error: %s" % e)
    exit(1)

该函数Ks返回一个 ARM 模式的汇编器,该asm()方法汇编代码,并返回字节以及它汇编的指令数。

字节码现在可以写入内存区域,并由 ARM 处理器执行(或模拟,在我们的例子中):

# memory address where emulation starts
ADDRESS = 0x1000000

print("Emulating the ARM code")
try:
    # Initialize emulator in ARM mode
    mu = Uc(UC_ARCH_ARM, UC_MODE_ARM)
    # map 2MB memory for this emulation
    mu.mem_map(ADDRESS, 2 * 1024 * 1024)
    # write machine code to be emulated to memory
    mu.mem_write(ADDRESS, ARM_BYTECODE)
    # Set the r0 register in the code, let's calculate factorial(5)
    mu.reg_write(UC_ARM_REG_R0, 5)
    # emulate code in infinite time and unlimited instructions
    mu.emu_start(ADDRESS, ADDRESS + len(ARM_BYTECODE))
    # now print out the R0 register
    print("Emulation done. Below is the result")
    # retrieve the result from the R1 register
    r1 = mu.reg_read(UC_ARM_REG_R1)
    print(">>  R1 = %u" % r1)
except UcError as e:
    print("Unicorn Error: %s" % e)

在上面的代码中,我们在ARM模式下初始化模拟器,我们在指定地址(2*1024*1024字节)映射2MB内存,我们将我们的汇编结果写入映射的内存区域,我们将r0寄存器设置为5,然后我们开始模拟我们的代码。

emu_start()方法采用一个可选timeout参数和一个可选的最大指令数来模拟,这对于沙箱代码或将模拟限制为代码的某个部分非常有用。

仿真完成后,我们读取r1寄存器的内容,其中应该包含仿真结果,运行代码输出以下结果:

Assembling the ARM code
Code successfully assembled (length = 20)
ARM bytecode: b'\x01\x10\xa0\xe3\x00\x00P\xe3\x91\x00\x01\xc0\x01\x00@\xc2\xfb\xff\xff\xca'
Emulating the ARM code
Emulation done. Below is the result
>>  R1 = 120

我们得到了预期的结果,5的阶乘是120。

反汇编 x86-64 代码

Python汇编、反汇编和仿真 - 现在如果我们有 x86 的机器码并且我们想反汇编它,下面的代码会这样做:

# We need to emulate ARM and x86 code
from unicorn import Uc, UC_ARCH_X86, UC_MODE_64, UcError
# for accessing the RAX and RDI registers
from unicorn.x86_const import UC_X86_REG_RDI, UC_X86_REG_RAX
# We need to disassemble x86_64 code
from capstone import Cs, CS_ARCH_X86, CS_MODE_64, CsError

X86_MACHINE_CODE = b"\x48\x31\xc0\x48\xff\xc0\x48\x85\xff\x0f\x84\x0d\x00\x00\x00\x48\x99\x48\xf7\xe7\x48\xff\xcf\xe9\xea\xff\xff\xff"
# memory address where emulation starts
ADDRESS = 0x1000000
try:
      # Initialize the disassembler in x86 mode
      md = Cs(CS_ARCH_X86, CS_MODE_64)
      # iterate over each instruction and print it
      for instruction in md.disasm(X86_MACHINE_CODE, 0x1000):
            print("0x%x:\t%s\t%s" % (instruction.address, instruction.mnemonic, instruction.op_str))
except CsError as e:
      print("Capstone Error: %s" % e)

Python如何反汇编?我们在 x86-64 模式下初始化一个反汇编器,反汇编提供的机器代码,迭代反汇编结果中的指令,对于每个指令,我们打印指令和它发生的地址。

这会产生以下输出:

0x1000: xor     rax, rax
0x1003: inc     rax
0x1006: test    rdi, rdi
0x1009: je      0x101c
0x100f: cqo
0x1011: mul     rdi
0x1014: dec     rdi
0x1017: jmp     0x1006

现在让我们尝试用 Unicorn 引擎模拟它:

try:
    # Initialize emulator in x86_64 mode
    mu = Uc(UC_ARCH_X86, UC_MODE_64)
    # map 2MB memory for this emulation
    mu.mem_map(ADDRESS, 2 * 1024 * 1024)
    # write machine code to be emulated to memory
    mu.mem_write(ADDRESS, X86_MACHINE_CODE)
    # Set the r0 register in the code to the number of 7
    mu.reg_write(UC_X86_REG_RDI, 7)
    # emulate code in infinite time & unlimited instructions
    mu.emu_start(ADDRESS, ADDRESS + len(X86_MACHINE_CODE))
    # now print out the R0 register
    print("Emulation done. Below is the result")
    rax = mu.reg_read(UC_X86_REG_RAX)
    print(">>> RAX = %u" % rax)
except UcError as e:
    print("Unicorn Error: %s" % e)

输出:

Emulation done. Below is the result
>>> RAX = 5040

我们得到5040的结果,我们输入7。如果我们仔细查看此 x86 汇编代码,我们会注意到此代码计算 rdi 寄存器的阶乘(5040是7的阶乘)。

Python汇编、反汇编和仿真总结

Python如何反汇编?这三个框架以统一的方式操作汇编代码,正如你在模拟 x86-64 汇编的代码中看到的那样,这与 ARM 模拟版本非常相似。对于任何受支持的体系结构,反汇编和汇编代码也以相同的方式完成。

要记住的一件事是 Unicorn 模拟器模拟原始机器代码,它不模拟Windows API调用,也不解析和模拟PEELF等文件格式。

在某些情况下,模拟整个操作系统、内核驱动程序形式的程序或用于不同操作系统的二进制文件是很有用的,在 Unicorn 之上构建了一个很好的框架来处理这些限制,在提供 Python 绑定的同时,这是Qiling 框架,它还允许二进制检测(例如,伪造系统调用返回值、文件描述符等)。

Python如何汇编代码?在测试了这三个 Python 框架后,我们得出结论,使用 Python 操作汇编代码非常容易,Python 的简单性加上 Keystone、Capstone 和 Unicorn 提供的方便统一的 Python 接口使得即使是初学者也可以轻松汇编、拆卸并模拟不同架构的汇编代码。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: