Ret2Libc in Action!

05 Nov 2018

This article is going to go over Return to Libc exploit. Whenever stdlib is included in a C file, a lot of functions are included as a by-product. One of the functions in stdlib/libc is system function.
This function takes one string argument and whatever argument is passed, it executes it.

     
     system("ls -l");
   
   

Above code executes ls -l command as if from a shell. The idea of a Ret2libc attack is to reference the function address of system function and to pass /bin/sh as an argument to it.
Let's give it a shot now. SSH into narnia6 with password obtained from here.

  • Snap of /narnia/narnia6.c
  • What is the vulnerability?
  • Strcpy of b1 and b2 to commandline arguments is done. Function pointer to puts() function is assigned and this passes b1 to it.

            
            strcpy(b1,argv[1]);
            strcpy(b2,argv[2]);
            fp(b1);
          
          
  • Exploitation Steps:
    1. Idea is to put address of "system" function in b1. Why? Because puts() prints b1 and could be tricked into calling system() function. Enter gdb ./narnia6 from /narnia folder. Run it. Find the address of system with (gdb)print system.
    2. Snap:
    3. Now pass this as argument to file after 8 bytes of "A"s. Where to put the "/bin/sh" to this function is the next question. Function's store their arguments generally at %ebp+8,%ebp+12 and so on(Formula is %(ebp +8 +4*(N-1))). So We need to store "/bin/sh" 8 bytes from function call. We have 8 bytes of b2 in between after which we could give "/bin/sh"
    4. Now construct the payload and run the program.
    5.         
              /narnia/narnia6 "$(python -c "print 'A'*8 + '\x50\xc8\xe4\xff')" "$(python -c "print 'A'*8 + '/bin/sh')"
            
            
    6. The shell prompt is displayed and you can cat the password for the next level.
    7. Snap:

  • Behind the scenes explanation:
  • Environmental variables are cleared and argv[] values greater than argv[2] i.e 3 and above are also cleared.
    This leads to use Ret2Libc using the 2 buffers cleverly.
    We use the fact a function looks for its arguments at specified locations from the function call address to our advantage.
    We also call system at the appropriate place with respect to this, thus gaining access to the shell.