> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/rev-eng/scripting/ghidra-scripting.md).

# Ghidra Scripting

## PyGhidra Installation

First, we need to make sure PyGhidra is installed and configured:

* Install Python 3.12 if needed
* Install PyGhidra with `pip install pyghidra`
* Make sure you have an environment variable called `GHIDRA_INSTALL_DIR` pointing to your Ghidra-directory
* Start Ghidra with `python.exe -m pyghidra --gui --install-dir "<Ghidra_install_dir>"` to launch Ghidra with PyGhidra activated

Then we select `Script Manager` in the `Window`-menu in Ghidra and click the `Create New Script`-button. Select the `PyGhidra` script type.

## Script examples

### Flag extraction #1

Script to extract flag from the picoCTF-challenge `ASCII FTW`

```python
# Script to extract the flag from the picoCTF-challenge ASCII FTW
#@author Cajac
#@category _NEW_
#@keybinding 
#@menupath 
#@toolbar 
#@runtime PyGhidra

def extract_flag():
    addr_factory = currentProgram.getAddressFactory()
    start_addr = addr_factory.getAddress("00101175")
    end_addr   = addr_factory.getAddress("00101200")

    listing = currentProgram.getListing()
    instruction = listing.getInstructionAt(start_addr)

    flag_chars = []

    while instruction is not None and instruction.getAddress().compareTo(end_addr) < 0:
        if instruction.getMnemonicString() == "MOV":
            op_objects = instruction.getOpObjects(1)

            if op_objects and len(op_objects) > 0:
                scalar = op_objects[0]
                if hasattr(scalar, 'getValue'):
                    flag_chars.append(chr(int(scalar.getValue())))

        instruction = listing.getInstructionAfter(instruction.getAddress())

    print("Flag:", ''.join(flag_chars))

extract_flag()
```

## Resources

Ghidra - Homepage: <https://ghidra-sre.org/>

Ghidra - Kali Tools: <https://www.kali.org/tools/ghidra/>

PyGhidra - README - Ghidra Docs: <https://pypi.org/project/pyghidra/>

pyghidra - PyPI Module: <https://pypi.org/project/pyghidra/>
