courses

Static Analysis

Static analysis is the examination of a binary without executing it. It is the safest form of analysis and often yields a great deal of information with no risk of infection.

File Identification and Triage

Before deep analysis, perform quick triage to understand what you’re working with.

File Type Identification

The file command reads magic bytes to identify file type regardless of extension:

$ file sample.exe
sample.exe: PE32 executable (GUI) Intel 80386, for MS Windows
$ file sample
sample: ELF 64-bit LSB executable, x86-64, dynamically linked

Hashing

Always compute and record hashes before analysis. The hash serves as the unique identifier for the sample.

$ sha256sum sample.exe
$ md5sum sample.exe   # legacy, but still used in threat intel feeds
$ ssdeep sample.exe   # fuzzy hash — useful for finding similar samples

String Extraction

The strings command extracts printable ASCII/Unicode sequences. This often reveals URLs, file paths, registry keys, error messages, and C2 addresses embedded in plaintext.

$ strings -n 6 sample.exe | less      # minimum length 6
$ strings -el sample.exe | less       # 16-bit little-endian (common in Windows)

FLOSS (the FLARE Obfuscated String Solver, formerly FireEye Labs Obfuscated String Solver) goes further by also recovering stack strings, encoded strings, and tight loops that concatenate characters:

$ floss sample.exe

PE File Format (Windows)

The Portable Executable (PE) format is used by Windows executables (.exe, .dll, .sys). Understanding the structure is essential for static analysis.

PE Structure Overview

┌──────────────────────┐
│   DOS Header         │  MZ magic bytes, legacy stub
├──────────────────────┤
│   PE Header (COFF)   │  machine type, section count, timestamps
├──────────────────────┤
│   Optional Header    │  entry point, image base, subsystem, data directories
├──────────────────────┤
│   Section Table      │  .text, .data, .rsrc, .rdata, ...
├──────────────────────┤
│   Sections           │  actual code and data
└──────────────────────┘

Examining the PE with pev

The pev toolkit provides focused views of PE structure:

$ pestr sample.exe        # strings with offset and section
$ pehash sample.exe       # multiple hash types
$ pepack sample.exe       # packing detection (entropy, section names)
$ pesec sample.exe        # security features (ASLR, DEP, CFG, SafeSEH)
$ pedis sample.exe        # disassemble entry point region
$ peres sample.exe        # resource section contents

Imports and Exports

The Import Address Table (IAT) lists functions the binary calls from external DLLs. This is one of the most valuable pieces of static information:

$ objdump -p sample.exe | grep -A 100 "Import"

Common suspicious import patterns:

Category Functions
Process injection VirtualAllocEx, WriteProcessMemory, CreateRemoteThread
Persistence RegSetValueEx, CreateService, SHGetSpecialFolderPath
Network WSAStartup, connect, InternetOpen, HttpSendRequest
Crypto CryptEncrypt, CryptHashData, BCrypt APIs
Anti-analysis IsDebuggerPresent, GetTickCount, QueryPerformanceCounter

ELF File Format (Linux)

ELF (Executable and Linkable Format) is used on Linux and most Unix-like systems.

$ readelf -h sample        # ELF header (architecture, entry point, etc.)
$ readelf -S sample        # section headers
$ readelf -d sample        # dynamic section (shared library dependencies)
$ readelf -s sample        # symbol table (if not stripped)
$ nm sample 2>/dev/null    # symbol names (works on unstripped binaries)
$ objdump -d sample | less # disassembly

Disassembly and Decompilation

We use two tools depending on the binary format:

Ghidra is the NSA’s open-source reverse engineering suite. Its decompiler is built in and costs nothing, so pseudocode is available for every supported architecture rather than being a separately licensed add-on.

Ghidra — PE Workflow

Ghidra is project-based: you create a project once and import samples into it, rather than opening a binary directly. That project is what preserves your renames, comments, and types between sessions, so create one per case rather than per sample.

  1. Launch ghidra, then File → New Project → Non-Shared Project
  2. File → Import File (or drag the sample in). Check the format and language Ghidra detected — for a 32-bit PE it should read Portable Executable (PE) and x86:LE:32:default — before clicking OK
  3. Double-click the imported file to open the CodeBrowser. Answer Yes to “… has not been analyzed. Analyze now?” and accept the default analyzers
  4. Pick a starting point from the Symbol Tree (Functions / Imports / Exports) or from

    Window → Defined Strings

  5. The Decompiler panel shows C-like pseudocode beside the listing and the two stay in sync — clicking a line in either one highlights the matching line in the other
  6. Press L to rename a function or variable, ; to comment, and G to go to an address or symbol
  7. Right-click a symbol → References → Show References To for cross-references

