Skip to content

ghidra_analyzer.py

ofrak_ghidra.components.ghidra_analyzer

GhidraProjectAnalyzer (Analyzer)

Use Ghidra backend to create project for and analyze a binary. This analyzer must run before Ghidra analysis can be accessed from OFRAK. This Analyzer can either create a new project and new analysis for a binary or, if a config is passed to it, load an existing Ghidra project.

analyze(self, resource, config=None) async

Analyze a resource for to extract specific ResourceAttributes.

Users should not call this method directly; rather, they should run Resource.run or Resource.analyze.

Parameters:

Name Type Description Default
resource Resource

The resource that is being analyzed

required
config Optional[ofrak_ghidra.components.ghidra_analyzer.GhidraProjectConfig]

Optional config for analyzing. If an implementation provides a default, this default will always be used when config would otherwise be None. Note that a copy of the default config will be passed, so the default config values cannot be modified persistently by a component run.

None

Returns:

Type Description
GhidraProject

The analysis results

Source code in ofrak_ghidra/components/ghidra_analyzer.py
async def analyze(
    self, resource: Resource, config: Optional[GhidraProjectConfig] = None
) -> GhidraProject:

    # TODO: allow multiple headless server instances
    os.system("pkill -if analyzeHeadless")
    if config is not None:
        full_fname = config.ghidra_zip_file
        tmp_dir = None
    else:
        tmp_dir = tempfile.TemporaryDirectory()
        data = await resource.get_data()
        hash_sha256 = hashlib.sha256()
        hash_sha256.update(data)
        full_fname = os.path.join(tmp_dir.name, hash_sha256.hexdigest())
        data = await resource.get_data()
        with open(full_fname, "wb") as f:
            f.write(data)

    ghidra_project = f"{GHIDRA_REPOSITORY_HOST}:{GHIDRA_REPOSITORY_PORT}/ofrak"

    program_name = await self._do_ghidra_import(ghidra_project, full_fname)
    await self._do_ghidra_analyze_and_serve(
        ghidra_project, program_name, skip_analysis=config is not None
    )

    if tmp_dir:
        tmp_dir.cleanup()

    return GhidraProject(ghidra_project, f"{GHIDRA_SERVER_HOST}:{GHIDRA_SERVER_PORT}")

GhidraProjectConfig (ComponentConfig) dataclass

Config for GhidraProjectAnalyzer to pass in a pre-analyzed Ghidra project for a binary as a Ghidra Zip file.

A Ghidra Zip File can be exported from Ghidra's project window, right-clicking on an analyzed file and "Export...". Then select the Ghidra Zip File format and save the file. This will create a .gzf file that you can import with this GhidraProjectConfig.