Saltar a contenido

Radare2 - Marco de ingeniería inversa

"Clase de la hoja"

########################################################################################################################################################################################################################################################## Copiar todos los comandos
########################################################################################################################################################################################################################################################## Generar PDF seleccionado/button

■/div titulada

Radare2 es uno de los marcos de ingeniería inversa de código abierto más potentes y versátiles disponibles hoy, lo que representa un cambio de paradigma completo en cómo investigadores de seguridad, analistas de malware y desarrolladores de software abordan el análisis binario. A diferencia de los desmontadores basados en GUI tradicionales, Radare2 abraza una filosofía de interfaz de línea de comandos que prioriza la automatización, la scriptabilidad y las capacidades de personalización profundas. Este marco integral proporciona un amplio conjunto de herramientas para el desmontaje, depuración, análisis binario, forenses y desarrollo de la explotación, todo unificado bajo una estructura de mando consistente y poderosa. Lo que hace que Radare2 particularmente convincente es su arquitectura modular que permite a los usuarios combinar diferentes técnicas de análisis sin problemas, desde el desmontaje estático y la depuración dinámica hasta el desprecio binario y el desarrollo de explotación. El compromiso del marco con los principios de código abierto, junto con su amplio ecosistema de plugins y el desarrollo comunitario activo, lo ha establecido como una herramienta esencial para los profesionales de seguridad que requieren tanto profundidad como flexibilidad en sus flujos de trabajo de análisis.

Instalación y configuración

Instalación Cross-Platform

# Ubuntu/Debian Installation
sudo apt update
sudo apt install radare2

# Alternative: Install latest version from source
git clone https://github.com/radareorg/radare2
cd radare2
sys/install.sh

# macOS Installation via Homebrew
brew install radare2

# Windows Installation
# Download from https://github.com/radareorg/radare2/releases
# Or use package managers:
# Chocolatey: choco install radare2
# Scoop: scoop install radare2

# Arch Linux Installation
sudo pacman -S radare2

# CentOS/RHEL/Fedora Installation
sudo dnf install radare2
# or
sudo yum install radare2

# Build from Source (Latest Features)
git clone https://github.com/radareorg/radare2
cd radare2
./configure --prefix=/usr/local
make -j$(nproc)
sudo make install

# Verify Installation
r2 -v
radare2 -v

# Update Radare2
r2pm update
r2pm upgrade

# Install Additional Packages
r2pm -i r2dec          # Decompiler plugin
r2pm -i r2ghidra       # Ghidra decompiler integration
r2pm -i r2frida        # Frida integration
r2pm -i r2pipe         # Programming language bindings

Configuración de configuración y entorno

# Radare2 Configuration Directory
# Linux/macOS: ~/.config/radare2/
# Windows: %APPDATA%\radare2\

# Main Configuration File
~/.config/radare2/radare2rc

# Basic Configuration Options
echo 'e scr.color=3' >> ~/.config/radare2/radare2rc      # Enable colors
echo 'e asm.syntax=intel' >> ~/.config/radare2/radare2rc # Intel syntax
echo 'e asm.describe=true' >> ~/.config/radare2/radare2rc # Show descriptions
echo 'e bin.strings=true' >> ~/.config/radare2/radare2rc  # Auto-detect strings

# Environment Variables
export R2_NOPLUGINS=0          # Enable plugins
export R2_DEBUG=0              # Disable debug output
export R2_MAGICPATH=/usr/share/radare2/magic

# Plugin Management
r2pm init                      # Initialize package manager
r2pm update                    # Update package database
r2pm list                      # List available packages
r2pm search keyword            # Search for packages
r2pm install package_name      # Install package
r2pm uninstall package_name    # Remove package

# Essential Plugins
r2pm -i r2dec                  # Decompiler
r2pm -i r2ghidra-dec          # Ghidra decompiler
r2pm -i r2pipe-py             # Python bindings
r2pm -i r2pipe-js             # JavaScript bindings
r2pm -i r2frida               # Dynamic instrumentation
r2pm -i r2yara                # YARA integration

