0

Possible Duplicate:
Stack Overflow Exploit in C

I need to write a program to exploit the stack overflow vulnerability of the following program. I have never done anything of this sort. I understand how it works in theory both the stack and the overflow. But I'm clueless about the implementation in C. Please help me with this. I just need a clear understanding of the steps to be taken in order to overflow the stack and generate the shell code.

#include <stdio.h>
int myprint(char* argv1)
{
    printf("%s", argv1);
}
void foo(char* argv1, char* argv2) 
{
    int (*fptr)(char*) = myprint;
    char buf[12];
    strcpy(buf, argv1);
    fptr(argv2);
}
int main(int argc, char **argv) 
{
    if (argc < 3) 
    {
            printf("error\n");
            return;
    }

    foo(argv[1], argv[2]);
}

Thanks

Community
  • 1
  • 1

1 Answers1

2

The key to your ability to exploit this code, is the following two lines:

char buf[12];
strcpy(buf, argv1);

You can see here that you have a buffer called buf of size 12 bytes, which has limited space. Now on the next line, you're taking argv1 and you're copying it into buf without checking that the size of argv1 is smaller than buf.

This means that this unchecked version of strcpy allows you to write past the end of buf and then potentially overwrite the return address of the stackframe of this function.

At the end of a stackframe just before the function returns you'll normally find in the assembler as statement like ret in assembler (can be different in different types of assembler, I'm assuming x86 here), which essentially jumps back to the caller, using the address stored on the stack (normally, depending on calling-convention, stored before this function was called).

You could then overwrite that address with something that points to some shellcode you've placed in some free space that will execute and open a shell.

Here is a section on calling-convention in X86 assembler that explains what happens when you call a function, and how the prologue and epilogue are done.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415