Skip to main content
Be Bitwise

Extending Binaries

Binary Patching & Modification · Advanced Reverse Engineering track

6 min read

In this module

Adding New Functionality to Existing Binaries

Simple patching is fine when you're disabling or tweaking existing code. What about adding new code to a binary? You can't just splice bytes into the middle of the file. Every relative reference downstream would shift and the whole thing would unravel. The trick is adding code in places that don't disturb the existing layout.

Code Caves

A code cave is empty space inside the binary where you can park new code. Caves exist because:

  • Alignment padding: PE sections are padded on disk to the FileAlignment (usually 512 bytes) and in memory to the SectionAlignment (usually 4096), so the tail of each section's raw data is often unused zeros. ELF loadable segments are mapped in whole pages, so the slack between the end of the executable segment's content and the next page boundary can hold code too.
  • Function alignment padding: compilers like to start functions on 16-byte boundaries, padding the gaps with NOPs or INT3.
  • Dead code: linker-pulled functions or conditional code that the program never actually reaches.

The recipe: find a region big enough by scanning for runs of zeros or 0xCC, write your code at the cave address, redirect the original code with a JMP, then at the end of your cave routine run any displaced instructions and JMP back.

nasm
; Original code at 0x401000:
call check_auth ; 5 bytes - we want to intercept this
; Patch: replace with jump to code cave at 0x405000
jmp 0x405000 ; 5 bytes (E9 relative_offset)
; Code cave at 0x405000:
push rdi ; save check_auth's arguments, which the hook may clobber
push rsi ; two pushes keep RSP 16-byte aligned for the call
call our_custom_hook ; call our injected function
pop rsi ; restore registers
pop rdi
call check_auth ; execute original displaced call
jmp 0x401005 ; jump back to instruction after original

The pushes come in pairs for a reason. At the original call site RSP is 16-byte aligned, as the System V ABI requires before a call. One push would leave it off by 8 when our_custom_hook is called, and a hook compiled from C that uses aligned SSE stores (movaps) on its stack would crash. If you only need to save one register, add a sub rsp, 8 to keep the count even.

Finding Code Caves

Use a hex editor to search for large runs of null bytes (0x00) or INT3 bytes (0xCC) within executable sections. In Ghidra, look for undefined regions between functions. On Linux, the gap between the .text and .rodata sections often contains usable space. Aim for caves that are already in executable memory - code in non-executable sections will crash unless you also modify section permissions.

Adding New Sections

When caves can't hold what you need, you can graft an entirely new section onto the binary. That means rewriting headers:

For ELF: add a PT_LOAD program header that maps the new section with read-execute permissions, add a matching section header, append the section's content at the end of the file (or into expanded space), and bump the program header count.

For PE: append a new section header, increment NumberOfSections, fill in the section's VirtualAddress and characteristics (read/execute), append the data, then bump SizeOfImage to cover it.

Doing this by hand is tedious and easy to get wrong, which is exactly why tools like LIEF exist (next lesson).

Import Table Modification

Adding imports lets your injected code call library functions the original binary never touched. Maybe you want MessageBoxA in a Windows tool that only spoke console, or dlopen/dlsym in a Linux binary that wasn't dynamic-loading anything.

On PE, the import table is a tangle of structures. The Import Directory Table lists each imported DLL; each entry points at parallel arrays — the Import Lookup Table (names or ordinals) and the Import Address Table (function addresses, filled in by the loader at runtime).

Adding an import means: a new Import Directory Table entry naming the DLL, ILT and IAT entries for the function, an updated data directory pointer, and enough breathing room for the loader to find every new structure. Tools automate the whole dance.

Trampolining

A trampoline (or detour) intercepts a function call by overwriting the first few instructions of the target with a jump into your hook code. Works at runtime, works in a patched binary on disk.

The catch is preserving the bytes you just overwrote. A trampoline has three parts:

  1. Hook code: your custom logic that runs before or after the original function
  2. Displaced instructions: the original bytes that were overwritten, relocated to a new location
  3. Jump back: a jump from after the displaced instructions to the remainder of the original function
nasm
; Before patching:
target_func:
push rbp ; 1 byte
mov rbp, rsp ; 3 bytes
sub rsp, 0x20 ; 4 bytes - total 8 bytes, enough for a 5-byte jump
...
; After patching:
target_func:
jmp hook_code ; 5 bytes (overwrites first 5 bytes)
nop ; pad remaining overwritten bytes (3 bytes)
...
hook_code:
; custom logic here
push rbp ; displaced instruction 1
mov rbp, rsp ; displaced instruction 2
sub rsp, 0x20 ; displaced instruction 3 (the jmp cut into it)
jmp target_func+8 ; jump back to the first untouched instruction

The wrinkle is relative addressing. Jumps, calls, and RIP-relative memory accesses encode offsets from their original location. Relocate them and the targets drift. You have to disassemble the displaced bytes and patch up every relative operand. This is precisely why trampolining frameworks exist — instruction analysis and relocation, on tap.

Practical Considerations

A few things to remember while you're at it:

  • ASLR: if the target is PIE, your cave code has to be position-independent too — otherwise update relocations to compensate.
  • Code signing: tampering invalidates signatures. On macOS you may need to re-sign with codesign. On Windows the signature is just gone.
  • DEP/NX: your injected bytes need to live in executable memory. New sections must carry the executable flag; a cave inside .data will trip NX and crash on first use.
  • Integrity checks: some binaries checksum themselves at startup. You'll be patching out the verifier as well.