示例#1
0
    def vncSetupStrategy(self):
        self.password = '******'

        logging.debug('%s Started.' % self)
        logging.debug('%s Connection started, sending protocol version: [%s]' %
                      (self, rfb.protocolVersion()))
        self.request.sendall(rfb.protocolVersion())

        cli_ver = self.request.recv(12)
        logging.debug('%s received client protocol [%s]' % (self, cli_ver))

        # Offer security types

        if cli_ver[:11] == rfb.protocolVersion()[:11]:
            logging.debug('%s Sending security types to client' % self)
            self.request.sendall(rfb.securityTypes())
        else:
            logging.debug("%s sending 'invalid version' to client" % self)
            self.request.sendall(rfb.invalidVersion())
            logging.debug('%s Closed connection due to invalid version.' %
                          self)
            self.request.close()

    # Receive client chosen security type

        cli_sec_type = self.request.recv(1)
        logging.debug('%s received security type [%s] from client' %
                      (self, hexlify(cli_sec_type)))

        # VNC authentification:

        if cli_sec_type == rfb.security['VNC_AUTH']:
            logging.debug('%s sending auth challenge: [%s] to client' %
                          (self, hexlify(rfb.vncStaticAuthChallenge())))
            self.request.sendall(rfb.vncAuthChallenge())

            cli_sec_response = self.request.recv(16)

            logging.debug('%s received security response [%s] from client' %
                          (self, hexlify(cli_sec_response)))

            # logging.debug("%s decrypted response [%s] from client" % (self, hexlify(decrypt_response(self.password, cli_sec_response))))

            # TODO: consider if verification of the userinputable jobidentifer can
            #       be verified at this stage
            # if verify_response(self.password, data, rfb.vncAuthChallenge()):

            if 1:
                logging.debug('%s sending security result OK2 to client' %
                              self)
                self.request.sendall(rfb.securityResult(True))

                # THIS IS THE MAGIC: THE IDENTFIER IS FOUND!

                self.provider_identifier = hexlify(cli_sec_response)
            else:
                logging.debug(
                    '%s Closed connection invalid authentification.' % self)
                self.request.sendall(rfb.securityResult(False))
                self.closeConnection()
        elif cli_sec_type == rfb.security['NONE']:

            # None: TODO: block this since it not usefull for proxy-awareness

            logging.debug('%s sending security result OK1 to client' % self)
            self.request.sendall(rfb.securityResult(True))
        else:

            # Implement other authentification mechanisms here if
            # specifications for TightVNC / UltraVNC can be found.
            # Note: this doesn't matter in the chase of proxy-awareness... anyway this is
            #       where it would be done.

            logging.debug('%s sending security result BAD to client' % self)
            self.request.sendall(rfb.securityResult(False))
            self.closeConnection()
示例#2
0
  def vncSetupStrategy(self):
    self.password  = '******'
    
    logging.debug("%s Started." % self)
    logging.debug("%s Connection started, sending protocol version: [%s]" % (self, rfb.protocolVersion()))
    self.request.sendall(rfb.protocolVersion())
    
    cli_ver = self.request.recv(12)
    logging.debug("%s received client protocol [%s]" % (self, cli_ver))

    # Offer security types
    if cli_ver[:11] == rfb.protocolVersion()[:11]:
      logging.debug("%s Sending security types to client" % self)
      self.request.sendall(rfb.securityTypes())      
    else:
      logging.debug("%s sending 'invalid version' to client" % self)
      self.request.sendall(rfb.invalidVersion())
      logging.debug('%s Closed connection due to invalid version.' % self)
      self.request.close()
      
    # Receive client chosen security type
    cli_sec_type = self.request.recv(1)
    logging.debug("%s received security type [%s] from client" % (self, hexlify(cli_sec_type)))
    
    # VNC authentification:
    if cli_sec_type == rfb.security['VNC_AUTH']:
      logging.debug("%s sending auth challenge: [%s] to client" % (self, hexlify(rfb.vncStaticAuthChallenge())))
      self.request.sendall(rfb.vncAuthChallenge())
      
      cli_sec_response = self.request.recv(16)
      
      logging.debug("%s received security response [%s] from client" % (self, hexlify(cli_sec_response)))
      #logging.debug("%s decrypted response [%s] from client" % (self, hexlify(decrypt_response(self.password, cli_sec_response))))
      
      # TODO: consider if verification of the userinputable jobidentifer can
      #       be verified at this stage
      #if verify_response(self.password, data, rfb.vncAuthChallenge()):
      if 1:
        logging.debug("%s sending security result OK2 to client" % self)
        self.request.sendall(rfb.securityResult(True))
        
        # THIS IS THE MAGIC: THE IDENTFIER IS FOUND!
        self.provider_identifier = hexlify(cli_sec_response)
      else:
        logging.debug('%s Closed connection invalid authentification.' % self)
        self.request.sendall(rfb.securityResult(False))
        self.closeConnection()
      
    # None: TODO: block this since it not usefull for proxy-awareness
    elif cli_sec_type == rfb.security['NONE']:
      logging.debug("%s sending security result OK1 to client" % self)
      self.request.sendall(rfb.securityResult(True))
      
    # Implement other authentification mechanisms here if
    # specifications for TightVNC / UltraVNC can be found.
    # Note: this doesn't matter in the chase of proxy-awareness... anyway this is
    #       where it would be done.
    else:
      logging.debug("%s sending security result BAD to client" % self)
      self.request.sendall(rfb.securityResult(False))
      self.closeConnection()
示例#3
0
  def datareceived(self, data):
    
    # Receive protocol version, send protocol version
    if self.state == 0:
      
      logging.debug('%s received protocol [%s] from vncserver ' % (self, data))
            
      if data == rfb.protocolVersion():
        logging.debug('%s sending protocol [%s] to vncserver ' % (self, rfb.protocolVersion()))
        self.buffersize = 1
        self.request.sendall(rfb.protocolVersion())
        self.state += 10
      else:
        logging.debug('%s Closed connection due to invalid version.' % self)
        self.closeConnection()

    # Receive security type count, choose one and send it back
    elif self.state == 10:
      
      self.securityTypeCount = unpack('!B', data)
      logging.debug('%s about to receive [%s] security types from vncserver' % (self, self.securityTypeCount))      
      
      if (self.securityTypeCount > 0):
        self.buffersize = self.securityTypeCount[0]
        self.state = 11
      else:
        self.closeConnection()
    
    # Receive "self.securityTypeCount" security types, then pick one
    elif self.state == 11:
      
      logging.debug('%s received security types [%s] from vncserver ' % (self, hexlify(data)))
      logging.debug('%s sending choice [%s] to vncserver ' % (self, hexlify(rfb.securityType(self.secType))))
      self.request.sendall(rfb.securityType(self.secType))
      self.buffersize = 4
      self.state = 30

    # Do authentification, this is skipped when choosing security type None
    elif self.state == 20:
      response = generate_response(self.password, data)
      logging.debug('%s received auth challenge [%s]: ' % (self, hexlify(data)))
      logging.debug('%s sending encrypted response [%s]: ' % (self, hexlify(response)))
      self.request.sendall(rfb.vncAuthResponse(response))
      
      # do auth based of chosen method      
      self.state = 30

    # Receive security result, send client init
    elif self.state == 30:
      
      secResult = unpack('!I', data)
      if secResult == (0,): # SUCCESS
        logging.debug('%s send client init message to vncserver'  % self)
        self.request.sendall(rfb.clientInit(True))
        self.buffersize = 24
        self.state = 40
      else: # FAILURE
        self.buffersize = secResult[0]
        self.state = 31
    
    # Received auth failure reason
    elif self.state == 31:
      
      logging.debug('%s received security result [%s] from vncserver ' % (self, hexlify(data)))
      
      if data == rfb.securityResult(False):
        logging.debug('Closed connection due to invalid auth.')
        self.closeConnection()
      else:
        logging.debug('%s send client init message to vncserver'  % self)
        self.request.sendall(rfb.clientInit(True))
        self.buffersize = 24
        self.state = 40
      
    # Receive server init, start sending client messages  
    elif self.state == 40:
          
      self.serverInit = unpack('!HHBBBBHHHBBBBBBI', data)
      logging.debug('%s received server init [%s] len %d hostlen %d'  % (self, self.serverInit, len(self.serverInit), self.serverInit[15]))
      
      self.buffersize = self.serverInit[15]
      self.state = 41

    # Receive server name, send pixelformat and encodings      
    elif self.state == 41:
      
      hostname = data
      
      self.migraId = generate_response(hostname, rfb.vncAuthChallenge())
      
      logging.info('[hostname=%s] [migraid=%s]' % (hostname, hexlify(self.migraId)))
      
      # Set pixel and set encodings
      self.request.sendall(rfb.setPixelFormat(32, 24, False, True, 255, 255, 255, 16, 8, 0))
      self.request.sendall(rfb.setEncodings())
      self.buffersize = 1024
      
      self.state = 50
      
    elif self.state == 50:
            
      # The first byte off all request are the messageType
      # Determine client request and based on policy: forward, local, drop the message.
      messageType = data[0:1]
      knownMessageType = False
      for messageTypesName, messageTypeValue in rfb.clientMessages.iteritems():
        if messageTypeValue == messageType:
          knownMessageType = True
          logging.debug('%s Received message type [%s] from vncserver' % (self, messageTypesName))
            
      # Forward request to client
      logging.debug("%s [clients=%d] >>" % (self, len(self.vnc_clients)))
        
      # Try to find a client connection      
      if len(self.vnc_clients)  == 0:
        
        logging.debug("%s Trying to find a matching vncclient" % self)
        
        self.lock.acquire()
        
        for t in self.threads:        
          if t.__class__.__name__ == 'VncClientHandler' and \
            t.migraId == self.migraId and \
            t.migraId != None:
            
            logging.debug("%s found %s migraIds:[\n %s,\n  %s]" % (self, t, hexlify(t.migraId), hexlify(self.migraId)))
            self.vnc_clients.append(t)
            
        self.lock.release()
      
      # Forward to client(s)
      if len(self.vnc_clients) > 0:
                
        for client in self.vnc_clients:
          logging.debug("%s [forwarding=%s,\n  to client=%s\n  from server %s]" % (self, hexlify(messageType), hexlify(client.migraId), hexlify(self.migraId)))
          
          try:
            client.request.sendall(data)
          except:
            self.vnc_clients.remove(client)
            logging.exception("%s client disconnected %s" % (self, hexlify(client.migraId)))
            logging.debug("%s client disconnected %s" % (self, hexlify(client.migraId)))
      
      logging.debug("%s   <<" % self)
          
    else:
      logging.debug('%s Closed connection due to invalid/unknown state.' % self)
      self.closeConnection()