Ghidra ships data type archives for the Windows API, so argument names and types appear automatically for known functions. When symbols are available, File → Load PDB File applies them. The Ghidra cheat sheet has the full keymap, and the installation ships the upstream one at /opt/ghidra/docs/CheatSheet.html.

Worked Example — Headless Triage

analyzeHeadless runs the same analysis without the GUI, which is how you script triage over a batch of samples. It lives in support/ inside the installation:

$ /opt/ghidra/support/analyzeHeadless /tmp/proj Demo \
    -import bomb2/bomb2 \
    -postScript ExportFunctionInfoScript.java /tmp/proj/functions.json \
    -deleteProject

The run reports each stage, ending with:

INFO  REPORT: Analysis succeeded for file: file:///.../bomb2
INFO  REPORT: Execute script: ExportFunctionInfoScript.java '/tmp/proj/functions.json'
INFO  REPORT: Post-analysis succeeded for file: file:///.../bomb2
INFO  REPORT: Import succeeded

functions.json then holds every function Ghidra recovered:

[{"name":"_init","entry":"00401000"},
 {"name":"FUN_00401020","entry":"00401020"},
 {"name":"__isoc23_sscanf","entry":"00401030"},
 {"name":"puts","entry":"00401040"}]

Names like FUN_00401020 are Ghidra’s placeholders for functions it found but could not name — those are exactly the ones worth your attention.

Two things that will bite you in headless mode:

-deleteProject discards the project when the run finishes — drop it to keep the analysis.

Worked Example — Dumping Decompilation Headlessly

The previous example exports a function list. Getting the decompiled C out of a headless run is a common need — the Rizin one-liner for it is rizin -q -A -c 'pdgo @@F' sample — and Ghidra has no equivalent flag. Check analyzeHeadless with no arguments: there is no -export and no -decompile. You script it, which means a post-script.

Write it in Java. Ghidra compiles a .java script on the fly and needs nothing installed, whereas a .py post-script fails under analyzeHeadless with “Ghidra was not started with PyGhidra. Python is not available” — the headless analyzer does not start the Python runtime.

Save this as ~/ghidra_scripts/DumpDecompilation.java, which is on the default script search path, so no -scriptPath is needed:

//Dump the whole program's decompilation to one C file.
//@category Decompiler
import java.io.File;
import ghidra.app.script.GhidraScript;
import ghidra.app.util.exporter.CppExporter;

public class DumpDecompilation extends GhidraScript {
    @Override
    public void run() throws Exception {
        String[] args = getScriptArgs();
        File out = new File(args.length > 0 ? args[0] : "decompiled.c");
        // CppExporter(options, createHeader, createFile, emitTypes, emitGlobals, excludeTags, tags)
        CppExporter exporter = new CppExporter(null, false, true, true, false, false, null);
        exporter.setExporterServiceProvider(state.getTool());
        exporter.export(out, currentProgram, null, monitor);
    }
}
$ /opt/ghidra/support/analyzeHeadless /tmp/proj Demo \
    -import sample \
    -postScript DumpDecompilation.java /tmp/decompiled.c \
    -deleteProject

CppExporter is the same code path as File → Export Program → C/C++ in the GUI. Mind the constructor: it takes seven arguments and createHeader comes before createFile, so the obvious guess silently gives you a header instead of a C file.

Per-function output, with offsets

For the equivalent of Rizin’s pdgo — decompiled C with the originating address on each line — drive the decompiler directly. This is a PyGhidra script, run through the pyghidra Python module rather than analyzeHeadless:

#!/usr/bin/env python3
import sys, pyghidra
pyghidra.start(install_dir="/opt/ghidra")
from ghidra.app.decompiler import DecompInterface, PrettyPrinter
from ghidra.util.task import ConsoleTaskMonitor

