Github Stackoverflow Email

Software developer notes

Every reverse engineer eventually ends up with a binary that is radioactive. Maybe it is malware you would not run on a bet. Maybe it is a 32-bit Windows executable from another decade, and your workstation is a Linux box. Maybe it is a packed, protected, hostile piece of code that checks for debuggers before it lets you see anything at all. In all three cases the question is the same: how do I watch this thing execute without giving it a real machine to play with?
The classic answer is a virtual machine — and it works, but it is a sledgehammer: gigabytes of guest OS, minutes of boot, a whole computer's worth of attack surface, and an environment the protected code is specifically trained to detect. But think about what the binary actually needs from that machine. Not the disk, not the network, not the window manager. It needs a processor that executes its instructions — and a handful of lies about the world around it.
That is the idea behind this post. Take the Unicorn Engine — a bare CPU emulator carved out of QEMU — give it memory, feed it the binary's bytes, and impersonate the operating system yourself, one API call at a time. The result is a sandbox where every instruction is observable, every memory access is a potential breakpoint, every run is bit-for-bit reproducible, and the guest cannot so much as sneeze without your Python code knowing about it. Below I will walk through what Unicorn is, how to install it, how the emulation loop works, and — the part I wish someone had written down before I started — the catalog of anti-debugging and anti-emulation tricks protected applications pull, with the exact answers your sandbox should give to each of them.

What is Unicorn Engine

