In this section

0.2 Loaders, Packers and Staged Payloads

Module 0

Introduction

The file that arrives is rarely the program that does the damage. Behind most deliveries sits a loader, a small program whose only job is to put the real payload in memory, and between them sit compression, encryption and downloads designed to keep the payload away from anything that scans files.

This lesson sets out why malware is staged, what packing is and how it shows, what entropy, sections and imports can and cannot prove, how a known packer is undone, and how an encrypted stage is recovered from inside a loader. It ends with the tool that reads capabilities from code, capa, and with what it reports about the compiler rather than the program.

1

Why the First File Is Rarely the Payload

Loaders and staged delivery

A loader is cheap to change and the payload behind it is not, so the two are kept apart. The loader can be rebuilt every day to defeat signatures, it can check where it is running before it fetches anything, and the operator behind it can deliver whichever payload a buyer has paid for:

Deliverythe file a useropened (0.1)runsLoadersmall, cheap,replaced oftenfetchesStagedownloaded,or decryptedstartsPayloadstealer, RATor beaconsellsHandoffaccess passedto another crew

A staged infection. Each link can be swapped without touching the others, which is why the file in front of you is so rarely the one that does the damage.

That last link is a market. In the App Installer campaigns from lesson 0.1, Microsoft saw loaders such as BATLOADER and EugenLoader delivered first, followed by remote access tools and stealers and, in some cases, a handoff to Black Basta ransomware.

Between 27 and 29 May 2024, Europol coordinated an operation against what it called the dropper ecosystem, naming IcedID, SystemBC, Pikabot, Smokeloader, Bumblebee and Trickbot, with four arrests and over 100 servers taken down.

Loaders also hide in plain sight by borrowing a trusted program. MITRE ATT&CK lists side-loading under Hijack Execution Flow: DLL, where an attacker plants a malicious DLL beside a legitimate application that loads it, so the code runs inside a trusted process. The program that starts is genuine; the library it loads is not.

Staging changes what an analyst can expect to find. The second stage often lives on a server that is taken down or rotated within days, so by the time a sample is examined the payload may no longer be downloadable.

The loader's own configuration, the address it would fetch from and anything it checks first, is then the most durable evidence there is, and the network records from the time of infection are the only place the payload's arrival was seen.

The lab pack holds three executables for this lesson, and on the surface they look much the same:

$ file mw02-*.exe | sed 's/ (stripped to external PDB)//'
mw02-loader-xor.exe: PE32+ executable (console) x86-64, for MS Windows, 10 sections
mw02-stage-upx.exe:  PE32+ executable (console) x86-64, for MS Windows, 3 sections
mw02-stage.exe:      PE32+ executable (console) x86-64, for MS Windows, 10 sections

All three are 64-bit Windows programs. The one difference file can see is the section count, and that difference is the first clue.

The compiler that built these specimens produces ten sections for even a small program, so a file from the same toolchain with three is either built very differently or has been reshaped after it was built. file cannot say which, and it cannot say anything about the loader, whose ten sections look exactly like the stage's.

Telling the three apart needs the structure inside them, which is what the rest of the lesson reads.

2

Packing

The same program, compressed

MITRE ATT&CK defines software packing as compressing or encrypting an executable, which changes the file's signature to avoid signature-based detection. The packed file carries a small stub that unpacks the original code in memory when it runs, and the utilities that do it are called packers.

MITRE names UPX and MPRESS as examples, and notes that attackers also write custom packers that leave fewer known artifacts. Sandworm used UPX to pack a copy of Mimikatz in the 2016 attack on Ukraine's power grid.

A packer reshapes the file it wraps, and radare2 shows the shape. iS entropy lists each section with its size on disk, its size in memory and its entropy:

$ r2 -q -c 'iS entropy' mw02-stage-upx.exe
[Sections]
nth paddr         size vaddr         vsize perm entropy    name
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
0   0x00000200     0x0 0x140001000  0xb000 -rwx            UPX0  # ◄ nothing on disk
1   0x00000200  0x1a00 0x14000c000  0x2000 -rwx 7.44313112 UPX1  # ◄ close to 8 bits
2   0x00001c00   0x200 0x14000e000  0x1000 -rw- 1.78981014 UPX2

