逆向自动化工具

sky123

keystone

capstone

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
from capstone import *
from capstone.x86 import *
from capstone.arm import *
from capstone.arm64 import *
from capstone.mips import *
from capstone.ppc import *


# 定义各架构的操作数处理函数(示例为 x86、ARM、ARM64、MIPS、PPC)
def handle_x86_operands(insn: CsInsn):
for i, op in enumerate(insn.operands):
print(f"Operand {i}:")
if op.type == X86_OP_REG:
op_type = "X86_OP_REG"
value = insn.reg_name(op.reg)
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == X86_OP_IMM:
op_type = "X86_OP_IMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == X86_OP_MEM:
mem = op.mem
print(f" Type: X86_OP_MEM")
print(f" Value:")
indent = " "
if mem.segment != 0:
print(f"{indent}Segment: {insn.reg_name(mem.segment)}")
if mem.base != 0:
print(f"{indent}Base: {insn.reg_name(mem.base)}")
if mem.index != 0:
print(f"{indent}Index: {insn.reg_name(mem.index)}")
print(f"{indent}Scale: {mem.scale}")
if mem.disp != 0:
print(f"{indent}Disp: {mem.disp:#x}")
if mem.segment == 0 and mem.base == 0 and mem.index == 0 and mem.disp == 0:
print(f"{indent}None")
else:
op_type = "Unknown"
value = "N/A"
print(f" Type: {op_type}")
print(f" Value: {value}")


def handle_arm64_operands(insn: CsInsn):
for i, op in enumerate(insn.operands):
print(f"Operand {i}:")
if op.type == ARM64_OP_REG:
op_type = "ARM64_OP_REG"
value = insn.reg_name(op.reg)
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == ARM64_OP_IMM:
op_type = "ARM64_OP_IMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == ARM64_OP_MEM:
mem = op.mem
print(f" Type: ARM64_OP_MEM")
print(f" Value:")
indent = " "
if mem.base != 0:
print(f"{indent}Base: {insn.reg_name(mem.base)}")
if mem.index != 0:
print(f"{indent}Index: {insn.reg_name(mem.index)}")
print(f"{indent}Scale: {mem.scale}")
if mem.disp != 0:
print(f"{indent}Disp: {mem.disp:#x}")
if mem.base == 0 and mem.index == 0 and mem.disp == 0:
print(f"{indent}None")
else:
op_type = "Unknown"
value = "N/A"
print(f" Type: {op_type}")
print(f" Value: {value}")


def handle_arm_operands(insn: CsInsn):
for i, op in enumerate(insn.operands):
print(f"Operand {i}:")
if op.type == ARM_OP_REG:
op_type = "ARM_OP_REG"
value = insn.reg_name(op.reg)
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == ARM_OP_IMM:
op_type = "ARM_OP_IMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == ARM_OP_MEM:
mem = op.mem
print(f" Type: ARM_OP_MEM")
print(f" Value:")
indent = " "
if mem.base != 0:
print(f"{indent}Base: {insn.reg_name(mem.base)}")
if mem.index != 0:
print(f"{indent}Index: {insn.reg_name(mem.index)}")
print(f"{indent}Scale: {mem.scale}")
if mem.disp != 0:
print(f"{indent}Disp: {mem.disp:#x}")
if mem.base == 0 and mem.index == 0 and mem.disp == 0:
print(f"{indent}None")
elif op.type == ARM_OP_PIMM:
op_type = "ARM_OP_PIMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
else:
op_type = "Unknown"
value = "N/A"
print(f" Type: {op_type}")
print(f" Value: {value}")


def handle_mips_operands(insn: CsInsn):
for i, op in enumerate(insn.operands):
print(f"Operand {i}:")
if op.type == MIPS_OP_REG:
op_type = "MIPS_OP_REG"
value = insn.reg_name(op.reg)
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == MIPS_OP_IMM:
op_type = "MIPS_OP_IMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == MIPS_OP_MEM:
mem = op.mem
print(f" Type: MIPS_OP_MEM")
print(f" Value:")
indent = " "
if mem.base != 0:
print(f"{indent}Base: {insn.reg_name(mem.base)}")
if mem.disp != 0:
print(f"{indent}Disp: {mem.disp:#x}")
if mem.base == 0 and mem.disp == 0:
print(f"{indent}None")
else:
op_type = "Unknown"
value = "N/A"
print(f" Type: {op_type}")
print(f" Value: {value}")


