r2 Emulation Basics

Emulation is a great way to find out what a function, basic block, or just a couple of instructions are doing without actually running the code. Emulation can often be used to assist with reverse engineering malware’s encryption/packing routines.

Radare2 supports emulation for all platforms that support ESIL uplifting.

Decrypting a XOR encrypted string with Radare2’s Emulation

Follow along and download the sample here!

This sample contains a XOR decryption routine in main. The first basic block of main (0x00001149) sets up the cipher text & the decryption key.

The next basic block (0x1215) is the loop counter. This will cause the XOR decryption basic block (0x11f1) to loop until var_74h >= 0x1b. Next the basic block at 0x121b is hit. At this point the decryption routine is complete.

Image of r2 graph

ESIL Emulation Steps

  1. r2 7d01917e812572aa277134b13ecd18819c2cf9f7ac70e13c66d303f497f4a824.bin
  2. s main Seek to the main function
  3. af Analyze the function (not required for emulation)
  4. e emu.str = true Will display contests of registers and memory addrs
  5. aei Initialize the ESIL VM
  6. aeim Initialize the ESIL VM memory stack
  7. aeip Set the initial ESIL VM instruction pointer

At this point the ESIL VM is setup and ready to run. The instruction pointer is set to 0x00001149 which is the first instruction in the function. The program can now be emulated a couple of ways.

Visual Emulation

Visually step in/over/back instructions, while also having r2 show the ESIL VM stack.

  1. Enter Visual Mode (Vpp)
  2. Press s (to step in) OR S (to step over)

Continue stepping until 0x00001206 is hit. One this instruction is expected the decrypted byte will be stored in the edx register. The value of all the registers can be viewed by running the aer or aerr commands.

Continue Emulation Until

It can be pretty tedious to step through each instruction, especially since it’s known that the entire decrypted string will be on the stack once 0x121b is hit.

Instead of single stepping each instruction, radare2 can be just run until a certain address is hit. To do this run aecu 0x121b. This instructs radare2 to run until 0x121b is hit.

At this point if the value of the stack is printed, the plaintext string can be seen:

[0x000011f2]> px 32 @ esp+0x50
- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF
0x00177fc8  6874 7470 733a 2f2f 6d61 6c77 6172 6561  https://malwarea
0x00177fd8  6e61 6c79 7369 732e 6465 762f 0000 0000  nalysis.dev/....