Alex Balgavy

Just some stuff about me.

Here's my dotfiles repository.

Check out my blog.

My keys: PGP, SSH

My crypto wallets (BTC, XMR)


What links here:

Ghidra scripting

Ghidra uses Python 2.

Get the current program:

prog = currentProgram.getListing()

Get information

func_addr = toAddr(0xB00B5)
func = prog.getFunctionContaining(func_addr)
func_entry = func.getEntryPoint()
func_name = func.getName()

inst = prog.getInstructionAt(func_addr)
instBefore = prog.getInstructionBefore(inst)
instAfter = prog.getInstructionAfter(inst)
instAddress = inst.getAddress()
instOp = inst.getMnemonicString() # => "CALL", "MOV", etc.
firstInstArg = inst.getDefaultOperandRepresentation(0)
nextInst = inst.getNext()

Check if a call operand is indirect

ghidra.program.model.lang.OperandType.isIndirect(inst.getOperandType(0))

Modifying things

removeFunctionAt(toAddr(0xB00B50))
createFunction(toAddr(0xB00B5), "boobs")

# Nop some bytes
for i in range(0, n_bytes):
    clearListing(some_addr.add(i))
    setByte(some_addr.add(i), 0x90)
    disassemble(some_addr.add(i))

# Patch an instruction (watch out for space!)
asm = ghidra.app.plugin.assembler.Assemblers.getAssembler(currentProgram)
clearListing(addr)
setEOLComment(addr, "patched here")
asm.assemble(addr, "CALL 0xB00B5")

Get arguments passed on the commandline (askFile doesn’t work in headless)

args = getScriptArgs()

Run a script headlessly

[ -z "$GHIDRA_HOME" ] && printf 'Please set $GHIDRA_HOME\n' >&2 && exit 1
[ -x "$GHIDRA_HOME"/support/analyzeHeadless ] || { printf 'analyzeHeadless not found in $GHIDRA_HOME\n' >&2 && exit 1; }
GHIDRA_PROJECT="headlessBinary"
BIN_FILE="binary"
PATCHED_BIN_FILE="$(pwd)/patched-$BIN_FILE"
GHIDRA_BIN_FILE=`basename $BIN_FILE`

# Output file has to exist
touch "$PATCHED_BIN_FILE"

# create project and import file
$GHIDRA_HOME/support/analyzeHeadless . $GHIDRA_PROJECT -import $BIN_FILE

# Run deobfuscator and patcher
$GHIDRA_HOME/support/analyzeHeadless . $GHIDRA_PROJECT -process $GHIDRA_BIN_FILE \
-scriptPath ./scripts \
-postScript scripts/deobfuscator.py arg1 \
-postScript scripts/FixedBinaryExporter.java "$PATCHED_BIN_FILE"

Useful sites: