Github Stackoverflow Email

Software developer notes

Packers used to mean one thing: compress an executable, prepend a small decompressor, done. Let's take a brief overview of abstract packer and its capabilities (don't reverse commercial applications and appreciate a work of developers!).
My goal is a mental map for the curious, not a recipe. Everything below is the kind of thing you discover by emulating the protector long enough to watch it work.

The big idea: never have the real code in one place at one time

A naive packer compresses the executable and decompresses it at startup — one memcpy and the game is over. A protector is paranoid: it assumes someone is watching, so it keeps the payload encrypted, split into many pieces, and only ever decrypts a small piece right before it is needed, often re-encrypting or discarding it afterwards. Unpacking becomes a long, stateful journey rather than a single transformation. And the journey is guarded at every step.
Protector architecture
Put together, the architecture is: a small native stub → a record-walking engine that decrypts a key-chained, integrity-checked stream → anti-emulation record-programs → hash-based IAT rebuilding → a bytecode VM for the crown jewels → and only then the original entry point. Each layer is designed so that defeating it requires the previous ones to be perfect.

Records: the payload as a key-chained stream

The encrypted payload is stored as a sequence of records (blocks). Each record has a small header — flags, a size, a checksum — and a body. The clever part is how the records are keyed:
  • The header of each record is obfuscated with a fast rolling XOR: a 32-bit key is XORed into each header field and then rotated (rol) before the next field, so the same key never encrypts two fields identically.
  • The key for record N+1 is derived from record N — typically a CRC32 of record N's body. This chains the records together: you cannot decrypt record 50 unless you have correctly decrypted and checksummed records 1 through 49, in order. Skip or reorder one and every subsequent key is garbage.
  • The body of each record is encrypted with a real block cipher (AES-128 in the sample I looked at), with the round keys built at runtime. A common construction XORs the cipher output with a per-block counter — a stream-like mode — so identical plaintext blocks encrypt differently.
Key-chained record stream
The effect is a single long dependency chain: header XOR keys roll forward via CRC, bodies are AES-protected, and a separate integrity accumulator (a running hash, e.g. MD5 folded over each block) feeds the decryption of later stages. The whole payload is one equation where every term depends on all previous ones.

Integrity as a weapon

Every record's body is CRC32-checked before use. If the checksum does not match — because you patched a byte, skipped a record, or emulated an instruction slightly wrong — the code does not crash. It calmly takes a suicide branch: shows a generic "internal error" and exits, or quietly steers into a wrong path that fails much later. Combined with self-hashing of the code sections, this makes "just patch it" surprisingly hard: the patch changes a hash, the hash changes a key, the key garbles a stage, and you are debugging a phantom three layers away from your edit.

Records that are code, not data

Not every record is payload. Some records carry small programs in their bodies — and this is where the anti-emulation lives. A dedicated group of these records runs before finalization, and their bodies are exactly the checks from the next section: probe the debugger, probe the VM, measure time, register a vectored exception handler and see if it fires. If any check fails, the record's program calls the protector's own "report and bail" routine through an internal command interface — so the failure is a controlled, encrypted, deniable branch rather than an obvious crash. In my run the very first record of this group politely printed a debugger warning and tried to shut everything down; the records around it probed for a VM's device files and the CPU's hypervisor bit.

Hash-based API resolution

The protector does not import functions by name — the static import table in the file is empty or fake. Instead it walks the export tables of the system DLLs at runtime and finds each function by a hash of its name (again CRC32), then writes the resolved addresses into the IAT itself. No strings, no imports to inspect statically. For the emulator this is actually convenient: you can answer the hash lookup from a precomputed "name → CRC32" map and skip the whole export-table sweep.

The VM

The most sensitive fragments are not x86 at all — they are compiled to a custom bytecode for a tiny embedded virtual machine with its own opcode set and its own dispatcher loop. There is no machine code to read; you would have to reverse the VM's instruction set first. In the sample I worked with, the finalization stage ran on such a VM, which is why simply "reading the disassembly" of that part gets you nowhere — you are looking at a bytecode interpreter, not the logic.

The anti-debugging and anti-emulation catalog

