The Analysis (a) Module explores the contents of the binary. We use it to understand the contents of functions, function calls, cross-references, and more. This module drives our static analysis, which analyzes the binary without running it. We do this by looking at the assembly instructions, strings, and symbols.
We will collect the following information using this module:
This will be the heart of our disassembly process. We will use this information to understand the binary and the underlying source code.
If you don't use flags to open the file, you will need to tell radare2 to analyze the binary. There are multiple levels of analysis listed under the aa submodule:
aaa?Usage: aa[a[a[a]]] # automatically analyze the whole program| a show code analysis statistics| aa alias for 'af@@ sym.*;af@entry0;afva'| aaa perform deeper analysis, most common use| aaaa same as aaa but adds a bunch of experimental iterations| aaaaa refine the analysis to find more functions after aaaaIn almost all scenarios, aaa is more than plenty. By using the -A flag, aaa is automatically executed.
a?Usage: a [abdefFghoprxstc] [...]| a alias for aai - analysis information| a:[cmd] run a command implemented by an analysis plugin (like : for io)| a* same as afl*;ah*;ax*| aa[?] analyze all (fcns + bbs) (aa0 to avoid sub renaming)| a8 [hexpairs] analyze bytes| ab[?] analyze basic block| ac[?] manage classes| aC[?] analyze function call| ad[?] analyze data trampoline (wip) (see 'aod' to describe mnemonics)| ad [from] [to] analyze data pointers to (from-to)| ae[?] [expr] analyze opcode eval expression (see ao)| af[?] analyze functions| aF same as above, but using anal.depth=1| ag[?] [options] draw graphs in various formats| ah[?] analysis hints (force opcode size, ...)| ai [addr] address information (show perms, stack, heap, ...)| aj same as a* but in json (aflj)| aL[jq] list all asm/anal plugins (See `e asm.arch=?` and `La[jq]`)| an[?] [name] show/rename/create whatever var/flag/function used in current instruction| ao[?] [len] analyze Opcodes (or emulate it)| aO[?] [len] analyze N instructions in M bytes| ap find prelude for current offset| ar[?] like 'dr' but for the esil vm. (registers)| as[?] [num] analyze syscall using dbg.regaxt - Find X-Refs to a functionafx - Analyze X-Refs from a functionaxf - axff - Find X-Refs from a functionafxc 0x08049050 -> 0x0804c010 jmp dword [reloc.fflush]Use the afl command to list the available functions. The afll command provides the list of available commands in verbose mode.
afl0x08049040 1 6 sym.imp.__libc_start_main0x08049050 1 6 sym.imp.fflush0x08049060 1 6 sym.imp.gets0x08049070 1 6 sym.imp.puts0x08049080 1 6 sym.imp.system0x08049090 1 44 entry00x080490bd 1 4 fcn.080490bd0x080490f0 4 40 sym.deregister_tm_clones0x08049130 4 53 sym.register_tm_clones0x08049170 3 34 sym.__do_global_dtors_aux0x080491a0 1 6 sym.frame_dummy0x080490e0 1 4 sym.__x86.get_pc_thunk.bx0x08049258 1 24 sym._fini0x080491a6 4 73 sym.win0x080490d0 1 5 sym._dl_relocate_static_pie0x0804923c 1 24 main0x08049254 1 4 sym.__x86.get_pc_thunk.ax0x080491ef 1 77 sym.read_in0x08049000 3 36 sym._initYou can use the aflm command to list the commands based on the function they're called in.
aflmentry0: fcn.080490bd sym.imp.__libc_start_mainsym.__do_global_dtors_aux: sym.deregister_tm_clonessym._fini: sym.__x86.get_pc_thunk.bxsym.win: sym.__x86.get_pc_thunk.ax sym.imp.puts sym.imp.systemmain: sym.__x86.get_pc_thunk.ax sym.read_insym.read_in: sym.__x86.get_pc_thunk.bx sym.imp.puts sym.imp.fflush sym.imp.getssym._init: sym.__x86.get_pc_thunk.bxA calling convention is the agreement between a function and whoever calls it: where the arguments go, which register holds the return value, and who cleans up the stack afterward. radare2 uses the calling convention to decide which values are a function's arguments, so it's worth knowing which one it picked.
32-bit Linux binaries use cdecl. Arguments are pushed onto the stack from right to left, the return value comes back in eax, and the caller cleans up the arguments. Use afc to see the convention of the current function:
afccdeclUse afci to see where the return value and arguments live, and afcf to print the function's signature as radare2 understands it:
afci @ sym.wineax cdecl (stack);Here, radare2 tells us win returns its value in eax and receives its arguments on the stack, the first being arg_8h. More on that name in Listing Variables.
radare2 knows a handful of other conventions. Use afcl to list them:
afclborlandcdeclcdecl-fastcall-msdlangfastcalloptlinkpascalregstdcallwatcomYou will rarely need anything other than cdecl for 32-bit binaries and amd64 for 64-bit binaries, where the first six arguments are passed in rdi, rsi, rdx, rcx, r8, and r9. If a function was written by hand (or compiled for Windows), the arguments radare2 shows you might be wrong. In that case, set the convention yourself with afc <name>, for example afc stdcall.
afc?Usage: afc[afhijklor?] # see also tcc command to manage all calling conventions| afc ccname manually set calling convention for current function| afc show default function calling convention (same as tcc)| afcr[j] show register usage for the current function| afcf[j] [name] prints return type function(arg1, arg2...), see afij| afch[j] dyncc syntax help; resolve and inspect the current function's dyncc| afci [name] information about the current calling convention| afcj show current calling convention info in JSON| afck list SDB details of call loaded calling conventions| afcl list all available calling conventions| afcll show all call conventions and its definition| afco path open Calling Convention sdb profile from given path| afcR register telescoping using the calling conventions orderC++ classes complicate reverse engineering. When a class has virtual methods, the compiler doesn't call them directly. Instead, every class gets a virtual table (vtable), an array of pointers to its methods, and every object stores a pointer to its class's vtable. Calling a virtual method means loading that pointer, indexing into the table, and calling whatever address is there.
This means the disassembly shows an indirect call rather than a function name:
| :| 0x00401211 ffd2 call rdxWithout the vtables, we can't tell which function this calls. The av submodule finds them for us. For this example, we use a small (64-bit) C++ program with a Shape class and two subclasses, Square and Rectangle, that each override area().
Use av to search the data sections for vtables:
avVtable Found at 0x00403d400x00403d40 : sym.Rectangle::_Rectangle____10x00403d48 : method.Rectangle._Rectangle__0x00403d50 : method.Rectangle.area__Vtable Found at 0x00403d680x00403d68 : sym.Square::_Square____10x00403d70 : method.Square._Square__0x00403d78 : method.Square.area__Vtable Found at 0x00403d900x00403d90 : method.Shape._Shape__0x00403d98 : sym.Shape::_Shape____10x00403da0 : method.Shape.area__Each class has its own table, and each area method sits in the same slot of its table. That's what makes the indirect call work: the program loads the slot, and the object decides which function is in it.
Compilers also store Run-Time Type Information (RTTI) next to each vtable, which includes the class's name and its parent. Use avra to parse it:
avraType Info at 0x00403da8: Type Info type: __si_class_type_info Belongs to class vtable: 0x00403d40 Reference to RTTI's type class: 0x00000000 Reference to type's name: 0x00402008 Type Name: Rectangle Name unique: true Reference to parent's type info: 0x00403dd8...Use avrr to turn the RTTI into classes, and then acl to list the class hierarchy:
avrraclRectangle: ShapeShapeSquare: Shape-fno-rtti still have vtables, but avra won't find names or parents for them. Stripped binaries also lose the method names, so the vtable entries show up as plain addresses.av?Usage: av[?jr*] C++ vtables and RTTI| av search for vtables in data sections and show results| avj like av, but as json| av* like av, but as r2 commands| avr[j@addr] try to parse RTTI at vtable addr (see anal.cxxabi)| avra[j] search for vtables and try to parse RTTI at each of them| avrr recover class info from all findable RTTI (see ac)| avrD [classname] demangle a class name from RTTIA system call is how a program asks the kernel to do something it can't do itself, like writing to the screen or opening a file. On 32-bit Linux, the program puts the syscall number in eax, the arguments in ebx, ecx, and edx, and runs int 0x80. On 64-bit Linux, the number goes in rax, the arguments in rdi, rsi, and rdx, and the instruction is syscall. We cover this in Syscalls and Interrupts.
Shellcode and hand-written assembly call the kernel directly, so finding and decoding syscalls is a big part of reversing them. For this example, we use a "Hello, World!" program written in Assembly:
1_start:
2 mov eax, 4 ; write
3 mov ebx, 1 ; stdout
4 mov ecx, msg
5Use /as to search the binary for every syscall instruction. radare2 names each one based on the value it finds in eax:
/as0x08049014 write0x0804901d exitUse asl to convert between syscall names and numbers. This is useful when you see a number in eax and want to know what it means, or vice versa:
asl 4writeUse as to show the current syscall along with its arguments. as reads the registers of the ESIL emulator (the ar registers), not the debugger, so we first emulate up to the syscall. aei initializes the emulator, aeim gives it a stack, aeip sets the instruction pointer to our seek address, and aesu emulates until the given address:
aeiaeimaeipaesu 0x08049014as4 = write (1, "Hello, World!..", 14)Now we know exactly what the program writes and where, without running it.
as while debugging returned -1 = unknown () even with the right number in eax. Emulating with aesu, as above, works every time.as?Usage: as[ljk?] syscall name <-> number utility| as show current syscall and arguments| as 4 show syscall 4 based on asm.os and current regs/mem| asc[a] 4 dump syscall info in .asm or .h| asj list of syscalls in JSON| asl list of syscalls by asm.os and asm.arch| asl close returns the syscall number for close| asl 4 returns the name of the syscall number 4| ask [query] perform syscall/ queriesUse afv to list a function's arguments and local variables. We'll look at read_in and win from our example binary:
afvvar int32_t var_4h @ ebp-0x4var char * s @ ebp-0x48Each line shows whether the entry is an argument (arg) or a local variable (var), its type, its name, and where it lives. The default names come from their offsets from ebp: var_4h sits at ebp-0x4. Arguments sit above ebp because the caller pushed them before the call. The saved base pointer is at ebp and the return address is at ebp+0x4, so the first argument lands at ebp+0x8, which is why win's argument is named arg_8h.
read_in called s?The variables are grouped by how they're accessed. afvb lists the ones relative to the base pointer (most variables in 32-bit binaries), afvs lists the ones relative to the stack pointer, and afvr lists the ones stored in registers (common in 64-bit binaries, where arguments arrive in registers).
Use afvx to see every instruction that reads (afvR) or writes (afvW) each variable:
afvxafvR s 0x804922a var_4h 0x8049237afvW s var_4hDefault names aren't very descriptive. Once you understand what a variable does, rename it with afvn <new_name> <old_name>. The new name shows up everywhere the variable is used, including the disassembly:
s sym.winafvn key arg_8hafvarg uint32_t key @ ebp+0x8var int32_t var_4h @ ebp-0x4afv?Usage: afv[rbs] Function variables manipulation| afv* output r2 command to add args/locals to flagspace| afv-([name]) remove all or given var| afv= list function variables and arguments with disasm refs| afva analyze function arguments/locals| afvb[?] manipulate bp based arguments/locals| afvd name output r2 command for displaying the value of args/locals in the debugger| afvf show BP relative stackframe variables| afvn [new_name] ([old_name]) rename argument/local| afvr[?] manipulate register based arguments| afvR [varname] list addresses where vars are accessed (READ)| afvs[?] manipulate sp based arguments/locals| afvt [name] ([type]) display or change type for given local variable/argument| afvW [varname] list addresses where vars are accessed (WRITE)| afvx show function variable xrefs (same as afvR+afvW)radare2 knows the signatures of hundreds of library functions. When a variable is passed to one of them, radare2 can work out the variable's type from that function's parameters. This is called type inferencing, and it's part of aaa (the aaft step).
We can see the difference by analyzing read_in with only aa, and then running the type-matching step ourselves:
afvvar int32_t var_4h @ ebp-0x4var int32_t var_48h @ ebp-0x48After aaft, the buffer at ebp-0x48 is a char * named s. radare2 saw it passed to gets, whose signature is char *gets(char *s), and gave the variable that parameter's type and name. The disassembly updates to match:
| 0x0804922a 8d45b8 lea eax, [var_48h]| 0x0804922e e81dfeffff call sym.imp.gets ; char *gets(char *s)Type inferencing only works when a variable meets a function radare2 knows. Use afvt to check a variable's type, or to set it yourself:
afvt schar *afvt var_4h intafvvar int var_4h @ ebp-0x4var char * s @ ebp-0x48Use afs to show or change the signature of the whole function:
s sym.winafsvoid sym.win (uint32_t arg_8h);"afs void win(int key)"afsvoid win (int key);radare2 treats the parentheses as part of its own syntax. Also note that afs changes the function's signature (and here, its name) but not the variables radare2 already found: afv still shows arg_8h. Use afvn to rename the variable as well.The type commands live in the t submodule. They let us define our own types, such as the structs a program uses, and apply them to data. This is how we make sense of memory that holds more than one value.
Use td to define a type from a C declaration. Like afs, wrap the whole command in quotes:
"td struct player { char name[64]; int score; };"Use ts to list the structs radare2 knows about, and tv to view one with the offset of each field:
tsplayertv is the quickest way to check where a field sits. Here, score starts 0x40 bytes into the struct, right after the 64-byte name. Overflowing name by four bytes overwrites score.
Use t <type> to see how radare2 will print the type. This is the format string the pf (print formatted) command uses:
t playerpf [64]zd name scoreOnce a type is defined, we can use it on data:
tp <type> <address> prints the data at an address as that type, field by field.tl <type> <address> links the type to an address, so radare2 shows the struct whenever it displays that address. Run tl on its own to list the links.radare2 also ships with the signatures of common library functions. Use tf to list them; these are what make type inferencing work.
tf~getsfgetsgetsgetsocknamegetsockopttgetstrt?Usage: t Parse, manage, and print C types| t list all loaded types| tj list all loaded types as json| t <type> show type in 'pf' syntax| t* list types info in r2 commands| t- <name> [name2..] delete type(s) by name (supports glob with *)| t-* remove all types| tc[?] [type.name] list all/given types in C output format| td <string> load types from string (quote the whole command: "td ...")| tde open cfg.editor to define new types| te[?] list all loaded enums| tf[?] list all loaded functions signatures| tk <sdb-query> perform sdb query| tl[?] show/Link type to an address| tn[?] [-][addr] manage noreturn function attributes and marks| to[?] <path> load types from C header file| tp[?] <type> [addr|varname] cast data at <address> to <type> and print it (XXX: type can contain spaces)| ts[?] print loaded struct types| tt[?] list all loaded typedefs| tu[?] print loaded union types| tv[?] view types with offsets and xrefs| tx[?] type xrefsIf a program comes with a header file, use to <path> to load all its types at once instead of typing each one with td.