Usando angr para descifrar binarios

angr is a powerful Python platform for analyzing binaries, combining decompilation, symbolic execution, and more into one scriptable toolkit.

Antes de usarlo vamos a mencionar algunas conceptos básicos sobre un tipo de software llamada "Satisfiability Modulo Theory" solvers. Son programados o librerías de funciones que ayudan a determinar si un conjunto de formulas lógicas son satisfacibles bajo teoría matemáticas específicas (e.g. la teoría de los números enteros, la teoría de como se comportan los registros)

Ejemplo obvio y de juguete: Imagina que te piden que resulvas para que si existen al menos dos enteros $x$$ y $y$ tal que: $x+y == 10$, $x > 2$ y $y > 5$. Una de las librerías más utilizadas para tales propositos es z3.

Z3 is an open-source Satisfiability Modulo Theories (SMT) solver and theorem prover developed by Microsoft Research. Unlike standard SAT solvers that work only with Boolean variables, Z3 checks the satisfiability of logical formulas over rich background theories.

from z3 import Int, Solver, sat, unsat, unknown

# 1. Define the unknown variables (Integers)
x = Int('x')
y = Int('y')

# 2. Create a solver instance
s = Solver()

# 3. Add the rules (constraints)
s.add(x + y == 10)
s.add(x > 2)
s.add(y > 5)

# 4. Ask Z3 if a solution exists ('sat' = satisfiable)
result = s.check() 
if (result == sat):
    print("Can satisfy those constraints")
    print(s.model())
else:
    print("Cannot satisfy those constraints")

Resulta en:

Can satisfy those constraints
[y = 6, x = 4]

Si las condiciones no son satisfacibles el SAT solver te lo indicará:

from z3 import Int, Solver, sat, unsat, unknown

# 1. Define the unknown variables (Integers)
x = Int('x')
y = Int('y')

# 2. Create a solver instance
s = Solver()

# 3. Add the rules (constraints)
s.add(x + y == 10)
s.add(x > 2)
s.add(y > 9)

# 4. Ask Z3 if a solution exists ('sat' = satisfiable)
result = s.check() 
if (result == sat):
    print("Can satisfy those constraints")
    print(s.model())
else:
    print("Cannot satisfy those constraints")
Cannot satisfy those constraints

Z3 también puede determinar satisfiability sobre variables que se comporten como registros. En este ejemplo, un registro de 8 bits. Nos interesa saber que valor debe tener un registro de 8 bits llamado $secret$ talque (secret ^ 0x55 + 10) == 100.

from z3 import *

# 1. Define an 8-bit BitVector variable (values 0 to 255)
secret = BitVec('secret', 8)

# 2. Create a solver instance
s = Solver()

# 3. Add the bitwise constraint
# In Python, '^' is bitwise XOR
s.add((secret ^ 0x55) + 10 == 100)

# 4. Solve and print the result
if s.check() == sat:
    model = s.model()
    ans = model[secret].as_long()
    print(f"Found secret: {ans} (Hex: {hex(ans)})")
Found secret: 15 (Hex: 0xf)

Remontándonos al principio del semestre habíamos analizado programas como este:

int main() {
    char buf[256];
    unsigned int hash = 0;
    unsigned char nib;
    int n;

    printf("Enter passphrase: ");
    scanf("%s", buf);

    n = strlen(buf);
    for (int i = n - 1; i >= 0; i--) {
        nib = buf[i] & 0xF;
        hash = (hash << 4) ^ nib;
    }

    hash ^= 0xFFFFFFFF;

    if (hash == 0xC001C0DE)
        printf("Access granted!\n");
    else
        printf("Access denied.\n");

    return 0;
}

Si conviertes la lógica del programa a expresiones como las que acepta Z3.

from z3 import BitVec, BitVecVal, Solver, ZeroExt, sat

# 0xC001C0DE has 8 hex digits (32 bits), and each character contributes 4 bits (one nibble)
LENGTH = 8
buf = [BitVec(f'buf_{i}', 8) for i in range(LENGTH)]

s = Solver()

# Constrain characters to printable ASCII (0x21 '!' to 0x7E '~', avoiding whitespace for scanf("%s"))
for c in buf:
    s.add(c >= 0x21, c <= 0x7E)

# Replicate the C loop: iterate backwards from n - 1 down to 0
hash_val = BitVecVal(0, 32)
for i in range(LENGTH - 1, -1, -1):
    # nib = buf[i] & 0xF (zero-extended from 8-bit to 32-bit for bitvector operations)
    nib = ZeroExt(24, buf[i] & 0x0F)
    hash_val = (hash_val << 4) ^ nib

# Final XOR operation
hash_val = hash_val ^ 0xFFFFFFFF

# Target hash check
s.add(hash_val == 0xC001C0DE)

if s.check() == sat:
    m = s.model()
    passphrase = "".join(chr(m[c].as_long()) for c in buf)
    print(f"Passphrase found: {passphrase}")
else:
    print("No solution found.")

Passphrase found: !"/#.//#

Finalmente angr

angr is an open-source, multi-architecture binary analysis framework written in Python that combines static and dynamic symbolic execution.

Dado un binario angr lo analiza y es capaz no solo de mostrarnos su metadata tal como secciones, entry point, etc.. (todo lo que puede hacer readelf) si no que es capaz de desensamblarlo, descompilarlo y simular su ejecución de forma simbólica, lo cual permite que durante ella se puedan capturar las restricciones que guian el programa en una u otra ruta, para luego resolver cual es el input que las llevará en la ruta que deseemos.

