Перейти к основному содержимому
End-to-End Controlled ELF Exploit Development
Урок 7 из 7

End-to-End Controlled ELF Exploit Development

Profile binary mitigations, align controlled lab binaries to target libc runtimes with patchelf, and verify memory-corruption primitives systematically using GDB and pwntools.

Эксперт 40 мин Бинарная эксплуатация
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Audit ELF security mitigations including NX, stack canaries, PIE, and RELRO to map residual attack surfaces
  • Reproduce an exact target dynamic linker and libc runtime in a local lab workspace using patchelf
  • Structure an end-to-end binary verification workflow separating environment sync, information leaks, and control-flow analysis
  • Diagnose runtime mismatches and mitigation failures using GDB and pwntools diagnostic harnesses
  • Recommend compiler, linker, and sandboxing controls that enforce defense in depth for production ELF binaries

Рекомендуется заранее: Mitigations: NX, ASLR, PIE, Stack Canaries & RELROReturn-Oriented Programming (ROP) & ret2libc ChainsHeap Internals, Use-After-Free & tcache Fundamentals

#Why this matters

Isolated vulnerability concepts rarely capture how modern Linux binaries behave in production or advanced security assessments. Real ELF executables combine NX, ASLR, PIE, stack canaries, and Full RELRO, and run against specific container libc builds. A proof-of-concept that works on one workstation can fail immediately in a staging container because of a minor libc offset shift or an unbypassed mitigation.

An end-to-end engineering methodology solves this by treating binary assessment as a reproducible workflow: profile every mitigation first, lock the local runtime to the target libc, verify primitives incrementally in a debugger, and translate findings into concrete compiler and architectural fixes.

#Profiling ELF mitigations and residual surface

Before examining disassembly or writing a test harness, inspect the binary's security posture with checksec and file. Each mitigation closes specific classes of memory corruption impact while leaving distinct requirements if a vulnerability still exists:

Mitigation What it enforces Residual exposure if a bug exists
NX Stack and heap pages are non-executable Code-reuse paths remain if control flow is hijacked
Stack Canary Random guard value checked before ret Non-contiguous writes or a canary leak bypass detection
PIE Executable .text and .got randomized by ASLR Requires leaking a binary pointer before computing offsets
Partial RELRO Reorders ELF sections; .got.plt stays writable Lazy-bound GOT entries can still be overwritten
Full RELRO Resolves GOT at load time and marks it read-only Blocks GOT overwrites; pointers in .got can still be read
  1. Inspect binary (checksec / file)Record arch, PIE, RELRO, Canary, NX
  2. Check runtime deps (ldd / strings)Identify target libc and ld-linux version
  3. Pin local environment (patchelf)Match target container libraries
  4. Analyze primitives in GDBSeparate info-leak from state corruption
  5. Verify remediationRecompile with full hardening and sanitizer tests

Notice that PIE and Full RELRO change the assessment strategy fundamentally. Without PIE, binary addresses are fixed; with PIE enabled, even locating a binary function or GOT slot requires an address leak first. With Full RELRO enabled, modifying a GOT entry triggers a segmentation fault because the page is mapped read-only.

#Reproducing the target runtime with patchelf

Because libc function offsets, tcache layout rules, and internal structs differ across distributions, debugging against your host OS libc often produces misleading results. Instead of altering system libraries, copy the target libc.so.6 and matching ld-linux-x86-64.so.2 into your lab directory and update a copy of the binary with patchelf.

Pinning a controlled lab binary to a specific libc and dynamic linker
$ cp ./target_lab ./target_lab_patched
$ patchelf --set-interpreter ./ld-linux-x86-64.so.2 ./target_lab_patched
$ patchelf --replace-needed libc.so.6 ./libc.so.6 ./target_lab_patched
$ ldd ./target_lab_patched
	linux-vdso.so.1 (0x00007fff8b3fe000)
	./libc.so.6 (0x00007f4c1a200000)
	./ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007f4c1a420000)

Always confirm with ldd that the binary loads ./libc.so.6 from your working folder rather than /lib/x86_64-linux-gnu/libc.so.6. Pairing mismatched libc and ld versions typically causes an immediate SIGSEGV inside _dl_start before main even executes.

#Structuring primitive analysis and GDB harnesses

When a binary enables PIE, ASLR, Stack Canaries, and Full RELRO simultaneously, an assessment splits into clearly separated verification phases rather than a single monolithic test:

  1. Environment and symbol synchronization: Load both the patched binary and target libc in pwntools so symbol offsets and section boundaries are queried programmatically rather than hardcoded.
  2. Information-disclosure verification: Confirm whether a format string, out-of-bounds read, or dangling pointer discloses an address from the binary (defeating PIE) or from libc (defeating ASLR), and verify page alignment (address & 0xfff == 0 for bases).
  3. Mitigated state-corruption check: With randomized bases resolved conceptually, validate in GDB how far a secondary write primitive reaches -- for instance, whether a canary prevents stack return overwrites or whether a heap object header can be reached.
Diagnostic verification flow for a full-protection lab binaryDiagnostic verification flow for a full-protection lab binaryHarnessTargetGDBStart patched binary with matched libc and GDB attachedTrigger diagnostic read primitive at controlled offsetHarness validates page-aligned PIE and libc base calculationsBreak before protected state transitionInspect stack canary, heap layout, and memory permissions

Using a clean pwntools diagnostic harness keeps debugging repeatable and separates target configuration from vulnerability inspection:

python
from pwn import *

context.binary = elf = ELF("./target_lab_patched", checksec=True)
libc = ELF("./libc.so.6", checksec=False)

# Attach GDB in a controlled lab session to inspect runtime mappings
gdb_script = """
break main
continue
"""

io = gdb.debug(elf.path, gdbscript=gdb_script)
log.info(f"PIE enabled: {elf.pie}, RELRO: {elf.relro}, Canary: {elf.canary}")

# Diagnostic check: inspect expected symbol offsets in the matched libc
puts_offset = libc.symbols["puts"]
log.info(f"Matched libc puts offset: {hex(puts_offset)}")

io.close()

Keep binary interaction harnesses modular. Separating mitigation checks, symbol resolution, and GDB breakpoints allows engineers to pinpoint immediately whether a test failed due to a bad offset, an unexpected newline delimiter, or an active defence blocking the path.

#Defending and common mistakes

Production ELF deployments should enforce full compile-time and runtime hardening together so no single bug provides an easy path forward:

  • Compile with full hardening: Enable -fPIE -pie, -fstack-protector-strong, -D_FORTIFY_SOURCE=2, and -Wl,-z,relro,-z,now across all C/C++ services handling untrusted input.
  • Add kernel sandboxing: Apply seccomp-bpf syscall allow-lists and least-privilege service accounts so compromised worker processes cannot spawn shells or access sensitive files.
  • Integrate sanitizers in CI: Run ASan and UndefinedBehaviorSanitizer (-fsanitize=address,undefined) on fuzz harnesses to catch off-by-one and uninitialized-read bugs before release.

Common mistakes in end-to-end binary analysis:

  • Debugging against the workstation's system libc instead of pinning the target's exact libc and dynamic linker with patchelf.
  • Patching the interpreter without matching ld-linux to the exact libc build, causing loader crashes before main.
  • Assuming a computed base address is valid without checking that its lowest three hexadecimal digits are 000 (4 KiB page alignment).
  • Treating Full RELRO as a fix for information leaks; it prevents GOT writes, not GOT or pointer reads.

#Summary

  • An end-to-end ELF assessment starts with profiling NX, Canary, PIE, and RELRO via checksec to understand which attack paths are blocked and which primitives are required.
  • patchelf pins a controlled binary to an exact libc.so.6 and ld-linux interpreter so local debugging matches the target environment.
  • Separating environment setup, address-leak validation, and state-corruption inspection inside modular pwntools and GDB harnesses prevents guesswork and runtime drift.
  • Combining full compiler/linker hardening with seccomp-bpf sandboxing and CI sanitizers provides resilient defense in depth.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания