Binary Rewriting Frameworks
Binary Patching & Modification · Advanced Reverse Engineering track
6 min read
In this module
Automating Binary Modification
Hex editors and code-cave scavenging are fine for one-off patches. Once you're adding sections, fiddling with import tables, or rewriting a dozen functions in one go, you want tools that grasp the binary's structure. Binary rewriting frameworks parse the file, hand you a sensible API, and emit a valid output binary with every header, offset, and bit of metadata patched up.
LIEF: Library to Instrument Executable Formats
LIEF is a cross-platform library (C++/Python) for parsing, modifying, and rebuilding ELF, PE, and Mach-O binaries. It handles the complex bookkeeping of header updates, offset adjustments, and format validation.
Common LIEF operations:
# Written against LIEF 1.0import lief
# Parse an ELF binarybinary = lief.parse("target")
# Add a new section with executable codesection = lief.ELF.Section(".inject")section.content = list(shellcode_bytes)section.type = lief.ELF.Section.TYPE.PROGBITSsection.flags = (lief.ELF.Section.FLAGS.ALLOC | lief.ELF.Section.FLAGS.EXECINSTR)section = binary.add(section, loaded=True) # returns the placed copy
# Modify the entry point to our injected code. Use the section that add()# returned: the object you built still has virtual_address 0.binary.header.entrypoint = section.virtual_address
# Add a new importbinary.add_library("libcustom.so")
# Rebuild and savebinary.write("target_modified")LIEF handles the complexity of updating ELF program headers, section headers, dynamic sections, and relocation entries. For PE files, it manages the section table, import directories, and optional headers. This makes it practical to write scripts that perform complex binary transformations.
LIEF is used for: adding DRM or watermarking to binaries, injecting instrumentation into executables for testing, modifying binaries for compatibility (e.g., changing the minimum OS version), building CTF challenges by modifying existing programs, and prototyping binary security tools. Its Python bindings make it accessible for scripting complex multi-step modifications.
e9patch: Static Binary Rewriting
e9patch is a tool specifically designed for static binary rewriting of x86-64 Linux binaries. Unlike LIEF which modifies the binary format, e9patch focuses on instruction-level rewriting - replacing individual instructions with trampolines to custom code.
e9patch's key innovation is its approach to instruction replacement. Instead of requiring a minimum instruction size for a trampoline (typically 5 bytes for a near JMP), e9patch uses a technique called instruction eviction that can replace even 1-byte instructions. It achieves this by evicting nearby instructions as well, relocating them to trampolines, and chaining the results.
# Example: insert a call to a custom function before every ret instruction# (e9compile.sh builds custom_handler.c into a binary called custom_handler,# whose entry() function the patch calls; output goes to a.out)./e9compile.sh custom_handler.c./e9tool -M ret -P 'before entry()@custom_handler' target_binarye9patch operates statically (on the file, not at runtime), producing a new binary with all modifications applied. The output is a standalone executable that does not require any runtime library or injection framework.
Dyninst: Binary Instrumentation
Dyninst is a library for both static and dynamic binary instrumentation. It provides a higher-level abstraction than raw bytes: you work with functions, basic blocks, edges, and instructions as objects, and insert "snippets" of code at specific points.
Static rewriting with Dyninst:
// Open the binaryBPatch bpatch;BPatch_binaryEdit *app = bpatch.openBinary("target");
// Find the target functionBPatch_image *image = app->getImage();std::vector<BPatch_function*> funcs;image->findFunction("vulnerable_func", funcs);
// Create a snippet that logs the function callBPatch_snippet *logCall = /* build snippet */;
// Insert the snippet at function entrystd::vector<BPatch_point*> *entries = funcs[0]->findPoint(BPatch_entry);app->insertSnippet(*logCall, *entries);
// Write the modified binaryapp->writeFile("target_instrumented");Dyninst understands control flow graphs, calling conventions, and instruction semantics, so it can safely insert code at arbitrary points without breaking the program. It handles register saving, stack alignment, and instruction relocation automatically.
Comparing Approaches
Each framework has strengths:
LIEF excels at format-level modifications: adding sections, changing imports, modifying headers. It works across all major binary formats. Use it when you need to change the binary's structure rather than its individual instructions.
e9patch excels at large-scale instruction-level rewriting on Linux x86-64. It can instrument every instruction of a particular type across the entire binary efficiently. Use it for instrumentation, sanitisation, or whole-program binary hardening.
Dyninst provides the highest-level abstraction, working with functions and control flow graphs. It supports both static rewriting and runtime instrumentation (attaching to running processes). Use it when you need to understand program structure and insert complex instrumentation.
These aren't the only options. Research tools such as Zipr and RetroWrite go further and reassemble the whole binary, and Ghidra can patch and re-export instructions for small jobs. Their maturity varies, so check what each supports before committing to one.
If you're not sure which to reach for, the first question is usually whether you're changing the container or the code inside it:
Building Custom Tools
These frameworks are building blocks for custom binary tools. Real-world applications include:
- Coverage-guided fuzzing: instrument every branch in a binary to collect coverage feedback (similar to how AFL works on source-available code).
- Automatic exploit mitigation: insert bounds checks, stack canaries, or control-flow integrity checks into binaries compiled without them.
- Performance profiling: insert timing code at function entries and exits to build a profile without source-level instrumentation.
- Compatibility shims: redirect calls from deprecated APIs to modern replacements in legacy binaries.
The key advantage of frameworks over manual patching is composability: you can combine multiple modifications, apply them to different binaries, and maintain them as the target binary is updated. A script-based approach is reproducible and reviewable, unlike manual hex editing.