Automating Binary Analysis with Ghidra's P-Code

Gergely Revay (Siemens)

BruCON 0x0D · Day 1

Overview

In this BruCON talk, Gergely Revay, a Security Researcher at Siemens, delves into the powerful capabilities of Ghidra, the National Security Agency's (NSA) open-source reverse engineering framework, with a particular focus on its intermediate representation (IR) known as P-Code. Revay's presentation highlights how P-Code can significantly enhance and automate binary analysis tasks, moving beyond the limitations of raw assembly code. He shares his positive experiences using Ghidra and P-Code for projects like backdoor detection, advocating for its utility to anyone involved in automating reverse engineering workflows.

Watch on YouTube

Visual summary for Automating Binary Analysis with Ghidra's P-Code by Gergely Revay
Visual summary for Automating Binary Analysis with Ghidra's P-Code by Gergely Revay

Key moments

  1. 0:00 Introduction to Ghidra and P-Code automation
  2. 6:28 Python vs. Java for Ghidra scripting
  3. 15:00 Demo 1: Listing imported functions with a Ghidra script
  4. 18:00 Understanding P-Code: Intermediate representation and advantages
  5. 30:50 Demo 3: Extracting COM object parameters using High P-Code
  6. 39:40 Q&A: Transitioning from Python to Java for Ghidra
  7. 42:00 Q&A: P-Code's awareness of calling conventions

Automating Binary Analysis with Ghidra's P-Code

Speakers: Gergely Revay, Security Researcher, Siemens

Conference: BruCON

YouTube: https://www.youtube.com/watch?v=Qift_6-3y3A

Overview

In this BruCON talk, Gergely Revay, a Security Researcher at Siemens, delves into the powerful capabilities of Ghidra, the National Security Agency's (NSA) open-source reverse engineering framework, with a particular focus on its intermediate representation (IR) known as P-Code. Revay's presentation highlights how P-Code can significantly enhance and automate binary analysis tasks, moving beyond the limitations of raw assembly code. He shares his positive experiences using Ghidra and P-Code for projects like backdoor detection, advocating for its utility to anyone involved in automating reverse engineering workflows.

The talk serves as both an introduction to Ghidra's scripting functionalities and a comprehensive exploration of P-Code's architecture and advantages. Revay meticulously explains the different levels of P-Code, demonstrates practical scripting examples in both Python and Java, and illustrates how P-Code can simplify complex analysis challenges, such as identifying and understanding Component Object Model (COM) object interactions in binaries. His insights underscore Ghidra's role as a robust, free, and open-source alternative to commercial tools like IDA Pro, especially for those needing flexible deployment without licensing constraints.

Revay emphasizes that while Ghidra's core is Java, its extensibility through scripting, particularly with the aid of P-Code, opens doors to sophisticated automated analyses. The presentation aims to equip attendees with the knowledge to leverage Ghidra's P-Code for more efficient and architecture-independent reverse engineering, making it a valuable addition to any analyst's toolkit. The speaker's journey from a self-proclaimed non-Ghidra expert to a proponent of its P-Code capabilities offers a relatable perspective for those looking to adopt new tools in their security research.

Background

▶ Watch: Introduction to Ghidra and P-Code automation (0:00)

The landscape of binary analysis has long been dominated by commercial tools like IDA Pro, revered for their powerful disassemblers and decompilers. However, these tools often come with significant licensing costs and restrictions, posing challenges for researchers or organizations requiring flexible, open-source solutions. The release of Ghidra by the NSA in 2019 dramatically shifted this dynamic, offering a free and open-source alternative that quickly gained traction within the cybersecurity community. Initially met with suspicion due to its NSA origins, Ghidra's robust feature set, including its integrated decompiler, soon established it as a credible competitor.

Gergely Revay's initial foray into Ghidra stemmed from a practical need: a project focused on backdoor detection where licensing constraints were a critical factor. His experience, initially driven by Ghidra's open-source nature, revealed the profound utility of its internal P-Code representation. P-Code, a form of Registered Transfer Language (RTL), is a low-level, architecture-independent intermediate representation that translates machine instructions into a standardized set of micro-operations. This approach is not unique to Ghidra; compilers and other reverse engineering tools like Binary Ninja also employ multi-layered IRs to abstract away architectural specifics and add higher-level context during the analysis process.

The fundamental problem P-Code addresses is the inherent complexity and architecture-dependence of assembly language. Analyzing assembly requires deep knowledge of specific instruction sets, register usage, and flag manipulation, which can vary significantly across different processor architectures (e.g., x86, ARM, MIPS). Furthermore, understanding the full impact of an assembly instruction, including its side effects on various flags or memory locations, often requires meticulous manual tracing. P-Code aims to simplify this by explicitly detailing every operation and its effects, providing a standardized, structured view of program execution that is easier to analyze programmatically and is portable across different architectures. This abstraction layer is crucial for developing automated analysis tools that are not tied to a single CPU architecture.

Key Findings

▶ Watch: Demo 1: Listing imported functions with a Ghidra script (15:00)

The talk's central findings revolve around Ghidra's extensibility and the transformative power of its P-Code intermediate representation for automated binary analysis. Revay underscores several critical points:

  1. Ghidra's Scripting Power: Ghidra offers robust scripting capabilities in both Java (its native language) and Python. While Python (via Jython or Ghidra Bridge) provides accessibility, Java offers a more native, integrated development experience with superior debugging tools (e.g., Eclipse plugin) and direct access to the full Software Development Kit (SDK). This flexibility allows users to automate tasks ranging from simple UI interactions to complex, standalone analysis tools.
  1. The Flat API vs. Program API: Ghidra provides two main API levels for scripting. The Flat Program API offers a stable, simplified set of about 150 core methods, ensuring future compatibility across Ghidra versions. The broader Program API grants access to Ghidra's entire internal class structure, offering immense power but at the cost of potential breakage with future Ghidra updates. Choosing between them depends on the script's complexity and desired longevity.
  1. P-Code as a Universal Language: P-Code acts as an architecture-independent intermediate representation (IR), translating diverse assembly instructions into a uniform set of micro-operations. This abstraction is invaluable for developing analysis tools that can operate consistently across different processor architectures without needing to understand each architecture's specific assembly dialect.
  1. Explicit Side Effects and Simplified Analysis: Unlike raw assembly, P-Code explicitly details all side effects of an instruction. For instance, instead of manually tracking which assembly instructions might set a zero flag, P-Code directly indicates when a flag is assigned. This significantly streamlines control flow analysis, making it easier to identify conditions for jumps or other conditional operations.
  1. Raw P-Code vs. High P-Code for Context: The talk distinguishes between two levels of P-Code. Raw P-Code is a direct, low-level translation of assembly instructions, providing fine-grained detail but lacking higher-level context. High P-Code, generated by Ghidra's decompiler, enriches this representation with concepts like function arguments, local variables, and structured control flow, making it much closer to a C-like representation and far more suitable for sophisticated automated semantic analysis.
  1. Automating Complex Data Extraction: High P-Code's ability to expose high-level context (e.g., function call parameters) enables automated extraction of complex data that would be extremely challenging to recover from raw assembly. The demonstration of extracting Component Object Model (COM) Class IDs (CLSIDs) and Interface IDs (IIDs) from CoCreateInstance calls exemplifies this, showcasing how High P-Code simplifies the identification of crucial program interactions.

Technical Deep Dive

▶ Watch: Understanding P-Code: Intermediate representation and advantages (18:00)

Gergely Revay's talk provides a comprehensive technical overview of Ghidra's scripting capabilities and the intricacies of its P-Code intermediate representation.

Ghidra Scripting Environment

Ghidra, being written in Java, naturally supports scripting in Java. However, recognizing the preference of many reverse engineers for Python, Ghidra also offers Python bindings via Jython. Revay notes that Jython, while functional, is limited to Python 2 and can be cumbersome due to the need for manual type casting and bridging Java objects. A more modern and recommended alternative for Python 3 scripting is Ghidra Bridge, an open-source project that significantly improves the Python scripting experience.

