pwndbg for beginners: debugging and pwn in CTF

Depov

Moderator
Staff member
MODERATOR
ULTIMATE
SUPREME
PREMIUM
MEMBER
Joined
Feb 18, 2025
Messages
646
Reaction score
1,454
Why pwndbg if there is a naked GDB

GDB is a powerful debugger for pwn, but its default interface is minimalist to pain. If you want registers, type info registers. Stack — x/20gx $rsp. Disassembly — disassemble main. Three separate commands, three walls of text without illumination. In pwn CTF, a task where you need to quickly iterate - change payload, restart the binary, check the stack - such a workflow stupidly kills time. More details in our Guidelines for Binary Vulnerability Analysis.

pwndbg solves the problem radically: at each stop (breakpoint, crash, crash) automatically outputs a context display - a block of registers, a block of disassembled code with an illuminated current instruction, a block of stack and backtrace. One stop and the whole picture is in front of your eyes. Plus dozens of specialized teams: checksec to check the protection of the binary, vmmap for virtual memory card, cyclic for the generation of patterns when searching for a shift, telescope for "smart" memory viewing with pointers.

Alternatives are GEF and PEDA. GEF is the closest competitor with a similar set of features. PEDA is outdated and practically does not develop. According to the README official pwndbg repository, it loads more than 175 commands at the start, is actively supported (including integration with Binary Ninja for stripped-binary clinics). Choosing between pwndbg and GEF is a matter of habit, but pwndbg is more likely to flash in CTF writeups and training courses in binary exploitation (pwn.college, Georgia Tech CS6265). I chose pwndbg, and I never regretted it.
Installing pwndbg on Linux

Three teams, less than a minute on Ubuntu, Debian or Kali:

git clone https://github.com/pwndbg/pwndbg
cd pwndbg
./setup.sh

The script will set the Python addictions and add the download string to ~/.gdbinit. After that every launch gdb automatically tightens pwndbg. Check: recruiting gdb in the terminal and see pwndbg: loaded 175 commands. Type pwndbg [filter] for a list.. No line – open ~/.gdbinit and make sure there is source /path/to/pwndbg/gdbinit.py.

A typical ambush on Kali Linux is a conflict with a pre-installed GEF or PEDA. If in ~/.gdbinit already sitting the download string of another plugin, pwndbg will not start or issue errors. The solution is simple: comment on old lines with a symbol #, leave only pwndbg. There is no clean system of conflict.

The second frequent scenario is working on a CTF server on SSH without root. Script setup.sh determines the environment automatically and uses pip install --user for Python addictions. The superuser's rights are not necessary. On the servers of some university CTF courses (Georgia Tech CS6265) pwndbg is pre-installed and launched by a separate team gdb-pwndbg.
First run: context display pwndbg

Loading the binary: gdb ./binary_name. Put breakpoint on main - break main, launch — run. pwndbg outputs a context display from four sections. Understanding each is the basis for effective debugging of binary.

REGISTERS – values of all processor registers. In x86-64 it rax, rbx, rcx, rdx, rsi, rdi, rbp, rsp, rip and the others. The registers, changed from the last step, are highlighted in color. For pwn key: rsp (top of the stack), rbp (base of the current frame), rip (address of the following instructions). Exactly rip need to be controlled to intercept the control.

DISASM Disassembled code around the current instruction. The arrow indicates that the following will be performed. You can see it here call, ret, mov, push, pop. pwndbg highlights the syntax and shows the function names instead of the bare addresses (if the binary strip is not folded). A similar conclusion gives nearpc, extended — pdisass.

STACK – the contents of the stack from the current rsp Down. Each line is 8 bytes (x64) with automatic demoration: if the value on the stack is a pointer per line or another memory area, the pwndbg will show where it leads. This is a key advantage over naked GDB. Instead of divination by hexadecimal numbers, the real data structure is visible.

BACKTRACE is a chain of function calls that led to the current point. Where the current function is caused, through which intermediate calls. Useful when debugging binary with complex nesting.

The context display is updated automatically at each step, next, continue. For manual upgrade — context. You do not need to ask to show registers, stacks, code every time - everything is already on the screen.
Basic pwndbg teams for debugging binary
checksec is the first action with any binary

Before you search for vulnerabilities in binary files, you need to understand what protections are included. checksec shows the state of the four mechanisms, and the entire attack vector depends on the result.

NX (No-Execute) - if enabled, the stack and the pile are not executed. You can not just put shellcode on the stack and jump there - you will have to build ROP chains.

Stack Canary is the protective value between local variables and saved return address. Overflow will spun the canary - the program will be completed before returning from the function. To bypass, you need to either leak the channel value (through a format string or info leak) or find a vulnerability that overwrites a return address without rubbing the canary.

PIE (Position Independent Executable) is the randomization of the basic address of the binary. The addresses of functions and gadgets change at each launch. Need info leak to determine the base.

RELRO (Relocation Read-Only) is the protection of GOT tables. Full RELRO makes GOT read-only after downloading, Partial RELRO leaves recorded — which is already GOT overwrite.