def handle_ppc_operands(insn: CsInsn):
for i, op in enumerate(insn.operands):
print(f"Operand {i}:")
if op.type == PPC_OP_REG:
op_type = "PPC_OP_REG"
value = insn.reg_name(op.reg)
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == PPC_OP_IMM:
op_type = "PPC_OP_IMM"
value = f"0x{op.imm:x}"
print(f" Type: {op_type}")
print(f" Value: {value}")
elif op.type == PPC_OP_MEM:
mem = op.mem
print(f" Type: PPC_OP_MEM")
print(f" Value:")
indent = " "
if mem.base != 0:
print(f"{indent}Base: {insn.reg_name(mem.base)}")
if mem.disp != 0:
print(f"{indent}Disp: {mem.disp:#x}")
if mem.base == 0 and mem.disp == 0:
print(f"{indent}None")
else:
op_type = "Unknown"
value = "N/A"
print(f" Type: {op_type}")
print(f" Value: {value}")


# 定义架构到操作数处理函数的映射
ARCH_OPERAND_HANDLERS = {
CS_ARCH_X86: handle_x86_operands,
CS_ARCH_ARM64: handle_arm64_operands,
CS_ARCH_ARM: handle_arm_operands,
CS_ARCH_MIPS: handle_mips_operands,
CS_ARCH_PPC: handle_ppc_operands,
# 添加更多架构的处理函数
}


def print_insn_detail(insn: CsInsn):
try:
# 打印指令的基本信息
print("========== Instruction Detail ==========")
print(f"{insn.address:#x} [{' '.join([f'{b:02X}' for b in insn.bytes])}]: {insn.mnemonic} {insn.op_str}")

# 打印寄存器读写情况
regs_read = insn.regs_read
regs_write = insn.regs_write

if regs_read:
regs_read_names = ', '.join(insn.reg_name(reg) for reg in regs_read)
print(f"Registers read: {regs_read_names}")

if regs_write:
regs_write_names = ', '.join(insn.reg_name(reg) for reg in regs_write)
print(f"Registers written: {regs_write_names}\n")

# 打印操作数详细信息
# 获取并调用对应架构的操作数处理函数
arch = insn._cs.arch
handler = ARCH_OPERAND_HANDLERS.get(arch)
if handler:
handler(insn)
else:
print(f"Unsupported architecture: {arch}\n")

print("=========================================\n")
except Exception as e:
print(f"Error processing instruction at 0x{insn.address:x}: {e}\n")

IdaPython

angr

Unicorn

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import time

from unicorn import *
from unicorn.x86_const import *
from capstone import *

CODE_ADDRESS = 0x74B000 # 0x6F8618 # Shellcode 的加载地址
STACK_ADDRESS = 0x0019C000 # 栈的起始地址(分配在高地址区域)
STACK_SIZE = 0x00080000 # 栈大小
ORIG_SP = STACK_ADDRESS + STACK_SIZE // 2
JUMP_BLOCK_RANGE = range(CODE_ADDRESS + 0x3fd0, CODE_ADDRESS + 0x137f0)

shellcode = open("shellcode.bin", "rb").read()

# 初始化 Unicorn 模拟器
mu = Uc(UC_ARCH_X86, UC_MODE_32)

# 映射内存
mu.mem_map(CODE_ADDRESS & ~0xFFF, ((len(shellcode) + 0xFFF) & ~0xFFF) + 0x1000) # 为代码分配内存

mu.mem_map(STACK_ADDRESS, STACK_SIZE) # 为栈分配内存

# 写入 Shellcode
mu.mem_write(CODE_ADDRESS, shellcode)

# 初始化栈指针(ESP 指向栈顶)
mu.reg_write(UC_X86_REG_ESP, STACK_ADDRESS + 0x0019F998 - 0x0019C000)

# 初始化 Capstone 用于反汇编
cs = Cs(CS_ARCH_X86, CS_MODE_32)



f = open("trace.txt", "w+")


