TExcelTAD
Home › Reverse Engineering & Binary Analysis › Packing and Recognising Packed Files

Packing and Recognising Packed Files

A packer compresses or encrypts a program and prepends a small stub that restores the original code in memory at run time and jumps to it. Legitimate software uses packers to shrink executables (UPX is the best known, and open source) or to protect commercial code (Themida, VMProtect). Malware uses them so that the file on disk reveals nothing: no strings, no imports, no recognisable code, a different hash for every copy. For an analyst, a packed file is a wrapped parcel: analysing the wrapping is pointless, so the first job is to recognise packing, and the second is to get at the unpacked code. This lesson is about recognition, which works without running anything, and the analyst's options afterwards. It does not build a packer: writing one to hide code from security products is exactly the evasion the track's safety line excludes.

Definitions

  • Stub: the small, unpacked piece of code that runs first; it allocates or reuses memory, decompresses or decrypts the payload into it, repairs imports and relocations, and jumps to the original entry point (OEP).
  • Typical PE layout after UPX: section UPX0 (raw size 0, large virtual size: room for the unpacked code), UPX1 (the compressed payload plus the stub, high entropy, entry point inside it), and a tiny import table (LoadLibraryA, GetProcAddress, VirtualProtect, ...).
  • Protectors / virtualisers (Themida, VMProtect) go further: they translate parts of the code into bytecode for a custom virtual machine, so the original instructions never exist in memory at all.
  • Overlay: data appended after the last section; not mapped by the loader. Installers and self-extracting archives keep their payload there.

Recognition without running anything

The example builds two synthetic section tables, one normal, one in the shape UPX produces, with section contents generated by the example (a code-like byte pattern, and that same code compressed with zlib). Then it applies the checks that tools such as Detect It Easy, PEiD-style signatures, pefile and capa apply.

python · try it yourself
import math, zlib, random
from collections import Counter

def entropy(d):
    n = len(d)
    return abs(-sum(c / n * math.log2(c / n) for c in Counter(d).values())) if n else 0.0

rng = random.Random(5)
# Code-like bytes: real instruction fragments repeated with variation, not uniform noise.
frags = [bytes.fromhex(h) for h in ["554889e5", "4883ec20", "488b45f8", "89c7e8", "31c0", "c9c3", "4889c6", "85c07405", "488d3d"]]
code = b"".join(rng.choice(frags) + rng.randbytes(rng.choice([0, 1, 4])) for _ in range(1500))[:8192]
packed_payload = zlib.compress(code, 9) + rng.randbytes(300)          # payload + stub bytes

# name, virtual size, raw data (bytes or None for raw size 0), permissions, entry point here?
normal = [(".text", len(code), code, "R-X", True), (".rdata", 2048, b"config v1\0" * 200, "R--", False),
          (".data", 512, bytes(512), "RW-", False)]
upxlike = [("UPX0", 0x6000, None, "RWX", False), ("UPX1", len(packed_payload) + 0x400, packed_payload, "RWX", True),
           (".rsrc", 512, bytes(400) + b"version info", "RW-", False)]
imports = {"normal": ["CreateFileW", "ReadFile", "WriteFile", "CloseHandle", "GetLastError", "HeapAlloc",
                      "HeapFree", "ExitProcess", "GetCommandLineW", "MultiByteToWideChar"],
           "upxlike": ["LoadLibraryA", "GetProcAddress", "VirtualProtect", "ExitProcess"]}

def assess(name, sections):
    score, notes = 0, []
    print(f"== {name}")
    for sname, vsize, raw, perms, entry in sections:
        h = entropy(raw) if raw else 0.0
        size = len(raw) if raw else 0
        print(f"  {sname:<7} vsize={vsize:6d} raw={size:6d} H={h:4.2f} {perms}{'  <- entry' if entry else ''}")
        if raw is None and vsize > 0:
            score += 1; notes.append(f"{sname}: raw size 0, virtual size {vsize} (room to unpack into)")
        if h > 7.2 and "X" in perms:
            score += 2; notes.append(f"{sname}: executable section with entropy {h:.2f}")
        if "W" in perms and "X" in perms:
            score += 1; notes.append(f"{sname}: writable and executable")
        if entry and sname != ".text":
            score += 1; notes.append(f"entry point in {sname}, not .text")
        if sname.upper().startswith("UPX"):
            score += 2; notes.append(f"section name {sname} (UPX)")
    imps = imports[name]
    if len(imps) < 6 and {"LoadLibraryA", "GetProcAddress"} <= set(imps):
        score += 1; notes.append(f"only {len(imps)} imports, including LoadLibraryA + GetProcAddress")
    for n in notes:
        print("   !", n)
    print(f"  packing score {score}: {'LIKELY PACKED' if score >= 4 else 'no sign of packing'}")

assess("normal", normal)
assess("upxlike", upxlike)
== normal
  .text   vsize=  7338 raw=  7338 H=6.24 R-X  <- entry
  .rdata  vsize=  2048 raw=  2000 H=3.32 R--
  .data   vsize=   512 raw=   512 H=0.00 RW-
  packing score 0: no sign of packing
== upxlike
  UPX0    vsize= 24576 raw=     0 H=0.00 RWX
  UPX1    vsize=  5912 raw=  4888 H=7.95 RWX  <- entry
  .rsrc   vsize=   512 raw=   412 H=0.28 RW-
   ! UPX0: raw size 0, virtual size 24576 (room to unpack into)
   ! UPX0: writable and executable
   ! section name UPX0 (UPX)
   ! UPX1: executable section with entropy 7.95
   ! UPX1: writable and executable
   ! entry point in UPX1, not .text
   ! section name UPX1 (UPX)
   ! only 4 imports, including LoadLibraryA + GetProcAddress
  packing score 11: LIKELY PACKED

The normal image has moderate entropy everywhere, code in .text, and a plausible import list. The UPX-shaped image trips every check: an empty section reserved for unpacking, a writable and executable section with near-maximal entropy holding the entry point, UPX section names, and four imports, all of them the ones a stub needs to rebuild the real import table. No single check is proof (compressed resources are high-entropy too, and some compilers emit odd section names), so tools combine them, exactly like the score above.

Section entropy works because it is measured per region. The entropy-scan lab shows what an entropy profile of a whole packed file looks like: a header, 6 KiB of machine-code-like bytes around 6 bits per byte, then a 16 KiB packed section that stays near 7.8 with a 1024-byte window. Half of the windows (62 of 125) cross the 7.2 threshold, yet the entropy of the whole file is only 6.981, below it: one number for the whole file averages the packed section away.

file: packed executable, 32 KiBmachinepackedASCIIentropy of a 1024-byte window, step 256 bytes024680 KiB8 KiB16 KiB24 KiB32 KiB7.2: likely compressed or encryptedheadermachine codezero paddingpacked sectionASCII text

Overlays: data after the image

Not all hidden content is packed code. The session appends a compressed payload to a normal ELF (as self-extracting installers do), then finds it the way an analyst does: the file is larger than the end of its last section, and the extra bytes have high entropy. The appended data is just a compressed copy of a text file; nothing executes it.

bash · try it yourself
printf 'int main(void){return 0;}\n' > app.c
gcc -O2 app.c -o app
cp app app-with-overlay
for i in $(seq 200); do echo "line $i of the bundled readme"; done | gzip -9n >> app-with-overlay
cat > overlay.py <<'PY'
import struct, sys
for path in sys.argv[1:]:
    d = open(path, "rb").read()
    shoff, = struct.unpack_from("<Q", d, 0x28)
    shentsize, shnum = struct.unpack_from("<HH", d, 0x3A)
    end = shoff + shentsize * shnum                       # end of the section header table
    for i in range(shnum):                                # and of every section's file data
        sh_type, = struct.unpack_from("<I", d, shoff + i * shentsize + 4)
        off, size = struct.unpack_from("<QQ", d, shoff + i * shentsize + 0x18)
        if sh_type != 8:                                  # SHT_NOBITS (.bss) has no file data
            end = max(end, off + size)
    print(f"{path:<17} file {len(d):6d} bytes, image ends at {end:6d}, overlay {len(d) - end:5d} bytes")
PY
python3 overlay.py app app-with-overlay
tail -c +$(( $(stat -c %s app) + 1 )) app-with-overlay > overlay.bin
file -b overlay.bin | cut -d, -f1
python3 -c "import math,collections,sys; d=open('overlay.bin','rb').read(); n=len(d); print(f'overlay entropy {-sum(c/n*math.log2(c/n) for c in collections.Counter(d).values()):.2f}')"
app               file  15776 bytes, image ends at  15776, overlay     0 bytes
app-with-overlay  file  16291 bytes, image ends at  15776, overlay   515 bytes
gzip compressed data
overlay entropy 7.02

The overlay starts exactly where the ELF's last structure (the section header table) ends, file identifies it as gzip data, and its entropy is high. An analyst would extract it and analyse it as a separate file. The same check on PE files (end of the last section's raw data versus file size) finds installer payloads, appended configuration and, sometimes, appended encrypted malware stages.