# Custom Plugin Directory
mkdir -p ~/.config/radare2/plugins
export R2_USER_PLUGINS=~/.config/radare2/plugins

Radare2 básico Usage

Cargando y análisis inicial

# Basic File Loading
r2 /path/to/binary             # Load binary for analysis
r2 -A /path/to/binary          # Load with automatic analysis
r2 -AA /path/to/binary         # Load with extended analysis
r2 -AAA /path/to/binary        # Load with experimental analysis

# Loading Options
r2 -d /path/to/binary          # Load in debug mode
r2 -w /path/to/binary          # Load in write mode
r2 -n /path/to/binary          # Load without parsing headers
r2 -B 0x1000 /path/to/binary   # Set base address

# Remote Analysis
r2 -                           # Read from stdin
r2 http://example.com/file     # Load from URL
r2 rap://host:port/file        # Remote access protocol

# Multiple File Analysis
r2 -m 0x400000 file1 file2     # Load multiple files

# Project Management
Ps project_name                # Save current session as project
Po project_name                # Open existing project
Pd project_name                # Delete project
Pl                             # List projects

# Session Management
. script.r2                    # Execute r2 script
q                              # Quit radare2
q!                             # Force quit without saving
# Basic Navigation
s address                      # Seek to address
s+10                          # Seek forward 10 bytes
s-10                          # Seek backward 10 bytes
s++                           # Seek to next function
s--                           # Seek to previous function

# Address Formats
s 0x401000                    # Hexadecimal address
s main                        # Symbol name
s entry0                      # Entry point
s +100                        # Relative offset

# Information Commands
i                             # File information
ii                            # Imports
iE                            # Exports
iz                            # Strings
iS                            # Sections
ih                            # Headers
ic                            # Classes (for OOP binaries)

# Binary Information
ib                            # Basic file info
iI                            # Binary info
iH                            # Headers
iM                            # Main function
ie                            # Entry points
ir                            # Relocations

# Architecture Information
iA                            # Architecture info
e asm.arch                    # Current architecture
e asm.bits                    # Current bit mode
e asm.cpu                     # CPU type

# Memory Layout
dm                            # Memory maps
dmi                           # Memory map info
dmh                           # Heap info
dms                           # Stack info

Desmontaje y análisis del código

# Basic Disassembly
pd                            # Print disassembly
pd 10                         # Print 10 instructions
pd @main                      # Print disassembly at main
pD 100                        # Print 100 bytes as disassembly

# Disassembly Modes
pda                           # Print disassembly with addresses
pdb                           # Print disassembly with bytes
pdc                           # Print disassembly with comments
pdi                           # Print disassembly with inline comments
pdj                           # Print disassembly as JSON

# Function Analysis
afl                           # List all functions
afi                           # Function information
afn new_name                  # Rename function
afc                           # Function calling convention
afv                           # Function variables
afa                           # Function arguments

# Code Analysis
aa                            # Analyze all
aaa                           # Analyze all (experimental)
aab                           # Analyze basic blocks
aac                           # Analyze function calls
aad                           # Analyze data references
aan                           # Analyze function names

# Cross-References
axt                           # Cross-references to
axf                           # Cross-references from
ax                            # List all cross-references
axg                           # Cross-reference graph

# Control Flow Analysis
agf                           # Function call graph
agc                           # Function call graph (compact)
agg                           # Global call graph
VV                            # Visual graph mode

Características del análisis avanzado

Análisis de funciones y manipulación

# Function Creation and Management
af                            # Analyze function at current address
af @address                   # Analyze function at specific address
af- @address                  # Delete function at address
afr new_name @address         # Rename function

# Function Signatures
afs signature                 # Set function signature
afs int main(int argc, char **argv)  # Example signature
afts                          # Show function signature

# Function Variables and Arguments
afv                           # List function variables
afvn old_name new_name        # Rename variable
afvt var_name type            # Set variable type
afva addr name type           # Add function argument

# Function Calling Conventions
afc                           # Show calling convention
afc cdecl                     # Set calling convention
afc stdcall                   # Windows standard call
afc fastcall                  # Fast calling convention

# Function Analysis Options
e anal.calls=true             # Analyze function calls
e anal.jmp.tbl=true          # Analyze jump tables
e anal.pushret=true          # Analyze push/ret sequences
e anal.hasnext=true          # Analyze function continuations

# Advanced Function Analysis
aab                           # Analyze basic blocks
aae                           # Analyze ESIL expressions
aai                           # Analyze imports
aar                           # Analyze references
aas                           # Analyze symbols
aat                           # Analyze types

# Function Diffing
cc                            # Compare functions
ccc                           # Compare code
ccf                           # Compare functions

Análisis de datos y estructuras

# Data Type Analysis
t                             # List types
t-                            # Remove type
tk                            # List type kinds
tl                            # List type links

# Structure Definition
ts struct_name                # Define structure
ts- struct_name               # Remove structure
ts struct_name field_type field_name  # Add field to structure

# Example Structure Definition
ts Person
ts Person int age
ts Person char name[32]
ts Person float height

# Apply Structure to Data
tss struct_name @address      # Apply structure at address
Ct struct_name @address       # Cast to structure type

# Array Analysis
ta array_name type size       # Define array type
ta int_array int 10           # Array of 10 integers

# Enum Definition
te enum_name                  # Define enumeration
te Colors RED=1 GREEN=2 BLUE=3

# String Analysis
iz                            # List strings
izz                           # List all strings (including data)
izzz                          # Deep string search
iz~keyword                    # Filter strings by keyword

# String Operations
ps @address                   # Print string at address
psz @address                  # Print zero-terminated string
psu @address                  # Print UTF-16 string
psw @address                  # Print wide string

# Data Visualization
px 100                        # Print 100 bytes as hex
pxw 20                        # Print as 32-bit words
pxq 10                        # Print as 64-bit words
pf format @address            # Print formatted data

Memoria y análisis binario

# Memory Operations
dm                            # List memory maps
dmi                           # Memory map information
dmm                           # Memory map with permissions
dmp                           # Memory protection

# Memory Search
/ pattern                     # Search for pattern
/x 41424344                   # Search for hex bytes
/i pattern                    # Case-insensitive search
// pattern                    # Repeat last search

# Advanced Search
/R                            # Search for ROP gadgets
/a                            # Search for AES keys
/c                            # Search for crypto constants
/r                            # Search for references

# Binary Operations
p8 100                        # Print 100 bytes as raw
pb 100                        # Print 100 bytes as binary
pc 100                        # Print 100 bytes as C array
pj 100                        # Print 100 bytes as JSON

# Binary Modification
w hello                       # Write string
wx 41424344                   # Write hex bytes
wa "mov eax, 1"              # Write assembly
wf file.bin                   # Write file contents

# Binary Comparison
c                             # Compare
cc                            # Compare code
cd                            # Compare data
cg                            # Compare graphs

# Entropy Analysis
p=e 1000                      # Show entropy graph
phe                           # Print entropy histogram

Depuración y análisis dinámico

Operaciones de Modo de Debug

# Starting Debug Session
r2 -d /path/to/binary         # Load in debug mode
r2 -d -A /path/to/binary      # Load with analysis in debug mode

# Process Attachment
r2 -d pid://1234              # Attach to process ID
r2 -d gdb://localhost:1234    # Connect to GDB server

# Debug Information
dp                            # List processes
dpt                           # List threads
dpr                           # Show registers
drr                           # Show register references