Vamos a tratar de poner a funcionar esa librería en oscar....

pyenv is a free, open-source command-line tool that lets you easily install, uninstall, and switch between multiple versions of Python on a single machine

Instalar pyenv

curl -fsSL https://pyenv.run | bash

Este comando instala localmente la versión 3.12.9 de python

pyenv install 3.12.9

Este comando la activa para la sesión corriente.

pyenv shell 3.12.9

Instala angr y ipython

pip install angr ipython

Basic Blocks

Cuando angr analiza un binario, separa el assembly en basic blocks: secuencias de instrucciones corridas que tienen un solo punto de entrada en el tope del bloque y un salida al final del bloque. No hay jumps a la mitad del bloque ni brincos desde el bloque, excepto al final.

Por ejemplo, un código como el siguiente....

0x401130:  mov    eax, DWORD PTR [rbp-0x4]   ; load x
0x401133:  cmp    eax, 0xa                   ; compare x with 10
0x401136:  jle    0x401142                   ; EXIT: branch if x <= 10 (ends block)
0x401138:  mov    eax, DWORD PTR [rbp-0x4]   ; load x
0x40113b:  add    eax, 0x1                   ; x + 1
0x40113e:  mov    DWORD PTR [rbp-0x8], eax   ; y = x + 1 (falls through to 0x401142)
0x401142:  mov    eax, 0x0                   ; return 0
0x401147:  ret                               ; EXIT: return

quedaría convertido en tres basic blocks:

; --- Basic Block A (Entry: 0x401130) ---
0x401130:  mov    eax, DWORD PTR [rbp-0x4]   ; load x
0x401133:  cmp    eax, 0xa                   ; compare x with 10
0x401136:  jle    0x401142                   ; EXIT: branch if x <= 10 (ends block)

; --- Basic Block B (Entry: 0x401138) ---
0x401138:  mov    eax, DWORD PTR [rbp-0x4]   ; load x
0x40113b:  add    eax, 0x1                   ; x + 1
0x40113e:  mov    DWORD PTR [rbp-0x8], eax   ; y = x + 1 (falls through to 0x401142)

; --- Basic Block C (Entry: 0x401142) ---
0x401142:  mov    eax, 0x0                   ; return 0
0x401147:  ret                               ; EXIT: return

Descarga el primer ejemplo de aquí: https://ccom.uprrp.edu/~rarce/stage1

El código básico para que angr analice un binario en búsqueda de las condiciones que hacen que el código llegue a un bloque GRANTED, evitando blockes DENIED es el siguiente:

import sys
import angr
claripy = angr.claripy

BIN = "./stage1"
DENIED = [___, ____]   
GRANTED  = ________  

proj = angr.Project(BIN, auto_load_libs=True)

# Aquí creamos una variable simbólica de 10 caracteres
pw = claripy.BVS("password", 10 * 8)
state = proj.factory.entry_state(args=[BIN, pw])

# Solo por mostrar el basic block del entry point
state.block().pp()

# Para cada uno de caracteres de password, restringir a symbolos 
# visibles 
for i in range(10):
    b = pw.get_byte(i)
    state.solver.add(b >= 0x20, b <= 0x7E)

# Creamos un objeto de clase simulation manager ... 
simgr = proj.factory.simulation_manager(state)
# ... y le indicamos que simule explore el programa en busca 
# de los bloques GRANTED y evitando bloques DENIED
simgr.explore(find=GRANTED, avoid=DENIED)


# Si no es exitoso, no hay nada que hacer
if not simgr.found:
    print("No path to 'Access granted' found")
    sys.exit(1)

# Si encontró el bloque, entonces podemos correr el SMT solver
# para que encuentre la solución (si las restricciones son satisfacibles)
found = simgr.found[0]
solution = found.solver.eval(pw, cast_to=bytes)
print("Password:", solution.decode())

Para que el script de python funcione, primero debemos localizar la dirección del bloque al que deseamos llegar y los que deseamos evitar.

Partes importantes de angr:

Continuemos analizando:

Apendice

import sys
import angr
claripy = angr.claripy

BIN = "./stage1"
DENIED = [___, ____]   
GRANTED = ________  

proj = angr.Project(BIN, auto_load_libs=True)

# Create a 10-byte symbolic variable for the password
pw = claripy.BVS("password", 10 * 8)

# Append a newline so scanf knows where the input ends
stdin_input = claripy.Concat(pw, claripy.BVV(b"\n"))

# Pass the symbolic input to stdin instead of args
state = proj.factory.entry_state(stdin=stdin_input)

# Display the entry point basic block
state.block().pp()

# Constrain each byte of the password to printable ASCII characters
for i in range(10):
    b = pw.get_byte(i)
    state.solver.add(b >= 0x20, b <= 0x7E)

# Create the simulation manager and explore
simgr = proj.factory.simulation_manager(state)
simgr.explore(find=GRANTED, avoid=DENIED)

if not simgr.found:
    print("No path to 'Access granted' found")
    sys.exit(1)

# Evaluate the symbolic password variable (excluding the appended newline)
found = simgr.found[0]
solution = found.solver.eval(pw, cast_to=bytes)
print("Password:", solution.decode())