Decompilation & Control Flow
Ghidra's decompiler is a powerful tool for converting machine code into human-readable pseudocode, enabling analysts to understand the logic of malware without manual disassembly. This section focuses on using Ghidra's decompiler to generate pseudocode and analyze control flow graphs (CFGs), which are essential for identifying execution paths, detecting obfuscation, and understanding malicious behavior.
Decompiling Machine Code to Pseudocode¶
-
Open a Binary in Ghidra
Load a binary file (e.g., a PE/ELF) viaFile > Openand ensure the binary is analyzed by Ghidra's auto-analysis tools. -
Select a Function for Decompile
In the Listing View, right-click a function (e.g.,mainor a suspicious routine) and choose Decompile. Ghidra will generate pseudocode in the Decompiler View, which resembles C-like syntax.
# Example: Decompile a function named "target_func"
# GUI Steps: Right-click "target_func" > "Decompile"
- Interpreting Pseudocode
Ghidra's decompiler translates assembly instructions into pseudocode, preserving logical operations. For example: This pseudocode reveals the function's logic, such as arithmetic operations or string manipulations.
Analyzing Control Flow Graphs (CFGs)¶
-
Generate a CFG
Right-click a function in the Listing View and select Generate Control Flow Graph. Ghidra will display nodes representing basic blocks and edges showing conditional/jump transitions. -
Understanding CFG Structure
- Nodes: Represent sequences of instructions with no branches.
- Edges: Indicate jumps (
jmp), conditional branches (je,jne), or function calls. -
Loops: Highlighted as cycles in the graph, useful for identifying repeated operations (e.g., loops in ransomware).
-
Analyzing CFG for Malicious Patterns
- Unusual Control Flow: Look for indirect jumps, excessive branching, or obfuscated conditionals (e.g., XORed addresses).
- Data Flow: Use the Data Flow Analysis tool to trace how data moves through the function (e.g., encryption keys or API calls).
# Example: Analyze data flow for a suspected encryption routine
# GUI Steps: Right-click function > "Data Flow Analysis" > "Trace Data"
Advanced Techniques¶
- CFG Export: Export the CFG as text or image (via
File > Export) for documentation or sharing. - Automated Scripting: Use Ghidra's API to script CFG generation for batch analysis.
- Cross-Referencing: Link CFG nodes to memory addresses or strings to identify hardcoded values or API calls.
Key takeaways¶
- Ghidra's decompiler converts machine code into pseudocode, simplifying malware analysis.
- Control flow graphs (CFGs) visualize execution paths, helping identify obfuscation or malicious logic.
- Combine pseudocode and CFG analysis to detect patterns like loops, conditionals, or data exfiltration.
- Use Ghidra's tools to automate CFG generation and data flow tracking for efficiency.