Ret2LibC

Ret2libc, short for "return-to-libc," is a type of attack that allows an attacker to execute arbitrary code in a program by redirecting the program's execution flow to a function in the libc shared library.

How it works ?

The main idea is to make a simulate a valid call to the system() function by arranging the stack correctly so that the system() function launches a shell.

As explained here, A validsystem() call will push the address of the parameter onto the stack followed by the return address ( saved EIP ) :

  address   |   values
------------+-------------------------------------------------------------------
            |   +---------------------- stack frame -------------------------+
            |   | +-saved eip -+ +-- param ---+                              |
0xffffd274: |   | | 0x565561dd | | 0xffffd35c |	0x00000002	0x00000001   |
            |   | +------------+ +------------+                              |
0xffffd284: |   |   0xffffd354	  0xffffd35c	0x00000000	0xffffd2b0   |
0xffffd294: |   |   0xffffd354	  0xffffd35c	0x00000000	0xffffd2b0   |
  ...       |    ...

When a function ends and calls the RET instruction, it is actually a POP EIP that is performed, followed by a JMP EIP. The POP EIP takes the value that is on top of the stack and stores it in the EIP register. Since this value is controled (using a Buffer overflow or format string exploit for example), the JMP EIP is controled.

So, there is the stack state after a buffer overflow in order to return to the system function with a valid call :

  address   |   values
------------+-------------------------------------------------------------------
            |   +------------------------- Buffer ---------------------------+
0xffffd264: |   |   0x41414141    0x41414141    0x41414141      0x41414141   |
            |   +------------------------------------------------------------+
            |     +system addr-+ +-saved eip -+ +--- param --+               |
0xffffd274: |     | 0x565561dd | | 0xffffd35c |	| 0xffffd12c |	0x00000001   |
            |     +------------+ +------------+ +------------+               |
  ...       |    ...

Because of the call of system the return address (saved EIP) isn't important, so any value can be send here.

In order to make the stack in this state, the following payload must be used :

Getting libc base address

Getting the "/bin/sh" and "system()" addresses

Using pwntools, it's easy to retrieve theses addresses till the libc version and base address are known :

Payload

Resources

Last updated