UPX itself: a lab transcript

Lab session: UPX on the course's own hello from the introduction, in the Linux lab VM. Abridged; the banner and exact sizes depend on the UPX version.

console
Lab session: UPX 4.x on hello (the course's own toy), Linux VM 10.10.0.40
$ upx -9 -o hello.upx hello
        File size         Ratio      Format      Name
   --------------------   ------   -----------   -----------
     15960 ->      6112   38.30%   linux/amd64   hello.upx
Packed 1 file.
$ strings -n 8 hello.upx | grep -c toy      # the message is no longer readable
0
$ strings hello.upx | grep -m1 UPX          # but UPX announces itself
$Info: This file is packed with the UPX executable packer http://upx.sf.net $
$ upx -t hello.upx                          # test the compressed file
$ upx -d -o hello.unpacked hello.upx        # UPX can always unpack its own format

UPX is the easy case: it marks its files and unpacks them with -d. Malware authors often modify the UPX headers so that upx -d refuses, which is itself a strong indicator.

Getting at the unpacked code

  • Known packer, known unpacker: upx -d, or a dedicated unpacker for the family.
  • Let the stub do the work in an isolated lab: run under a debugger until the jump to the OEP (a far jmp from the stub into the formerly empty section, often after a popad/pop sequence or a VirtualProtect call), dump the process memory (x64dbg with Scylla, or gcore on Linux), and rebuild the import table.
  • Emulate the stub (unipacker, Qiling, Speakeasy) to unpack without running the sample natively.
  • Memory scanning: run the sample in a sandbox and scan its memory with YARA after it has unpacked itself.

How packing is detected and handled in defence

  • Security products treat "packed with an unusual packer and unsigned" as a risk signal, unpack known formats in their engines, and scan memory after execution starts.
  • Allow-listing signed software reduces the problem: a legitimate vendor that packs its binaries still signs them (Code Signing).
  • For developers: avoid packers on software you distribute unless you need them; packed binaries trigger false positives, slow start-up and complicate crash analysis. If you protect code, sign it.

Pitfalls

  • High entropy is not packing: compressed resources (images, fonts, archives) and embedded certificates score high too; look at executable sections and the entry point.
  • Section names lie: a packer can name its sections .text and .data.
  • Packed .NET or Python programs (PyInstaller, a .NET single-file bundle) are archives with an interpreter, not compressed machine code; use format-specific extractors.
  • Unpacking runs the sample's code, so it belongs in the lab with all the safety rules.

Practice

1. Which three section-table facts together strongly suggest a UPX-packed PE?

Sections named UPX0/UPX1; UPX0 with raw size 0 and a large virtual size; the entry point in UPX1, which is writable, executable and high-entropy.

2. A sample has entropy 7.9 in .rsrc and 6.1 in .text, a normal import table and its entry point in .text. Packed?

Probably not packed in the usual sense: the code looks normal. The resource is compressed or encrypted data worth extracting (it might be an embedded payload, or just images).

3. How did the session compute where the ELF image ends?

With a small struct parser of the ELF header and section table: the maximum of the end of every section's file data (except NOBITS sections such as .bss, which occupy no file space) and the end of the section header table (e_shoff + e_shentsize * e_shnum); bytes beyond that are an overlay.

Test yourself

What does a packer's stub do at run time?

  1. Deletes the file
  2. Restores the original code in memory and jumps to the original entry point
  3. Signs the program
  4. Encrypts the user's files

Why does a UPX-packed PE have very few imports?

  1. UPX removes all functionality
  2. The stub imports only what it needs (LoadLibraryA, GetProcAddress...) and rebuilds the real import table at run time
  3. Imports are encrypted in the header
  4. Because it is a DLL

What is an overlay?

  1. A packed section
  2. Data appended after the last part of the image that the loader doesn't map
  3. A debugger window
  4. The DOS stub

Why is high entropy alone not proof of packing?

  1. Entropy is always high
  2. Compressed resources and embedded data also have high entropy; executable sections and the entry point matter
  3. Packers lower entropy
  4. Entropy only applies to text

In the entropy-scan lab, half of the packed executable's windows are above 7.2 bits per byte, but the whole file scores 6.981. What follows?

  1. The file is not packed
  2. Measure entropy per section or per window: a whole-file average hides a packed region
  3. The threshold should be lowered to 6.9 for every file
  4. Entropy can't be measured on executables