Scripting Ghidra
Binary Analysis with Ghidra · Reverse Engineering track
13 min read
In this module
Automating Analysis with Scripts
Manual analysis takes you far, but it doesn't scale. Ghidra's scripting API lets you automate the repetitive parts: bulk cross-reference searches, pattern-based renaming, vulnerability indicator scanning, whole firmware images processed overnight without you touching a keyboard.
Ghidra's Scripting APIs
Ghidra supports two primary scripting languages:
Java - Ghidra itself is written in Java, so Java scripts have the most complete API access. They are compiled and run natively within Ghidra, offering the best performance. For complex analysis tasks and production-quality tools, Java is the preferred choice.
Python - available two ways. Jython is built into the Script Manager and sees the whole Java API, but it's Python 2.7, so modern syntax and CPython libraries such as NumPy are out. Since Ghidra 11.3, PyGhidra ships with Ghidra and runs scripts under CPython 3 with the same API (start Ghidra through the PyGhidra launcher in its support folder); extensions like Ghidrathon offered CPython support before that. The examples below stick to syntax that runs under either. Python scripts are faster to write for one-off tasks and prototyping.
Both languages access the same underlying Ghidra API through the FlatProgramAPI base class, which provides convenience methods for common operations.
Writing Your First Ghidra Script
Open the Script Manager (Window -> Script Manager) and create a new script. Here is a Python script that finds all calls to potentially dangerous functions:
# FindDangerousCalls.py# Finds calls to common vulnerability-associated functions
from ghidra.program.model.symbol import SymbolType
dangerous_functions = [ "strcpy", "strcat", "sprintf", "gets", "scanf", "memcpy", "memmove", "strncpy", "system", "popen", "execve", "printf", "fprintf", "syslog"]
program = currentProgramlisting = program.getListing()refManager = program.getReferenceManager()
for func_name in dangerous_functions: # Find the symbol for this function symbols = list(program.getSymbolTable().getSymbols(func_name)) if not symbols: continue
for sym in symbols: # Get all references TO this function refs = refManager.getReferencesTo(sym.getAddress()) call_count = 0
for ref in refs: if ref.getReferenceType().isCall(): caller = listing.getFunctionContaining(ref.getFromAddress()) caller_name = caller.getName() if caller else "unknown" print(" {} called from {} at {}" .format(func_name, caller_name, ref.getFromAddress())) call_count += 1
if call_count > 0: print("[*] {} has {} call sites\n".format(func_name, call_count))Run this script and it produces a catalogue of every call to dangerous functions, along with which function contains the call. This is the automated equivalent of the grep-based sink finding from Source Code Auditing, but operating on compiled binaries where source is unavailable.
Finding Cross-References Programmatically
Cross-reference queries are the foundation of many analysis scripts. Here is a Java script that builds a call graph from a specific function:
// CallGraphFromFunction.java// Builds a call graph starting from a selected function
import ghidra.program.model.listing.Function;import ghidra.program.model.listing.FunctionIterator;import ghidra.program.model.symbol.Reference;import java.util.*;
public class CallGraphFromFunction extends GhidraScript { @Override public void run() throws Exception { Function startFunc = getFunctionContaining(currentAddress); if (startFunc == null) { println("Place cursor inside a function first."); return; }
Set<String> visited = new HashSet<>(); Queue<Function> queue = new LinkedList<>(); queue.add(startFunc);
println("Call graph from: " + startFunc.getName());
while (!queue.isEmpty()) { Function func = queue.poll(); if (visited.contains(func.getName())) continue; visited.add(func.getName());
Set<Function> calledFuncs = func.getCalledFunctions(monitor); for (Function called : calledFuncs) { println(" " + func.getName() + " -> " + called.getName()); if (!called.isThunk() && !called.isExternal()) { queue.add(called); } } }
println("\nTotal functions in call graph: " + visited.size()); }}This builds a breadth-first call graph from the function under the cursor. For vulnerability research, you would start from a network input handler and trace all functions reachable from it - these are the functions that process untrusted data.
Bulk Renaming
When analysing firmware or large binaries, you often discover naming patterns that should be applied in bulk. For example, if you identify a logging function, all strings passed to it as the first argument are likely function names:
# BulkRenameFromStrings.py# Rename functions based on strings passed to a logging function
from ghidra.program.model.symbol import SourceType
log_func_name = "debug_log" # The logging functionsymbols = list(currentProgram.getSymbolTable().getSymbols(log_func_name))
if not symbols: print("Function '{}' not found".format(log_func_name))else: log_addr = symbols[0].getAddress() refs = currentProgram.getReferenceManager().getReferencesTo(log_addr)
for ref in refs: if not ref.getReferenceType().isCall(): continue
call_addr = ref.getFromAddress() caller = currentProgram.getListing().getFunctionContaining(call_addr) if caller is None: continue
# Look at the instruction at the call site # Try to find the string argument (first parameter) inst = currentProgram.getListing().getInstructionAt(call_addr) # Walk backward to find the string being loaded prev = inst.getPrevious() found = None while prev is not None and prev.getAddress().subtract(call_addr) > -20: for ref2 in prev.getReferencesFrom(): data = currentProgram.getListing().getDataAt(ref2.getToAddress()) if data is not None and data.hasStringValue(): found = str(data.getValue()) break if found is not None: break prev = prev.getPrevious()
# Only touch auto-named functions, and make the name a valid, # unique symbol: two call sites can log the same string if found is not None and caller.getName().startswith("FUN_"): base = "".join(c if c.isalnum() else "_" for c in found)[:60] new_name, n = base, 1 while list(currentProgram.getSymbolTable().getGlobalSymbols(new_name)): n += 1 new_name = "{}_{}".format(base, n) caller.setName(new_name, SourceType.USER_DEFINED) print("Renamed {} to {}".format(caller.getEntryPoint(), new_name))Ghidra scripts modify the program database directly. Always save your project before running experimental scripts. If a script goes wrong, you can undo changes (Ctrl+Z) or revert to a saved state. For destructive operations like bulk renaming, consider running on a copy of the binary first.
Searching for Vulnerability Patterns
Scripts excel at finding vulnerability patterns across an entire binary:
# FindUncheckedMalloc.py# Heuristic: flag malloc calls whose result is never compared with NULL
from ghidra.app.decompiler import DecompInterfacefrom ghidra.program.model.pcode import PcodeOp
PASS_THROUGH = (PcodeOp.COPY, PcodeOp.CAST, PcodeOp.MULTIEQUAL, PcodeOp.INDIRECT)COMPARES = (PcodeOp.INT_EQUAL, PcodeOp.INT_NOTEQUAL)
def is_null_checked(value, seen): # Follow the pointer through copies, casts and phi nodes, looking # for a comparison with the constant 0 for use in value.getDescendants(): opc = use.getOpcode() if opc in COMPARES: for inp in use.getInputs(): if inp.isConstant() and inp.getOffset() == 0: return True elif opc in PASS_THROUGH and use.getOutput() is not None: out = use.getOutput() if out.getUniqueId() not in seen: # phi nodes can loop seen.add(out.getUniqueId()) if is_null_checked(out, seen): return True return False
decomp = DecompInterface() # one decompiler process for the whole rundecomp.openProgram(currentProgram)fm = currentProgram.getFunctionManager()findings = []
for func in fm.getFunctions(True): if monitor.isCancelled(): break
results = decomp.decompileFunction(func, 30, monitor) if results is None or results.getHighFunction() is None: continue
for op in results.getHighFunction().getPcodeOps(): if op.getOpcode() != PcodeOp.CALL: continue target_func = fm.getFunctionAt(op.getInput(0).getAddress()) if target_func is None or target_func.getName() != "malloc": continue result = op.getOutput() # No output at all means the pointer was thrown away if result is None or not is_null_checked(result, set()): findings.append((func.getName(), op.getSeqnum().getTarget()))
decomp.dispose()
print("malloc calls with no NULL comparison found:")for func_name, addr in findings: print(" {} at {}".format(func_name, addr))It works on the decompiler's p-code rather than the assembly: each CALL to malloc has an output varnode, and getDescendants() lists the operations that use it. A check written as if (p == NULL) or if (!p) shows up as INT_EQUAL or INT_NOTEQUAL against 0. It's still a heuristic. A pointer handed to a helper that does the check, or one tested through a wrapper, will be reported anyway, so treat the output as a list to review.
Headless Analysis Mode
For batch processing, Ghidra's headless analyzer runs without the GUI:
# Import and analyse a binary, then run a script/opt/ghidra/support/analyzeHeadless \ /path/to/project MyProject \ -import target_binary \ -postScript FindDangerousCalls.py \ -scriptlog /tmp/analysis.log
# Analyse multiple binariesfor bin in firmware/*.bin; do /opt/ghidra/support/analyzeHeadless \ /path/to/project FirmwareAudit \ -import "$bin" \ -postScript VulnScan.py \ -scriptlog "/tmp/$(basename $bin).log"doneHeadless mode is essential for:
- Firmware analysis - importing and scanning hundreds of binaries extracted from firmware images
- CI/CD integration - running vulnerability scans as part of a build pipeline
- Batch variant analysis - searching for the same vulnerability pattern across all versions of a library
Integrating with Other Tools
Ghidra scripts can export data for use in other tools:
# ExportFunctionList.py# Export all functions with their addresses for use in GDB scripts
import json
functions = []func_iter = currentProgram.getListing().getFunctions(True)
for func in func_iter: functions.append({ "name": func.getName(), "address": str(func.getEntryPoint()), "size": func.getBody().getNumAddresses(), "is_thunk": func.isThunk() })
output_path = "/tmp/functions.json"with open(output_path, "w") as f: json.dump(functions, f, indent=2)
print("Exported {} functions to {}".format(len(functions), output_path))This JSON output can be consumed by GDB scripts (to set breakpoints on functions of interest), fuzzing harnesses (to identify target functions), or custom analysis tools (to build call graphs or perform additional analysis).
Scripts turn hours of manual triage into seconds of automated scanning. Whether you're picking through a single binary or running a firmware image through a vulnerability pipeline, the combination of Ghidra's analysis depth and its scripting API is genuinely hard to beat.