示例#4
0
    def handle(self):

        logging.debug('%s MIP Server is here!' % self)

        keep_running = True
        identifier = None
        proxyHost = None

        try:
            self.request.settimeout(900)
            data = self.request.recv(1)
        except:
            logging.debug('%s Proxy Agent Request timeout!' % self)
            data = -1

        if data == mip.messages['HANDSHAKE']:

            try:
                logging.debug('%s Data-raw [%s] ' % (self, repr(data)))
                handshake = self.request.recv(5)
                logging.debug('%s Init-raw [%s] ' % (self, repr(handshake)))
                initMessage = unpack('!BI',
                                     handshake)  # Grab the proxys handshake
                logging.debug('%s Init [%s] ' % (self, initMessage))

                identifier = self.request.recv(initMessage[1])

                # Transform identifier to user inputable representation, vnc style

                identifier = \
                    hexlify(generate_response(vnc_jobid(identifier),
                            rfb.vncAuthChallenge()))

                logging.debug('%s Ident [%s] ' % (self, identifier))

                proxyHost = mip.ServerInfo(self.request, self.client_address,
                                           initMessage[1], identifier)
                logging.debug('%s Proxy Agent [%s] ' % (self, proxyHost))
            except:

                # Handle premature close of request

                logging.exception('%s Error receiving data.' % self)

            if not data:
                logging.debug('%s Data empty' % self)
                pass

            logging.debug('%s Taking a lock' % self)

            MiGTCPServer.proxyLock.acquire()

            # Check if it already there ( in case of reconnect )

            if identifier in MiGTCPServer.proxy_agents:
                del MiGTCPServer.proxy_agents[identifier]

            # Add proxy agent to list of agent

            MiGTCPServer.proxy_agents[identifier] = proxyHost
            MiGTCPServer.proxyLock.release()

            logging.debug('%s Thats it im done..' % self)
        elif data == mip.messages['SETUP_REQUEST']:

            # TODO: this is where daisy chaining stuff chould be added...

            logging.debug('%s setup request ' % self)
        elif data == mip.messages['SETUP_RESPONSE']:

            logging.debug('%s response request ' % self)

            (ticket, status) = unpack('!IB', self.request.recv(5))
            logging.debug('%s ticket %s, status %s' % (self, ticket, status))

            # handle vnc server

            self.vncServerStrategy()

            # Add proxy_agent to connection pool

            MiGTCPServer.connectionCondition.acquire()
            MiGTCPServer.connections[ticket] = \
                mip.ServerInfo(self.request, self.client_address, 0, 3)
            MiGTCPServer.connectionCondition.notifyAll()
            MiGTCPServer.connectionCondition.release()
        else:

            logging.debug('%s Incorrect messagetype %s' % (self, repr(data)))
            keep_running = False

        # TODO: still relevant after we added timeout above and stop on error?
        # This is f*****g annoying! If the handler exited then the socket is
        # closed... so it must stay alive doing shit but consume resources...

        while keep_running:
            time.sleep(1000)
示例#5
0
  def datareceived(self, data):
        
    # receive protocol version and send security types
    if self.state == 0:
     
      logging.debug("%s received client protocol [%s]" % (self, data))
      
      if data == rfb.protocolVersion():
        logging.debug("%s Sending security types to client" % self)
        self.request.sendall(rfb.securityTypes())
        self.buffersize = 1
        self.state += 10
      else:
        logging.debug("%s sending 'invalid auth' to client" % self)
        self.request.sendall(rfb.invalidVersion())
        logging.debug('%s Closed connection due to invalid version.' % self)
        self.closeConnection()

    # received clients chosen security type, start authentification
    elif self.state == 10:
      
      logging.debug("%s received security type [%s] from client" % (self, hexlify(data)))
      
      # VNC authentification:
      if data == rfb.security['VNC_AUTH']:
        logging.debug("%s sending auth challenge: [%s] to client" % (self, hexlify(rfb.vncAuthChallenge())))
        self.request.sendall(rfb.vncAuthChallenge())
        self.state += 10
        self.buffersize = 16
      # None
      elif data == rfb.security['NONE']:
        logging.debug("%s sending security result OK1 to client" % self)
        self.request.sendall(rfb.securityResult(True))
        self.buffersize = 0
        self.state += 20 # Proceed to initilization (30)
        
      # Implement other authentification mechanisms here if
      # specifications for TightVNC / UltraVNC can be found.
      else:
        logging.debug("%s sending security result BAD to client" % self)
        self.request.sendall(rfb.securityResult(False))
        self.closeConnection()
    
    # received security response from client, send security result back
    elif self.state == 20:
      
      logging.debug("%s received security response [%s] from client" % (self, hexlify(data)))
      logging.debug("%s decrypted response [%s] from client" % (self, hexlify(decrypt_response(self.password, data))))
      
      self.buffersize = 1 # TODO: does this work??
      
      # Do a stuff depending on auth method, currently only
      #if verify_response(self.password, data, rfb.vncAuthChallenge()):
      if 1:
        logging.debug("%s sending security result OK2 to client" % self)
        self.request.sendall(rfb.securityResult(True))
        self.state += 10
        
        # TODO: store the auth reponse
        self.migraId = data
      else:
        logging.debug('%s Closed connection invalid authentification.' % self)
        self.request.sendall(rfb.securityResult(False))
        self.closeConnection()
    
    # received client init, sending server init
    elif self.state == 30:
      
      logging.debug("%s received client init [%s]" % (self, hexlify(data)))
      logging.debug("%s sending server init to client" % self)
      
      if 1: # TODO: Verify client message and store it in client structure
        
        serverInit = None
        
        # TODO: IMPROVE ON THIS
        self.lock.acquire()
        
        for t in self.threads:        
          if t.__class__.__name__ == 'VncServerHandler' and \
            t.migraId == self.migraId and \
            t.migraId != None:

            serverInit = t.serverInit
            logging.debug("%s trying to find a serverInit [%s] [%s,%s]" % (self, serverInit, serverInit[0],serverInit[1]))

        self.lock.release()
        
        if serverInit != None:
            self.request.sendall(rfb.serverInit(serverInit[0], serverInit[1], rfb.PIXEL_FORMAT, 'MIG Virtual Machine.'))
        else:
            # TODO: do something better when server is not connected yet.
            self.request.sendall(rfb.serverInit(1024, 768, rfb.PIXEL_FORMAT, 'MIG Virtual Machine.'))
            
        self.buffersize = 1024
        self.state += 10
      else:
        logging.debug('%s Closed connection due to bad initialisation.'  % self)
        self.closeConnection()
    
    # Vnc doing it's thing
    elif self.state == 40:
      
      # The first byte off all request are the messageType
      # Determine client request and based on policy: forward, local, drop the message.
      messageType = data[0:1]
      knownMessageType = False
      for messageTypesName, messageTypeValue in rfb.clientMessages.iteritems():
        if messageTypeValue == messageType:
          knownMessageType = True
          logging.debug('%s Received message [%s]' % (self, messageTypesName))
      
      if not knownMessageType:
        logging.debug('%s Unknown messagetype [%s]' % (self, messageType))
      
      logging.debug("%s   >>" % self)
      
      # Try to find a server connection
      if self.vnc_server == None:
        
        logging.debug("%s Trying to find a matching vncserver" % self)
        
        self.lock.acquire()
        for t in self.threads:        
          if t.__class__.__name__ == 'VncServerHandler' and \
            t.migraId == self.migraId and \
            t.migraId != None:
            self.vnc_server = t
            logging.debug("%s found %s migraIds:[\n %s,\n  %s]" % (self, self.vnc_server, hexlify(self.vnc_server.migraId), hexlify(self.migraId)))

        self.lock.release()

      # Forward request to server
      if self.vnc_server != None:
        
        try:
          logging.debug("%s [forwarding=%s,\n from client=%s\n to server %s]" % (self, hexlify(messageType), hexlify(self.migraId), hexlify(self.vnc_server.migraId)))        
          self.vnc_server.request.sendall(data)
        except:
          logging.exception("%s server disconnected %s" % (self, hexlify(self.vnc_server.migraId)))
          self.vnc_server = None
                
      logging.debug("%s   <<" % self)
      
      # Put this somewhere else, it's very sexy and very experimental :)
      # TODO:  reverse the text, fix colors
      if messageType == rfb.clientMessages.get('FRAMEBUFFER_UPDATE_REQUEST') and self.vnc_server == None:
        
        logging.debug("%s trying to send fake framebufferupdate" % self)
        blockSize = 1024 * 768 * (32 / 8)
        input = open('/home/safl/proxy/vncmedia/wait.bmp', 'r')
        block = input.read(blockSize+70) # funny offset due to bmp representation
        block = block[70::]
        
        fakestatus = rfb.Rectangle(0, 0, 1024, 768, block)
        
        framebufferupdate = pack("!BBHHHHHi", 0, 0, 1,
                                 fakestatus.x, fakestatus.y, fakestatus.width, fakestatus.height,
                                 0)
        try:          
          self.request.sendall(framebufferupdate)
          self.request.sendall(block[::-1]) # reverse the order
        except:
          logging.exception('%s Closed connection due to failure in sending status image!' % self)
          self.closeConnection()          
      
    else:
      logging.debug('%s Closed connection due to unknown data input!' % self)
      self.closeConnection()