with pyghidra.open_program(sys.argv[1], project_location=sys.argv[2]) as api:
    prog = api.getCurrentProgram()
    d = DecompInterface(); d.openProgram(prog)
    for fn in prog.getFunctionManager().getFunctions(True):
        res = d.decompileFunction(fn, 60, ConsoleTaskMonitor())
        if not res.decompileCompleted():
            print("; %s: %s" % (fn.getName(), res.getErrorMessage())); continue
        print("; ---- %s @ %s ----" % (fn.getName(), fn.getEntryPoint()))
        for line in PrettyPrinter(fn, res.getCCodeMarkup(), None).getLines():
            addrs = [t.getMinAddress() for t in line.getAllTokens() if t.getMinAddress()]
            print("%8s  %s" % (min(addrs) if addrs else "", PrettyPrinter.getText(line)))
    d.dispose()
; ---- check_key @ 00101149 ----
          bool check_key(char *param_1)
00101155    local_14 = 0;
00101192    while( true ) {
00101189      sVar1 = strlen(param_1);
0010116e      local_14 = local_14 + (char)(param_1[local_10] ^ 0x5a);
00101194    return local_14 == 0x539;

Pass project_location explicitly. Left to itself open_program puts the project beside the binary, and if that is under a dot-directory you get the same “Path element starting with ‘.’ is not permitted” rejection noted above.

Which to reach for

Approach Wall clock, one small ELF
rizin -q -A -c 'pdgo @@F' 0.3 s
PyGhidra + DecompInterface 5.7 s
analyzeHeadless + Java post-script 6.7 s

Rizin links the Ghidra decompiler as a native library; the Ghidra routes pay JVM startup every run, and across a directory of samples that dominates. Reach for headless Ghidra when you want Ghidra’s analysis — its type propagation, its data type archives, its symbol recovery — and not merely its decompiler. For “show me the C, quickly”, Rizin wins.

Cutter / Rizin / radare2 — ELF Workflow

Rizin is a community fork of radare2 with a cleaner API; Cutter is its GUI. The command vocabularies mostly overlap, and the single-command examples below work in either tool — but they have diverged, and the differences are silent rather than loud. Do not assume a command means the same thing in both.

Launch cutter, open the binary, and accept the analysis defaults. The Console pane accepts Rizin commands directly:

$ rizin -A sample        # rizin
$ r2 -A sample           # radare2

[0x00401000]> afl        # list all functions
[0x00401000]> pdf @main  # disassemble main
[0x00401000]> pdg @main  # decompile main (needs rz-ghidra, a separate package)
[0x00401000]> iz         # strings in data sections
[0x00401000]> ii         # imports

Where the two actually diverge

The foreach iterators are not the same, and this is the one that will cost you an afternoon, because the wrong iterator produces plausible output rather than an error:

Iterator radare2 6.2 Rizin 0.8
@@f every function every flag
@@F alias for @@c:afla every function

So pdgo @@f is correct in radare2 and wrong in Rizin, where it decompiles once per flag and repeats functions — on an 11-function binary that is 210 lines of output instead of 121. Nothing warns you. Check with @@? in whichever tool you are in.

Two smaller differences worth knowing:

So the batch “decompile everything” one-liner differs only in the iterator:

$ r2    -q -AA -c 'pdgo @@f' sample     # radare2
$ rizin -q -A  -c 'pdgo @@F' sample     # Rizin

Entropy Analysis

High-entropy sections indicate packed, encrypted, or compressed data:

$ binwalk -E sample.exe

A .text section with entropy > 7.0 is a strong indicator of packing. Cutter’s Dashboard shows a per-section entropy bar chart, and Ghidra shows the same under Window → Entropy.

Useful Resources


🛠️ Maintenance note: the headless and CLI material here is version-sensitive, and was verified against Ghidra 12.1.2, Rizin 0.8.2 with rz-ghidra 0.8.0, and radare2 6.2.2. Three things to re-check each term: radare2 has moved its Ghidra commands into a pd:g namespace and the pdg/pdgo aliases are likely to be retired; Rizin’s @@F / @@f split is the opposite of radare2’s and could change again on either side (confirm with @@?); and CppExporter’s constructor signature is not API-stable across Ghidra releases, so if the Java post-script stops compiling, check the argument list against the installed Decompiler.jar with javap before assuming the script is wrong. Timings are from one small ELF on one machine — the ratio is the point, not the numbers.