class TraceInfo:
def __init__(self, uc: unicorn.Uc, address, size):
code = uc.mem_read(address, size)
self.addr = address
self.insn = next(cs.disasm(code, address))
self.regs = self.get_registers(uc)
self.regs_change = ""
self.mem_change = ""

def get_registers(self, uc: unicorn.Uc):
return {
'eax': uc.reg_read(UC_X86_REG_EAX),
'ebx': uc.reg_read(UC_X86_REG_EBX),
'ecx': uc.reg_read(UC_X86_REG_ECX),
'edx': uc.reg_read(UC_X86_REG_EDX),
'esi': uc.reg_read(UC_X86_REG_ESI),
'edi': uc.reg_read(UC_X86_REG_EDI),
'esp': uc.reg_read(UC_X86_REG_ESP),
'ebp': uc.reg_read(UC_X86_REG_EBP),
# 'eip': uc.reg_read(UC_X86_REG_EIP),
'eflags': uc.reg_read(UC_X86_REG_EFLAGS),

# 段寄存器(如需要可以添加调试信息)
# 'cs': uc.reg_read(UC_X86_REG_CS),
# 'ds': uc.reg_read(UC_X86_REG_DS),
# 'es': uc.reg_read(UC_X86_REG_ES),
# 'fs': uc.reg_read(UC_X86_REG_FS),
# 'gs': uc.reg_read(UC_X86_REG_GS),
# 'ss': uc.reg_read(UC_X86_REG_SS),
}

def set_regs_change(self, uc: unicorn.Uc):
new_regs = self.get_registers(uc)
diffs = []
for reg, old_val in self.regs.items():
new_val = new_regs[reg]
if old_val != new_val:
diffs.append(f"{reg}: {hex(old_val)}-> {hex(new_val)}")
self.regs_change = " ".join(diffs)

def set_mem_change(self, uc: unicorn.Uc, address, size, value):
old_value = int.from_bytes(uc.mem_read(address, size), byteorder="little")
self.mem_change = f"{hex(address)}: {hex(old_value)}-> {hex(value)}"

def get_state_trace_info(self):
addr_str = f"{hex(self.addr)}".ljust(10)
insn_str = f"{self.insn.mnemonic} {self.insn.op_str}".ljust(40)
regs_str = self.regs_change.ljust(60)
mem_str = self.mem_change.ljust(60)
return f"{addr_str} | {insn_str} | {regs_str} | {mem_str}"


trace_info: TraceInfo = None


# Hook:捕获内存写入
def hook_mem_write(uc, access, address, size, value, user_data):
trace_info.set_mem_change(uc, address, size, value)

# 初始化计数器和时间
trace_count = 0
start_time = time.time()

# Hook:捕获指令执行后的状态
def hook_code(uc, address, size, user_data):
global trace_info, trace_count, start_time

# 更新指令计数器
trace_count += 1

# 动态显示执行速度
current_time = time.time()
elapsed_time = current_time - start_time
if elapsed_time > 1:
print(
f"\rProcessed: {trace_count} instructions, Speed: {trace_count / elapsed_time:.2f} instructions/sec",
end="",
)

if trace_info is not None:
trace_info.set_regs_change(uc)
print(trace_info.get_state_trace_info(), file=f)

trace_info = TraceInfo(uc, address, size)


# 添加 Hook
mu.hook_add(UC_HOOK_MEM_WRITE, hook_mem_write) # 捕获内存写入
mu.hook_add(UC_HOOK_CODE, hook_code) # 捕获指令执行后的状态

# 开始模拟执行
try:
print("Starting execution...")
mu.emu_start(CODE_ADDRESS, CODE_ADDRESS + len(shellcode))
print("Execution finished.")
except UcError as e:
print(f"Unicorn execution failed: {e}")
print(hex(mu.reg_read(UC_X86_REG_ESP)))
print(hex(mu.reg_read(UC_X86_REG_EIP)))
esp = mu.reg_read(UC_X86_REG_ESP)
for i in range(esp, esp + 0x50, 4):
print(hex(int.from_bytes(mu.mem_read(i, 4), byteorder="little")))
  • Title: 逆向自动化工具
  • Author: sky123
  • Created at : 2025-01-02 01:21:55
  • Updated at : 2025-01-03 03:09:04
  • Link: https://skyi23.github.io/2025/01/02/逆向自动化工具/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
逆向自动化工具