Now the part every reverse engineer actually cares about: what does the protector do to find out it is being watched? Below is the taxonomy I encountered, roughly from trivial to nasty. Each probe is simply a question you must answer correctly from inside the emulator.
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 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. A particularly instructive member of this family is VEH — it gets its own section below.
4. The trap flag (single-step) check. A close relative. The code sets the TF bit in EFLAGS (pushfd; or [esp], 0x100; popfd) and executes a plain instruction. On a clean machine the CPU raises a single-step exception (STATUS_SINGLE_STEP, 0x80000004) which the program's own handler catches and clears. A debugger, however, swallows single-step events for its own stepping machinery — so if the handler never fires, a debugger is present. In an emulator you must actually deliver that single-step exception through the SEH/VEH machinery; simply ignoring TF reads as "debugger".
5. 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.
6. 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. 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. Beware the opposite failure too: if you freeze the clock completely, a timing loop that waits for time to advance will spin forever.
7. CPU and platform fingerprinting. CPUID vendor/hypervisor bit, 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.
8. Debugger/driver/VM device probes. Attempts to open tell-tale device objects: \\.\SICE, \\.\NTICE (SoftICE), \\.\NTFIRE, \\.\VBoxGuest (VirtualBox), 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.
9. Window and desktop probes. A sneakier environmental check: the code creates a window, enumerates windows (EnumWindows, FindWindow), or reads window-station properties, looking for debugger/VM artifacts — or simply verifying that the environment behaves like a real interactive desktop. Your stubs need to return plausible handles and "nothing found" results; a window handle that is then dereferenced as a pointer will happily crash your fake OS if you are not careful.
10. 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.
  • Deliberate hangs. The nastiest anti-emulation I met is not a branch but a wall: when the environment smells wrong, the code enters an infinite loop (jmp $) or a timing loop waiting for a clock that, in your deterministic sandbox, never advances. Nothing crashes, nothing reports — the run just stops making progress. The only symptom is an EIP that refuses to change across millions of instructions. Detect it by watching for a non-advancing EIP, then work backwards to find which check armed the trap.

A closer look: vectored exception handling (VEH)

This one deserves a slower explanation, because it confused me at first and it is a beautiful example of turning the OS's own machinery against the analyst.
Windows has two exception-handling layers. The one everybody knows is SEH (Structured Exception Handling): the per-function try/except blocks, chained through fs:[0]. Less known is VEH — Vectored Exception Handling: a process-wide list of callback functions that ntdll calls for every exception, before it even looks at the SEH chain. You register a handler with AddVectoredExceptionHandler(First, Handler), and it receives a pointer to an EXCEPTION_POINTERS structure (the exception record plus the full CPU context). The handler returns one of two magic values:
EXCEPTION_CONTINUE_EXECUTION  (-1)  // "I fixed it, resume from the context"
EXCEPTION_CONTINUE_SEARCH      (0)  // "not mine, ask the next handler"
The order of an exception's journey on Windows is:
  1. the debugger gets first chance (if one is attached);
  2. the VEH list is walked;
  3. the SEH chain is walked;
  4. the debugger gets a second chance;
  5. nobody handled it → the process dies.
Now the anti-debug trick writes itself. The protector does this:
AddVectoredExceptionHandler(1, my_handler);   // 1 = "put me first"
RaiseException(SOME_CODE, 0, 0, NULL);         // or a deliberate fault
// ... later, somewhere quiet:
if (!my_handler_was_called)
    report_debugger();                          // somebody ate my exception
On a clean machine there is no debugger, so the very first thing that sees the exception is the protector's own VEH — it gets called, notes "yep, I'm alive", returns CONTINUE_EXECUTION, and life goes on. Under a debugger, the debugger intercepts the exception at step 1 and (depending on its settings) may never pass it down — the VEH stays silent, and the protector concludes it is being watched. The elegance is that the check needs no suspicious API and no PEB read; it measures the behavior of the exception machinery itself.
For the emulator author this means two things. First, AddVectoredExceptionHandler must actually register the handler in a list you keep. Second — and this is the part I initially missed — when an exception fires (including one raised through RaiseException, which a lazy stub tends to just "return 0" from), you must walk your VEH list before the SEH chain and honor the return value. A minimal dispatcher:
def dispatch_exception(exc_code, fault_eip, ctx):
    # build EXCEPTION_RECORD + CONTEXT, wrap them in EXCEPTION_POINTERS
    exptrs = make_exception_pointers(exc_code, fault_eip, ctx)
    for handler in veh_list:                    # VEH first!
        ret = call_guest(handler, exptrs)       # run the handler in the guest
        if ret == 0xFFFFFFFF:                   # EXCEPTION_CONTINUE_EXECUTION
            resume_from(ctx)                    # honor possibly-edited EIP/regs
            return
        # 0 = CONTINUE_SEARCH -> fall through to the next handler
    dispatch_seh(exc_code, fault_eip, ctx)      # only then the SEH chain
My first version registered the VEH but never called it (and stubbed RaiseException as a no-op). The protected code registered its handler, raised the exception, saw that nobody answered, and politely reported a debugger — a completely correct conclusion given what my sandbox had shown it. The fix was not to hide anything, but to be a better operating system: actually deliver the exception. That is a recurring theme — most anti-emulation is defeated not by lying harder, but by implementing the real behavior more faithfully.

Conclusion

A protector is a layered, stateful, self-defending system: key-chained encrypted records, integrity checks wired into the key schedule, dedicated anti-emulation record-programs, runtime IAT rebuilding, and a bytecode VM for the parts it cares about most. Each layer assumes the previous one is perfect, and each is designed to fail silently and deniably when it is not. It is genuinely elegant engineering — and, from the analyst's side, a wonderfully honest adversary: every layer you peel teaches you exactly how it was glued.
The good news is that none of it is magic. Every probe is a question, and every question has a correct answer — you just have to know the operating system well enough to give it. And that is where a CPU emulator shines: it lets you observe the questions and rehearse the answers in a fully deterministic, fully instrumented environment.

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.