示例#6
0
  def handle(self):
    
    logging.debug('%s MIP Server is here!' % self)
    
    identifier  = None
    proxyHost   = None
    
    #try:
    #  self.request.settimeout(30)
    data = self.request.recv(1)
    #except:
    #  logging.debug('%s Proxy Agent Request timeout!' % self)
    #  data = -1

    if data == mip.messages['HANDSHAKE']:
      
      try:
        logging.debug('%s Data-raw [%s] ' % (self, repr(data)))
        handshake = self.request.recv(5)
        logging.debug('%s Init-raw [%s] ' % (self, repr(handshake)))
        initMessage = unpack('!BI', handshake) # Grab the proxys handshake
        logging.debug('%s Init [%s] ' % (self, initMessage))
        
        identifier  = self.request.recv(initMessage[1])
        
        # Transform identifier to user inputable representation, vnc style
        identifier = hexlify(generate_response(vnc_jobid(identifier), rfb.vncAuthChallenge()))
        
        logging.debug('%s Ident [%s] ' % (self, identifier))
              
        proxyHost   = mip.ServerInfo(self.request, self.client_address, initMessage[1], identifier)
        logging.debug('%s Proxy Agent [%s] ' % (self, proxyHost))        
        
      except: # Handle premature close of request
        logging.exception('%s Error receiving data.' % self)
        
      if not data:
        logging.debug('%s Data empty' % self)
        pass
      
      logging.debug('%s Taking a lock' % self)
      
      MiGTCPServer.proxyLock.acquire()
                  
      # Check if it already there ( in case of reconnect )
      if identifier in MiGTCPServer.proxy_agents:
        del MiGTCPServer.proxy_agents[identifier]
      
      # Add proxy agent to list of agent
      MiGTCPServer.proxy_agents[identifier] = proxyHost
      MiGTCPServer.proxyLock.release()      
      
      logging.debug('%s Thats it im done..' % self)    
    
    # TODO: this is where daisy chaining stuff chould be added...
    elif data == mip.messages['SETUP_REQUEST']:
      
      logging.debug('%s setup request ' % self)

    elif data == mip.messages['SETUP_RESPONSE']:
      
      logging.debug('%s response request ' % self)
      
      (ticket,status) = unpack('!IB', self.request.recv(5))
      logging.debug('%s ticket %s, status %s' % (self, ticket, status))
      
      # handle vnc server
      self.vncServerStrategy()
      
      # Add proxy_agent to connection pool
      MiGTCPServer.connectionCondition.acquire()
      MiGTCPServer.connections[ticket] = mip.ServerInfo(self.request, self.client_address, 0, 3)
      MiGTCPServer.connectionCondition.notifyAll()
      MiGTCPServer.connectionCondition.release()  
        
    else:
      logging.debug('%s Incorrect messagetype %s' % (self, repr(data)))
      
    # This is f*****g annoying! If the handler exited then the socket is closed... so it must stay alive doing shit but consume resources...
    while 1: 
      time.sleep(1000)