Unicorn is a lightweight, cross-platform CPU emulator framework. It was extracted from QEMU and stripped down to the bare minimum: a CPU core with a JIT compiler (QEMU's TCG — Tiny Code Generator), and a flat virtual memory manager. Everything else — the operating system, devices, files, network, syscalls — is deliberately not there. That is the whole point: Unicorn gives you a processor and a memory bus, and nothing more.
Unicorn architecture
Key properties that make it attractive for sandboxing:
  1. Multi-architecture. x86 (16/32/64-bit), ARM, ARM64, MIPS, PowerPC, SPARC, RISC-V, S390X. One API for all of them.
  2. Multi-platform. Runs on Linux, Windows, macOS, *BSD. The emulated code never touches your real system — it cannot open a file, send a packet or spawn a process unless you implement that behavior in a hook.
  3. Simple binding-friendly API. Roughly a dozen functions: create a machine, map memory, write code, set registers, start emulation, stop emulation. Official bindings exist for Python, C, Go, Rust, Java, .NET and others.
  4. Hooks everywhere. You can subscribe to every executed instruction, every memory read or write, every interrupt, every invalid access. Hooks are your eyes and your hands inside the emulated machine.
  5. Speed. Because of the TCG JIT, translated basic blocks run at a fraction of native speed — orders of magnitude faster than single-stepping an interpreter.
A useful mental model: Unicorn is to a full emulator what a bare engine is to a car. QEMU (its parent project) is a complete vehicle with wheels, dashboard and a GPS — Unicorn is just the engine on a test bench. You bolt on your own transmission, wheels and steering wheel, and that is precisely what makes it so flexible for reverse engineering.

Installation

The easiest way is Python and pip:
# system-wide or in a venv
pip install unicorn

# quick sanity check
python3 -c "import unicorn; print(unicorn.__version__)"
If you prefer building from source (for example, to patch the engine — more on that later):
git clone https://github.com/unicorn-engine/unicorn
cd unicorn
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
sudo make install          # installs libunicorn + headers
# Python bindings against your build:
cd ../bindings/python
pip install .
On Debian/Ubuntu there is also apt install libunicorn-dev, but distribution packages tend to lag behind; for anything serious I recommend the git master — emulation edge cases get fixed there regularly.

How it works: the 30-line sandbox

Here is a complete, minimal example: we emulate a tiny piece of x86-64 machine code that computes a value in a register.
from unicorn import *
from unicorn.x86_const import *

CODE = b"\x48\xc7\xc0\x2a\x00\x00\x00"   # mov rax, 42
CODE += b"\x48\x89\xc3"                    # mov rbx, rax

mu = Uc(UC_ARCH_X86, UC_MODE_64)

ADDRESS = 0x1000000
mu.mem_map(ADDRESS, 0x1000)                # code page
mu.mem_write(ADDRESS, CODE)

STACK = 0x2000000
mu.mem_map(STACK, 0x10000)                 # stack
mu.reg_write(UC_X86_REG_RSP, STACK + 0x8000)

mu.emu_start(ADDRESS, ADDRESS + len(CODE))
print(hex(mu.reg_read(UC_X86_REG_RBX)))    # 0x2a
Three calls to rule them all: mem_map creates a page-aligned region of guest memory, mem_write fills it, emu_start begins execution at a given address and runs until another address is reached, an error occurs, or emu_stop is called from a hook. Registers are read and written with reg_read/reg_write — including from inside hooks, which is how you patch the guest's behavior on the fly.
Emulation loop with hooks
Hooks are registered with hook_add. The ones you will use constantly:
# called before EVERY instruction — slow, but total visibility
mu.hook_add(UC_HOOK_CODE, lambda mu, addr, size, ud: print(hex(addr)))

# watch memory: reads, writes, or accesses to unmapped pages
mu.hook_add(UC_HOOK_MEM_UNMAPPED, on_unmapped)   # lazy allocation lives here
mu.hook_add(UC_HOOK_MEM_WRITE, on_write)         # watchpoints live here

# interrupts and syscalls: int 0x80, int 0x2e, syscall, sysenter
mu.hook_add(UC_HOOK_INTR, on_interrupt)
A hook can read and modify registers, read and modify memory, change RIP to redirect execution, or call emu_stop(). This is the core technique of emulation-based sandboxing: the guest executes real machine code, but every interesting moment is observable and patchable from Python.

Emulating an OS, not just a CPU

Real applications are not self-contained blobs of arithmetic — they constantly talk to their operating system. When you emulate a Windows PE executable, the CPU part is the easy half. The hard half is that you must become the operating system. There is no loader, no kernel, no DLLs in Unicorn; every one of them is a Python function you write.
A practical checklist for a Windows user-mode sandbox:
  1. PE loader. Parse the PE headers yourself, map sections at their virtual addresses, apply base relocations, resolve the import table. For imports you do not want real DLLs at all: create "fake" modules — small memory regions containing a plausible export table whose function addresses point into a reserved "magic" range. When the guest calls such an address, your code hook recognizes it, dispatches to a Python implementation of the API, writes the return value into EAX and pops the arguments (remember ret N for stdcall!).
  2. TEB / PEB. Windows code reads thread and process information directly, bypassing the API: fs:[0x30] gives the PEB, fs:[0] is the head of the SEH chain. You must allocate these structures and keep them consistent — protected code inspects them for debugging artifacts (more below).
  3. SEH. Structured exception handling on 32-bit Windows is a linked list rooted at fs:[0]. Protected binaries deliberately raise exceptions (int3, int 2d, division by zero, accesses to guard pages) and use their own handlers as part of normal control flow. Your emulator needs an exception dispatcher that walks the chain, builds EXCEPTION_RECORD / CONTEXT structures on the guest stack, and transfers control to the handler — exactly like ntdll does.
  4. Heap and VirtualAlloc. Implement a trivial allocator over mem_map. Keep a table of "handles" for files, events, mutexes — anything returning a HANDLE.
  5. Segment registers. Do not forget to set up the FS base (via UC_X86_REG_FS_BASE on 64-bit hosts / MSR writes, or by choosing a Unicorn mode where fs is flat and simply mapping memory at the expected addresses).
Fake Windows address space
The good news: you do not need to implement all of Win32. A packed or protected executable usually touches a few dozen APIs before it reaches its original entry point. Log every unknown API call, return a plausible value, and iterate — the implementation grows only where the guest actually steps.

Determinism: the superpower nobody talks about

Here is something a real machine will never give you: bit-exact reproducibility. On real hardware every run differs — clocks tick, the scheduler preempts, ASLR shuffles addresses. In your sandbox you control every source of nondeterminism, and that changes debugging from guesswork into science: run A and run B with a single change and diff everything.
The main sources of entropy inside a guest, and how to tame them:
  1. RDTSC / RDTSCP. The classic timing instruction. Two counters read in a row tell the guest how fast "time" flows — and emulators are slow, so the delta screams "emulator!". Fix: patch the instruction bytes before execution, or maintain a virtual counter that advances by a fixed amount per instruction. I keep a recorded "clock trace" from a reference run and replay plausible values.
  2. System time APIs. GetSystemTime, GetTickCount, QueryPerformanceCounter, time — route them all to one virtual clock.
  3. CPU identity. CPUID exposes the vendor string and — critically — the hypervisor bit (leaf 1, ECX bit 31). Answer with a fixed, boring genuine-Intel profile.
  4. Randomness. RDRAND/RDSEED, rand(), crypto RNG APIs — seed them with constants.
With all of these pinned, my emulation runs became byte-for-byte identical across invocations. That is what allowed me to set a memory watchpoint, find the exact instruction that diverges after a change, and iterate in seconds.

Anti-debugging and anti-emulation tricks — and how to answer them

Protected applications assume they might run under a debugger or an emulator, and they actively probe for both. From the sandbox author's side, each probe is simply a question you must answer correctly. Below is the taxonomy I encountered, roughly from trivial to nasty.
1. The "polite" API checks. The beginner tier — single API calls whose honest answer under a debugger would be "yes":
IsDebuggerPresent()                # reads PEB.BeingDebugged (offset 0x02)
CheckRemoteDebuggerPresent()
NtQueryInformationProcess(cls=7)   # ProcessDebugPort    -> must be 0
NtQueryInformationProcess(cls=30)  # ProcessDebugObjectHandle -> must be 0
NtQueryInformationProcess(cls=31)  # ProcessDebugFlags   -> must be 1 (NOT debugged!)
NtQuerySystemInformation(cls=35)   # SystemKernelDebuggerInformation -> 0
Note the trap in class 31: the flag semantics are inverted (1 means no debugger). A sloppy stub that fills zeros "to be safe" actually reports a debugger. Always check the real Windows semantics, not just the return status — protected code often verifies buffer contents, not the NTSTATUS.
2. Direct PEB/TEB reads. The same checks, but reading memory directly: PEB.BeingDebugged, PEB.NtGlobalFlag (0x70 when debugged, 0 normally), PEB.ProcessHeap flags (HEAP_TAIL_CHECKING_ENABLED and friends appear under a debugger heap). No API call happens here — the only way to answer correctly is to lay out a byte-accurate PEB in guest memory. This is where "knowledge of the OS" stops being optional: you need the real structure layouts, per Windows version.
3. Exception-based control flow. The code raises an exception and expects its own SEH handler to catch it and continue. Under a debugger the first chance goes to the debugger; under a naive emulator there is no dispatcher at all and the run dies. Tricks in this family: int3, int 2d (kernel debugger check — with a debugger it behaves differently!), icebp (single-byte 0xF1), division by zero, popfd with the trap flag set. Your sandbox must implement the full SEH walk or these checks read your answer for you.
4. Hardware breakpoint detection. GetThreadContext (or direct access to the saved context in an exception) reveals DR0–DR7. In your sandbox hardware breakpoints do not exist, so simply report DR7 = 0 — but make sure the context structure you hand out has realistic values everywhere else, or the zeros themselves become the tell.
5. Timing checks. RDTSC pairs, QueryPerformanceCounter brackets around a trivial operation. On real hardware a cpuid; rdtsc pair costs hundreds of cycles; under emulation without a virtual clock it costs millions. There are two defenses: patch RDTSC to a virtual counter (simple, covers most cases), or record a clock trace from a real run and replay it (more faithful when the protection correlates several time sources). A single constant is often not enough — some protectors measure distributions, so replayed realistic jitter beats a flat line.
6. CPU and platform fingerprinting. CPUID vendor/hypervisor bit (already mentioned), cpuid leaves that real CPUs implement and emulators sometimes do not, MSR reads via rdmsr, and the presence of hypervisor devices. Answer with a consistent, boring consumer-CPU profile — and make it consistent across leaves, because protectors cross-check.
7. Debugger/driver device probes. Attempts to open tell-tale device objects: \\.\SICE, \\.\NTICE (SoftICE), \\.\NTFIRE, known VM driver names. The correct answer from a clean machine is INVALID_HANDLE_VALUE with ERROR_FILE_NOT_FOUND — return exactly that, not a generic failure.
8. Anti-emulation heuristics. The deepest tier targets the emulator itself rather than the debugger:
  • Instruction edge cases. Emulators historically get flags wrong in rare corner cases (AF/OF after odd operations, fnstenv FPU environment layout, string instruction edge behavior). A protector computes a value through such an instruction and CRCs the result — a wrong flag bit changes the hash and the code takes a suicide branch. This is the hardest class to detect: nothing "fails", the program just quietly goes down a wrong path. The fix is a per-instruction diff against real hardware or a patch to the engine itself.
  • Self-checksumming. The code hashes its own bytes and compares against a stored value. In an emulator this actually works for you (memory is pristine), unless you patched code bytes (e.g. to stub RDTSC) — then keep your patches outside hashed regions, or fix up the comparison when your code hook sees it.
  • Stack and environment shape. The protector inspects initial stack contents, environment variables, the command line block, module list order. A hand-built process environment that differs from a real Windows launch is detectable; imitate a genuine loader's layout.

Practical lessons

A few lessons I learned the hard way, in no particular order:
  1. Build the fake OS incrementally. Do not implement Win32 upfront. Log unknown API calls with arguments, return a plausible constant, rerun. Your sandbox grows to exactly the size the target needs.
  2. Snapshot early, snapshot often. Because the whole machine state is yours, you can dump all mapped regions plus registers at any point and resume later. Bisecting a 100-million-instruction run becomes trivial.
  3. Watchpoints beat breakpoints. "Who writes this byte?" is the question you will ask a hundred times. A UC_HOOK_MEM_WRITE filtered to one address answers it precisely.
  4. Keep runs short and deterministic. If a full run takes minutes, you will iterate slowly and start guessing. Pin the clock, log to a file, diff logs between runs.
  5. When the engine itself is wrong, patch the engine. Unicorn is C and builds in minutes. If you confirm a CPU bug (we hit flag and FPU-environment discrepancies), fixing the source is cheaper than working around it in Python — and your patch may be upstreamed.
  6. Network isolation for free. Since Unicorn has no network, the only way the guest can "reach out" is through an API you implemented. Run your harness in a network namespace anyway (unshare -rn) — defense in depth costs one word.

Conclusion

Unicorn Engine occupies a sweet spot between "run it on a real machine" and "stare at it in a disassembler". It gives you a real CPU executing real instructions at decent speed, while every byte of memory and every system service is under your control and observable. The price is that you must impersonate the operating system — and it is exactly there, in SEH dispatching, PEB layouts and API invariants, that deep knowledge of the target OS pays off. The reward is a sandbox that is deterministic, scriptable, snapshot-able, and safe by construction. For analyzing protected or hostile binaries, I find it hard to go back to anything else.

Reverse-Engineering

Leave a comment




Solve the puzzle

About me

Hi! I am Alex, the author of this blog. Here are my technical (in the majority) thoughts and stories. I will be hoping that you find this site interesting and fun. Feel free to leave comments under the articles.