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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
| from capstone import * from capstone.arm import * from unicorn import * from unicorn.arm_const import * from keystone import *
from elftools.elf.elffile import ELFFile
def get_section(filename, sectionName): file = open(filename, 'rb')
elf_file = ELFFile(file) for section in elf_file.iter_sections(): if section.name == sectionName: return section
def reg_ctou(reg_name): if reg_name == "sp": return UC_ARM_REG_SP if reg_name == "pc": return UC_ARM_REG_PC
reg_idx = int(reg_name[1:]) if reg_idx >= 0 and reg_idx <= 12: return UC_ARM_REG_R0 + reg_idx
raise Exception("reg_ctou: have new type?")
def is_block_end(dasm): if dasm.mnemonic == "mov" and dasm.op_str == "pc, r0": return True if dasm.mnemonic == "b": return True return False
def hook_mem_access(uc, type, address,size,value,userdata): pc = uc.reg_read(UC_ARM_REG_PC) print('pc:%x type:%d addr:%x size:%x' % (pc, type, address, size)) return True def is_preproc(addr): preprocessor_addrs = [27514, 3200, 5784, 10490, 15456, 17002, 19836, 20578, 22440]
return addr in preprocessor_addrs
def get_context(): global mu
return mu.context_save()
def set_context(context): global mu if context == None: return mu.context_restore(context)
def print_regs(): global mu msg = "" for i in range(8): msg += f"r{i}:{hex(mu.reg_read(UC_ARM_REG_R0 + i))}\t" msg += f"sp:{hex(mu.reg_read(UC_ARM_REG_SP))}\tpc:{hex(mu.reg_read(UC_ARM_REG_PC))}" print(msg)
def get_ins_size(addr): for ins in md.disasm(sodata[addr:addr+4], addr): return ins.size
def get_dasm(addr, size): global md global sodata
for dasm in md.disasm(sodata[addr:addr+size], addr): return dasm
def hook_code(uc, address, size, user_data): global is_success global mu global branch_control global g_start_addr global list_trace global dst_addr global end global md
if is_success or address > end: mu.emu_stop() return
ban_ins = ["bl", "blx"] if address in [0x5ED6]: print("debug addr: ", hex(address))
for ins in md.disasm(sodata[address:address+size], address): print(">>> Tracing instruction at 0x%x, instruction size = 0x%x" % (address, size)) print(">>> 0x%x:\t%s\t%s\t%d" % (ins.address, ins.mnemonic, ins.op_str, ins.size)) print_regs()
if address in real_blocks: if address in list_trace: print("have fake block?") uc.emu_stop() else: list_trace[address] = 1
if address != g_start_addr: is_success = True dst_addr = address print(f"find: {hex(address)}") uc.emu_stop() return
if address in ret_blocks: print(f"end_block: {hex(address)} ") mu.emu_stop() return
flag_pass = False
for b in ban_ins: if ins.mnemonic.find(b) != -1: flag_pass = True break if ins.op_str.find("[") != -1:
if ins.op_str.find("[r7") != -1 and ins.op_str.find("0xf4") != -1: print()
if ins.op_str.find("[sp") != -1: flag_pass = True for op in ins.operands: if op.type == ARM_OP_MEM: reg_name = ins.reg_name(op.value.base) addr = mu.reg_read(reg_ctou(reg_name))
if addr >= 0x80000000 and addr < 0x80000000 + 0x10000 * 8: flag_pass = False if flag_pass: print(f"[pass] addr: {hex(ins.address)} size: {ins.size}") uc.reg_write(UC_ARM_REG_PC, (ins.address + ins.size) | 1) return if branch_control == None: return next_dasm = get_dasm(ins.address + ins.size, 4) if next_dasm.mnemonic == "itt" and next_dasm.op_str == "ne": if ins.mnemonic == "cmp": ops = ins.op_str.split(", ") reg = reg_ctou(ops[0]) if ops[1].startswith("#"): cmp_num = int(ops[1][1:], 16) else: assert ops[1].startsWith("r") cmp_num = mu.reg_read(ops[1])
if branch_control == 0: mu.reg_write(reg, cmp_num) else: mu.reg_write(reg, cmp_num + 1)
elif ins.mnemonic == "tst": regs = [reg_ctou(x) for x in ins.op_str.split(", ")] if branch_control == 0: mu.reg_write(regs[0], 0) mu.reg_write(regs[1], 0) else: mu.reg_write(regs[0], 1) mu.reg_write(regs[1], 1)
elif next_dasm.mnemonic == "itt" and next_dasm.op_str == "lt" or \ next_dasm.mnemonic == "itt" and next_dasm.op_str == "mi" or \ next_dasm.mnemonic == "itt" and next_dasm.op_str == "lo": if ins.mnemonic == "cmp": ops = ins.op_str.split(", ") reg = reg_ctou(ops[0]) if ops[1].startswith("#"): cmp_num = int(ops[1][1:], 16) else: assert ops[1].startswith("r") cmp_num = mu.reg_read(reg_ctou(ops[1]))
if branch_control == 0: mu.reg_write(reg, cmp_num + 1) else: mu.reg_write(reg, cmp_num - 1) elif next_dasm.mnemonic == "itt" and next_dasm.op_str == "gt": if ins.mnemonic == "cmp": ops = ins.op_str.split(", ") reg = reg_ctou(ops[0]) if ops[1].startswith("#"): cmp_num = int(ops[1][1:], 16) else: assert ops[1].startswith("r") cmp_num = mu.reg_read(reg_ctou(ops[1]))
if branch_control == 0: mu.reg_write(reg, cmp_num - 1) else: mu.reg_write(reg, cmp_num + 1) elif next_dasm.mnemonic == "itt" and next_dasm.op_str == "eq": if ins.mnemonic == "cmp": ops = ins.op_str.split(", ") reg = reg_ctou(ops[0]) if ops[1].startswith("#"): cmp_num = int(ops[1][1:], 16) else: assert ops[1].startswith("r") cmp_num = mu.reg_read(reg_ctou(ops[1]))
if branch_control == 0: mu.reg_write(reg, cmp_num - 1) else: mu.reg_write(reg, cmp_num) elif next_dasm.mnemonic == "itt": raise Exception("ollvm branch new type") def find_path(start_addr, branch = None): global real_blocks global mu global g_start_addr global branch_control global list_trace global dst_addr global is_success
branch_control = branch g_start_addr = start_addr list_trace = {} dst_addr = 0 is_success = False
try: mu.emu_start(start_addr | 1, start_addr + 0x10000) print("============= emu end =============") except UcError as e: pc = mu.reg_read(UC_ARM_REG_PC) if pc != 0: _size = get_ins_size(pc) return find_path(pc + _size, branch) else: print("ERROR: %s pc:%x" % (e,pc))
if is_success: return dst_addr
return None
def patch_nop(addr, size): global sodata nop_bytes = bytearray(b'\x00\xbf') for i in range(size): sodata[addr + i] = nop_bytes[i % 2]
def patch_bytes(addr, bytes: bytearray): for i in range(len(bytes)): sodata[addr + i] = bytes[i]
def ks_asm(arch, mode, code, addr = 0): ks = Ks(arch, mode)
encoding, count = ks.asm(code, addr) return bytearray(encoding)
def patch_branch(addr, b0, b1): dasm = get_dasm(addr, 4) assert dasm.mnemonic == "itt"
print(f"{hex(addr)}:\t{dasm.mnemonic}\t{dasm.op_str}") patch_nop(addr, 28 + 2)
b1_addr = b1 - addr - 4 b0_addr = b0
branch_true_bytes = ks_asm(KS_ARCH_ARM, KS_MODE_THUMB, f"b{dasm.op_str} #{hex(b1_addr)}", addr) branch_false_bytes = ks_asm(KS_ARCH_ARM, KS_MODE_THUMB, f"b {hex(b0_addr)}", addr + len(branch_true_bytes))
patch_bytes(addr, branch_true_bytes) patch_bytes(addr + len(branch_true_bytes), branch_false_bytes)
def get_branch_pa(addr): global md global sodata
for dasm in md.disasm(sodata[addr:end], addr): if dasm.mnemonic == "itt": return dasm.address
raise Exception("cant find itt????")
def start_patch(flow, start_addr): global block_list global sodata
sodata = bytearray(sodata)
visited = {} queue = [start_addr] while len(queue) != 0: current_addr = queue.pop() if current_addr in visited or current_addr == None: continue
visited[current_addr] = 1
next_blocks = flow[current_addr]
rb_end_addr = block_list[current_addr]["end_addr"] rb_start_addr = block_list[current_addr]["start_addr"]
if len(next_blocks) == 1: queue.append(next_blocks[0]) patch_addr = rb_end_addr - 10
next_start_addr = queue[-1] patch_nop(patch_addr, 10)
if next_start_addr != None: asm_bytes = ks_asm(KS_ARCH_ARM, KS_MODE_THUMB, f"mov r0, #{hex(next_start_addr)}") patch_bytes(patch_addr, asm_bytes) print(f"{hex(patch_addr)} ---> {hex(next_start_addr)}") else:
ret_block_addr = ret_blocks[0] asm_bytes = ks_asm(KS_ARCH_ARM, KS_MODE_THUMB, f"mov r0, #{hex(ret_block_addr)}") patch_bytes(patch_addr, asm_bytes) print(f"{hex(patch_addr)} ---> ret block: {hex(ret_block_addr)}") else: queue.append(next_blocks[0]) queue.append(next_blocks[1]) b0 = next_blocks[0] b1 = next_blocks[1]
patch_addr = get_branch_pa(rb_start_addr) patch_branch(patch_addr, b0, b1) print(f"{hex(patch_addr)} --->\n\t1. {hex(b0)}\n\t2. {hex(b1)}")
def load_file(filename): global sodata with open(filename, mode = "rb") as f: sodata = f.read()
def save_file(filename): with open(filename, mode="wb") as f: f.write(sodata)
def collect_blocks(offset, end, ret_addr): global block_list global real_blocks global ret_blocks global md
block_list = {} real_blocks = [] ret_blocks = []
md = Cs(CS_ARCH_ARM, CS_MODE_THUMB) md.detail = True
preproc_flag = False
ins_str = "" is_new = True for dasm in md.disasm(sodata[offset:end], offset):
if dasm.address >= 0x612E and dasm.address < 0x617C: continue
ins_str += f"{hex(dasm.address)}:\t{dasm.mnemonic}\t{dasm.op_str}\n"
if is_new: is_new = False block_item = {} block_item["start_addr"] = dasm.address block_item["capstone"] = dasm
if is_preproc(dasm.address): preproc_flag = True
if is_block_end(dasm): is_new = True block_item["end_addr"] = dasm.address block_item["ins_str"] = ins_str ins_str = "" block_list[block_item["start_addr"]] = block_item
if dasm.mnemonic == "mov" and dasm.op_str == "pc, r0": if preproc_flag: preproc_flag = False else: real_blocks.append(block_item["start_addr"])
ret_blocks.append(ret_addr)
def init_unicorn(filename): global mu global sodata
if isinstance(sodata, bytearray): sodata = bytes(sodata)
mu = Uc(UC_ARCH_ARM, UC_MODE_THUMB) mu.mem_map(0x80000000, 0x1000 * 8) mu.mem_map(0, 4 * 1024 * 1024) mu.mem_write(0, sodata) mu.reg_write(UC_ARM_REG_SP, 0x80000000 + 0x1000 * 4) mu.hook_add(UC_HOOK_CODE, hook_code) mu.hook_add(UC_HOOK_MEM_UNMAPPED, hook_mem_access)
data_section = get_section(filename, '.data') DATA_MEM_OFFSET = data_section.header["sh_addr"] DATA_FILE_OFFSET = data_section.header["sh_offset"] DATA_SIZE = data_section.header["sh_size"] mu.mem_write(DATA_MEM_OFFSET, sodata[DATA_FILE_OFFSET:DATA_FILE_OFFSET+DATA_SIZE])
def start_emu(offset): global is_success global flow
if offset in real_blocks: real_blocks.remove(offset)
queue = [(offset, None)]
flow = {}
is_success = False while len(queue) != 0: env = queue.pop() pc = env[0] set_context(env[1]) item = block_list[pc]
if pc in flow: continue flow[pc] = []
if item["ins_str"].find("itt") != -1: ctx = get_context()
p1 = find_path(pc, 0) if p1 != None: queue.append((p1, get_context())) flow[pc].append(p1) set_context(ctx) p2 = find_path(pc, 1)
if p1 != p2: queue.append((p2, get_context())) flow[pc].append(p2) else: p = find_path(pc) if p != None: queue.append((p, get_context()))
flow[pc].append(p)
def run(offset, end_addr, ret_addr): global end global flow
end = end_addr
collect_blocks(offset = offset, end = end, ret_addr = ret_addr)
init_unicorn("libBlackMamBa.so")
start_emu(offset)
start_patch(flow, offset)
if __name__ == "__main__":
offset_list = [0x584c, 0xC90, 0x1700, 0x2968, 0x50A4, 0x42DC] end_list = [0x6b90, 0x16AE, 0x2910, 0x3C76, 0x57BE, 0x4D92] ret_list = [0x6B58, 0x1666, 0x28E0, 0x3C3C, 0x578E, 0x4D54] load_file("libBlackMamBa.so")
for i in range(len(offset_list)): run(offset_list[i], end_list[i], ret_list[i])
save_file("patch3.so")
|