Despite initial reservations, Revay ultimately advocates for Java for more complex and extensive Ghidra scripting projects. He highlights the robust Java development environment support, particularly the Eclipse plugin provided by the NSA. This plugin allows developers to write, run, and debug Ghidra scripts directly within Eclipse, offering features like code completion, type information, and seamless debugging of script execution within a running Ghidra instance. This level of IDE integration significantly reduces the development overhead associated with understanding Ghidra's extensive SDK.

For script execution, Ghidra offers a headless mode, which allows running analysis scripts without the graphical user interface. This is crucial for building fully automated tools or integrating Ghidra into larger analysis pipelines, effectively turning Ghidra into a powerful reversing library.

Ghidra's SDK is vast, offering two primary access points:

  • Flat Program API: This API provides a curated set of approximately 150 stable methods and attributes. Its primary advantage is stability; methods are guaranteed not to be removed or have their signatures changed, ensuring scripts written against it remain compatible across Ghidra versions. It covers common tasks like accessing functions, memory, and program information.
  • Program API: This encompasses the entirety of Ghidra's internal classes and methods. It offers unparalleled power, allowing scripts to interact with virtually any aspect of Ghidra's functionality. However, this power comes with a caveat: scripts using the full Program API are more susceptible to breaking with Ghidra updates due to potential changes in internal class structures or method signatures. Access to Ghidra's source code and Javadoc documentation are essential for navigating this extensive API.

A simple Ghidra script typically extends the GhidraScript class and implements a run method, which serves as the script's entry point. Within this method, developers can interact with the currentProgram object to access the binary under analysis, its symbol table, memory, and other program components.

P-Code: The Intermediate Representation

At the core of Revay's talk is P-Code, Ghidra's Registered Transfer Language (RTL). P-Code is an intermediate representation (IR) designed to abstract away the specifics of different processor architectures. It translates each assembly instruction into a sequence of simpler, architecture-independent micro-operations.

The key advantage of P-Code lies in its explicit representation of side effects. In assembly, an instruction might implicitly modify several registers or flags (e.g., a CMP instruction sets various flags). Understanding these implicit effects often requires deep architectural knowledge and manual tracing. P-Code, however, explicitly states every operation and its impact. For example, instead of inferring that a JZ (jump if zero) instruction checks the zero flag, P-Code directly shows the assignment of the zero flag in a preceding operation, simplifying the analysis of conditional jumps and data flow.

Revay distinguishes between two levels of P-Code:

  1. Raw P-Code: This is the direct, instruction-by-instruction translation of assembly into P-Code operations. It provides a granular view of what each instruction does, including all its side effects. While architecture-independent, Raw P-Code still operates at a low level, lacking higher-level concepts like function parameters or local variables. It's essentially a structured, universal assembly.
  2. High P-Code: This is the output of Ghidra's decompiler. It takes Raw P-Code and applies further analysis to reconstruct higher-level constructs. High P-Code incorporates context about variables, function arguments, and control flow structures, making it much closer to a human-readable C-like representation. To access High P-Code, a script must set up Ghidra's decompiler and call the getHighFunction method on a target function, which returns a HighFunction object containing the structured P-Code.

The primary motivation for using P-Code, especially High P-Code, is architecture independence and the ability to perform semantic analysis more effectively. By working with a standardized IR, analysis tools can be written once and applied to binaries compiled for various CPU architectures. High P-Code, with its rich contextual information, enables automated recovery of function call parameters, variable definitions, and data flow paths that would be immensely challenging or impossible to extract reliably from raw assembly.

Demo / Proof of Concept

▶ Watch: Q&A: Transitioning from Python to Java for Ghidra (39:40)

Revay illustrates the power of Ghidra scripting and P-Code through three progressively complex demonstrations.

Demo 1: Listing Imported Functions (Flat API)

The first example is a simple Ghidra script designed to list all imported functions from a binary. This script showcases the basic structure of a Ghidra script and the use of the Flat Program API.