How to read result: NX off + no canary — classic ret2sellcode. NX is included + no PIE – ret2libc or ROP at fixed addresses. All inclusive – need info leak + ROP. The same check can be performed from pwntools through ELF('./binary').checksec(), but in pwndbg the result is available directly in the session, without window switching.
vmmap – virtual memory card

vmmap outputs all segments of the virtual memory of the process: program code, data sections (.data, .bss), stack, pile, loaded libraries (libc, ld-linux). For each segment - initial and final addresses, access rights (r--, rw-, r-x) and the source of the mapping.

In practice: when building an exploit, you need to know where the libc (for ret2libc) lies, which areas are executable (for shellcode), where the stack is located (to calculate buffer addresses). If the PIE is turned off, the addresses of the code section are fixed, you can immediately look for gadgets. If the PIE is enabled, the addresses change at each start, but inside one run vmmap will show the current layout.

Another useful thing is the team aslr. Shows whether the address space randomization is enabled in the current GDB session. By default, GDB disables ASLR for playability. To check the exploit in the conditions close to the CTF server: set disable-randomization off.
telescope and stack analysis in GDB

Standard x/20gx $rsp will show 20 eight-byte values from the vertex of the stack - bare numbers. telescope $rsp 20 in pwndbg does the same, but with recursive examination: the value on the stack is a pointer? pwndbg will show where he points. That address is also a pointer, it will go further. In the end, you can't see 0x7fffffffde08, and the chain 0x7fffffffde08 → 0x7ffff7a2d830 (__libc_start_main+240).

This radially speeds up the analysis of the stack: instead of manual x/s address for each suspicious value, the telescope defuses everything automatically. For the pile is also useful - you can quickly see where the forward/backward pointers of chunks lead.

From additional teams: hexdump for hex/ASCII-dump, search to search for a string or byte sequence throughout the process memory (sent payload - perform search "AAAA" and see in which segments the input landed), stack for compact display of the current frame.
Search for offset to return address: cyclic

The most popular thing in pwndbg when solving pwn CTF tasks with buffer overflow. Task: Determine the exact number of bytes between the start of the controlled buffer and the saved return address on the stack.

Algorithm by steps:

Step 1. Generate a cyclic pattern: cyclic 200. pwndbg creates a string of 200 bytes where each substring of a given length is unique. By default, the substring is 4 bytes (for x86). For x86-64 we use cyclic -n 8 200.

Step 2. Starting the binary (run), on the request input, submit the generated pattern. You can copy from output or transmit via pipe.

Step 3. Binarnik falls with SIGSEGV - the pattern re-recorded the return address with garbage, the processor is trying to move to an invalid address. See the top of the stack through telescope $rsp 1 – there is a fragment of the pattern that took the place of return address.

Step 4. Performing cyclic -l 0x6161616861616167 -n 8 (set the value from the stack) - pwndbg will return the exact displacement in bytes.

This is a shift — the number of bytes padding in front of the address we want to write to the return address. Classic mistake of beginners: forget -n 8 for 64-bit binary. If cyclic uses 4-byte substrings, and the binary is 64-bit, the value from RSP may not be found in the pattern – and the displacement will be wrong. I was sitting on it for half an hour until I reached.

The same feature is available from pwntools: cyclic(200) generates a pattern, cyclic_find(value) finds a shift. But in pwndbg it is more convenient to iterate on the fly: sent, fell, found - you do not need to restart the script.
Step-by-step disassembly: buffer overflow operation

Typical pwn CTF script assignment: given ELF-binary for Linux x86-64, no source code, the task is to get a shell or read the flag. The whole process from the first contact with the binary to the working exploit.

Разведка. Загружаем: gdb ./vuln. Performing checksec. Let's say, we see: NX molded, no canary, no PIE, Partial RELRO. The stack is not executable (shellcode will not work), there are no canaries (you can overwrite the stack freely), PIE is off (addresses are fixed), GOT recorded. It is already possible to estimate the vector.

Static analysis. info functions – see the list of functions. If the binary is not stripped, we will see the names. In entry-level CTFs, there is often a function win, flag or get_shell – target for redirecting management. Address take through print &win or from a disassembler. Stripped-binary - there will be no names, you need Ghidra or tracing from entry point.

Finding vulnerability. Put it break main, launch run, walking through next and step. In the context display, the functions are called. Looking for dangerous: gets (does not limit the length of input - hello, 1990s), scanf("%s", ...) (similar), read with a size larger than a buffer. When calling the pwndbg function, shows arguments – the buffer address and its position on the stack.

Definition of displacement. Generate the pattern, apply to the entrance, catch crash, determine the offset through cyclic -l the process is described above. Let's say, offset = 72 bytes.

Building a payload. 72 bytes of trash + 8 bytes of the function address win in little-endian. Check in GDB: restart, submit payload, put breakpoint on ret vulnerable function. At the moment ret Watching telescope $rsp 1 - if there's an address win, the shift is correct. If not, we recalculate.

Launch. Let’s move on to automation through pwntools.
Bundbg and pwntools in pwn CTF tasks

pwndbg is a debugging tool. pwntools — Python library for automation of operation. Together they cover the full cycle: we explore the binary in pwndbg, find vulnerability and displacement, write an exploit on pwntools.

Standard exploit template (this pattern is found in every second CTF writeup on binary exploitation):

from pwn import *

elf = ELF('./vuln')
p = process('./vuln')
# p = remote('ctf.example.com', 1337)

offset = 72
win_addr = elf.sym['win']
payload = b'A' * offset + p64(win_addr)

p.sendline(payload)
p.interactive()

ELF downloads binary and gives access to symbol addresses through elf.sym['name'], to sections through elf.bss(), to build an ROP through ROP(elf). p64() packs the address in little-endian for x86-64. process() Launching locally, remote() connects to the CTF server. Switching between local debugging and remote operation is replacing one line.

For debugging an exploit with connection to pwndbg — gdb.attach(p). Opens the terminal with pwndbg connected to the process from the script. You can put breakpoints and watch how payload falls into memory at every step.

Critical nuance for remote servers (izzy.sh analyzes this in detail in «The Pwner's Roadmap"): non-conformity of libc versions. The exploit works locally, but falls on the server because the feature shifts in the libc differ between versions. On the local machine glibc 2.39, on server 2.31 — ROP-chain indicating system(), jumping into the trash. The utility pwninit solves the problem: serve a binary and server libc, it patches the binary for the correct version. For heap-tasks – glibc-all-in-one, a set of compiled glibc versions for local testing. Without this zoo, heap-pwn turns into a guess.
Debugging stripped-binary and reverse engineering in GDB

In CTF tasks of increased complexity often give stripped-binary - function names and debugging characters are deleted. info functions show only system symbols from libc, and break main will not work. Essentially the same technique as described in MITRE ATT&CK as Stripped Payloads (T1027.008) to hide the malvari, only here strip is applied to a legitimate binary to make life more difficult for participants.

pwndbg partially saves. Team entry puts breakpoint on the entry point of the ELF. From there we trace: in x86-64 address main transmitted as an argument in __libc_start_main through the register rdi. Having reached the appropriate call, put the breakpoint at the address from rdi - and we're inside main, let and without a name.

For deeper analysis, pwndbg supports integration with Binary Ninja via XML-RPC — synchronizes function names, variable stacks, and decompiled code. If Binary Ninja is not present, Ghidra does the same for static analysis: decompile, find the structure of the code and the addresses of the key functions, put breakpoints on them in pwndbg. Ghidra + pwndbg bundle is a working option for those who are not willing to pay for Binary Ninja.

Teams nearpc and pdisass display disassembled backlit code even for stripped-binary. nextcall, nextret, nextjmp allow you to quickly navigate through the code without function names - put breakpoint on the following call or ret and step according to the logic of the program, focusing on the arguments in the registers and the context of the stack.
Frequent mistakes of beginners when working with pwndbg

pwndbg is not loaded. Checking ~/.gdbinit There should be one line source for pwndbg. Multiple GDB plugins do not work at the same time. If you used to stand GEF or PEDA, we comment on their lines.

Breakpoint does not work on PIE-binary. break *0x401234 put breakpoint at a fixed address, but when the PIE is included, the code will be uploaded to another address. Solution: break main (by name) or break *$rebase(0x1234) – pwndbg will recalculate the address taking into account the current database. $rebase – a function specific to pwndbg, it is not in the naked GDB.

Confusion with calling conventions x86 and x86-64. On 32-bit binary arguments are transmitted through the stack. On 64-bit, the first six arguments go through the registers rdi, rsi, rdx, rcx, r8, r9. When building an ROP chain for a call system("/bin/sh") on x64 you need a gadget pop rdi; ret to upload the address of the line to rdi. On x86, it is enough to put the argument on the stack after the function address. Forget about this difference - guaranteed to break the exploit. I burned on it twice.

cyclic gives the wrong offset. If the binary is 64-bit, and cyclic uses 4-byte substrings (default), value from RSP may not be in the pattern. Always check architecture through file ./binary before generating the pattern and use -n 8 for x64.

Binarnik ends to breakpoint. Some CTFs use alarm() for timeout or check the presence of a debugger - the Debugger Evasion (T1622) technique. To bypass the timeout: handle SIGALRM ignore. To bypass the basic anti-debug checks based on ptrace (T1055.008): Binary causes ptrace(PTRACE_TRACEME) and the result understands that it is tracing. Bypass — catch syscall ptrace (catchpoint will work twice: when entering syscall and when exiting), after the first trigger continue, on the second (exit from syscall) – set $rax=0. It's a dirty hack, but it works.

There is no output of the program. When working in GDB stdout, the binary is sometimes buffered. If the binary uses printf without \n – withdrawal may not appear until completion. Solution: call (void)setvbuf(stdout, 0, 2, 0) in GDB (disables stdout buffering), or use pwntools with process(), where the stdout is redirected automatically.
 
Top Bottom