GScripter – Using Python to Automate GDB
As security researchers, we often have multiple tools in our toolbox for decompiling, disassembling and debugging code, as well as performing static and dynamic analysis of binaries. This is often a very personal choice where a researcher will have learned, through experience, which tools work best for them (e.g. IDA vs Ghidra). In this post, we want to share how we took one of those everyday tools, the well-known GDB debugger, and utilised an underused feature, its Python API, to enhance our vulnerability research projects. We call this GScripter.
What is GDB?
GDB (The GNU Symbolic Debugger) is a debugger (which is older than the author of this blog) that allows you to run, inspect, monitor and even manipulate the behaviour of software. For vulnerability researchers, it is a tool that helps us understand the running state of a software program, from memory layout and call stacks to examining crashes from a triggered memory corruption.
A common use case for using GDB is to inspect a program’s running state during a specific function call. A researcher can use pre-defined commands to instruct GDB to pause a program when a specific function is called and pass control over to the user; this is known as a breakpoint.
With GDB, a user can run a program, set a breakpoint at the desired location and wait for GDB to pause the program and hand control over to the GDB user. For example, take this simple C program that adds two numbers together and outputs the result to the screen:
#include
int add_numbers(int a, int b)
{
return a + b;
}
int main()
{
int a = 7;
int b = 10;
printf("Adding %i and %i\n", a, b);
int answer = add_numbers(a, b);
printf("Answer: %i\n", answer);
return 0;
}
If you were to run this program you would get the following output:
$ ./simple
Adding 7 and 10
Answer: 17
With GDB we can set a breakpoint using the following commands:
$ gdb simple
(gdb) b *add_numbers+0
Breakpoint 1 at 0x1149: file simple.c, line 4.
(gdb) run
Adding 7 and 10
Breakpoint 1, add_numbers (a=7, b=10) at simple.c:5
5 return a + b;
(gdb)
After running the program we can see the breakpoint was hit (line 7) and GDB handed control over to us. From here, we can start to inspect the state, for example we can see the arguments being passed to the add_numbers function in rdi and rsi:
(gdb) info registers
rax 0x7 7
rbx 0x7fffffffd9b8 140737488345528
rcx 0x0 0
rdx 0xa 10
rsi 0xa 10
rdi 0x7 7
If we wanted to, we could modify one of the input arguments, then continue the program, which would in turn change the output:
(gdb) set $rdi = 256
(gdb) c
Continuing.
Answer: 266
Of course, trying to replicate the above example multiple times becomes tedious and time consuming. GDB does offer Break Commands, where a series of commands or instructions can be run when a breakpoint gets hit. So to use a slightly contrived example, we may wish to automate our previous steps, by using the commands keyword to have the same sequence of instructions execute on each breakpoint, without stopping the program, like so:
(gdb) b *add_numbers+0
Breakpoint 1 at 0x1149: file simple.c, line 4.
(gdb) commands
Type commands for breakpoint(s) 1, one per line.
End with a line saying just "end".
>set $rdi = 256
>c
>end
(gdb) run
Adding 7 and 10
Breakpoint 1, add_numbers (a=0, b=0) at simple.c:4
4 {
Answer: 266
[Inferior 1 (process 54840) exited normally]
(gdb)
You can also save a set of commands to a text file and have them loaded when GDB is invoked using the -x flag.
GDB Python API
GDB also has a Python API that lets you extend it in various ways. You can add new commands, customise your own Breakpoint class, and even listen for events from GDB. Perhaps more importantly, you can use the Python API to build your own tools with GDB at the core, but that’s enough foreshadowing.
The common problem
As a researcher, you may find yourself needing to trace and inspect state across multiple libraries within a target process or want to execute code from a specific standpoint in a process. You may have been reverse engineering a binary or a set of binaries in Ghidra and probably got tothe point where you need to do some dynamic analysis to verify some assumptions.
Often, when a researcher needs to perform some dynamic analysis, they find that there are a lot of tedious steps required to be able to carry out some of those tasks. For example, think of the scenario where you have to attach to a process and add breakpoints across several stripped libraries, but their base addresses are randomised (thanks ASLR!). A reasonable approach might look something like this:
- Figure out the load addresses of your target libraries
- If you are using Ghidra with a default base address, adjust your target function offset to match the real base
- Create a GDB commands file that inserts the relevant breakpoints using
ASLR_addresses + adjusted function offsetsalong with any instructions you want to execute at each breakpoint.
This is the simplest case and requires a fair bit of manual command crafting which would likely need to be repeated after each new launch of the target process. Depending on your task, the set of steps required may be even more convoluted.
Enter GScripter
GScripter is a tool that extends GDB using its Python API with the goal of aiding researchers by reducing the need for manual intervention during debugging.
A simple GScripter script
Let’s take the example we have been using so far which is changing add_numbers in our simple binary. Below is a GScripter Python file:
// file: mysimple.py
from gscripter import GScripter
gs = GScripter(logfile="test.log")
gs.breakpoints.remove_all()
gs.starti()
simple_bin = gs.modules.get("simple")
def add_numbers_hook(gs: GScripter):
stop_execution = False
gs.log.info(f"add_numbers_hook Adding: a = {gs.regs.rdi} b = {gs.regs.rsi}")
gs.log.info(f"Changing answer to 1337")
gs.regs.rdi = 1336
gs.regs.rsi = 1
return stop_execution
gs.breakpoints.add(gs.address_of("add_numbers"), add_numbers_hook)
gs.do_cmd("c")
We can have GDB run this Python script using the source command:
(gdb) source mysimple.py
Program stopped.
0x00007ffff7fe4540 in _start () from /lib64/ld-linux-x86-64.so.2
Breakpoint 1 at 0x555555555149: file simple.c, line 4.
Adding 7 and 10
Answer: 1337
[Inferior 1 (process 104804) exited normally]
(gdb)
As you can see, we’ve replicated the previous behaviour in that we have changed the result shown by Answer. Let’s walk through what the script is doing.
This is main object class where you can specify where to save anything that you’d like to log.
gs = GScripter(logfile="test.log")
Here we are removing all previous breakpoints that are currently active in our GDB session.
gs.breakpoints.remove_all()
Removing all breakpoints allows you to:
- ensure that there are no stale commands associated with a previous run
- avoid breakpoint duplication inside GDB.
Say you wanted to change the Answer to 1338 then all you have to do is edit the following line:
gs.regs.rdi = 1337
And source your script again:
(gdb) source mysimple.py
...
Breakpoint 1 at 0x555555555149: file simple.c, line 4.
Adding 7 and 10
Answer: 1338
[Inferior 1 (process 106658) exited normally]
(gdb)
If we are not attaching to a running process we can start it using the command you saw in the GScripter script:
gs.starti()
So we’ve replicated the previous steps, but now we have the scaffolding to perform more advanced actions. The following two lines showcase the simplicity of adding breakpoints across multiple libraries even in the presence of ASLR:
simple_bin = gs.modules.get("simple")
gs.breakpoints.add(simple_bin.offset(0x1149), add_numbers_hook)
gs.breakpoints.add(simple_bin.ghidra(0x00101149), add_numbers_hook)
In the example above you will notice two ways in which the address of the add_numbers function is being acquired:
- Offset:
0x1149is the offset ofadd_numberswithin thesimplebinary. Thesimple_bin.offsetfunction will apply the ASLR load address to that offset, behind the scenes. - Ghidra: the
simple_bin.ghidrais an extension ofsimple_bin.offsetthat will strip the Ghidra base address from your target offset. That way if you are reverse engineering inside Ghidra, you can just copy the offset you see without having to keep doing the calculations yourself. For example, the default Ghidra base address is0x100000soadd_numbersis0x00101149 - 0x100000 = 0x1149. You can override the Ghidra base address that GScripter applies if you want to.
After examining state in your binary you may want to pause and drop back into GDB after sourcing your GScripter script. You can do this by modifying the boolean that your script returns:
return stop_execution // Make this True instead of False
For example:
(gdb) source mysimple.py
Program stopped.
0x00007ffff7fe4540 in _start () from /lib64/ld-linux-x86-64.so.2
Breakpoint 1 at 0x555555555149: file simple.c, line 4.
Adding 7 and 10
Breakpoint 1, add_numbers (a=0, b=0) at simple.c:4
4 {
(gdb) c
Continuing.
Answer: 1338
[Inferior 1 (process 118911) exited normally]
(gdb)
As you can see on line 10 above, we dropped back into the GDB session where we had to enter c (for continue) to continue program execution.
The last line in the GScripter script showcases that you still have access to standard GDB commands from within your Python script.
gs.do_cmd("c")
Features
Below are some of the features GScripter provides.
Memory Inspection
GScripter allows you read and write memory to examine/manipulate state easily:
def process(gs):
# Read an 8 bytes from the X21 register
ptr = gs.mem.read_uint64(gs.regs.x21)
gs.log.info(f"ptr_context {hex(ptr)} P count({gs.mem.read_uint32(ptr+0x68)})"
f" O count({gs.mem.read_uint32(ptr+0x2000)})")
gs.breakpoints.add(my_bin.ghidra(0x005f7180, 0x100000), process)
Thread-specific breakpoints
Depending on your target program, you may have multiple threads calling your target function. With GScripter, you can create thread-specific breakpoints to follow program state:
def hooking_stub(gs):
current_thread_num = gs.get_current_thread_num()
stop_execution = False
def process(gs):
stop_execution = False
global t_buffer
t_buffer = gs.regs.rax
return stop_execution
gs.breakpoints.add(gs.address_of("binder_transaction") + 0x1780,
process, thread_num=current_thread_num)
return stop_execution
gs.breakpoints.add("binder_transaction+0x07b4", hooking_stub)
Hook Symbols
You can hook specific symbols in a target binary or all symbols across multiple binaries. Supports C++ mangled/demangled and C-style symbol names.
BINDER_SYMBOL_NAME = "_ZN7android14IPCThreadState8transactEijRKNS_6ParcelEPS1_j"
BINDER_SYMBOL_NAME_CPP = "IPCThreadState::transact"
BINDER_LIBRARY_NAME = "libbinder.so"
def process(gs):
stop_execution = False
gs.log.info("Hooked")
return stop_execution
gs.hook_symbol(BINDER_LIBRARY_NAME, BINDER_SYMBOL_NAME, process)
#gs.hook_symbol( BINDER_LIBRARY_NAME, BINDER_SYMBOL_NAME_CPP, process)
#gs.hook_symbol_all(BINDER_SYMBOL_NAME, process)
#gs.hook_symbol_all(BINDER_SYMBOL_NAME_CPP, process)
Custom GDB Commands
GDlOpenCommand
Adds a new custom command, gdl, to the existing list of GDB commands to dlopen a library and call a function.
(gdb) gdl
[gscripter] [?] Gscripter Dlopen a library and call a function.
[gscripter] [?] Usage: gdl
(gdb) gdl /data/local/tmp/myminimal.so _Z3runv
[gscripter] [?] Calling dlopen(/data/local/tmp/myminimal.so, RTLD_NOW)
[gscripter] [?] Dlopened success!
[gscripter] [?] Calling dlsym: _Z3runv
[gscripter] [?] dlsym successful
[gscripter] [?] About to call function
[gscripter] [?] $3 = 1
This allows you write your own program and have it run inside your target process.
GAddrToGhidraCommand and GAddrFromGhidraCommand
We have talked about the pain between working statically and dynamically with ASLR addresses, well these commands allow you to chop and change between them e.g.
(gdb) addr_to_ghidra
[gscripter] [?] Gscripter addr_to_ghidra converts a virtual address to a Ghidra offset.
[gscripter] [?] Usage: addr_to_ghidra
(gdb) addr_to_ghidra mylib 0x7253288400 0x100000
Addr '0x7253288400' to Ghidra offset: '0x4e0400'
You might be interested in examining a global pointer you identified in Ghidra from within GDB:
(gdb) addr_from_ghidra mylib 0x4e0400 0x100000
Ghidra offset '0x4e0400' to Addr: '0x7253288400'
GSourceSetter
A command for simplifying “sourcing” a file. Unless changed, the last sourced file is sourced again. That way incremental changes in your GScripter script can be updated without having to keep specifying the path. e.g.
(gdb) gss
[gscripter] [x] Source path not defined. Nothing to source
(gdb) gss /home/jasonn/work/mygscripter.py
[gscripter] [?] source /home/jasonn/work/mygscripter.py
[gscripter] [?] [gscripter] [d] Adding registers x0, x1,
...
(gdb) gss
[gscripter] [?] source /home/jasonn/work/mygscripter.py
[gscripter] [?] [gscripter] [d] Adding registers x0, x1
...
Users can write their own custom GDB commands if they wanted to and you can even access them from within your GScripter script e.g.:
from gscripter import GScripter
gs = GScripter()
gs.log.info(gs.do_cmd("gdl /data/local/tmp/myminimal.so _Z3runv"))
Re-inventing the wheel?
Experienced researchers may well be wondering why someone would do this rather than using a popular and well-established tool such as Frida, particularly since they released their barebone-agent last year. There are a couple of reasons for this:
- If you are currently using GDB to manually do something, it can most likely be automated with GScripter. You’re probably not looking to setup Frida to quickly do something you’re already doing manually in GDB
- Frida (even the barebone-agent) is targeted against common OS and architecture combinations. We often have research targets which do not fit into this subset. GScripter helped us automate much of our existing GDB workflow in several of our own projects.
So GScripter is an enhancement for GDB. Frida is a whole dynamic instrumentation toolkit. This is very much a case of “horses for courses”.
Closing Thoughts
As researchers, we constantly work on complex problems that require us to be familiar with a plethora of different and complex tooling in order to come up with novel solutions. Sometimes, the tool itself may not be complex, but it can significantly simplify your workflow and make your day-to-day working life that much easier.
Hopefully, GScripter is a helpful tool to add to your arsenal! If you want to give it a try you can grab it from CoreTech’s GitHub.
This post was written by Jason, with contributions from Adam, both of whom are members of CoreTech’s Vulnerability Research team.
Do you have an endless curiosity for technology?
Get ready to work with some of the most brilliant minds who care more about solving problems than climbing hierarchies.