Three sections replace the original's ten. UPX0 occupies nothing on disk and reserves memory, which is where the original code will be unpacked. UPX1 holds the compressed program, and its entropy sits close to 8 bits per byte, the most a byte can carry.

When the packed program starts, the stub runs first. It decompresses the original code into the empty UPX0 section, rebuilds the import table the original program needs, marks the memory executable and jumps to the original entry point. From then on the program in memory is the original one, and the file on disk never contained it in readable form. The imports tell the same story:

$ r2 -q -c 'ii' mw02-stage-upx.exe
[Imports]
nth vaddr       bind type lib          name
―――――――――――――――――――――――――――――――――――――――――――
1   0x14000e03c NONE FUNC KERNEL32.DLL LoadLibraryA  # ◄ load any DLL
2   0x14000e044 NONE FUNC KERNEL32.DLL ExitProcess
3   0x14000e04c NONE FUNC KERNEL32.DLL GetProcAddress  # ◄ find any function
4   0x14000e054 NONE FUNC KERNEL32.DLL VirtualProtect  # ◄ make memory executable
1   0x14000e064 NONE FUNC msvcrt.dll   exit

A program that loads libraries by name, finds functions by name and changes memory protection can rebuild any import table it likes at run time. Those few functions are the stub's whole kit, and the real imports are hidden until it runs.

Section names, an empty section that grows in memory, high entropy and a skeleton import table together are what "packed" means in evidence. Detect It Easy, the packer identifier in REMnux, run as diec FILE, reads the same signs and names the packer.

None of those signs is proof on its own. A section called UPX1 can be renamed, and some packers keep ordinary section names. A small import table is normal for a tiny program. What makes the verdict sound is that several independent signs agree and that the packer itself confirms it, which for UPX is its own test mode in section 4.

3

What Entropy Can and Cannot Prove

A measure of randomness, nothing more

Entropy measures how unpredictable a section's bytes are, from 0, where every byte is the same, to 8, where every byte value is equally likely. Compressed and well-encrypted data both sit near 8, because both remove the patterns ordinary code and text are full of. That makes high entropy a good lead and a poor verdict:

1. Measure each sectionentropy, from 0 to 8 bits per byte2. Close to 8?compressed or encrypted data, or both3. Then say whichpacker section names, empty raw sections, a stub's imports4. Not close to 8?look for structure: a short XOR key leaves repeats5. Neither resultsays the file is malicious, or that it is notHigha lead, not a verdictOrdinarynot a clean bill

What entropy can and cannot prove. It answers one question, how random the bytes are, and every step after that needs other evidence.

The loader shows why the lower branch matters. It is not packed, and none of its sections look unusual:

$ r2 -q -c 'iS entropy' mw02-loader-xor.exe | head -n 7
[Sections]
nth paddr         size vaddr         vsize perm entropy    name
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
0   0x00000400  0x6c00 0x140001000  0x7000 -r-x 6.35325504 .text
1   0x00007000   0x200 0x140008000  0x1000 -rw- 0.88948457 .data
2   0x00007200  0x4800 0x140009000  0x5000 -r-- 6.12757280 .rdata  # ◄ a PE inside

Its .rdata section sits around 6, an ordinary figure for a section of constants and strings, and section 6 of this lesson recovers a complete Windows executable from it. The stage inside was encrypted with a four-byte XOR key, and a short repeating key keeps much of the structure of what it hides, so the entropy barely moves.

The other direction fails too. The clean corpus holds a utility packed with the same packer, and its UPX1 section is as random as the suspect stage's. Packing is how a file was built, and legitimate software uses it.

An entropy figure is a reason to look further, never a finding about intent, and a report that says "high entropy, therefore malicious" or "normal entropy, therefore clean" has stated an inference as a fact.

Entropy is also measured per section for a reason. A whole-file figure averages a compressed section with an empty header and a table of imports, and lands somewhere unremarkable.

Very small sections give unstable figures because there are too few bytes to measure: the 512-byte UPX2 section reads under 2, which says only that it is mostly zeros. Data appended after the last section, called an overlay, belongs to no section at all and needs its own measurement, because installers and droppers often keep their cargo there.

4

Unpacking a Known Packer

When the packer can undo itself

UPX is the easy case, because UPX can reverse its own work. Its test mode checks that a file is intact UPX output, and its decompress mode writes the original program back out:

$ upx -t mw02-stage-upx.exe | tail -n 1
Tested 1 file.
$ upx -d -q -o unpacked.exe mw02-stage-upx.exe | tail -n 2
Unpacked 1 file.
$ r2 -q -c 'ii' unpacked.exe | grep -c FUNC
35
$ sha256sum unpacked.exe mw02-stage.exe
7113382eff4177d9e4dbe3235e83de0a456d124afe2b66828f86648b7a3af716  unpacked.exe
662771724662746f12b08df93b44d80e62eb5652fb3ce490347ca1c170e07ef6  mw02-stage.exe

The unpacked file has its full import table back, the same number of functions as the original stage, and its strings and sections are readable again. It does not have the same hash. UPX restores the program, not the exact bytes, so the hash of an unpacked file is a new identifier and cannot be used to search for the original.

That matters when the record is written:

Arrivedmw02-stage-upx.exe on diskupx -dUnpackedupx -d writesnew bytesreadAnalyzedunpacked.exe,its own hash

Two files, two hashes, one relationship. The fleet is searched for the file that arrived; the notes describe the copy that was analyzed.

The original and the unpacked copy are recorded as two hashes, one for what arrived and one for what was analyzed, with the relationship between them stated. A search across the fleet uses the hash of what arrived, because that is what is on disk elsewhere.

Most packers seen in real intrusions cannot be undone this way. Custom packers and protectors have no decompress option, and the usual route is to let the sample unpack itself in a sandbox or debugger and take the code from memory. That is hands-on reverse engineering, outside this course, which works from what static tools show and from prepared sandbox reports later in the course.

The memory route has costs the analyst records. Code taken from memory has its sections laid out as they are when loaded rather than as they were on disk, and its import table has to be rebuilt before tools read it cleanly.

The result is a copy for analysis, not a file that ever existed on any host, so its hash identifies nothing in the fleet. The record keeps three things apart: the file that arrived, the copy that was analyzed, and how one was produced from the other.

5

Encrypted Stages

A loader that carries its payload

A packer wraps a whole program. A loader that carries an encrypted stage is different: the loader is an ordinary program, unpacked and readable, and one of its data sections holds another program it will decrypt when it runs. The loader in the lab pack says what it does in its own message, and the bytes right after it give the rest away:

$ od -A x -t x1 -v -j 0x7200 -N 160 mw02-loader-xor.exe
007200 52 49 44 47 45 4c 49 4e 45 2d 53 50 45 43 49 4d  # ◄ the loader's own message
007210 45 4e 20 6d 77 30 32 20 6c 6f 61 64 65 72 3a 20
007220 64 65 63 6f 64 65 64 20 25 75 20 62 79 74 65 73
007230 2c 20 6e 6f 74 20 65 78 65 63 75 74 65 64 0a 00
007240 5a 13 c4 7e 00 00 00 00 00 00 00 00 00 00 00 00  # ◄ four bytes, then zeros
007250 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
007260 17 49 54 7e 59 13 c4 7e 5e 13 c4 7e a5 ec c4 7e  # ◄ "MZ" under the key
007270 e2 13 c4 7e 5a 13 c4 7e 1a 13 c4 7e 5a 13 c4 7e
007280 5a 13 c4 7e 5a 13 c4 7e 5a 13 c4 7e 5a 13 c4 7e  # ◄ the same four bytes
007290 5a 13 c4 7e 5a 13 c4 7e 5a 13 c4 7e da 13 c4 7e
0072a0

The rows from offset 0x7260 are the start of the hidden file. A Windows executable begins with the letters MZ and its header is mostly zero bytes, and the same four bytes keep repeating where those zeros should be. That is not a coincidence of the data. It is how XOR behaves:

Plain PEMZ, then a headerfull of zero bytesXORXOR key5a 13 c4 7erepeatedgivesCiphertextzero XOR keyis the keyreadRead the keyfrom any runof repeatsapplyDecryptthe whole blob,check the hash

Why a short XOR key gives itself away. Anything combined with zero is unchanged, so every run of zeros in the hidden file prints the key in the clear.

The key is therefore the repeating four bytes, and it is also stored in the clear just above the stage, where the loader keeps it for its own use. A key of any short length shows the same way. Longer keys and real ciphers do not, and recovering those means finding the decryption routine in the code, which lesson 0.9 does.

Where the key lives decides what static analysis can recover. A key embedded in the loader, as here, can always be found. A key derived from something on the victim machine, such as its name or a value in the registry, can be recomputed if the derivation is understood.

A key the loader downloads from its server at run time is not in the file at all, and without the network capture from the infection, the stage cannot be decrypted by anyone.

6

Recovering the Stage

Decrypt, trim, compare

With the offset and the key, decryption is a few lines of Python. The decrypted data runs on past the end of the stage into whatever followed it in the section, so the decoder reads the recovered PE's own section table to find where the file ends and keeps only that much:

$ python3 - <<'EOF'
import pefile
data = open('mw02-loader-xor.exe', 'rb').read()[0x7260:]
key = bytes.fromhex('5a13c47e')
plain = bytes(c ^ key[i % 4] for i, c in enumerate(data))
pe = pefile.PE(data=plain)
end = max(s.PointerToRawData + s.SizeOfRawData for s in pe.sections)
open('stage.bin', 'wb').write(plain[:end])
print(end, 'bytes written')
EOF
14848 bytes written
$ sha256sum stage.bin mw02-stage.exe
662771724662746f12b08df93b44d80e62eb5652fb3ce490347ca1c170e07ef6  stage.bin
662771724662746f12b08df93b44d80e62eb5652fb3ce490347ca1c170e07ef6  mw02-stage.exe

The hash matches the stage in the lab pack exactly, which proves the offset, the key and the trimming are all right. Unlike UPX's output, this is the original file, because XOR returns the same bytes it was given.

The record of a recovery is what lets someone else repeat it: the offset of the encrypted data, the algorithm and key, the length kept and why, and the hash of the result.

With those four, a colleague or a later analysis can reproduce the stage from the loader without trusting anyone's description of it, and the hash can be searched across the fleet in case the decrypted stage was ever written to disk.

Strings show what the encryption was hiding. FLOSS extracts readable strings from a file, and run on the loader and on the recovered stage it finds different things:

$ floss -q --only static -n 8 mw02-loader-xor.exe | grep RIDGELINE
RIDGELINE-SPECIMEN mw02 loader: decoded %u bytes, not executed
$ floss -q --only static -n 8 stage.bin | grep RIDGELINE
RIDGELINE-SPECIMEN mw02 stage: inert

The loader's own message is in the clear. The stage's message only exists once the stage is decrypted, and so would its server addresses, mutex names and file paths in a real sample. Searching the loader's strings for indicators would have found none of them.

FLOSS does more than list static strings. It also emulates parts of a program to recover strings the code builds at run time, one character at a time on the stack or through a small decoding loop, which is how much malware hides its strings without encrypting a whole stage.

The static pass used here is the quick first look; the full run is slower and finds the strings that only exist while the program executes. Neither recovers a stage encrypted as a blob, which is why the decryption came first.

7

What capa Reports

Capabilities, and whose they are

capa reads a program's code and matches it against a library of rules describing capabilities, such as encoding data, writing files or injecting code. It refuses to guess on a packed file:

$ capa mw02-stage-upx.exe 2>&1 | grep -E 'appears to be packed|unpack this'
WARNING  capa.capabilities.common:  This sample appears to be packed.   common.py:99
         unpack this input file before analyzing it with capa.

On the unpacked stage it reports capabilities, and one of them sounds alarming for a program that only prints a line:

$ capa unpacked.exe | sed -n '/Capability/,$p'
┃ Capability                                  ┃ Namespace                          ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ contain a thread local storage (.tls)       │ executable/pe/section/tls          │
│ section                                     │                                    │
│ write file on Windows                       │ host-interaction/file-system/write │
│ get thread local storage value              │ host-interaction/process           │
│ allocate or change RWX memory               │ host-interaction/process/inject    │
│ terminate process                           │ host-interaction/process/terminate │
│ enumerate PE sections (4 matches)           │ load-code/pe                       │
│ parse PE header (9 matches)                 │ load-code/pe                       │
└─────────────────────────────────────────────┴────────────────────────────────────┘

The way to read a capa result is to ask whose code matched. The clean corpus holds a utility built with the same compiler, so the same question can be put to it. Every capability is identical, and the loader adds exactly one of its own:

$ diff <(capa unpacked.exe | sed -n '/Capability/,$p') \
    <(capa clean-tool-1.exe | sed -n '/Capability/,$p') && echo identical
identical
$ capa mw02-loader-xor.exe | grep -i 'encode data'
│ DATA                 │ Encode Data::XOR [C0026.002]                              │
│ encode data using XOR                       │ data-manipulation/encoding/xor     │

The RWX memory, the file writing and the section parsing all come from the C runtime the compiler links into every program it builds. The XOR encoding is the loader's own, and it is the one finding that describes this sample rather than its toolchain. Comparing a result against a clean file built the same way is how an analyst tells the two apart.

capa does try to skip library code. It identifies known library functions with signature files and leaves them out of its matches, but the signatures it ships cover Microsoft's compiler libraries and common open source code, and these specimens were built with MinGW, so its runtime goes unrecognized.

A sample built with an unusual compiler, or a language such as Go or Rust that links a large runtime, produces the same kind of noise. Running capa with -v lists the address of each match, which shows whether it sits in the program's own functions or in runtime code reached from them.

8

Working With the Assistant

Prompt, session, record

Packing is a quick question to hand an assistant, and the quickest form of it gets the quickest answer:

OpenCode in REMnux, files namedPrepared example
Are these files packed?
One is, one is not.
  1. mw02-stage-upx.exe is packed with UPX.
  2. mw02-loader-xor.exe is not packed: its entropy is normal, so there is nothing hidden in it.
Numbered for checking against the tool output

The first line is right and the second is the inference section 3 warned against. The question invited it: it asked about packing only, so ordinary entropy looked like the end of the matter. The prompt that works asks both questions, names the confirming check and sets the standard:

PromptThe prompt that works
Two executables from one incident are in REMnux: mw02-stage-upx.exe and mw02-loader-xor.exe. For each, I need to know whether it is packed or carries an encrypted stage, and the evidence for it. Use section names, entropy, imports and the packer's own test, and treat no single sign as proof. One command at a time; wait for its output.
  1. from one incidenttells it the files belong together, so a loader and its stage are on the table
  2. packed or carries an encrypted stageasks two questions, so ordinary entropy cannot end the analysis
  3. the packer's own testnames the check that confirms a known packer instead of inferring it
  4. treat no single sign as proofsets the standard each verdict is held to
  5. wait for its outputkeeps every step on output you have seen

The session that follows shows the assistant doing most of the work well, and the two points where a short reply from the analyst changed where it went:

Packed, encrypted or neitherOpenCode in REMnux, mw02-stage-upx.exe and mw02-loader-xor.exePrepared example
  1. You
    Two executables from one incident are in REMnux: mw02-stage-upx.exe and mw02-loader-xor.exe. For each, I need to know whether it is packed or carries an encrypted stage, and the evidence for it. Use section names, entropy, imports and the packer's own test, and treat no single sign as proof. One command at a time; wait for its output.
  2. Assistant
    Start with the section table and entropy of the first file; UPX leaves its own section names.
  3. REMnux
    $ r2 -q -c 'iS entropy' mw02-stage-upx.exe | grep UPX | cut -c1-80
    0   0x00000200     0x0 0x140001000  0xb000 -rwx            UPX0
    1   0x00000200  0x1a00 0x14000c000  0x2000 -rwx 7.44313112 UPX1
    2   0x00001c00   0x200 0x14000e000  0x1000 -rw- 1.78981014 UPX2
  4. Assistant
    UPX section names, an empty UPX0 and UPX1 near 8 bits per byte. Confirm with UPX's own test mode.
  5. REMnux
    $ upx -t mw02-stage-upx.exe | tail -n 1
    Tested 1 file.
  6. Assistant
    Confirmed: UPX. Unpack it with upx -d and you have the original stage to analyze, so you can search for its hash.
  7. You
    Is the unpacked file byte for byte the original? I need to know which hash goes to the fleet search.
  8. Assistant
    Good question: UPX restores the program, not necessarily the bytes. Compare the hashes.
  9. REMnux
    $ upx -d -q -o s.exe mw02-stage-upx.exe > /dev/null
    $ sha256sum s.exe mw02-stage.exe | cut -c1-24,65-
    7113382eff4177d9e4dbe323  s.exe
    662771724662746f12b08df9  mw02-stage.exe
  10. Assistant
    They differ, so record both: search the fleet for the packed file that arrived, and analyze the copy. The loader's sections are ordinary and its entropy is normal, so it holds nothing encrypted.
  11. You
    A short XOR key would not raise the entropy. Can we look at .rdata for a hidden executable?
  12. Assistant
    Yes. A PE header is mostly zeros, and XOR over zeros prints the key. Dump the bytes after the loader's message.
  13. REMnux
    $ od -A x -t x1 -j 0x7260 -N 48 mw02-loader-xor.exe
    007260 17 49 54 7e 59 13 c4 7e 5e 13 c4 7e a5 ec c4 7e
    007270 e2 13 c4 7e 5a 13 c4 7e 1a 13 c4 7e 5a 13 c4 7e
    007280 5a 13 c4 7e 5a 13 c4 7e 5a 13 c4 7e 5a 13 c4 7e
    007290
  14. Assistant
    The same four bytes repeat where a header's zeros should be: a PE under a four-byte XOR key. I can write the decoder: read from this offset, XOR with the key, and stop at the end of the PE its own headers describe.
REMnux turns are the commands as run, with their output

Both steering points came from the analyst knowing this lesson. The first was a question about hashes, which the assistant answered correctly once asked, and which decides what the fleet search uses.

The second rejected a conclusion about entropy and proposed where to look instead, and the assistant took it straight to the key. Neither needed a long argument. A question that names the doubt is usually enough, because the assistant knows the facts and was only reaching the common conclusion too early.

The time saved sits on either side of those points. The confirming test, the hash comparison and the reason a PE header gives the key away each came at the moment they were needed, and the decoder it offered at the end is the same few lines section 6 runs, written in seconds and checked by its result.

The classification goes into the record on three facts, each from a tool rather than from the conversation:

What the classification rests on

Packed

upx -t passes on mw02-stage-upx.exe

Two hashes

the unpacked copy differs from mw02-stage.exe: the fleet search uses the file that arrived

Encrypted stage

the decrypted .rdata hashes to mw02-stage.exe (section 6)

The last is the strongest check in the lesson, because a decrypted stage that hashes to a known file cannot be a coincidence of a wrong key or offset. capa's RWX hit stays out of the record as a finding about the program, for the reason section 7 gives: a clean tool built the same way carries it too.

Do

Practice

Packed, encrypted or neither?
prepared evidence

The scenario below holds the working session and the section, import, capa and decryption results from this lesson, with the packed clean utility for comparison. Decide how to steer the assistant, then classify each file.

In the lab, run the same commands on the three mw02 files and the two clean-tool-1 files in your REMnux machine, try Detect It Easy on each with diec, and work both files in OpenCode, started in the pack's lab folder, using the prompt above. The pack's answer key, answer-key/answers.json, records which file is packed, which carries an encrypted stage and the key.

The first file is rarely the payload because loaders are cheap to change and payloads are not, and a market sells each separately. Packing shows as packer section names, empty sections that grow in memory, entropy close to 8 and a skeleton import table, and a known packer can be reversed, at the cost of a new hash.

An encrypted stage can sit at ordinary entropy, and a short XOR key gives itself away in the zeros it covers. Entropy and capability hits are leads; the record states what was shown, by which output, and keeps inference out.

Resources

Vendors and projects revise these pages; where a page and this lesson disagree, the page is newer.