Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ghidra

Use case

Deobfuscate bogus control flow (bcf).

Usage

Script Manager –> Manage Script Directories –> add/enable $USER_HOME/ghidra_scripts

$ cp deobf-bcf.py $HOME/ghidra_scripts/
deobf-bcf.py> Running...
x    @ 00130db0
y    @ 00130db4
x.1  @ 00130db8
y.2  @ 00130dbc
main: patched 16 opaque branch(es)
deobf-bcf.py> Finished!
# Remove obfuscator-llvm bogus control flow (bcf) from listing and decompiler views.
# https://github.com/eshard/obfuscator-llvm/blob/main/bogus/BogusControlFlow.cpp
#
# predicates: (y < 10 || x * (x + 1) % 2 == 0), always true
# https://github.com/eshard/obfuscator-llvm/blob/ad26aa21b90cc5c5118d32114b674d1455f54168/bogus/BogusControlFlow.cpp#L43
#
# Ghidra cannot prove the "always true" part so we give it x, y concrete values:
# 0 (.bss) and let the decompiler constant fold.
#
# Step 1:
#   0 fill .bss and mark x, y as constants. The decompiler folds
#   the predicates and hides the bogus blocks.
#
# Step 2:
#   The decompiler lists the hidden blocks ("Removing unreachable block").
#   Any branch that can go to a hidden block is essentially a one way branch:
#     - target hidden -> never taken -> replace with nop
#     - fall-through hidden -> always taken -> replace with b target
#
# @category Deobfuscation

import re
from ghidra.app.cmd.function import CreateFunctionCmd
from ghidra.app.decompiler import DecompileOptions
from ghidra.app.decompiler.flatapi import FlatDecompilerAPI
from ghidra.program.flatapi import FlatProgramAPI
from ghidra.app.plugin.assembler import Assemblers
from ghidra.program.model.data import MutabilitySettingsDefinition as Mutability

# x, y, x.1, y.2, ...
OPAQUE_NAME = re.compile(r"^[xy]([._]\d+)?$")
# /* WARNING: Removing unreachable block (ram,0x00110968) */
DEAD_BLOCK = re.compile(r"Removing unreachable block \(\w+,0x([0-9a-fA-F]+)\)")


# step 1


def find_opaque_globals():
    opaque = []
    for sym in currentProgram.getSymbolTable().getAllSymbols(True):
        if not OPAQUE_NAME.match(sym.getName()):
            continue  # not named x, y, x.1, y.2, ...
        if not sym.getAddress().isMemoryAddress():
            continue  # e.g. a local variable named x (stack/register, not a global)
        opaque.append(sym)
    return opaque


def mark_constant(sym):
    addr = sym.getAddress()

    # Ghidra models .bss as uninitialized and the decompiler will not
    # read a value from it. We 0 fill it like the loader does at runtime.
    block = getMemoryBlock(addr)
    if not block.isInitialized():
        currentProgram.getMemory().convertToInitialized(block, 0)

    # mark x/y constant (Ghidra defines them as undefined4)
    Mutability.DEF.setChoice(getDataAt(addr), Mutability.CONSTANT)
    print("%-4s @ %s" % (sym.getName(), addr))


# step 2


def dead_blocks(func):
    decomp = FlatDecompilerAPI(FlatProgramAPI(currentProgram, monitor))
    # Without an options object the decompiler might leave out the
    # "Removing unreachable block" warnings.
    decomp.initialize()
    opts = DecompileOptions()
    opts.grabFromProgram(currentProgram)
    # the warning comments are on by default (uncomment if they are missing)
    # opts.setHeadCommentIncluded(True)
    # opts.setWARNCommentIncluded(True)
    decomp.getDecompiler().setOptions(opts)

    try:
        c_code = decomp.decompile(func, 60)  # 60 s timeout
    finally:
        decomp.dispose()
    # /* WARNING: Removing unreachable block (ram,0x00110968) */
    dead = set()
    for hex_addr in DEAD_BLOCK.findall(c_code):
        dead.add(int(hex_addr, 16))  # "00110810" -> 0x110810
    return dead


