-
-
Save apkunpacker/ad2d129894c8cf6697cf48ead0ef3494 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Recover Hikari AArch64 indirect control flow with PREOPT microcode. | |
| Patch one-way BRs to B, model two-way BRs as synthetic switches, expand function ranges until the CFG reaches a fixed point, then restore conditional branches through the F5 hook. | |
| Requires IDA Pro 9.4+, Hex-Rays, and keystone-engine; load the script and choose "deobfuscate it" or call recover_current_function(), with changes saved only to the IDB and reversible through rollback_function(). | |
| Thanks to Hex-Rays for sponsoring the r3kapig team! | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from typing import Dict, List, Optional, Set, Tuple, Union | |
| from keystone import Ks, KsError, KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN | |
| import ida_auto | |
| import ida_bytes | |
| import ida_funcs | |
| import ida_hexrays | |
| import ida_ida | |
| import ida_idaapi | |
| import ida_idp | |
| import ida_kernwin | |
| import ida_name | |
| import ida_nalt | |
| import ida_range | |
| import ida_segment | |
| import ida_typeinf | |
| import ida_ua | |
| import ida_xref | |
| import idautils | |
| PREFIX = "[hikari-ir-cfg]" | |
| TOOL_ATTRIBUTE = "_hikari_ir_cfg_preopt_tool_instance" | |
| DEOBFUSCATE_ACTION = "hikari-ir-cfg:deobfuscate" | |
| MAX_SUCCESSORS = 2 | |
| POINTER_SIZE = 8 if ida_ida.inf_is_64bit() else 4 | |
| SWITCH_SEGMENT_NAME = ".hikari_preopt_switch" | |
| SWITCH_SEGMENT_SIZE = 0x10000 | |
| SWITCH_RECORD_SIZE = 0x40 | |
| SWITCH_JUMPS_OFFSET = 0x20 | |
| ARM64_ASSEMBLER = Ks(KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN) | |
| BRANCH_RANGE = 128 * 1024 * 1024 | |
| def log(message: str) -> None: | |
| """Write to the IDA output window.""" | |
| ida_kernwin.msg(f"{PREFIX} {message}\n") | |
| def function_info(ea: int): | |
| """Read function metadata without a legacy func_t pointer.""" | |
| info = ida_funcs.func_entry_info_t() | |
| return info if ida_funcs.get_func_entry_info(info, ea) else None | |
| def segment_info(ea: int): | |
| """Read segment metadata without a legacy segment_t pointer.""" | |
| info = ida_segment.segment_info_t() | |
| return info if ida_segment.get_segment_info(info, ea) else None | |
| @dataclass(frozen=True) | |
| class IRSite: | |
| branch_ea: int | |
| targets: Tuple[int, ...] | |
| @dataclass(frozen=True) | |
| class StackAddress: | |
| offset: int | |
| Atom = Union[int, StackAddress] | |
| Values = Tuple[Atom, ...] | |
| Location = Tuple[str, int] | |
| State = Dict[Location, Values] | |
| @dataclass(frozen=True) | |
| class DeletedFunction: | |
| start: int | |
| end: int | |
| flags: int | |
| color: int | |
| @dataclass | |
| class RecoveryPlan: | |
| entry_ea: int | |
| original_ranges: Tuple[Tuple[int, int], ...] | |
| original_flags: int | |
| original_color: int | |
| sites: Dict[int, IRSite] = field(default_factory=dict) | |
| switch_tables: Dict[int, Tuple[int, int, int]] = field(default_factory=dict) | |
| user_xrefs: Set[Tuple[int, int]] = field(default_factory=set) | |
| patched_branches: Dict[int, int] = field(default_factory=dict) | |
| deleted_functions: List[DeletedFunction] = field(default_factory=list) | |
| iterations: int = 0 | |
| complete: bool = False | |
| @property | |
| def one_way(self) -> int: | |
| """Count jumps with one successor.""" | |
| return sum(len(site.targets) == 1 for site in self.sites.values()) | |
| @property | |
| def two_way(self) -> int: | |
| """Count jumps with two successors.""" | |
| return sum(len(site.targets) == 2 for site in self.sites.values()) | |
| def generate_preopt(entry_ea: int): | |
| """Generate PREOPT microcode for a function.""" | |
| if entry_ea == ida_idaapi.BADADDR or ida_funcs.get_func_start(entry_ea) != entry_ea: | |
| return None | |
| failure = ida_hexrays.hexrays_failure_t() | |
| ranges = ida_hexrays.decomp_ranges_t(entry_ea) | |
| flags = ida_hexrays.DECOMP_NO_CACHE | ida_hexrays.DECOMP_ALL_BLKS | |
| microcode = ida_hexrays.gen_microcode(ranges, failure, None, flags, ida_hexrays.MMAT_PREOPTIMIZED) | |
| if microcode is None or not ensure_microcode_graph(microcode): | |
| return None | |
| return microcode | |
| def ensure_microcode_graph(mba) -> bool: | |
| """Build the CFG if the PREOPT callback runs before graph construction.""" | |
| if int(mba.get_mblock(0).type) != ida_hexrays.BLT_NONE: | |
| return True | |
| return mba.build_graph() == ida_hexrays.MERR_OK | |
| def number(operand) -> Optional[int]: | |
| """Read a microcode immediate.""" | |
| if operand.t == ida_hexrays.mop_n: | |
| return int(operand.nnn.value) | |
| return None | |
| def atom_key(value: Atom): | |
| """Provide a stable order for abstract values.""" | |
| if isinstance(value, StackAddress): | |
| return 1, value.offset | |
| return 0, value | |
| def bounded_values(values, preserve_order: bool = False) -> Optional[Values]: | |
| """Collect at most two distinct values.""" | |
| result = [] | |
| for value in values: | |
| if value not in result: | |
| result.append(value) | |
| if len(result) > MAX_SUCCESSORS: | |
| return None | |
| if not preserve_order: | |
| result.sort(key=atom_key) | |
| return tuple(result) | |
| def location(operand) -> Optional[Location]: | |
| """Map a register or stack variable to a state key.""" | |
| if operand.t == ida_hexrays.mop_r: | |
| return "r", int(operand.r) | |
| if operand.t == ida_hexrays.mop_S: | |
| return "s", int(operand.s.off) | |
| return None | |
| def stack_pointer_mreg() -> int: | |
| """Get the microcode stack pointer register.""" | |
| for name in ("SP", "sp"): | |
| register = ida_idp.str2reg(name) | |
| if register >= 0: | |
| return int(ida_hexrays.reg2mreg(register)) | |
| return -1 | |
| STACK_POINTER_MREG = stack_pointer_mreg() | |
| def read_memory(ea: int, size: int) -> Optional[int]: | |
| """Read an integer using the target byte order.""" | |
| if ea < 0 or size <= 0 or not ida_bytes.is_loaded(ea) or not ida_bytes.is_loaded(ea + size - 1): | |
| return None | |
| raw = ida_bytes.get_bytes(ea, size) | |
| if raw is None or len(raw) != size: | |
| return None | |
| byteorder = "big" if ida_ida.inf_is_be() else "little" | |
| return int.from_bytes(raw, byteorder=byteorder, signed=False) | |
| def unary_values(values: Optional[Values], operation) -> Optional[Values]: | |
| """Apply a unary operation to each abstract value.""" | |
| if values is None: | |
| return None | |
| return bounded_values((operation(value) for value in values), preserve_order=True) | |
| def binary_values(left: Optional[Values], right: Optional[Values], operation) -> Optional[Values]: | |
| """Evaluate the Cartesian product in input order.""" | |
| if left is None or right is None: | |
| return None | |
| result = [] | |
| for lhs in left: | |
| for rhs in right: | |
| value = operation(lhs, rhs) | |
| if value is None: | |
| return None | |
| result.append(value) | |
| return bounded_values(result, preserve_order=True) | |
| def add_atoms(left: Atom, right: Atom) -> Optional[Atom]: | |
| """Add integers or stack offsets.""" | |
| if isinstance(left, int) and isinstance(right, int): | |
| return left + right | |
| if isinstance(left, StackAddress) and isinstance(right, int): | |
| return StackAddress(left.offset + right) | |
| if isinstance(left, int) and isinstance(right, StackAddress): | |
| return StackAddress(left + right.offset) | |
| return None | |
| def subtract_atoms(left: Atom, right: Atom) -> Optional[Atom]: | |
| """Subtract integers or stack offsets.""" | |
| if isinstance(left, int) and isinstance(right, int): | |
| return left - right | |
| if isinstance(left, StackAddress) and isinstance(right, int): | |
| return StackAddress(left.offset - right) | |
| return None | |
| def integer_operation(operation): | |
| """Wrap an integer operation for abstract evaluation.""" | |
| def apply(left: Atom, right: Atom) -> Optional[Atom]: | |
| if not isinstance(left, int) or not isinstance(right, int): | |
| return None | |
| return operation(left, right) | |
| return apply | |
| def extend_values(values: Optional[Values], source_size: int, signed: bool) -> Optional[Values]: | |
| """Sign-extend or zero-extend integers.""" | |
| if values is None or source_size <= 0: | |
| return values | |
| bits = source_size * 8 | |
| mask = (1 << bits) - 1 | |
| def extend(value: Atom) -> Atom: | |
| if not isinstance(value, int): | |
| return value | |
| value &= mask | |
| if signed and value & (1 << (bits - 1)): | |
| value -= 1 << bits | |
| return value | |
| return unary_values(values, extend) | |
| def truncate_values(values: Optional[Values], size: int) -> Optional[Values]: | |
| """Truncate integers to the result width.""" | |
| if values is None or size <= 0: | |
| return values | |
| mask = (1 << (size * 8)) - 1 | |
| return unary_values(values, lambda value: value & mask if isinstance(value, int) else value) | |
| def evaluate_load(addresses: Optional[Values], size: int, state: State) -> Optional[Values]: | |
| """Load from known global or stack addresses.""" | |
| if addresses is None or size <= 0: | |
| return None | |
| result = [] | |
| for address in addresses: | |
| if isinstance(address, StackAddress): | |
| values = state.get(("s", address.offset)) | |
| if values is None: | |
| return None | |
| result.extend(values) | |
| continue | |
| value = read_memory(address, size) | |
| if value is None: | |
| return None | |
| result.append(value) | |
| return bounded_values(result, preserve_order=True) | |
| def evaluate_operand(operand, state: State) -> Optional[Values]: | |
| """Evaluate an operand in the current state.""" | |
| if operand.t == ida_hexrays.mop_n: | |
| return (int(operand.nnn.value),) | |
| if operand.t == ida_hexrays.mop_v: | |
| value = read_memory(int(operand.g), int(operand.size)) | |
| return (value,) if value is not None else None | |
| if operand.t == ida_hexrays.mop_a: | |
| if operand.a.t == ida_hexrays.mop_S: | |
| return (StackAddress(int(operand.a.s.off)),) | |
| if operand.a.t == ida_hexrays.mop_v: | |
| return (int(operand.a.g),) | |
| return evaluate_operand(operand.a, state) | |
| if operand.t in (ida_hexrays.mop_r, ida_hexrays.mop_S): | |
| operand_location = location(operand) | |
| if operand_location == ("r", STACK_POINTER_MREG): | |
| return (StackAddress(0),) | |
| return state.get(operand_location) | |
| if operand.t == ida_hexrays.mop_d: | |
| return evaluate_instruction(operand.d, state) | |
| return None | |
| def evaluate_instruction(instruction, state: State) -> Optional[Values]: | |
| """Evaluate a microinstruction without side effects.""" | |
| opcode = instruction.opcode | |
| if ida_hexrays.is_mcode_set(opcode): | |
| return 0, 1 | |
| if opcode == ida_hexrays.m_mov: | |
| return evaluate_operand(instruction.l, state) | |
| if opcode == ida_hexrays.m_xdu: | |
| return extend_values(evaluate_operand(instruction.l, state), int(instruction.l.size), False) | |
| if opcode == ida_hexrays.m_xds: | |
| return extend_values(evaluate_operand(instruction.l, state), int(instruction.l.size), True) | |
| if opcode == ida_hexrays.m_low: | |
| return extend_values(evaluate_operand(instruction.l, state), int(instruction.d.size), False) | |
| if opcode == ida_hexrays.m_high: | |
| shift = max(0, int(instruction.l.size) - int(instruction.d.size)) * 8 | |
| return unary_values(evaluate_operand(instruction.l, state), lambda value: value >> shift if isinstance(value, int) else value) | |
| if opcode == ida_hexrays.m_ldx: | |
| return evaluate_load(evaluate_operand(instruction.r, state), int(instruction.d.size), state) | |
| if opcode == ida_hexrays.m_neg: | |
| values = unary_values(evaluate_operand(instruction.l, state), lambda value: -value if isinstance(value, int) else value) | |
| return truncate_values(values, int(instruction.d.size)) | |
| if opcode == ida_hexrays.m_bnot: | |
| values = unary_values(evaluate_operand(instruction.l, state), lambda value: ~value if isinstance(value, int) else value) | |
| return truncate_values(values, int(instruction.d.size)) | |
| left = evaluate_operand(instruction.l, state) | |
| right = evaluate_operand(instruction.r, state) | |
| if opcode == ida_hexrays.m_and and (number(instruction.l) == 1 or number(instruction.r) == 1): | |
| if left is None or right is None: | |
| return 0, 1 | |
| if opcode == ida_hexrays.m_add: | |
| return binary_values(left, right, add_atoms) | |
| if opcode == ida_hexrays.m_sub: | |
| return binary_values(left, right, subtract_atoms) | |
| if opcode == ida_hexrays.m_mul: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs * rhs)) | |
| if opcode == ida_hexrays.m_and: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs & rhs)) | |
| if opcode == ida_hexrays.m_or: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs | rhs)) | |
| if opcode == ida_hexrays.m_xor: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs ^ rhs)) | |
| if opcode == ida_hexrays.m_shl: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs << rhs)) | |
| if opcode == ida_hexrays.m_shr: | |
| return binary_values(left, right, integer_operation(lambda lhs, rhs: lhs >> rhs)) | |
| return None | |
| def write_location(state: State, operand, values: Optional[Values]) -> None: | |
| """Update a register or stack value.""" | |
| destination = location(operand) | |
| if destination is None: | |
| return | |
| if values is None: | |
| state.pop(destination, None) | |
| else: | |
| state[destination] = values | |
| def execute_store(instruction, state: State) -> None: | |
| """Handle writes to the current stack frame.""" | |
| addresses = evaluate_operand(instruction.d, state) | |
| values = evaluate_operand(instruction.l, state) | |
| if addresses is None: | |
| return | |
| for address in addresses: | |
| if not isinstance(address, StackAddress): | |
| continue | |
| destination = ("s", address.offset) | |
| if values is None: | |
| state.pop(destination, None) | |
| else: | |
| state[destination] = values | |
| def execute_instruction(instruction, state: State) -> None: | |
| """Apply a top-level microinstruction to the state.""" | |
| if instruction.opcode == ida_hexrays.m_stx: | |
| execute_store(instruction, state) | |
| return | |
| if location(instruction.d) is not None: | |
| write_location(state, instruction.d, evaluate_instruction(instruction, state)) | |
| def merge_states(states: List[State]) -> State: | |
| """Merge incoming states from predecessors.""" | |
| if not states: | |
| return {} | |
| locations = set(states[0]) | |
| for state in states[1:]: | |
| locations.intersection_update(state) | |
| merged = {} | |
| for destination in locations: | |
| values = bounded_values(value for state in states for value in state[destination]) | |
| if values is not None: | |
| merged[destination] = values | |
| return merged | |
| def block_input(block, outputs: List[Optional[State]]) -> Optional[State]: | |
| """Compute the block entry state.""" | |
| if block.npred() == 0: | |
| return {} | |
| predecessors = [] | |
| for index in range(int(block.npred())): | |
| state = outputs[int(block.pred(index))] | |
| if state is not None: | |
| predecessors.append(state) | |
| return merge_states(predecessors) if predecessors else None | |
| def execute_block(block, state: State) -> State: | |
| """Compute the block exit state.""" | |
| result = dict(state) | |
| instruction = block.head | |
| while instruction is not None: | |
| execute_instruction(instruction, result) | |
| instruction = instruction.next | |
| return result | |
| def is_executable_code(ea: int) -> bool: | |
| """Check whether an address contains executable code.""" | |
| segment = segment_info(ea) | |
| if segment is None or (int(segment.get_perm()) & ida_segment.SEGPERM_EXEC) == 0: | |
| return False | |
| return ida_bytes.is_code(ida_bytes.get_flags(ea)) | |
| def find_ir_jump(instruction): | |
| """Find an indirect jump in PREOPT microcode.""" | |
| if instruction.opcode == ida_hexrays.m_ijmp: | |
| return instruction | |
| for operand in (instruction.l, instruction.r, instruction.d): | |
| if operand.t == ida_hexrays.mop_d: | |
| found = find_ir_jump(operand.d) | |
| if found is not None: | |
| return found | |
| return None | |
| return None | |
| def find_block_jump(block): | |
| """Find an indirect jump in a block.""" | |
| instruction = block.head | |
| while instruction is not None: | |
| found = find_ir_jump(instruction) | |
| if found is not None: | |
| return found | |
| instruction = instruction.next | |
| return None | |
| def resolve_block(block, state: State) -> Optional[IRSite]: | |
| """Resolve an indirect jump from the block entry state.""" | |
| current = dict(state) | |
| instruction = block.head | |
| while instruction is not None: | |
| if instruction.opcode == ida_hexrays.m_ijmp: | |
| targets = evaluate_operand(instruction.d, current) | |
| if targets is None or not 1 <= len(targets) <= MAX_SUCCESSORS: | |
| return None | |
| if not all(isinstance(target, int) and is_executable_code(target) for target in targets): | |
| return None | |
| return IRSite(int(instruction.ea), tuple(targets)) | |
| execute_instruction(instruction, current) | |
| instruction = instruction.next | |
| return None | |
| def analyze_preopt_states(microcode): | |
| """Compute exit states for target resolution and branch rewriting.""" | |
| outputs = [None for _ in range(int(microcode.qty))] | |
| while True: | |
| changed = False | |
| for index in range(int(microcode.qty)): | |
| block = microcode.get_mblock(index) | |
| input_state = block_input(block, outputs) | |
| if input_state is None: | |
| continue | |
| output = execute_block(block, input_state) | |
| if output != outputs[index]: | |
| outputs[index] = output | |
| changed = True | |
| if not changed: | |
| break | |
| return outputs | |
| def resolve_preopt(microcode): | |
| """Resolve indirect jumps across the function.""" | |
| outputs = analyze_preopt_states(microcode) | |
| candidates = [] | |
| sites = [] | |
| for index in range(int(microcode.qty)): | |
| block = microcode.get_mblock(index) | |
| jump = find_block_jump(block) | |
| if jump is None: | |
| continue | |
| candidates.append(int(jump.ea)) | |
| input_state = block_input(block, outputs) | |
| site = resolve_block(block, input_state) if input_state is not None else None | |
| if site is not None: | |
| sites.append(site) | |
| return candidates, sites | |
| def find_site_block(mba, branch_ea: int): | |
| """Find the block ending at a branch address.""" | |
| for index in range(int(mba.qty)): | |
| block = mba.get_mblock(index) | |
| if block.tail is not None and int(block.tail.ea) == branch_ea: | |
| return block | |
| return None | |
| def is_automatic_function(function) -> bool: | |
| """Check whether a function has an automatic IDA name.""" | |
| if function is None: | |
| return False | |
| name = ida_name.get_ea_name(int(function.start_ea)) | |
| return not name or name.startswith(("sub_", "loc_", "nullsub_")) | |
| def target_can_join(entry_ea: int, target_ea: int) -> bool: | |
| """Check whether a target can join the current function.""" | |
| owner = function_info(target_ea) | |
| if owner is None or int(owner.start_ea) == entry_ea: | |
| return True | |
| return is_automatic_function(owner) | |
| def append_target(plan: RecoveryPlan, target_ea: int) -> bool: | |
| """Merge the target fragment into the root function.""" | |
| owner = function_info(target_ea) | |
| if owner is not None and int(owner.start_ea) == plan.entry_ea: | |
| return True | |
| deleted = None | |
| if owner is not None: | |
| if not is_automatic_function(owner): | |
| return False | |
| deleted = DeletedFunction(int(owner.start_ea), int(owner.end_ea), int(owner.get_flags()), int(owner.get_color())) | |
| if not ida_funcs.del_func(deleted.start): | |
| return False | |
| tail_start = deleted.start if deleted is not None else target_ea | |
| tail_end = deleted.end if deleted is not None else ida_idaapi.BADADDR | |
| if not ida_funcs.append_func_tail_ea(plan.entry_ea, tail_start, tail_end): | |
| if deleted is not None: | |
| ida_funcs.add_func(deleted.start, deleted.end) | |
| return False | |
| if deleted is not None: | |
| plan.deleted_functions.append(deleted) | |
| return True | |
| def align_up(value: int, alignment: int) -> int: | |
| """Round an address up to the given alignment.""" | |
| return (value + alignment - 1) & ~(alignment - 1) | |
| def branch_target_register(branch_ea: int) -> Optional[int]: | |
| """Read the indirect branch target register.""" | |
| instruction = ida_ua.insn_t() | |
| if ida_ua.decode_insn(instruction, branch_ea) <= 0: | |
| return None | |
| operand = instruction.ops[0] | |
| return int(operand.reg) if operand.type == ida_ua.o_reg else None | |
| def ensure_switch_segment(): | |
| """Get or create the synthetic switch data segment.""" | |
| start = ida_segment.get_segment_ea_by_name(SWITCH_SEGMENT_NAME) | |
| if start != ida_idaapi.BADADDR: | |
| return segment_info(start) | |
| start = align_up(int(ida_ida.inf_get_max_ea()), 0x1000) | |
| if not ida_segment.add_segm(0, start, start + SWITCH_SEGMENT_SIZE, SWITCH_SEGMENT_NAME, "DATA"): | |
| return None | |
| segment = segment_info(start) | |
| if segment is None: | |
| return None | |
| segment.set_perm(ida_segment.SEGPERM_READ) | |
| segment.set_type(ida_segment.SEG_DATA) | |
| if not ida_segment.set_segment_info(segment): | |
| return None | |
| return segment | |
| def switch_record_is_unused(record_ea: int) -> bool: | |
| """Check whether a switch table slot is free.""" | |
| offsets = (0, POINTER_SIZE, SWITCH_JUMPS_OFFSET, SWITCH_JUMPS_OFFSET + POINTER_SIZE) | |
| return all(ida_bytes.is_unknown(ida_bytes.get_flags(record_ea + offset)) for offset in offsets) | |
| def allocate_switch_tables(branch_ea: int) -> Optional[Tuple[int, int]]: | |
| """Allocate values and jumps tables for a two-way branch.""" | |
| segment = ensure_switch_segment() | |
| if segment is None: | |
| return None | |
| for record_ea in range(int(segment.start_ea), int(segment.end_ea), SWITCH_RECORD_SIZE): | |
| if not switch_record_is_unused(record_ea): | |
| continue | |
| values_ea = record_ea | |
| jumps_ea = record_ea + SWITCH_JUMPS_OFFSET | |
| name_flags = ida_name.SN_NOCHECK | ida_name.SN_NOWARN | |
| ida_name.set_name(values_ea, f"hikari_switch_values_{branch_ea:X}", name_flags) | |
| ida_name.set_name(jumps_ea, f"hikari_switch_jumps_{branch_ea:X}", name_flags) | |
| return values_ea, jumps_ea | |
| return None | |
| def write_pointer(ea: int, value: int) -> bool: | |
| """Write an address using the database pointer width.""" | |
| if POINTER_SIZE == 8: | |
| if not ida_bytes.create_qword(ea, POINTER_SIZE, True): | |
| return False | |
| ida_bytes.put_qword(ea, value) | |
| return True | |
| if not ida_bytes.create_dword(ea, POINTER_SIZE, True): | |
| return False | |
| ida_bytes.put_dword(ea, value) | |
| return True | |
| def create_target_address_switch(plan: RecoveryPlan, site: IRSite) -> bool: | |
| """Create a sparse switch using the BR target register.""" | |
| register = branch_target_register(site.branch_ea) | |
| tables = allocate_switch_tables(site.branch_ea) | |
| if register is None or tables is None: | |
| return False | |
| values_ea, jumps_ea = tables | |
| for index, target in enumerate(site.targets): | |
| if not write_pointer(values_ea + index * POINTER_SIZE, target): | |
| return False | |
| if not write_pointer(jumps_ea + index * POINTER_SIZE, target): | |
| return False | |
| switch = ida_nalt.switch_info_t() | |
| switch.flags |= ida_nalt.SWI_USER | ida_nalt.SWI_SPARSE | |
| switch.values = values_ea | |
| switch.jumps = jumps_ea | |
| switch.ncases = len(site.targets) | |
| switch.startea = site.branch_ea | |
| switch.expr_ea = site.branch_ea | |
| switch_dtype = ida_ua.dt_qword if POINTER_SIZE == 8 else ida_ua.dt_dword | |
| switch.set_expr(register, switch_dtype) | |
| switch.set_vtable_element_size(POINTER_SIZE) | |
| switch.set_jtable_element_size(POINTER_SIZE) | |
| switch.set_elbase(0) | |
| ida_nalt.set_switch_info(site.branch_ea, switch) | |
| if not ida_xref.create_switch_table(site.branch_ea, switch): | |
| ida_nalt.del_switch_info(site.branch_ea) | |
| return False | |
| ida_xref.create_switch_xrefs(site.branch_ea, switch) | |
| plan.switch_tables[site.branch_ea] = values_ea, jumps_ea, len(site.targets) | |
| return True | |
| def patch_direct_branch(plan: RecoveryPlan, site: IRSite) -> bool: | |
| """Assemble a direct B with Keystone and save the original for rollback.""" | |
| target = site.targets[0] | |
| if site.branch_ea % 4 or target % 4: | |
| return False | |
| # Keystone 0.9.2 wraps out-of-range B offsets; enforce the 128 MiB limit. | |
| if not -BRANCH_RANGE <= target - site.branch_ea < BRANCH_RANGE: | |
| log(f"{site.branch_ea:#x}: B target {target:#x} out of range") | |
| return False | |
| try: | |
| patch, count = ARM64_ASSEMBLER.asm(f"b {target:#x}", addr=site.branch_ea, as_bytes=True) | |
| except KsError as error: | |
| log(f"{site.branch_ea:#x}: B assembly failed: {error}") | |
| return False | |
| if count != 1 or len(patch) != 4: | |
| return False | |
| original = int(ida_bytes.get_dword(site.branch_ea)) | |
| ida_bytes.patch_bytes(site.branch_ea, patch) | |
| if ida_bytes.get_bytes(site.branch_ea, 4) != patch: | |
| return False | |
| plan.patched_branches.setdefault(site.branch_ea, original) | |
| return True | |
| def commit_site(plan: RecoveryPlan, site: IRSite) -> bool: | |
| """Commit resolved successors to the IDB.""" | |
| previous_targets = set(idautils.CodeRefsFrom(site.branch_ea, False)) | |
| if len(site.targets) == 1: | |
| if not patch_direct_branch(plan, site): | |
| return False | |
| else: | |
| if ida_nalt.get_switch_info(site.branch_ea) is not None: | |
| return False | |
| if not create_target_address_switch(plan, site): | |
| return False | |
| for target in site.targets: | |
| if target not in previous_targets: | |
| ida_xref.add_cref(site.branch_ea, target, ida_xref.fl_JN | ida_xref.XREF_USER) | |
| plan.user_xrefs.add((site.branch_ea, target)) | |
| return True | |
| def reanalyze(entry_ea: int) -> None: | |
| """Reanalyze the function and clear the decompiler cache.""" | |
| root = function_info(entry_ea) | |
| if root is not None: | |
| ida_funcs.reanalyze_function_ea(int(root.start_ea)) | |
| ida_auto.plan_and_wait(int(root.start_ea), int(root.end_ea), True) | |
| ida_auto.auto_wait() | |
| ida_hexrays.clear_cached_cfuncs() | |
| def invalidate_guessed_prototype(entry_ea: int) -> bool: | |
| """Clear a stale inferred prototype after CFG recovery. | |
| Preserve user-defined types. An earlier void() guess can make Hex-Rays | |
| discard return-value computations even after its cache is cleared. | |
| """ | |
| if ida_nalt.is_userti(entry_ea): | |
| return False | |
| prototype = ida_typeinf.tinfo_t() | |
| if not ida_nalt.get_tinfo(prototype, entry_ea) or not prototype.is_func(): | |
| return False | |
| previous = str(prototype) | |
| ida_nalt.del_tinfo(entry_ea) | |
| ida_hexrays.clear_cached_cfuncs() | |
| log(f"{entry_ea:#x}: cleared inferred prototype {previous}; re-infer on decompilation") | |
| return True | |
| def recover_function(ea: Optional[int] = None) -> Optional[RecoveryPlan]: | |
| """Resolve and rebuild indirect control flow to a fixed point.""" | |
| if not ida_hexrays.init_hexrays_plugin(): | |
| log("Hex-Rays unavailable") | |
| return None | |
| ida_auto.auto_wait() | |
| if ea is None: | |
| ea = int(ida_kernwin.get_screen_ea()) | |
| root = function_info(int(ea)) | |
| if root is None: | |
| log(f"{int(ea):#x}: no function") | |
| return None | |
| entry_ea = int(root.start_ea) | |
| instance = tool() | |
| if entry_ea in instance.plans: | |
| plan = instance.plans[entry_ea] | |
| if plan.complete and plan.sites: | |
| invalidate_guessed_prototype(entry_ea) | |
| log(f"{entry_ea:#x}: plan exists; roll back before retrying") | |
| return plan | |
| tails = ida_range.rangevec_t() | |
| if not ida_funcs.get_func_tails(tails, entry_ea): | |
| log(f"{entry_ea:#x}: cannot read function ranges") | |
| return None | |
| original_ranges = ((int(root.start_ea), int(root.end_ea)),) + tuple( | |
| (int(tail.start_ea), int(tail.end_ea)) for tail in tails | |
| ) | |
| plan = RecoveryPlan( | |
| entry_ea=entry_ea, | |
| original_ranges=original_ranges, | |
| original_flags=int(root.get_flags()), | |
| original_color=int(root.get_color()), | |
| ) | |
| instance.plans[entry_ea] = plan | |
| # Rebuild whole-function PREOPT microcode after adding edges. | |
| iteration = 0 | |
| while True: | |
| iteration += 1 | |
| plan.iterations = iteration | |
| microcode = generate_preopt(entry_ea) | |
| if microcode is None: | |
| log(f"{entry_ea:#x}: PREOPT generation failed") | |
| break | |
| candidates, resolved = resolve_preopt(microcode) | |
| if not candidates: | |
| plan.complete = True | |
| if plan.sites: | |
| invalidate_guessed_prototype(entry_ea) | |
| ida_hexrays.clear_cached_cfuncs() | |
| log(f"{entry_ea:#x}: fixed point after {iteration} rounds; sites={len(plan.sites)}, one-way={plan.one_way}, two-way={plan.two_way}") | |
| return plan | |
| if not resolved: | |
| addresses = ", ".join(f"{address:#x}" for address in candidates) | |
| log(f"{entry_ea:#x}: unresolved PREOPT jumps: {addresses}") | |
| break | |
| failed = False | |
| for site in resolved: | |
| if not all(target_can_join(entry_ea, target) for target in site.targets): | |
| log(f"{site.branch_ea:#x}: target belongs to a named function; stopped") | |
| failed = True | |
| break | |
| if not commit_site(plan, site): | |
| log(f"{site.branch_ea:#x}: CFG update failed") | |
| failed = True | |
| break | |
| plan.sites[site.branch_ea] = site | |
| if not all(append_target(plan, target) for target in site.targets): | |
| log(f"{site.branch_ea:#x}: target merge failed") | |
| failed = True | |
| break | |
| targets = ", ".join(f"{target:#x}" for target in site.targets) | |
| log(f"round {iteration}: {site.branch_ea:#x} -> {targets}") | |
| if failed: | |
| break | |
| reanalyze(entry_ea) | |
| log(f"{entry_ea:#x}: incomplete; sites={len(plan.sites)}, one-way={plan.one_way}, two-way={plan.two_way}") | |
| return plan | |
| def find_block_start(mba, ea: int): | |
| """Find a microcode block by its start address.""" | |
| for index in range(int(mba.qty)): | |
| block = mba.get_mblock(index) | |
| if int(block.start) == ea: | |
| return block | |
| return None | |
| def replace_one_way(mba, site: IRSite) -> bool: | |
| """Replace a one-way indirect jump with a goto.""" | |
| block = find_site_block(mba, site.branch_ea) | |
| target = find_block_start(mba, site.targets[0]) | |
| if block is None or target is None or block.tail is None: | |
| return False | |
| block.tail.opcode = ida_hexrays.m_goto | |
| block.tail.l.make_blkref(int(target.serial)) | |
| block.tail.r.erase() | |
| block.tail.d.erase() | |
| block.mark_lists_dirty() | |
| return True | |
| def find_verified_selector(block, input_state: State, site: IRSite): | |
| """Find a Boolean selector and verify its targets for 0 and 1. | |
| Include incoming states: PREOPT may split CSET into predecessor assignments. | |
| """ | |
| current = dict(input_state) | |
| definition = block.head | |
| while definition is not None and definition != block.tail: | |
| execute_instruction(definition, current) | |
| destination = location(definition.d) | |
| values = current.get(destination) if destination is not None else None | |
| size = int(definition.d.size) | |
| if values is not None and set(values) == {0, 1} and size in (1, 2, 4, 8): | |
| targets = [] | |
| for value in (0, 1): | |
| state = dict(current) | |
| state[destination] = (value,) | |
| cursor = definition.next | |
| while cursor is not None and cursor != block.tail: | |
| execute_instruction(cursor, state) | |
| cursor = cursor.next | |
| result = evaluate_operand(block.tail.l, state) | |
| if result is None or len(result) != 1 or not isinstance(result[0], int): | |
| break | |
| targets.append(result[0]) | |
| if len(targets) == 2 and set(targets) == set(site.targets): | |
| return definition, tuple(targets) | |
| definition = definition.next | |
| return None | |
| def set_block_successors(block, successors, block_type) -> None: | |
| """Update successors; rebuild predecessors after all edits.""" | |
| block.succset.clear() | |
| # BLT_2WAY requires fallthrough at succset[0]; preserve order. | |
| for serial in dict.fromkeys(successors): | |
| block.succset.push_back(serial) | |
| block.type = block_type | |
| block.mark_lists_dirty() | |
| def rebuild_predecessors(mba) -> None: | |
| """Rebuild predecessor lists from the updated successors.""" | |
| for index in range(int(mba.qty)): | |
| mba.get_mblock(index).predset.clear() | |
| for index in range(int(mba.qty)): | |
| block = mba.get_mblock(index) | |
| for successor in block.succset: | |
| mba.get_mblock(int(successor)).predset.push_back(index) | |
| def replace_two_way(mba, site: IRSite, input_state: State) -> bool: | |
| """Replace a two-way synthetic switch with a conditional branch.""" | |
| block = find_site_block(mba, site.branch_ea) | |
| if block is None or block.tail is None or block.tail.opcode != ida_hexrays.m_jtbl: | |
| return False | |
| verified = find_verified_selector(block, input_state, site) | |
| if verified is None: | |
| return False | |
| definition, targets = verified | |
| zero_target = find_block_start(mba, targets[0]) | |
| one_target = find_block_start(mba, targets[1]) | |
| if zero_target is None or one_target is None: | |
| return False | |
| selector_size = int(definition.d.size) | |
| selector_register = mba.alloc_kreg(selector_size) | |
| snapshot_ea = int(mba.alloc_fict_ea(int(definition.ea))) | |
| snapshot = ida_hexrays.minsn_t(snapshot_ea) | |
| snapshot.opcode = ida_hexrays.m_mov | |
| snapshot.l.assign(definition.d) | |
| snapshot.d.make_reg(selector_register, selector_size) | |
| block.insert_into_block(snapshot, definition) | |
| selector = ida_hexrays.mop_t() | |
| selector.make_reg(selector_register, selector_size) | |
| # Insert an adjacent goto block for the implicit fallthrough. | |
| trampoline = mba.insert_block(int(block.serial) + 1) | |
| if trampoline is None: | |
| return False | |
| fake_ea = int(mba.alloc_fict_ea(site.branch_ea)) | |
| trampoline.start = fake_ea | |
| trampoline.end = fake_ea | |
| trampoline.flags |= ida_hexrays.MBL_FAKE | ida_hexrays.MBL_KEEP | |
| # Insertion renumbers blocks; use their updated serials. | |
| jump = ida_hexrays.minsn_t(fake_ea) | |
| jump.opcode = ida_hexrays.m_goto | |
| jump.l.make_blkref(int(one_target.serial)) | |
| trampoline.insert_into_block(jump, None) | |
| tail = block.tail | |
| tail.opcode = ida_hexrays.m_jz | |
| tail.l.assign(selector) | |
| tail.r.make_number(0, selector_size, site.branch_ea) | |
| tail.d.make_blkref(int(zero_target.serial)) | |
| set_block_successors(block, (int(trampoline.serial), int(zero_target.serial)), ida_hexrays.BLT_2WAY) | |
| set_block_successors(trampoline, (int(one_target.serial),), ida_hexrays.BLT_1WAY) | |
| return True | |
| class HikariIRCFGHook(ida_hexrays.Hexrays_Hooks): | |
| def mba_maturity(self, mba, requested_maturity): | |
| """Rewrite synthetic switches at PREOPT maturity.""" | |
| if int(mba.maturity) != ida_hexrays.MMAT_PREOPTIMIZED: | |
| return ida_hexrays.MERR_OK | |
| plan = tool().plans.get(int(mba.entry_ea)) | |
| if plan is None or not plan.complete or not plan.sites: | |
| return ida_hexrays.MERR_OK | |
| if not ensure_microcode_graph(mba): | |
| log(f"{int(mba.entry_ea):#x}: PREOPT CFG build failed; switches unchanged") | |
| return ida_hexrays.MERR_OK | |
| outputs = analyze_preopt_states(mba) | |
| changed = 0 | |
| two_way = [site for site in plan.sites.values() if len(site.targets) == 2] | |
| # Process blocks in reverse order to keep pending indices valid. | |
| ordered = [] | |
| skipped = [] | |
| for site in two_way: | |
| block = find_site_block(mba, site.branch_ea) | |
| if block is not None: | |
| input_state = block_input(block, outputs) | |
| if input_state is not None: | |
| ordered.append((int(block.serial), site, input_state)) | |
| continue | |
| skipped.append(site.branch_ea) | |
| for _, site, input_state in sorted(ordered, key=lambda item: item[0], reverse=True): | |
| if replace_two_way(mba, site, input_state): | |
| changed += 1 | |
| else: | |
| skipped.append(site.branch_ea) | |
| if changed: | |
| rebuild_predecessors(mba) | |
| mba.mark_chains_dirty() | |
| mba.verify(True) | |
| log(f"{int(mba.entry_ea):#x}: rewrote {changed} synthetic switches") | |
| if skipped: | |
| addresses = ", ".join(f"{ea:#x}" for ea in sorted(skipped)) | |
| log(f"{int(mba.entry_ea):#x}: {len(skipped)} switches skipped (missing block or unverified selector): {addresses}") | |
| return ida_hexrays.MERR_OK | |
| class HikariIRCFGTool: | |
| def __init__(self): | |
| """Store recovery plans and hooks for this IDA session.""" | |
| self.plans: Dict[int, RecoveryPlan] = {} | |
| self.hook: Optional[HikariIRCFGHook] = None | |
| self.ui_hook: Optional[ida_kernwin.UI_Hooks] = None | |
| self.action_handler: Optional[ida_kernwin.action_handler_t] = None | |
| def tool() -> HikariIRCFGTool: | |
| """Get the tool instance shared across script reloads.""" | |
| instance = getattr(ida_hexrays, TOOL_ATTRIBUTE, None) | |
| if instance is None: | |
| instance = HikariIRCFGTool() | |
| setattr(ida_hexrays, TOOL_ATTRIBUTE, instance) | |
| return instance | |
| def install_hook() -> bool: | |
| """Install the F5 microcode hook.""" | |
| if not ida_hexrays.init_hexrays_plugin(): | |
| log("Hex-Rays unavailable") | |
| return False | |
| instance = tool() | |
| if instance.hook is not None: | |
| instance.hook.unhook() | |
| hook = HikariIRCFGHook() | |
| if not hook.hook(): | |
| log("Hex-Rays hook installation failed") | |
| return False | |
| instance.hook = hook | |
| ida_hexrays.clear_cached_cfuncs() | |
| log("F5 hook installed") | |
| return True | |
| def uninstall_hook() -> bool: | |
| """Remove the F5 microcode hook.""" | |
| instance = tool() | |
| if instance.hook is None: | |
| log("F5 hook not installed") | |
| return False | |
| instance.hook.unhook() | |
| instance.hook = None | |
| ida_hexrays.clear_cached_cfuncs() | |
| log("F5 hook removed; IDB changes retained") | |
| return True | |
| def rollback_function(ea: Optional[int] = None) -> bool: | |
| """Revert recovery changes recorded for this function.""" | |
| if ea is None: | |
| ea = int(ida_kernwin.get_screen_ea()) | |
| entry_ea = int(ida_funcs.get_func_start(int(ea))) | |
| if entry_ea == ida_idaapi.BADADDR: | |
| entry_ea = int(ea) | |
| instance = tool() | |
| plan = instance.plans.get(entry_ea) | |
| if plan is None: | |
| log(f"{entry_ea:#x}: no plan to roll back") | |
| return False | |
| for branch_ea, table in plan.switch_tables.items(): | |
| switch = ida_nalt.get_switch_info(branch_ea) | |
| if switch is not None: | |
| ida_xref.delete_switch_table(branch_ea, switch) | |
| ida_nalt.del_switch_info(branch_ea) | |
| values_ea, jumps_ea, count = table | |
| table_size = count * POINTER_SIZE | |
| ida_name.del_global_name(values_ea) | |
| ida_name.del_global_name(jumps_ea) | |
| ida_bytes.del_items(values_ea, ida_bytes.DELIT_DELNAMES, table_size) | |
| ida_bytes.del_items(jumps_ea, ida_bytes.DELIT_DELNAMES, table_size) | |
| for branch_ea, original_dword in plan.patched_branches.items(): | |
| ida_bytes.patch_dword(branch_ea, original_dword) | |
| for branch_ea, target_ea in plan.user_xrefs: | |
| ida_xref.del_cref(branch_ea, target_ea, False) | |
| ida_funcs.del_func(entry_ea) | |
| main_start, main_end = plan.original_ranges[0] | |
| if not ida_funcs.add_func(main_start, main_end): | |
| log(f"{entry_ea:#x}: root function rebuild failed") | |
| return False | |
| for tail_start, tail_end in plan.original_ranges[1:]: | |
| ida_funcs.append_func_tail_ea(entry_ea, tail_start, tail_end) | |
| restored_root = function_info(entry_ea) | |
| restored_root.set_flags(plan.original_flags) | |
| restored_root.set_color(plan.original_color) | |
| ida_funcs.set_func_entry_info(restored_root) | |
| for deleted in plan.deleted_functions: | |
| if ida_funcs.add_func(deleted.start, deleted.end): | |
| restored = function_info(deleted.start) | |
| restored.set_flags(deleted.flags) | |
| restored.set_color(deleted.color) | |
| ida_funcs.set_func_entry_info(restored) | |
| del instance.plans[entry_ea] | |
| reanalyze(entry_ea) | |
| log(f"{entry_ea:#x}: recovery changes rolled back") | |
| return True | |
| def recover_current_function(ea: Optional[int] = None) -> Optional[RecoveryPlan]: | |
| """Recover the function at ea or the cursor, then install the hook.""" | |
| plan = recover_function(ea) | |
| if plan is not None and plan.complete and plan.sites: | |
| install_hook() | |
| elif plan is not None and not plan.complete: | |
| log("recovery incomplete; F5 hook not installed") | |
| return plan | |
| def popup_function_ea(ctx) -> int: | |
| """Use the displayed function in pseudocode, even when the cursor is on a call.""" | |
| if ctx.widget_type == ida_kernwin.BWN_PSEUDOCODE: | |
| view = ida_hexrays.get_widget_vdui(ctx.widget) | |
| if view is not None and view.cfunc is not None: | |
| return int(view.cfunc.entry_ea) | |
| elif ctx.widget_type == ida_kernwin.BWN_DISASM: | |
| return int(ida_funcs.get_func_start(ctx.cur_ea)) | |
| return ida_idaapi.BADADDR | |
| class DeobfuscateAction(ida_kernwin.action_handler_t): | |
| def activate(self, ctx): | |
| ea = popup_function_ea(ctx) | |
| if ea == ida_idaapi.BADADDR: | |
| return 0 | |
| plan = recover_current_function(ea) | |
| if plan is not None and plan.complete and ctx.widget_type == ida_kernwin.BWN_PSEUDOCODE: | |
| view = ida_hexrays.get_widget_vdui(ctx.widget) | |
| if view is not None: | |
| view.refresh_view(True) | |
| return 1 | |
| def update(self, ctx): | |
| if popup_function_ea(ctx) != ida_idaapi.BADADDR: | |
| return ida_kernwin.AST_ENABLE | |
| return ida_kernwin.AST_DISABLE | |
| class DeobfuscatePopupHook(ida_kernwin.UI_Hooks): | |
| def finish_populating_widget_popup(self, widget, popup_handle, ctx=None): | |
| if ida_kernwin.get_widget_type(widget) in (ida_kernwin.BWN_DISASM, ida_kernwin.BWN_PSEUDOCODE): | |
| ida_kernwin.attach_action_to_popup(widget, popup_handle, DEOBFUSCATE_ACTION) | |
| def uninstall_context_menu() -> None: | |
| """Remove the menu and UI hook, keeping recovery plans.""" | |
| instance = tool() | |
| previous_hook = getattr(instance, "ui_hook", None) | |
| if previous_hook is not None: | |
| previous_hook.unhook() | |
| ida_kernwin.unregister_action(DEOBFUSCATE_ACTION) | |
| instance.ui_hook = None | |
| instance.action_handler = None | |
| def install_context_menu() -> bool: | |
| """Replace the menu on reload to avoid duplicate actions.""" | |
| uninstall_context_menu() | |
| handler = DeobfuscateAction() | |
| action = ida_kernwin.action_desc_t( | |
| DEOBFUSCATE_ACTION, "deobfuscate it", handler, None, "Recover Hikari control flow in this function" | |
| ) | |
| if not ida_kernwin.register_action(action): | |
| log("menu registration failed; use recover_current_function()") | |
| return False | |
| popup_hook = DeobfuscatePopupHook() | |
| if not popup_hook.hook(): | |
| ida_kernwin.unregister_action(DEOBFUSCATE_ACTION) | |
| log("menu UI hook installation failed") | |
| return False | |
| instance = tool() | |
| instance.action_handler = handler | |
| instance.ui_hook = popup_hook | |
| return True | |
| def tool_status() -> None: | |
| """Show hook and recovery plan status.""" | |
| instance = tool() | |
| hook_state = "installed" if instance.hook is not None else "not installed" | |
| log(f"hook={hook_state}, plans={len(instance.plans)}") | |
| for entry_ea, plan in sorted(instance.plans.items()): | |
| log(f" {entry_ea:#x}: rounds={plan.iterations}, sites={len(plan.sites)}, one-way={plan.one_way}, two-way={plan.two_way}, complete={plan.complete}") | |
| if install_context_menu(): | |
| log("loaded; right-click > deobfuscate it, or call recover_current_function() then press F5") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment