Unpacking Binaries

Many binaries, especially malware samples, are packed. On a high-level, a packed binary stores the real code compressed and often encrypted inside the binary file, and at runtime, a small piece of start-up code restores the real code in memory. Unpacking a binary means getting the real, uncompressed, and unencrypted code back.

Note that binary packing is different from emulation-based binary code obfuscation. Modern commercial binary obfuscators, such as VMProtect and Themida, may employ both obfuscation and packing when protecting a binary. This page only covers unpacking.

angr provides a generic unpacker analysis for unpacking packed binaries, which contains three main steps:

  1. angr emulates the packed program; for performnace concerns, angr will use either the Unicorn engine or the Icicle engine (instead of pure Python-based engine) for emulation.

  2. angr waits until observing the execution reaching OEP (original entry point), which is when the start-up code has restored the real code and jumps to the real code.

  3. angr dumps the memory of the now unpacked process as a new executable file. This dumped process image does not run natively. Optionally, angr can rebuild a runnable PE file from the dumped process image.

Note that angr only emulates the packed binary and never natively runs the packed program, which means the packed binary cannot touch your files, change your local configurations, or access your network (unless it exploits a vulnerability inside angr).

angr also provides static unpacking analyses, such as VMProtectUnpacker, for situations where static unpacking is possible.

The following table summarizes all Unpacking analyses that angr provides.

Analysis

Type

Purpose

Unpacker

Dynamic

Identify how the file is protected and run the matching unpacking analysis. Start with this analysis.

PackerIdentifier

Static

Identify which packer was used and whether the real code is packed.

GenericUnpacker

Dynamic

A generic unpacking approach that unpacks a file via emulation and process dumping once reaching OEP.

VMProtectUnpacker

Dynamic

Unpack binaries that are protected with VMProtect.

ThemidaUnpacker

Dynamic

Unpack binaries that are protected with Themida or WinLicense. Only support certain versions and configurations.

VMProtectStaticUnpacker

Static

This analysis decompresses a VMProtect-packed file without emulation. Only support certain versions and configurations of VMProtect-packed binaries.

Unpacking a File

Unpacker is the starting analysis if you want to unpack a binary. The analysis runs when the analysis is created.

>>> import angr
>>> p = angr.Project("../binaries/tests/i386/windows/unpacker/xor_packed.exe")
>>> unpacker = p.analyses.Unpacker()

# the address where the real program starts
>>> hex(unpacker.oep)
'0x401800'

# dump the unpacked executable
>>> with open("xor_packed.unpacked.exe", "wb") as f:
...     f.write(unpacker.unpacked)
16384

# load the unpacked file in angr again
>>> unpacked = angr.Project("xor_packed.unpacked.exe")
>>> hex(unpacked.entry)
'0x401800'

You can use the saved file for further analysis. Unpacker updates the entry point of the saved file to the OEP and rebuilt the import table if possible. The saved file does not run in a real Windows environment.

VMProtect-Protected Binaries

For a VMProtect-protected binary, Unpacker first runs VMProtectUnpacker. If emulating the binary does not reach the original entry point, Unpacker runs VMProtectStaticUnpacker, and unpacked is the output of VMProtectStaticUnpacker. In that case oep is None, and the unpacked file keeps the entry point and the import handling of VMProtect.

>>> p = angr.Project("../binaries/tests/i386/windows/unpacker/vmprotect_like_plain_table.exe")
>>> unpacker = p.analyses.Unpacker(timeout=30)
>>> unpacker.oep is None
True
>>> unpacker.unpacked is unpacker.static_unpacker.unpacked
True

Results

unpacked

The bytes of the unpacked executable file. unpacked is None if nothing was unpacked.

oep

The original entry point. oep is None if the program never jumped into restored code.

info

What Unpacker found out about the protection of the file before running the program. See Identifying the Protection.

unpacker

The analysis that emulated the binary, which is a GenericUnpacker, a VMProtectUnpacker or a ThemidaUnpacker. unpacker is None if the file is not packed. Only Unpacker has this attribute.

static_unpacker

The VMProtectStaticUnpacker that Unpacker ran after emulating a VMProtect-protected binary did not reach the original entry point. static_unpacker is None in every other case, and when the static unpacking failed. Only Unpacker has this attribute. See VMProtect-Protected Binaries.

stop

Why the emulated program stopped running. stop.reason is one of the values in the table below. stop.addr is the address where the program stopped. stop.detail is a short description.

layers

Every copy of the memory of the program that the unpacker saved during the run. See Binaries Packed More Than Once.

unlisted_exports

The functions that the program asked Windows for and that the lists of Windows functions do not contain. See Choosing the Lists of Windows Functions.

stop.reason

Meaning

StopReason.EXITED

The program ended itself, for example by calling ExitProcess.

StopReason.RETURNED

The entry function of the program returned.

StopReason.BUDGET

The time limit ran out. The time limits are timeout, settle_timeout and return_timeout.

StopReason.ERROR

The program crashed, or the program did something that the emulator cannot handle. stop.detail says what happened.

StopReason.EXEC_TRAP

The unpacker stopped the program right after the program jumped into restored code.

Options

All of the unpackers that run the program accept these options.

timeout

The longest time in seconds that the program may run. The default is 300 seconds for GenericUnpacker, 600 seconds for VMProtectUnpacker and 1800 seconds for ThemidaUnpacker. Unpacker uses the default of the unpacker that Unpacker picks unless you give a value.

engine

The emulator that runs the program. The value is "unicorn", which is the default, or "icicle". See Choosing the Emulator.

return_timeout

How long in seconds the program keeps running after the start-up code calls a function of the real code. The default is 20 seconds. See `Finding the Original Entry Point`_.

exports_dir

A directory with your own lists of Windows functions. See Choosing the Lists of Windows Functions.

icicle_jit, icicle_jit_threshold, icicle_thread_slice

The settings of the Icicle emulator. See Choosing the Emulator.

GenericUnpacker also accepts settle_timeout. The section about GenericUnpacker describes this option.

>>> unpacker = p.analyses.Unpacker(timeout=120, engine="icicle")

Choosing the Emulator

angr can run the program on one of two emulators.

"unicorn"

This emulator is Unicorn, which the rest of angr uses for fast concrete execution. Unicorn is the default emulator.

"icicle"

This emulator is Icicle. On packed programs, Icicle is usually between 10 and 30 times faster than Unicorn. This speed decides whether angr can unpack a heavily protected program within the time limit.

Icicle takes the description of x86 instructions from the pypcode package. This description needs a number of corrections that pypcode does not include yet. Without these corrections, Icicle computes a few uncommon instructions incorrectly, so Icicle is not the default emulator.

The following three options only have an effect with engine="icicle".

icicle_jit

Whether Icicle translates code that runs often into native machine code. The default is True. When icicle_jit is False, Icicle interprets every instruction. Interpreting is slower, but turning icicle_jit off can help when you suspect a problem in the translation.

icicle_jit_threshold

How many times a piece of code must run before Icicle translates the piece of code. The default is 32. A packed program runs most of the start-up code only a few times, so translating all of the start-up code would cost more time than the translation saves.

icicle_thread_slice

How many instructions one thread runs before the next thread gets a turn. The default is 4000000. This option only matters when the program has more than one thread.

Identifying the Protection

PackerIdentifier identifies how a binary is packed. It is a static analysis, so it finishes quickly.

>>> p = angr.Project("../binaries/tests/x86_64/windows/Project1.vmp.exe")
>>> identifier = p.analyses.PackerIdentifier()
>>> identifier.protector
'VMProtect'
>>> identifier.packed
False
>>> identifier.info.reason
'original code is readable on disk (35 repeated call targets)'
protector

"VMProtect", "Themida" or "Themida+VMProtect". protector is None if PackerIdentifier cannot recognize what packer the binary is protected with.

packed

True if the binary is packed, False if the binary is not packed, and None if we cannot determine.

info

A PackerInfo object with the details.

info.outer_packer

The name of a common compression-packing tool. PackerIdentifier currently recognizes UPX, MPRESS, ASPack, PECompact, Petite, NsPack, Enigma, and MEW.

info.reason

Explanation of the value of packed.

info.evidence

The signs that lead to the identification of protector.

info.sections

Measurements of each section of the file, such as the size of the section and how random the bytes of the section are.

Using The Individual Unpackers

Unpacker automatically identifies the likely packer and dispatches the unpacking effort to one of the underlying dynamic unpacking analyses. In case any step of this process goes wrong, you can also create an unpacking analysis directly.

GenericUnpacker

GenericUnpacker runs the program and watches every section that the binary’s unpacking logic might restore during runtime. When the binary jumps into a section whose contents have changed, GenericUnpacker dumps the memory of the unpacked binary and uses the target of the jump as the original entry point.

GenericUnpacker takes an option, settle_timeout, which allows you to specify how long angr keeps emulating the binary after seeing the first jump. This is to support binaries that were packed more than once. The default is 20 seconds.

>>> unpacker = p.analyses.GenericUnpacker(timeout=60, settle_timeout=5)

VMProtectUnpacker

VMProtectUnpacker knows which sections of a VMProtect-protected file belong to the real binary and only watches changes in these sections. VMProtectUnpacker only emulates the binary. unpacked is None if running the binary does not reach the original entry point. Use VMProtectStaticUnpacker to decompress the binary without running it, or use Unpacker, which runs VMProtectStaticUnpacker when emulating the binary fails.

ThemidaUnpacker

ThemidaUnpacker unpacks files that are protected with Themida or WinLicense. It only watches the sections of the real binary. The start-up code can take minutes even on the faster emulator, so the default time limit is 30 minutes.

VMProtectStaticUnpacker

VMProtectStaticUnpacker does not emulate the binary; instead, it attempts to statically unpack the binary, and may work when the VMProtect-protected binary is one of the supported VMProtect versions and configurations. Some versions of VMProtect keep a table in the packed binary indicating where each compressed section is stored. VMProtectStaticUnpacker finds this table and decompresses the sections. This analysis does not fix the OEP or rebuild the import table. It raises VMProtectStaticError if the analysis cannot find the table.

>>> p = angr.Project("../binaries/tests/i386/windows/unpacker/vmprotect_like_plain_table.exe")
>>> static = p.analyses.VMProtectStaticUnpacker()

# the number of bytes decompressed into each section
>>> static.result.blocks
{'.text': 6144, '.rdata': 1984, '.vmp0': 1024}
>>> len(static.unpacked)
24576

Finding the OEP

The start-up code of a packer usually ends with a jump to the original entry point. Before this jump, the start-up code removes everything that the start-up code put on the stack. The real program then starts with the same stack that Windows gave to the packed program.

Some packers run restored code before this jump. For example, VMProtect can rewrite the first instructions of the real program into the private instruction set of VMProtect. The interpreter of VMProtect then calls an ordinary function of the real program before the rest of the real program starts. As another example, the start-up code of a packer can have a second part that the packer stores in the same section as the real program.

For this reason, the unpacker looks at the stack when the program first jumps into restored code. If the stack is the same as at the start of the program, the unpacker reports the target of the jump as the original entry point. If the program has more on the stack, the unpacker saves the memory of the program and lets the program continue. When the program later jumps into the same section with the same stack as at the start of the program, the unpacker saves the memory again and reports the target of this jump as the original entry point. If the program never makes such a jump, the unpacker reports the target of the first jump.

After the first jump, the program continues for settle_timeout seconds. If the value on top of the stack is a return address in the start-up code, the start-up code called the restored code, and the program continues for return_timeout seconds instead when return_timeout is longer. During this extra time, the unpacker only saves the memory again when the program jumps into restored code with the same stack as at the start of the program. VMProtectUnpacker and ThemidaUnpacker use a settle_timeout of 0, so these two unpackers only let the program continue after such a call.

When a packer rewrote the first instructions of the real program, the original entry point no longer exists as ordinary code. The unpacker then reports the first ordinary code that runs with the same stack as at the start of the program.

Binaries Packed More Than Once

A binary can be packed several times. For example, a binary is compressed first and then packed with another packer. Running a binary packed several times restores the code in several steps. Each time the binary jumps into newly restored code, the unpacker saves the memory of the program. We call each saved copy of the memory a layer. The copies of the memory that Finding the OEP describes are layers too. layers lists the layers in the order in which the unpacker saved the layers.

unpacked and oep come from the layer that is most likely the original binary.

>>> p = angr.Project("../binaries/tests/i386/windows/unpacker/xor_packed.exe")
>>> unpacker = p.analyses.GenericUnpacker()
>>> for layer in unpacker.layers:
...     print(hex(layer.oep), layer.section, layer.seconds < 60)
0x401800 .text True

# we can build an executable file from any layer
>>> data = unpacker.layers[0].rebuild(p.loader.main_object.mapped_base)

Each layer has these attributes.

oep

The address that the program jumped to. oep is None for a layer that the unpacker saved at the end of a run in which the program restored the code but never jumped into the restored code.

section

The name of the section that contains the address in oep.

seconds

How long the program had been running when the unpacker saved the layer.

image

The memory of the program when the unpacker saved the layer. When the unpacker had to add entries to the import table, the new entries follow the memory of the program.

imports

The Windows functions that the unpacker recovered for the import table.

entropy

How random the bytes of the section look, from 0 to 8. Readable code is usually below 7. Compressed or encrypted data is close to 8.

Choosing the Lists of Windows Functions

A packed program looks up the Windows functions that the program needs while the program runs. Some programs check that a system library offers exactly the functions that the real Windows library offers. For this reason, the emulator needs to know which functions each Windows library contains. The angr-data package ships these lists as one JSON file per library.

Pass exports_dir to use a directory with your own lists. For example, you can use lists that were taken from a different version of Windows.

>>> unpacker = p.analyses.Unpacker(exports_dir="/path/to/my/lists")

After a run, unlisted_exports names the functions that the program asked for and that the lists did not contain. An entry in unlisted_exports is not always a mistake in the lists. Some programs ask for functions that do not exist to find out whether the programs are being analyzed.

Limitations

  • Only packed x86 and x86-64 PE binaries are supported for now.

  • The unpacking emulator implements the Windows functions that packed binaries commonly call, but this list is incomplete. A program can call a function that is missing or behaves slightly differently. When this happens, stop.reason is usually StopReason.ERROR, and stop.detail indicates the problem. Please consider submitting a PR that fixes such issues!

  • Some packers try to detect emulators and debuggers. angr does not bypass all such attempts.

  • The rebuilt import table can be incomplete. Packers may hide the calls to Windows APIs in several ways, and angr may not be able to trace every hidden call back to a Windows function. Again, PR welcome :)