#Why this matters
When you open an unfamiliar binary in Ghidra and see only two imported APIs, three unreadable sections, and a tiny entry function full of loops, the problem is rarely a broken compiler. Both commercial protectors and malware authors wrap executables with packers, encrypt configuration strings, and scramble control flow to slow down reverse engineers.
In teskari-muhandislik challenges and real incident-response triage, recognising these layers early saves hours of wasted static analysis. Instead of trying to decompile compressed ciphertext or dead branches, you peel back the outer layer first, recover clean code and strings, and focus your analysis on what the program actually does.
#How packing hides a binary
A packer transforms a compiled PE or ELF file on disk without changing its behaviour at runtime. It compresses or encrypts the original code and data sections, stores that payload inside a new section, and prepends a small unpacking stub. The header's entry point (AddressOfEntryPoint in PE, e_entry in ELF) is changed to point at the stub instead of the original program.
- OS LoaderMaps packed file and jumps to stub entry point
- Unpacking StubDecompresses or decrypts payload into memory
- Import ResolverLoads DLLs and resolves APIs via GetProcAddress
- Tail JumpTransfers control to the Original Entry Point (OEP)
Before opening a debugger, inspect the binary's structure. Packing leaves clear statistical and structural footprints compared to a normal compiled executable:
| Indicator | Normal compiled binary | Packed binary |
|---|---|---|
| Section names | Standard names (.text, .rdata, .data) |
Custom or packer names (UPX0, UPX1, .packed) |
| Section sizes (PE) | RawSize and VirtualSize roughly match |
RawSize is 0 while VirtualSize is large |
| Shannon entropy | Code around 5.5 to 6.7 bits/byte |
Payload section above 7.0 bits/byte |
| Import table | Dozens of OS APIs (CreateFileW, recv, etc.) |
Very few imports (often LoadLibraryA, GetProcAddress, VirtualProtect) |
strings output |
Readable errors, URLs, format strings | Mostly random characters or stub messages |
Shannon entropy measures byte unpredictability on a scale from 0.0 (all identical bytes) to 8.0 (uniformly random bytes). Compressed or encrypted payloads distribute all 256 byte values nearly evenly, pushing section entropy past 7.0. You can check section entropy quickly with Python 3 during static triage:
import math
from collections import Counter
def shannon_entropy(data: bytes) -> float:
if not data:
return 0.0
counts = Counter(data)
length = len(data)
return -sum((c / length) * math.log2(c / length) for c in counts.values())#Unpacking in practice: static triage and OEP recovery
Always test for a standard packer first. UPX is widely used in both legitimate utilities and CTF binaries. Standard UPX files store metadata that the upx tool itself can reverse without running a single instruction:
$ file lab_sample.exe
lab_sample.exe: PE32+ executable (console) x86-64, for MS Windows, UPX compressed
$ upx -t lab_sample.exe
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2024
...
testing lab_sample.exe [OK]
$ upx -d -o lab_sample_unpacked.exe lab_sample.exe
Unpacked 1 file.Custom packers and modified UPX binaries (where section names or the "UPX!" magic bytes are overwritten) will fail upx -d. When static unpacking fails, let the stub unpack itself in x64dbg and stop right as it jumps to the Original Entry Point (OEP):
- Break on memory allocation or permission changes. Stubs commonly allocate writable memory and make it executable using
VirtualAllocorVirtualProtecton Windows (mmapormprotecton Linux). Setting a breakpoint on those APIs catches the moment the unpacked code is ready. - Watch the stack (
ESP/RSPtrick). Classic stubs save all registers at the start (pushadon x86, or a cluster ofpushinstructions on x64) and restore them just before jumping to the OEP. Step over the initial register saves, set a hardware read breakpoint on the saved stack address, and run: the debugger pauses right after the registers are restored, a few instructions above the tail jump (jmp <OEP>orpush <OEP>; ret). - Break on execution in the target section. If the PE has an empty section like
UPX0(RawSize = 0), set a memory-execute breakpoint on that section's virtual address range. The first instruction executed there is typically the OEP.
Once paused at the OEP, the unpacked code lives in memory, not on disk. Dumping that memory directly leaves the PE Import Address Table (IAT) broken because the stub resolved imports manually at runtime. Use a dump-and-fix plugin such as Scylla (built into x64dbg) at the OEP: point it to the OEP address, scan for the IAT, rebuild the import table, and save the fixed executable so Ghidra can label every API call cleanly.
#Deobfuscating encrypted strings
Even after unpacking, static analysis often shows no readable URLs, commands, or flags. Authors hide sensitive text with three common string-encryption patterns:
- Stack strings: Instead of storing
"cmd.exe"in.rdata, the compiler or obfuscator emits individual byte moves onto the stack (mov byte ptr [rbp-0x10], 0x63,0x6d,0x64, ...). Because no contiguous string exists in the binary file,stringsreturns nothing, though Ghidra's decompiler often reveals sequential character assignments. - XOR encoding: A short loop XORs an embedded byte array with a single byte or a repeating multi-byte key right before use.
- Cipher blobs: Larger configurations are encrypted with RC4 or AES and decrypted once into heap memory.
When you spot a string decryption function in Ghidra, avoid reimplementing the entire binary. Check cross-references (XREFs) to that helper: every call site typically passes a pointer to an encrypted buffer and a length. You can decode those buffers offline with a short Python script:
enc = bytes.fromhex("3934377b393a363439")
key = b"\x55"
decoded = bytes(b ^ key[i % len(key)] for i, b in enumerate(enc))
print(decoded.decode("utf-8")) # lab.localIf the key is derived dynamically at runtime, setting a breakpoint right after the decryption function returns in x64dbg or GDB lets you read the plaintext string directly from the output buffer.
#Control-flow obfuscation
Decompiling an unpacked binary can still produce giant, tangled functions in Ghidra. Two transforms cause most of this noise:
| Technique | How it works | Visual sign in Ghidra | Practical countermeasure |
|---|---|---|---|
| Opaque predicate | Branch condition always evaluates true or false (for example, ((x * (x + 1)) & 1) == 0) |
Dead branches referencing junk code or unreachable blocks | Prove the constant outcome mathematically or patch the conditional jump |
| Control-flow flattening (CFF) | Splits basic blocks into case labels of one switch inside a while loop |
Huge switch statement driven by a state variable |
Trace state-variable updates per case or step through in a debugger |
| Instruction substitution | Replaces simple ops (xor eax, eax) with multi-instruction arithmetic |
Bloated expressions for trivial constants or additions | Use constant propagation or inspect register values dynamically |
In control-flow flattening, every original if/else and loop edge disappears. Instead, each basic block finishes by assigning a new integer (or hash) to a dispatcher variable and looping back to the central switch. Static decompilers cannot recover the original hierarchy automatically because every block appears to be a sibling inside one loop.
To analyse a flattened function efficiently, start from an observable anchor such as a string decryptor, a comparison instruction, or an API call (strcmp, CryptDecrypt, send). Identify which case label contains that call, record the state value it checks, and search backwards for which case blocks assign that state value. You rarely need to rebuild the entire control-flow graph to understand what a target routine checks.
#Detection and common mistakes
- Trusting section names alone: Pack-aware tools often flag
UPX0, yet custom packers or renamed UPX binaries use.textor.data. Always combine entropy, import-count checks, andRawSizeversusVirtualSizecomparisons. - Dumping before imports are resolved: Taking a memory dump before the stub finishes rebuilding the IAT leaves indirect calls pointing to empty or invalid thunks in Ghidra. Dump right at the OEP and repair imports with a tool like Scylla.
- Deobfuscating dead code: Opaque predicates deliberately hide fake error handlers and decoy loops. Confirm whether a branch is actually reachable before spending time reversing its body.
- Running samples outside a snapshot: Unpacking stubs may check for sandboxes or drop secondary payloads before reaching the OEP; always work inside a disposable VM snapshot.
#Summary
- Packers wrap compressed or encrypted executables in a runtime stub, leaving footprints such as high Shannon entropy (
> 7.0), mismatchedRawSize/VirtualSize, and minimal imports. - Try standard static unpackers (
upx -d) first; for custom packers, useVirtualAlloc/VirtualProtect, stack hardware breakpoints, or section-execute breakpoints to catch the tail jump to the OEP, then dump and rebuild the IAT. - Defeat string encryption by locating stack-string construction or finding XREFs to decoding wrappers and reimplementing or trapping their output.
- Navigate opaque predicates and control-flow flattening by anchoring on key API calls and tracing only the relevant state-variable transitions.