def patch_branches(func, dead):
    asm = Assemblers.getAssembler(currentProgram)
    # collect conditional jumps (tbz, cbz, b.gt, ...)
    # skip plain b, bl, ret
    branches = []
    for insn in currentProgram.getListing().getInstructions(func.getBody(), True):
        flow = insn.getFlowType()
        if flow.isConditional() and flow.isJump():
            branches.append(insn)

    patched = 0
    for insn in branches:
        addr = insn.getAddress()
        target = insn.getFlows()[0].getOffset()  # jump target
        fall = insn.getFallThrough().getOffset()  # fallthrough target

        if fall in dead and target not in dead:
            # The fallthrough is never taken -> it always jumps.
            #   0x1107f8  ldr   w8,[x22]          ; w8 = x
            #   0x1107fc  adrp  x23,0x120000
            #   0x110800  ldr   x23,[x23,#->y]    ; x23 = &y
            #   0x110804  sub   w9,w8,#1          ; w9 = x - 1
            #   0x110808  mul   w8,w8,w9          ; w8 = x * (x - 1)
            #   0x11080c  tbz   w8,#0,0x11081c    ; bit 0 is 0 (even) -> always jumps
            #   0x110810  ldr   w8,[x23]          ; dead
            #   0x110814  cmp   w8,#9             ; dead
            #   0x110818  b.gt  0x1107f8          ; dead
            #   0x11081c  cmp   w21,#2            ; jump target
            # becomes
            #   0x11080c  b     0x11081c
            asm.assemble(addr, "b 0x%x" % target)
        elif target in dead and fall not in dead:
            # The jump is never taken -> it always falls through.
            #   0x11096c  cset  w8,lt             ; w8 = predicate = 1 (always)
            #   ...
            #   0x110998  cbz   w8,0x1109c8       ; w8 == 0? never -> never jumps
            #   0x11099c  mov   w0,w19            ; live
            #   0x1109a0  mov   w1,w21            ; live
            #   0x1109a4  bl    mix               ; live
            # becomes
            #   0x110998  nop
            asm.assemble(addr, "nop")
        else:
            # Both paths live.
            # Both paths dead.
            continue
        patched += 1

    # Recompute the function from its entry point. Dead blocks are dropped.
    CreateFunctionCmd.fixupFunctionBody(currentProgram, func, monitor)
    print("%s: patched %d opaque branch(es)" % (func.getName(), patched))


def main():
    opaque = find_opaque_globals()
    if not opaque:
        print("No x, y globals found.")
        return
    for sym in opaque:
        mark_constant(sym)

    func = getFunctionContaining(currentAddress)
    if func is None:
        print("Move the cursor in the target function.")
        return

    dead = dead_blocks(func)
    if not dead:
        print("%s: no unreachable blocks found" % func.getName())
        return

    patch_branches(func, dead)


main()
#include <stdio.h>
#include <stdlib.h>

__attribute__((noinline)) static int mix(int a, int b) {
  int r = 0;
  for (int i = 0; i < b; i++) {
    if (i & 1)
      r += a ^ i;
    else
      r -= a & i;
  }
  return r;
}

int main(int argc, char **argv) {
  int a = argc > 1 ? atoi(argv[1]) : 7;
  int b = argc > 2 ? atoi(argv[2]) : 3;
  int r;

  if (a > b)
    r = a - b;
  else
    r = mix(a, b);

  printf("r=%d\n", r);
  return 0;
}
#!/usr/bin/env bash
set -euo pipefail

LLVM=/opt/llvm/bin
PLUGIN=$HOME/git-repos/obfuscator-llvm/build/libLLVMObfuscator.so
SYSROOT=/opt/a64
T="--target=aarch64-linux-gnu --sysroot=$SYSROOT"

SRC=test_bcf.c
OUT=test_bcf_a64

export LLVM_OBF_SEED=0xA04252B187478C00A40BC6D81D1A8A52

$LLVM/clang $T -O1 -fPIC -S -emit-llvm $SRC -o ${OUT}.ll
$LLVM/llc -filetype=obj ${OUT}.ll -o ${OUT}.o
$LLVM/clang $T -fuse-ld=lld ${OUT}.o -o ${OUT}

$LLVM/opt -load "$PLUGIN" -load-pass-plugin "$PLUGIN" \
	-bcf_prob=100 -bcf_loop=1 \
	-passes='function(bogus)' -S ${OUT}.ll -o ${OUT}_obf.ll

$LLVM/llc -filetype=obj ${OUT}_obf.ll -o ${OUT}_obf.o
$LLVM/clang $T -fuse-ld=lld ${OUT}_obf.o -o ${OUT}_obf

echo "opaque globals in IR:"
grep -E '^@(x|y)(\.[0-9]+)? ' ${OUT}_obf.ll || true

$LLVM/clang $T -shared -fuse-ld=lld ${OUT}_obf.o -o lib${OUT}_obf.so

Before:

undefined8 main(int param_1,long param_2)

{
  int iVar1;
  int iVar2;
  int param1;
  long lVar3;
  
  do {
    if ((x * (x + -1) & 1U) == 0) break;
  } while (9 < y);
  if (param_1 < 2) {
    iVar1 = 7;
  }
  else {
    if (((x * (x + -1) & 1U) != 0) && (9 < y)) goto LAB_0011087c;
    while( true ) {
      lVar3 = strtol(*(char **)(param_2 + 8),(char **)0x0,10);
      iVar1 = (int)lVar3;
      if (((x * (x + -1) & 1U) == 0) || (y < 10)) break;
LAB_0011087c:
      strtol(*(char **)(param_2 + 8),(char **)0x0,10);
    }
  }
  do {
    if ((x * (x + -1) & 1U) == 0) break;
  } while (9 < y);
  if (param_1 < 3) {
    iVar2 = 3;
  }
  else {
    if (((x * (x + -1) & 1U) != 0) && (9 < y)) goto LAB_00110918;
    while( true ) {
      lVar3 = strtol(*(char **)(param_2 + 0x10),(char **)0x0,10);
      iVar2 = (int)lVar3;
      if (((x * (x + -1) & 1U) == 0) || (y < 10)) break;
LAB_00110918:
      strtol(*(char **)(param_2 + 0x10),(char **)0x0,10);
    }
  }
  do {
    if ((x * (x + -1) & 1U) == 0) break;
  } while (9 < y);
  param1 = iVar1 - iVar2;
  if (param1 == 0 || iVar1 < iVar2) {
    if ((x * (x + -1) & 1U) != 0 && 9 < y) goto LAB_001109c8;
    while ((param1 = mix(iVar1,iVar2), (x * (x + -1) & 1U) != 0 && (9 < y))) {
LAB_001109c8:
      mix(iVar1,iVar2);
    }
  }
  else {
    do {
      if ((x * (x + -1) & 1U) == 0) break;
    } while (9 < y);
  }
  if (((x * (x + -1) & 1U) != 0) && (9 < y)) goto code_r0x00110a24;
  while ((printf("r=%d\n",param1), (x * (x + -1) & 1U) != 0 && (9 < y))) {
code_r0x00110a24:
    printf("r=%d\n",param1);
  }
  return 0;
}

After:

/* WARNING: Removing unreachable block (ram,0x00110968) */

undefined8 main(int param_1,long param_2)

{
  int iVar1;
  int iVar2;
  int param1;
  long lVar3;
  
  if (param_1 < 2) {
    iVar1 = 7;
  }
  else {
    lVar3 = strtol(*(char **)(param_2 + 8),(char **)0x0,10);
    iVar1 = (int)lVar3;
  }
  if (param_1 < 3) {
    iVar2 = 3;
  }
  else {
    lVar3 = strtol(*(char **)(param_2 + 0x10),(char **)0x0,10);
    iVar2 = (int)lVar3;
  }
  param1 = iVar1 - iVar2;
  if (param1 == 0 || iVar1 < iVar2) {
    param1 = mix(1,iVar1,iVar2);
  }
  printf("r=%d\n",param1);
  return 0;
}