The script extends the GhidraScript class and implements the run() method. Inside run(), it accesses the currentProgram object, then retrieves the symbolTable. From the symbol table, it obtains an iterator for externalSymbols, which represent the imported functions. The script then iterates through these symbols, printing their names and the libraries from which they are imported.

This demo highlights:

  • The minimal boilerplate for a Ghidra script (GhidraScript and run method).
  • Accessing core program information (currentProgram, symbolTable).
  • Iterating over program elements (external symbols/imported functions).
  • The simplicity of using the Flat API for common tasks.

Demo 2: COM Object Reconnaissance (Raw P-Code)

The second demo focuses on identifying the use of Component Object Model (COM) objects within a binary, a common technique in malware for obfuscating C2 communication or interacting with system functionalities (e.g., Internet Explorer). The script aims to detect calls to specific COM-related Windows API functions, particularly CoCreateInstance, and then display the Raw P-Code around these call sites for manual analysis.

The script first defines a list of COM-related functions to search for. It then iterates through the imported functions (similar to Demo 1). If CoCreateInstance is found, the script retrieves all cross-references to that function. For each cross-reference, it identifies the containing basic block (a sequence of instructions with a single entry and exit point). Finally, it iterates through each instruction in that basic block and prints its corresponding Raw P-Code.

This demonstration emphasizes:

  • Identifying specific function calls of interest (e.g., CoCreateInstance).
  • Using cross-references to trace function usage.
  • Extracting and displaying Raw P-Code for specific instruction sequences.
  • Showing how Raw P-Code explicitly represents the CALL operation and its direct operands, but still requires manual interpretation for higher-level context. The speaker notes that at this stage, manual analysis is still required to understand what COM object is being created.

Demo 3: Recovering COM CLSID/IID (High P-Code)

This is the most advanced demonstration, showcasing the power of High P-Code for automated extraction of complex information. The goal is to automatically recover the Class ID (CLS ID) and Interface ID (IID) passed as arguments to CoCreateInstance calls. These UUIDs (Universally Unique Identifiers) are crucial for identifying the specific COM object and interface being used.

The script begins with boilerplate code to set up Ghidra's decompiler. When CoCreateInstance is detected, instead of just printing Raw P-Code, the script calls a helper function that leverages the decompiler. This helper function obtains the High P-Code for the function containing the CoCreateInstance call using getHighFunction().

With the HighFunction object, the script can iterate through the High P-Code operations. Crucially, when it encounters a CALL operation (specifically the call to CoCreateInstance), High P-Code provides direct access to the inputs or parameters of that function call using methods like getInputs(). The CoCreateInstance function takes the CLSID as its first parameter and the IID as its fourth. The script directly requests these parameters, which are then processed (e.g., converted from byte arrays to human-readable UUID strings) and printed.

This demo vividly illustrates:

  • The setup and use of Ghidra's decompiler within a script.
  • The distinction and superior context provided by High P-Code over Raw P-Code.
  • The ability of High P-Code to directly expose high-level concepts like function call arguments, eliminating the need for manual register tracking or stack analysis.
  • Automating the recovery of critical program data (CLS ID, IID) that would be extremely difficult to extract reliably from assembly or Raw P-Code. Revay notes that these UUIDs can then be looked up in the Windows registry or online to identify the specific COM component being used.

Defensive Implications

▶ Watch: Q&A: P-Code's awareness of calling conventions (42:00)

The insights and techniques presented in Gergely Revay's talk have significant defensive implications for cybersecurity professionals. By leveraging Ghidra's P-Code and scripting capabilities, defenders can enhance their ability to analyze, detect, and respond to sophisticated threats.

  1. Advanced Malware Analysis: P-Code provides a powerful lens for analyzing malware. Its architecture-independent nature means that analysis scripts can be developed once and applied to malware targeting various CPU architectures (e.g., x86, ARM), streamlining cross-platform threat intelligence. Explicitly detailing instruction side effects helps in understanding obfuscated code, anti-analysis techniques, or complex control flow, making it easier to pinpoint the true intent of malicious code. Identifying COM object usage, as demonstrated, is particularly relevant for malware that leverages Windows built-in functionalities (like Internet Explorer for C2) to evade detection.
  1. Automated Feature Extraction and Signature Generation: Defenders can write Ghidra scripts that automatically extract specific patterns, API calls, or data structures from binaries, even when heavily obfuscated. For instance, scripts can be developed to identify common cryptographic routines, anti-debugging tricks, or specific network communication patterns by analyzing their P-Code representation. This allows for the automated generation of more robust and resilient signatures for Intrusion Detection Systems (IDS), Endpoint Detection and Response (EDR) solutions, or threat intelligence platforms, which are less susceptible to simple changes in compilation or instruction reordering.
  1. Vulnerability Research and Patch Analysis: P-Code's ability to abstract away architectural details is invaluable for vulnerability researchers. It allows for more efficient analysis of patches to understand underlying vulnerabilities across different versions or platforms. Automated P-Code analysis can help identify subtle changes in critical functions, detect new attack surfaces, or verify whether a patch truly mitigates a specific vulnerability. Scripts can also be used to find specific code patterns known to lead to vulnerabilities, such as insecure memory operations or improper input validation.
  1. Supply Chain Security and Binary Auditing: Organizations can integrate Ghidra and P-Code-based analysis into their software supply chain security processes. Automated scripts can audit third-party binaries, firmware, or software components for suspicious behaviors, embedded backdoors, or compliance violations. By analyzing P-Code, security teams can gain deeper insights into the actual operations of deployed software, complementing traditional static analysis tools and ensuring that software adheres to security policies.
  1. Reverse Engineering Training and Education: The structured and explicit nature of P-Code can serve as an excellent educational tool for aspiring reverse engineers. Understanding how assembly instructions translate into P-Code helps in grasping the fundamental operations of a CPU and the effects of code execution, bridging the gap between low-level machine code and higher-level programming concepts.

By embracing Ghidra's P-Code, defenders can move beyond manual, time-consuming assembly analysis to build powerful, automated tools that provide deeper, more consistent, and architecture-independent insights into binary behavior, ultimately strengthening their defensive posture against evolving cyber threats.

Key Takeaways

  • Ghidra is a powerful, free, and open-source alternative to commercial reverse engineering tools like IDA Pro, offering robust features including a built-in decompiler and flexible scripting capabilities.
  • P-Code is Ghidra's architecture-independent intermediate representation (IR), translating assembly instructions into a standardized set of micro-operations that explicitly detail all instruction side effects, simplifying binary analysis.
  • High P-Code (from the decompiler) provides crucial high-level context, such as function arguments and variables, enabling automated semantic analysis that is difficult or impossible with raw assembly or Raw P-Code.
  • Ghidra scripting supports both Python and Java, with Java offering a more integrated development experience (especially with the Eclipse plugin) for complex projects, while Python (via Ghidra Bridge) is suitable for simpler tasks.
  • Automated analysis with P-Code streamlines tasks like identifying COM object usage and extracting complex data (e.g., CLS ID, IID), significantly accelerating malware analysis and vulnerability research.
  • Leveraging P-Code enhances defensive capabilities by enabling architecture-independent malware analysis, automated feature extraction for signature generation, and more efficient vulnerability research across diverse platforms.

About the Speaker(s)

Gergely Revay, or "Gary" for short, is a Security Researcher at Siemens. His work primarily involves security research, where he applies his expertise in analyzing and understanding complex systems. In addition to his corporate role, Gergely also contributes to the cybersecurity community by creating tutorials on YouTube, sharing his knowledge and practical insights with a broader audience. His experience with Ghidra and P-Code, as highlighted in this talk, stems from a project on backdoor detection, which led him to explore and ultimately advocate for the use of open-source tools and advanced intermediate representations in reverse engineering.

Reviews

→ Top-rated talks at BruCON 0x0D

All talks from BruCON 0x0D