# Execution Control
dc                            # Continue execution
ds                            # Step one instruction
dso                           # Step over
dsu address                   # Step until address
dt                            # Trace execution

# Breakpoints
db address                    # Set breakpoint
db- address                   # Remove breakpoint
dbc address                   # Set conditional breakpoint
dbt                           # Backtrace
dbl                           # List breakpoints

# Memory Breakpoints
dbh address                   # Hardware breakpoint
dbw address                   # Write breakpoint
dbr address                   # Read breakpoint

# Watchpoints
dw address                    # Set watchpoint
dw- address                   # Remove watchpoint
dwl                           # List watchpoints

# Register Manipulation
dr                            # Show all registers
dr eax                        # Show specific register
dr eax=0x1234                 # Set register value
drt                           # Show register types

Características avanzadas de depuración

# Memory Analysis During Debug
dm                            # Memory maps
dmi                           # Memory info
dmh                           # Heap analysis
dms                           # Stack analysis

# Dynamic Memory Operations
dma address size              # Allocate memory
dmf                           # Free memory
dmd address                   # Dump memory

# Tracing and Logging
dt                            # Trace execution
dtl                           # Trace with logging
dts                           # Trace syscalls
dte                           # Trace events

# Advanced Tracing
e dbg.trace=true              # Enable tracing
e dbg.trace.tag=1             # Tag traced instructions
dtt                           # Trace to file

# Signal Handling
dk                            # Send signal
dk 9                          # Send SIGKILL
dko                           # Signal handling options

# Process Information
dpl                           # List loaded libraries
dpj                           # Process info as JSON
dpp                           # Process permissions

# Remote Debugging
r2 -d rap://host:port         # Remote debugging
=!rarun2                      # Use rarun2 for debugging

ESIL (Evaluable Strings Intermediate Language)

# ESIL Introduction
# ESIL is Radare2's intermediate language for emulation
# Allows platform-independent analysis and emulation

# ESIL Operations
aei                           # Initialize ESIL VM
aeim                          # Initialize ESIL memory
aeip                          # Initialize ESIL stack

# ESIL Execution
aes                           # Step one ESIL instruction
aeso                          # Step over ESIL instruction
aesu address                  # Step until address
aec                           # Continue ESIL execution

# ESIL State
aer                           # Show ESIL registers
aer reg=value                 # Set ESIL register
aets                          # Show ESIL stack
aem                           # Show ESIL memory

# ESIL Analysis
aea                           # Analyze with ESIL
aef                           # Analyze function with ESIL
aeg                           # Generate ESIL graph

# ESIL Emulation
e asm.emu=true                # Enable emulation
e emu.str=true                # Emulate string operations
e emu.write=true              # Enable write emulation

# ESIL Debugging
aed                           # Debug ESIL
aedc                          # Continue ESIL debugging
aeds                          # Step ESIL debugging

Escritura y automatización

Interfaz de programación R2Pipe

# Python R2Pipe Example
import r2pipe

# Open binary
r2 = r2pipe.open("/path/to/binary")

# Execute commands
info = r2.cmd("i")
functions = r2.cmdj("aflj")  # JSON output
disasm = r2.cmd("pd 10")

# Analysis automation
r2.cmd("aaa")  # Analyze all
strings = r2.cmdj("izj")  # Get strings as JSON

# Function analysis
for func in functions:
    print(f"Function: \\\\{func['name']\\\\} at \\\\{hex(func['offset'])\\\\}")

# Search operations
xrefs = r2.cmdj("axtj @main")  # Cross-references to main

# Close session
r2.quit()

R2 Scripting Language

# R2 Script Basics (.r2 files)
# Comments start with #
# Commands are executed sequentially

# Example analysis script
#!/usr/bin/env r2 -i
# Auto-analysis script

# Load and analyze
aaa

# Find interesting functions
afl~main
afl~crypto
afl~password

# Search for strings
iz~password
iz~key
iz~secret

# Generate function graph
agf @main > main_graph.dot

# Export analysis
Ps analysis_project

Técnicas de escritura avanzada

# Conditional Execution
?e "Starting analysis"
? eax==0x1234; ?e "EAX is 0x1234"

# Loops and Iteration
# Iterate through functions
afl~[0]|while read addr; do
    echo "Analyzing function at $addr"
    s $addr
    pdf
done

# Macros
(macro_name arg1 arg2; command1; command2)
(analyze_func addr; s $addr; af; pdf)

# Variables
$var=value
?e $var

# Environment Variables
e var.name=value
?e $var.name

# Function Hooks
e cmd.hit=px 32              # Execute on breakpoint hit
e cmd.load=aaa               # Execute on file load

# Custom Commands
"(custom_cmd arg; echo Custom command with $arg)"

Plugin Development

// Basic R2 Plugin Structure (C)
#include <r_core.h>

static int r2_cmd_example(void *user, const char *input) \\\\{
    RCore *core = (RCore *)user;

    switch (*input) \\\\{
        case '?':
            r_cons_printf("Usage: example [args]\n");
            break;
        case ' ':
            // Handle arguments
            r_cons_printf("Example command executed\n");
            break;
        default:
            r_cons_printf("Unknown command\n");
            break;
    \\\\}

    return true;
\\\\}

RCorePlugin r_core_plugin_example = \\\\{
    .name = "example",
    .desc = "Example plugin",
    .license = "MIT",
    .call = r2_cmd_example,
\\\\};

#ifndef CORELIB
RLibStruct radare_plugin = \\\\{
    .type = R_LIB_TYPE_CORE,
    .data = &r_core_plugin_example,
    .version = R2_VERSION
\\\\};
#endif

Análisis de malware con Radare2

Análisis estadístico del malware

# Initial Triage
i                             # Basic file information
iI                            # Detailed binary info
ih                            # File headers
iS                            # Sections analysis
ie                            # Entry points

# Packer Detection
rabin2 -I /path/to/binary     # Binary information
rabin2 -S /path/to/binary     # Sections
rabin2 -z /path/to/binary     # Strings

# Entropy Analysis
p=e 1000                      # Entropy visualization
rahash2 -a entropy file       # Calculate entropy

# Import/Export Analysis
ii                            # Imports
iE                            # Exports
ir                            # Relocations

# String Analysis
iz                            # Strings in data sections
izz                           # All strings
izzz                          # Deep string search
iz~http                       # Filter HTTP-related strings
iz~password                   # Filter password-related strings

# Cryptographic Constants
/x 67452301                   # MD5 constants
/x 01234567                   # SHA constants
/x 61707865                   # "apxe" (expand 32-byte k)

# Suspicious API Detection
ii~CreateFile
ii~WriteFile
ii~RegOpenKey
ii~socket
ii~connect

Análisis dinámico de malware

# Safe Analysis Environment Setup
# Use isolated VM with network monitoring
# Snapshot VM before analysis

# Debug Mode Analysis
r2 -d /path/to/malware        # Load in debug mode
aaa                           # Analyze all

# API Monitoring
dcs                           # Syscall tracing
dt                            # Trace execution
dtl                           # Trace with logging

# Breakpoint Strategy
db sym.CreateFileA            # Break on file creation
db sym.RegOpenKeyA            # Break on registry access
db sym.socket                 # Break on network activity

# Memory Analysis
dm                            # Memory maps
dmi                           # Memory info
dmh                           # Heap analysis

# Network Behavior
# Monitor with external tools while debugging
# Wireshark, netstat, etc.

# Unpacking Analysis
# Set breakpoint at entry point
db entry0
dc                            # Continue to entry
# Step through unpacking routine
ds                            # Step instruction
# Look for jumps to unpacked code
# Dump unpacked code when found

Técnicas avanzadas de malware

# Anti-Analysis Detection
# Look for anti-debugging checks
/x 64A118000000              # PEB access (Windows)
/x 0F31                      # RDTSC instruction
ii~IsDebuggerPresent         # Debugger detection API

# Obfuscation Analysis
# Control flow obfuscation
agf                          # Function graph
VV                           # Visual graph mode

# String Obfuscation
# Look for string decryption routines
afl~decrypt
afl~decode
afl~xor

# Code Injection Detection
ii~VirtualAlloc
ii~VirtualProtect
ii~WriteProcessMemory
ii~CreateRemoteThread

# Persistence Mechanisms
iz~Run                       # Registry run keys
iz~Service                   # Windows services
iz~Task                      # Scheduled tasks

# Communication Analysis
iz~http
iz~tcp
iz~udp
ii~socket
ii~connect
ii~send
ii~recv

# Evasion Techniques
# VM detection
iz~VMware
iz~VirtualBox
iz~QEMU
iz~Xen

# Sandbox evasion
iz~sleep
iz~delay
ii~GetTickCount
ii~timeGetTime

Explotación binaria e ingeniería inversa

Análisis de vulnerabilidad

# Buffer Overflow Detection
# Look for dangerous functions
ii~strcpy
ii~strcat
ii~sprintf
ii~gets

# Format String Vulnerabilities
ii~printf
ii~sprintf
ii~fprintf
iz~%s
iz~%x
iz~%n

# Integer Overflow Detection
# Look for arithmetic operations
/x 01C0                      # add eax, eax
/x 29C0                      # sub eax, eax
/x F7E0                      # mul eax

# Use-After-Free Detection
ii~free
ii~malloc
ii~realloc

# Stack Analysis
afv                          # Function variables
afc                          # Calling convention
K                            # Show stack frame

# ROP Gadget Search
/R                           # Search ROP gadgets
/R pop                       # Search specific gadgets
/R ret                       # Search return gadgets

# Shellcode Analysis
# Look for shellcode patterns
/x 31C0                      # xor eax, eax
/x 50                        # push eax
/x 68                        # push immediate

Exploit Development

# Pattern Generation
ragg2 -P 100 -r             # Generate pattern
ragg2 -q 0x41414141          # Find pattern offset

# Address Calculation
? 0x401000+0x100            # Calculate addresses
? 0x7fff0000-0x7ffe0000     # Calculate offsets

# Shellcode Generation
ragg2 -a x86 -b 64 -i exec  # Generate shellcode
ragg2 -a x86 -b 32 -i connect # Network shellcode

# Binary Patching
wa "nop"                     # Write NOP instruction
wx 90                        # Write NOP byte
wa "jmp 0x401234"           # Write jump

# Exploit Testing
r2 -d ./vulnerable_app       # Debug target
dc                           # Continue execution
dr                           # Check registers after crash

# ASLR Bypass
dm                           # Check memory layout
dmi libc                     # Find libc base
? libc_base+system_offset    # Calculate system address

El conjunto completo de funciones de Radare2, la potente interfaz de línea de comandos y las amplias capacidades de automatización lo convierten en una herramienta indispensable para la ingeniería inversa moderna y el análisis de seguridad. Su naturaleza de código abierto, junto con el desarrollo comunitario activo y el amplio ecosistema de plugins, asegura que permanezca en el borde de vanguardia de la tecnología de análisis binario. Ya sea utilizado para análisis de malware, investigación de vulnerabilidad, desarrollo de explotación o tareas generales de ingeniería inversa, Radare2 proporciona la profundidad, flexibilidad y poder que los profesionales de seguridad requieren para su trabajo de análisis más difícil. El compromiso del marco con la scriptabilidad y automatización hace que sea particularmente valioso para los proyectos de análisis a gran escala e integración en los flujos de trabajo de seguridad, estableciendo que es una herramienta de piedra angular en el kit de herramientas del analista de seguridad moderno.