73 lines
3.5 KiB
Python
73 lines
3.5 KiB
Python
"""Re-run the extractor, or any snippet, against a kept and already analysed Ghidra project.
|
|
|
|
Auto-analysis dominates a batch attempt (~40 s per DLL). Iterating on
|
|
ghidra_scripts/extract_engine_surface.py against a project analysed once takes seconds:
|
|
|
|
.venv-ghidra/bin/python tools/ghidra_probe.py --project /tmp/probe DLL --extract out.json
|
|
.venv-ghidra/bin/python tools/ghidra_probe.py --project /tmp/probe DLL --snippet probe.py [args...]
|
|
|
|
A snippet runs with `program`, `flat` (FlatProgramAPI), `extractor` (the extractor's globals,
|
|
loaded without running it) and `ARGS` in scope. The DLL is only read; the project directory
|
|
is scratch state and can be deleted at any time.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
import time
|
|
from pathlib import Path
|
|
|
|
EXTRACTOR = Path(__file__).resolve().parents[1] / "ghidra_scripts/extract_engine_surface.py"
|
|
|
|
|
|
def extractor_globals(program, monitor, script_args=()):
|
|
"""The extractor's module namespace bound to `program`, without its trailing run()."""
|
|
source = EXTRACTOR.read_text(encoding="utf-8").rsplit("\nrun()", 1)[0]
|
|
scope = {"currentProgram": program, "monitor": monitor, "getScriptArgs": lambda: list(script_args),
|
|
"getSourceFile": None, "__name__": "extract_engine_surface"}
|
|
exec(compile(source, str(EXTRACTOR), "exec"), scope)
|
|
return scope
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("dll", type=Path)
|
|
parser.add_argument("--project", type=Path, required=True, help="kept Ghidra project directory")
|
|
parser.add_argument("--ghidra-home", default=os.environ.get("GHIDRA_INSTALL_DIR") or os.environ.get("GHIDRA_HOME"))
|
|
action = parser.add_mutually_exclusive_group(required=True)
|
|
action.add_argument("--extract", type=Path, metavar="OUT", help="write a snapshot like the batch does")
|
|
action.add_argument("--snippet", type=Path, metavar="PY", help="run a Python snippet against the program")
|
|
parser.add_argument("args", nargs="*", help="snippet arguments (ARGS)")
|
|
args = parser.parse_args(argv)
|
|
if not args.ghidra_home:
|
|
parser.error("set --ghidra-home or GHIDRA_INSTALL_DIR")
|
|
os.environ["GHIDRA_INSTALL_DIR"] = args.ghidra_home
|
|
args.project.mkdir(parents=True, exist_ok=True)
|
|
|
|
import pyghidra
|
|
from pyghidra.launcher import HeadlessPyGhidraLauncher
|
|
launcher = HeadlessPyGhidraLauncher(verbose=False)
|
|
launcher.vm_args.extend(["-Duser.home=" + str(args.project / "runtime-home"), "-Xmx4G"])
|
|
launcher.start()
|
|
from ghidra.util.task import ConsoleTaskMonitor
|
|
|
|
# Ghidra domain-file names reject some Polish letters; only the project-internal name changes.
|
|
name = re.sub(r"[^A-Za-z0-9_.-]", "_", args.dll.name)
|
|
with pyghidra.open_program(str(args.dll), project_location=str(args.project), project_name="probe",
|
|
program_name=name, analyze=True) as flat:
|
|
program = flat.getCurrentProgram()
|
|
started = time.monotonic()
|
|
if args.extract:
|
|
scope = extractor_globals(program, ConsoleTaskMonitor(), [str(args.extract.resolve())])
|
|
scope["run"]()
|
|
else:
|
|
scope = {"program": program, "flat": flat, "ARGS": args.args,
|
|
"extractor": extractor_globals(program, ConsoleTaskMonitor())}
|
|
exec(compile(args.snippet.read_text(encoding="utf-8"), str(args.snippet), "exec"), scope)
|
|
print("[probe] %.1fs" % (time.monotonic() - started))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|