如何在 IDE 中调试 Ghidra 插件 Python 脚本?

逆向工程 调试 吉德拉 Python
2021-06-23 19:34:30

我想使用 Eclipse 等 IDE 调试用 python 编写的 Ghidra 插件脚本。我已经安装了 Pydev 和 GhidraDev 插件(从 Ghidra 在 Eclipse 中打开一个脚本来自动安装插件)。

在 Eclipse 中打开插件脚本后,我将设置一个断点(例如在下面的打印 stmt 上),然后单击 Debug > GhidraScripts 启动 Ghidra,最后手动启动脚本(参见下面的示例脚本)。我看到了线程并且可以从 Eclipse 暂停脚本线程,但是断点永远不会被命中。

我已经尝试了 GhidraScripts (Headless) 和基于 GUI 的 GhidraScript 启动,但是我没有休息。

# Hello Function Script
# @author mechgt
# @category _NEW_
# @keybinding
# @menupath
# @toolbar

import ghidra
import time
    
# Iterate through functions, parsing and printing each
function = getFirstFunction()
while function is not None:
    print("Function: {} Address: {}".format(function.getName(), function.getEntryPoint()))
    time.sleep(3)
    function = getFunctionAfter(function)

如何获得 Ghidra Python 脚本的调试功能?

注意:Eclipse/Ghidra/PyDev 调试问题似乎与一个可能的错误有关:https : //github.com/NationalSecurityAgency/ghidra/issues/1707

1个回答

我自己不将 Eclipse 用于 Ghidra,但据我刚刚检查过,它也应该支持这一点。我可以确认这种方法(远程调试加上 Python 存根)适用于 PyCharm。

使用 pydevd 进行远程调试

基本思想是使用与pydevd或类似的远程调试https://stackoverflow.com/a/41492711/13220684解释了基本用法。

这样做的问题是您必须安装pydevd在 Ghidra Jython 环境中。以下内容改编自https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator#python-packages

# Create a virtualenv for Ghidra packages.
# It is important to use Python2.7 for this venv!
# If you want, you can skip this step and use your default Python installation.
mkvirtualenv ghidra
 
# Create Jython's site-pacakges directory.
jython_site_packages="~/.local/lib/jython2.7/site-packages"
mkdir -p $jython_site_packages
 
# Create a PTH file to point Jython to Python's site-packages directories.
# Again, this has to be Python2.7.

# Outside a virtualenv, use
python -c "import site; print(site.getusersitepackages()); print(site.getsitepackages()[-1])" > $jython_site_packages/python.pth

# If using virtualenv, use the following instead
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())" > $jython_site_packages/python.pth

 
# Use pip to install packages for Ghidra
pip install pydevd

现在应该可以import pydevd在 Ghidra Python 脚本(甚至集成的 REPL)中使用。

我不记得 eclipse 的 GhidraDev 插件是否为ghidraPython 脚本中模块提供选项卡补全,但这种设置足够通用,如果您更喜欢另一个 Python IDE,则不需要再使用 Eclipse。

IDE 只需要通过pydevd. 如果您使用另一个 IDE 向 IDE 提供 Ghidra API 的类型信息、方法签名和文档字符串,我还强烈建议使用https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator

另一种解决方法

我个人主要使用ghidra_bridge和前面提到的 Python 类型存根和 Ghidra。因为ghidra_bridge是一个完整的 RPC 接口,所以您可以编写一个具有完整 IDE 支持的 Python 3 脚本并通过 IDE 运行它。ghidra_bridge然后处理与 Ghidra Python 环境的连接并代理所有相关对象。对于类型存根,IDE 只是将脚本视为通用 Python 脚本,并将ghidra模块视为任何 Python 3 模块。