示例#1
0
文件: mcs.py 项目: ChrisTruncer/rdpy
    def recvData(self, data):
        """
        @summary: Main receive method
        @param data: {Stream} 
        """
        opcode = UInt8()
        data.readType(opcode)
        
        if self.readMCSPDUHeader(opcode.value, DomainMCSPDU.DISCONNECT_PROVIDER_ULTIMATUM):
            log.info("MCS DISCONNECT_PROVIDER_ULTIMATUM")
            self._transport.close()
            return
        
        #client case
        elif not self.readMCSPDUHeader(opcode.value, self._receiveOpcode):
            raise InvalidExpectedDataException("Invalid expected MCS opcode receive data")
        
        #server user id
        per.readInteger16(data, Channel.MCS_USERCHANNEL_BASE)
        
        channelId = per.readInteger16(data)
        
        per.readEnumerates(data)       
        per.readLength(data)
        
        #channel id doesn't match a requested layer
        if not self._channels.has_key(channelId):
            log.error("receive data for an unconnected layer")
            return

        self._channels[channelId].recv(data) 
示例#2
0
文件: rdpwn.py 项目: 5l1v3r1/rdpwn
            def checkPrompt(self):
                prompt = False
                binitial = self.countColor(self.initial, (0, 0, 0))
                bfinal = self.countColor(self.final, (0, 0, 0))
                winitial = self.countColor(self.initial, (255, 255, 255))
                wfinal = self.countColor(self.final, (255, 255, 255))
                # this is "good enough"
                if wfinal == winitial:  # unlikely, but possible
                    ratio = (bfinal - binitial) / float(wfinal)
                else:
                    ratio = (bfinal - binitial) / float(wfinal - winitial)
                # bi: 108, bf: 1431, wi: 753, wf: 74051
                # bi: 108, bf: 191513, wi: 753, wf: 3094
                log.debug("bi: {}, bf: {}, wi: {}, wf: {}".format(
                    binitial, bfinal, winitial, wfinal))
                if ratio > 10:
                    prompt = True
                    log.info("Prompt detected")
                    self.sendCommand(self.commands)
                else:
                    log.warning("No prompt")

                if not self.methods or prompt:
                    self.reactor.callLater(.5, self._controller.close)
                    return

                log.debug("Trying next method: " + self.methods[-1].__name__)
                self.inittimer = None
                self.lastUpdate = None
                self.do_final = False
                self.initial = self.final.copy()
                del self.final
                self._scDownUp(0x01)
示例#3
0
    def recvChannelJoinRequest(self, data):
        """
        @summary: Receive for each client channel a request
        Send Channel Join Confirm or Connect upper layer when all channel are joined
        @param data: {Stream}
        
        """
        opcode = UInt8()
        data.readType(opcode)

        if not self.readMCSPDUHeader(opcode.value,
                                     DomainMCSPDU.CHANNEL_JOIN_REQUEST):
            log.info("Invalid MCS PDU : CHANNEL_JOIN_REQUEST expected")
            pass

        userId = per.readInteger16(data, Channel.MCS_USERCHANNEL_BASE)
        if self._userId != userId:
            log.info("Invalid MCS User Id")
            pass

        channelId = per.readInteger16(data)
        #actually algo support virtual channel but RDPY have no virtual channel
        confirm = 0 if channelId in self._channels.keys(
        ) or channelId == self._userId else 1
        self.sendChannelJoinConfirm(channelId, confirm)
        self._nbChannelConfirmed += 1
        if self._nbChannelConfirmed == self._serverSettings.getBlock(
                gcc.MessageType.SC_NET).channelCount.value + 2:
            self.allChannelConnected()
示例#4
0
    def sendPointerEvent(self, x, y, button, isPressed):
        """
        @summary: send pointer events
        @param x: x position of pointer
        @param y: y position of pointer
        @param button: 1 or 2 or 3
        @param isPressed: true if button is pressed or false if it's released
        """
        if not self._isReady:
            return

        try:
            event = pdu.data.PointerEvent()
            if isPressed:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_DOWN

            if button == 1:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON1
            elif button == 2:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON2
            elif button == 3:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON3
            else:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_MOVE

            #position
            event.xPos.value = x
            event.yPos.value = y

            #send proper event
            self._pduLayer.sendInputEvents([event])

        except InvalidValue:
            log.info("try send pointer event with incorrect position")
示例#5
0
    def sendWheelEvent(self, x, y, step, isNegative=False, isHorizontal=False):
        """
        @summary: Send a mouse wheel event
        @param x: x position of pointer
        @param y: y position of pointer
        @param step: number of step rolled
        @param isHorizontal: horizontal wheel (default is vertical)
        @param isNegative: is upper (default down)
        """
        if not self._isReady:
            return

        try:
            event = pdu.data.PointerEvent()
            if isHorizontal:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_HWHEEL
            else:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_WHEEL

            if isNegative:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_WHEEL_NEGATIVE

            event.pointerFlags.value |= (
                step & pdu.data.PointerFlag.WheelRotationMask)

            #position
            event.xPos.value = x
            event.yPos.value = y

            #send proper event
            self._pduLayer.sendInputEvents([event])

        except InvalidValue:
            log.info("try send wheel event with incorrect position")
示例#6
0
 def onReady(self):
     """
     @summary:  Event use to inform state of server stack
                 First time this event is called is when human client is connected
                 Second time is after color depth nego, because color depth nego
                 restart a connection sequence
     @see: rdp.RDPServerObserver.onReady
     """
     if self._rssFile is None:
         #compute which RSS file to keep
         width, height = self._controller.getScreen()
         size = width * height
         rssFilePath = sorted(self._rssFileSizeList, key = lambda x: abs(x[0][0] * x[0][1] - size))[0][1]
         log.info("select file (%s, %s) -> %s"%(width, height, rssFilePath))
         self._rssFile = rss.createReader(rssFilePath)
     
     domain, username, password = self._controller.getCredentials()
     hostname = self._controller.getHostname()
     log.info("""Credentials:
     \tdomain : %s
     \tusername : %s
     \tpassword : %s
     \thostname : %s
     """%(domain, username, password, hostname));
     self.start()
示例#7
0
 def RegisterCSSP(self, *params):
     try:
         self._fastPathPresentation.RegisterCSSP(
             *params)  #using it to register CSSP on the pdu layer
         log.info('Ready For RDP connections')
     except AttributeError:
         pass
示例#8
0
    def recvConnectResponse(self, data):
        """
        @summary: Receive MCS connect response from server
        Send Erect domain Request
        Send Attach User Request
        Wait Attach User Confirm
        @param data: {Stream}
        """
        ber.readApplicationTag(data, UInt8(Message.MCS_TYPE_CONNECT_RESPONSE))
        ber.readEnumerated(data)
        ber.readInteger(data)
        self.readDomainParams(data)
        if not ber.readUniversalTag(data, ber.Tag.BER_TAG_OCTET_STRING, False):
            log.info("invalid expected BER tag")
            pass
        gccRequestLength = ber.readLength(data)
        if data.dataLen() != gccRequestLength:
            raise InvalidSize("bad size of GCC request")
            pass
        self._serverSettings = gcc.readConferenceCreateResponse(data)

        #send domain request
        self.sendErectDomainRequest()
        #send attach user request
        self.sendAttachUserRequest()
        #now wait user confirm from server
        self.setNextState(self.recvAttachUserConfirm)
 def onClose(self):
     """
     @summary: callback use when RDP stack is closed
     """
     log.info("save screenshot into %s" % self._path)
     self._buffer.save(self._path)
     check_ssdeep_hash(self._path)
示例#10
0
 def onReady(self):
     """
     @summary: callback use when RDP stack is connected (just before received bitmap)
     """
     log.info("connected %s"%addr)
     width, height = self._controller.getScreen()
     self._buffer = QtGui.QImage(width, height, QtGui.QImage.Format_RGB32)
示例#11
0
文件: rdp.py 项目: ChrisTruncer/rdpy
    def sendWheelEvent(self, x, y, step, isNegative = False, isHorizontal = False):
        """
        @summary: Send a mouse wheel event
        @param x: x position of pointer
        @param y: y position of pointer
        @param step: number of step rolled
        @param isHorizontal: horizontal wheel (default is vertical)
        @param isNegative: is upper (default down)
        """
        if not self._isReady:
            return

        try:
            event = pdu.data.PointerEvent()
            if isHorizontal:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_HWHEEL
            else:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_WHEEL
                
            if isNegative:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_WHEEL_NEGATIVE
                
            event.pointerFlags.value |= (step & pdu.data.PointerFlag.WheelRotationMask)
            
            #position
            event.xPos.value = x
            event.yPos.value = y
            
            #send proper event
            self._pduLayer.sendInputEvents([event])
            
        except InvalidValue:
            log.info("try send wheel event with incorrect position")
示例#12
0
文件: rdp.py 项目: ChrisTruncer/rdpy
    def sendPointerEvent(self, x, y, button, isPressed):
        """
        @summary: send pointer events
        @param x: x position of pointer
        @param y: y position of pointer
        @param button: 1 or 2 or 3
        @param isPressed: true if button is pressed or false if it's released
        """
        if not self._isReady:
            return

        try:
            event = pdu.data.PointerEvent()
            if isPressed:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_DOWN
            
            if button == 1:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON1
            elif button == 2:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON2
            elif button == 3:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_BUTTON3
            else:
                event.pointerFlags.value |= pdu.data.PointerFlag.PTRFLAGS_MOVE
            
            #position
            event.xPos.value = x
            event.yPos.value = y
            
            #send proper event
            self._pduLayer.sendInputEvents([event])
            
        except InvalidValue:
            log.info("try send pointer event with incorrect position")
示例#13
0
    def onReady(self):
        """
        @summary:  Event use to inform state of server stack
                    First time this event is called is when human client is connected
                    Second time is after color depth nego, because color depth nego
                    restart a connection sequence
        @see: rdp.RDPServerObserver.onReady
        """
        if self._rssFile is None:
            #compute which RSS file to keep
            width, height = self._controller.getScreen()
            size = width * height
            rssFilePath = sorted(
                self._rssFileSizeList,
                key=lambda x: abs(x[0][0] * x[0][1] - size))[0][1]
            log.info("select file (%s, %s) -> %s" %
                     (width, height, rssFilePath))
            hpfeedslog.info("select file (%s, %s) -> %s" %
                            (width, height, rssFilePath))
            self._rssFile = rss.createReader(rssFilePath)

        domain, username, password = self._controller.getCredentials()
        hostname = self._controller.getHostname()
        log.info("\n%s,domain:%s,username:%s,password:%s,hostname:%s" %
                 (datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
                  domain, username, password, hostname))
        hpfeedslog.info(
            "%s, domain:%s, username:%s, password:%s, hostname:%s " %
            (datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
             domain, username, password, hostname))
        self.start()
示例#14
0
    def recvConnectInitial(self, data):
        """
        @summary: Receive MCS connect initial from client
        Send Connect Response
        Wait Erect Domain Request
        @param data: {Stream}
        """
        ber.readApplicationTag(data, UInt8(Message.MCS_TYPE_CONNECT_INITIAL))
        ber.readOctetString(data)
        ber.readOctetString(data)

        if not ber.readBoolean(data):
            log.info("invalid expected BER boolean tag")
            pass

        self.readDomainParams(data)
        self.readDomainParams(data)
        self.readDomainParams(data)
        self._clientSettings = gcc.readConferenceCreateRequest(
            Stream(ber.readOctetString(data)))

        if not self._clientSettings.CS_NET is None:
            i = 1
            for channelDef in self._clientSettings.CS_NET.channelDefArray._array:
                self._serverSettings.SC_NET.channelIdArray._array.append(
                    UInt16Le(i + Channel.MCS_GLOBAL_CHANNEL))
                #if channel can be handle by serve add it
                for serverChannelDef, layer in self._virtualChannels:
                    if channelDef.name == serverChannelDef.name:
                        self._channels[i + Channel.MCS_GLOBAL_CHANNEL] = layer
                i += 1

        self.sendConnectResponse()
        self.setNextState(self.recvErectDomainRequest)
示例#15
0
def mytest(ip, port, username, password):
    domain = ""
    width = 1024
    height = 800
    fullscreen = False
    optimized = False
    recodedPath = None
    keyboardLayout = 'en'
    app = QtGui.QApplication(sys.argv)

    #add qt4 reactor
    import qt4reactor
    qt4reactor.install()

    if fullscreen:
        width = QtGui.QDesktopWidget().screenGeometry().width()
        height = QtGui.QDesktopWidget().screenGeometry().height()

    log.info("keyboard layout set to %s"%keyboardLayout)

    from twisted.internet import reactor
    ret = {"connected": False}
    mytimer = TimerThread(app, reactor, ret)
    mytimer.start()

    reactor.connectTCP(ip, int(port), RDPClientQtFactory(width, height, username, password, domain, fullscreen, keyboardLayout, optimized, "nego", recodedPath, mytimer))
    reactor.runReturn()
    app.exec_()
    return ret["connected"]
示例#16
0
    def recvData(self, data):
        """
        @summary: Main receive method
        @param data: {Stream} 
        """
        opcode = UInt8()
        data.readType(opcode)

        if self.readMCSPDUHeader(opcode.value,
                                 DomainMCSPDU.DISCONNECT_PROVIDER_ULTIMATUM):
            log.info("MCS DISCONNECT_PROVIDER_ULTIMATUM")
            self._transport.close()
            return

        #client case
        elif not self.readMCSPDUHeader(opcode.value, self._receiveOpcode):
            raise InvalidExpectedDataException(
                "Invalid expected MCS opcode receive data")

        #server user id
        per.readInteger16(data, Channel.MCS_USERCHANNEL_BASE)

        channelId = per.readInteger16(data)

        per.readEnumerates(data)
        per.readLength(data)

        #channel id doesn't match a requested layer
        if not self._channels.has_key(channelId):
            log.error("receive data for an unconnected layer")
            return

        self._channels[channelId].recv(data)
示例#17
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     self._mytimer.conn_fail()
     log.info("Connection failed : %s"%reason)
示例#18
0
 def buildObserver(self, controller, addr):
     """
     @param controller: {rdp.RDPServerController}
     @param addr: destination address
     @see: rdp.ServerFactory.buildObserver
     """
     log.info("Connection from %s:%s" % (addr.host, addr.port))
     return HoneyPotServer(controller, self._rssFileSizeList)
示例#19
0
 def onReady(self):
     """
     @summary: Call when server is ready
     to send and receive messages
     """
     domain, username, password = self._controller.getCredentials()
     log.info("Credentials: " + str(username) + " " + str(password))
     self._controller.close()
示例#20
0
 def buildObserver(self, controller, addr):
     """
     @param controller: {rdp.RDPServerController}
     @param addr: destination address
     @see: rdp.ServerFactory.buildObserver
     """
     log.info("Connection from %s:%s"%(addr.host, addr.port))
     return HoneyPotServer(controller, self._rssFileSizeList)
示例#21
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("Connection failed : %s" % reason)
     reactor.stop()
     app.exit()
示例#22
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("Connection failed : %s"%reason)
     reactor.stop()
     app.exit()
示例#23
0
 def buildObserver(self, controller, addr):
     """
     @param controller: {rdp.RDPServerController}
     @param addr: destination address
     @see: rdp.ServerFactory.buildObserver
     """
     log.info("\n%s,Connection from %s:%s" %
              (datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
               addr.host, addr.port))
     return HoneyPotServer(controller, self._rssFileSizeList)
 def onKeyEventUnicode(self, code, isPressed):
     """
     @summary: Event call when a keyboard event is catch in unicode format
     @param code: unicode of key
     @param isPressed: True if key is down
     @see: rdp.RDPServerObserver.onKeyEventUnicode
     """
     if not isPressed:
         k.type_string(chr(code))
         log.info("KeyEventUnicode: " + chr(code))
示例#25
0
 def onClose(self):
     """
     @summary: callback use when RDP stack is closed
     """
     log.info("save screenshot into %s" % self._path)
     if self._complete:
         if self._dbm:
             self._dbm.open_connection()
             self._dbm.update_vnc_rdp_object(self._obj)
             self._dbm.close()
         self._buffer.save(self._path)
示例#26
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rfb connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("connection failed : %s"%reason)
     RFBScreenShotFactory.__INSTANCE__ -= 1
     if(RFBScreenShotFactory.__INSTANCE__ == 0):
         reactor.stop()
         app.exit()
示例#27
0
 def onClose(self):
     """
     @summary: callback use when RDP stack is closed
     """
     log.info("save screenshot into %s" % self._path)
     if self._complete:
         if self._dbm:
             self._dbm.open_connection()
             self._dbm.update_vnc_rdp_object(self._obj)
             self._dbm.close()
         self._buffer.save(self._path)
示例#28
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("connection failed : %s"%reason)
     RDPScreenShotFactory.__STATE__.append((connector.host, connector.port, reason))
     RDPScreenShotFactory.__INSTANCE__ -= 1
     if(RDPScreenShotFactory.__INSTANCE__ == 0):
         self._reactor.stop()
         self._app.exit()
示例#29
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("connection failed : %s"%reason)
     RDPScreenShotFactory.__STATE__.append((connector.host, connector.port, reason))
     RDPScreenShotFactory.__INSTANCE__ -= 1
     if(RDPScreenShotFactory.__INSTANCE__ == 0):
         self._reactor.stop()
         self._app.exit()
示例#30
0
文件: rfb.py 项目: ChrisTruncer/rdpy
 def recvSecurityResult(self, data):
     """
     Read security result packet
     Use by server to inform connection status of client
     @param data: Stream that contain well formed packet 
     """
     result = UInt32Be()
     data.readType(result)
     if result == UInt32Be(1):
         log.info("Authentification failed")
         if self._version.value == ProtocolVersion.RFB003008:
             self.expectWithHeader(4, self.recvSecurityFailed)
     else:
         log.debug("Authentification OK")
         self.sendClientInit()
示例#31
0
文件: rfb.py 项目: chushuai/rdpy
 def recvSecurityResult(self, data):
     """
     Read security result packet
     Use by server to inform connection status of client
     @param data: Stream that contain well formed packet 
     """
     result = UInt32Be()
     data.readType(result)
     if result == UInt32Be(1):
         log.info("Authentification failed")
         if self._version.value == ProtocolVersion.RFB003008:
             self.expectWithHeader(4, self.recvSecurityFailed)
     else:
         log.debug("Authentification OK")
         self.sendClientInit()
 def onPointerEvent(self, x, y, button, isPressed):
     """
     @summary: Event call on mouse event
     @param x: x position
     @param y: y position
     @param button: 1, 2 or 3 button
     @param isPressed: True if mouse button is pressed
     @see: rdp.RDPServerObserver.onPointerEvent
     """
     if isPressed:
         m.press(x, y, button)
         time.sleep(0.05)
         m.release(x, y)
     else:
         m.move(x, y)
     log.info("PointerEvent: " + str(x) + " " + str(y) + " @" + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
示例#33
0
 def buildObserver(self, controller, addr):
     """
     @param controller: {rdp.RDPServerController}
     @param addr: destination address
     @see: rdp.ServerFactory.buildObserver
     """
     log.info("\n%s,Connection from %s:%s" %
              (datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
               addr.host, addr.port))
     message_json = json.dumps({
         'src_ip': addr.host,
         'src_port': str(addr.port),
         'dst_ip': os.environ.get('HPFEEDS_CLIENT'),
         'dst_port': '3389'
     })
     send_hpfeeds(self._hpc, message_json)
     return HoneyPotServer(controller, self._rssFileSizeList, self._hpc)
示例#34
0
 def recvServerName(self, data):
     """
     @summary: Read server name
     @param data: Stream that contains well formed packet
     """
     data.readType(self._serverName)
     log.info("Server name %s"%str(self._serverName))
     #end of handshake
     #send pixel format
     self.sendPixelFormat(self._pixelFormat)
     #write encoding
     self.sendSetEncoding()
     #request entire zone
     self.sendFramebufferUpdateRequest(False, 0, 0, self._serverInit.width.value, self._serverInit.height.value)
     #now i'm ready to send event
     self._clientListener.onReady()
     self.expect(1, self.recvServerOrder)
示例#35
0
文件: rfb.py 项目: ChrisTruncer/rdpy
 def sendKeyEvent(self, isDown, key):
     """
     @summary: Send a key event throw RFB protocol
     @param isDown: boolean notify if key is pressed or not (True if key is pressed)
     @param key: ASCII code of key
     """
     if not self._isReady:
         log.info("Try to send key event on non ready layer")
         return
     try:
         event = KeyEvent()
         event.downFlag.value = isDown
         event.key.value = key
     
         self._rfbLayer.sendKeyEvent(event)
     except InvalidValue:
         log.debug("Try to send an invalid key event")
示例#36
0
 def onReady(self):
     """
     @summary:  Event use to inform state of server stack
                 First time this event is called is when human client is connected
                 Second time is after color depth nego, because color depth nego
                 restart a connection sequence
     @see: rdp.RDPServerObserver.onReady
     """
     domain, username, password = self._controller.getCredentials()
     hostname = self._controller.getHostname()
     log.info("""Credentials:
     \tdomain : %s
     \tusername : %s
     \tpassword : %s
     \thostname : %s
     """%(domain, username, password, hostname));
     self.start()
示例#37
0
    def recvAttachUserRequest(self, data):
        """
        @summary: Receive Attach user request
        Send Attach User Confirm
        Wait Channel Join Request
        @param data: {Stream}
        """
        opcode = UInt8()
        data.readType(opcode)

        if not self.readMCSPDUHeader(opcode.value,
                                     DomainMCSPDU.ATTACH_USER_REQUEST):
            log.info("Invalid MCS PDU : ATTACH_USER_REQUEST expected")
            pass

        self.sendAttachUserConfirm()
        self.setNextState(self.recvChannelJoinRequest)
示例#38
0
文件: rfb.py 项目: chushuai/rdpy
    def sendKeyEvent(self, isDown, key):
        """
        @summary: Send a key event throw RFB protocol
        @param isDown: boolean notify if key is pressed or not (True if key is pressed)
        @param key: ASCII code of key
        """
        if not self._isReady:
            log.info("Try to send key event on non ready layer")
            return
        try:
            event = KeyEvent()
            event.downFlag.value = isDown
            event.key.value = key

            self._rfbLayer.sendKeyEvent(event)
        except InvalidValue:
            log.debug("Try to send an invalid key event")
示例#39
0
    def clientConnectionLost(self, connector, reason):
        """
        @summary: Connection lost event
        @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
        @param reason: str use to advertise reason of lost connection
        """
        #try reconnect with basic RDP security
        if reason.type == RDPSecurityNegoFail and self._nego:
            #stop nego
            log.info("due to security nego error back to standard RDP security layer")
            self._nego = False
            self._security = rdp.SecurityLevel.RDP_LEVEL_RDP
            self._client._widget.hide()
            connector.connect()
            return

        self._mytimer.conn_fail()
        log.info("Lost connection : %s"%reason)
示例#40
0
    def recvErectDomainRequest(self, data):
        """
        @summary: Receive erect domain request
        Wait Attach User Request
        @param data: {Stream}
        """
        opcode = UInt8()
        data.readType(opcode)

        if not self.readMCSPDUHeader(opcode.value,
                                     DomainMCSPDU.ERECT_DOMAIN_REQUEST):
            log.info("Invalid MCS PDU : ERECT_DOMAIN_REQUEST expected")
            pass

        per.readInteger(data)
        per.readInteger(data)

        self.setNextState(self.recvAttachUserRequest)
示例#41
0
 def clientConnectionLost(self, connector, reason):
     """
     @summary: Connection lost event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     if reason.type == RDPSecurityNegoFail and self._security != "rdp":
         log.info("due to RDPSecurityNegoFail try standard security layer")
         self._security = rdp.SecurityLevel.RDP_LEVEL_RDP
         connector.connect()
         return
     
     log.info("connection lost : %s"%reason)
     RDPScreenShotFactory.__STATE__.append((connector.host, connector.port, reason))
     RDPScreenShotFactory.__INSTANCE__ -= 1
     if(RDPScreenShotFactory.__INSTANCE__ == 0):
         self._reactor.stop()
         self._app.exit()
示例#42
0
    def clientConnectionLost(self, connector, reason):
        """
        @summary: Connection lost event
        @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
        @param reason: str use to advertise reason of lost connection
        """
        if reason.type == RDPSecurityNegoFail and self._security != "rdp":
            log.info("due to RDPSecurityNegoFail try standard security layer")
            self._security = rdp.SecurityLevel.RDP_LEVEL_RDP
            connector.connect()
            return

        log.info("connection lost : %s" % reason)
        RDPScreenShotFactory.__STATE__.append((connector.host, connector.port, reason))
        RDPScreenShotFactory.__INSTANCE__ -= 1
        if(RDPScreenShotFactory.__INSTANCE__ == 0):
            self._reactor.stop()
            self._app.exit()
示例#43
0
 def clientConnectionLost(self, connector, reason):
     """
     @summary: Connection lost event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     #try reconnect with basic RDP security
     if reason.type == RDPSecurityNegoFail and self._nego:
         #stop nego
         log.info("due to security nego error back to standard RDP security layer")
         self._nego = False
         self._security = rdp.SecurityLevel.RDP_LEVEL_RDP
         self._client._widget.hide()
         connector.connect()
         return
     
     QtGui.QMessageBox.warning(self._w, "Warning", "Lost connection : %s"%reason)
     reactor.stop()
     app.exit()
示例#44
0
文件: rfb.py 项目: chushuai/rdpy
    def sendPointerEvent(self, mask, x, y):
        """
        @summary: Send a pointer event throw RFB protocol
        @param mask: mask of button if button 1 and 3 are pressed then mask is 00000101
        @param x: x coordinate of mouse pointer
        @param y: y pointer of mouse pointer
        """
        if not self._isReady:
            log.info("Try to send pointer event on non ready layer")
            return
        try:
            event = PointerEvent()
            event.mask.value = mask
            event.x.value = x
            event.y.value = y

            self._rfbLayer.sendPointerEvent(event)
        except InvalidValue:
            log.debug("Try to send an invalid pointer event")
示例#45
0
文件: rfb.py 项目: ChrisTruncer/rdpy
 def sendPointerEvent(self, mask, x, y):
     """
     @summary: Send a pointer event throw RFB protocol
     @param mask: mask of button if button 1 and 3 are pressed then mask is 00000101
     @param x: x coordinate of mouse pointer
     @param y: y pointer of mouse pointer
     """
     if not self._isReady:
         log.info("Try to send pointer event on non ready layer")
         return
     try:
         event = PointerEvent()
         event.mask.value = mask
         event.x.value = x
         event.y.value = y
         
         self._rfbLayer.sendPointerEvent(event)
     except InvalidValue:
         log.debug("Try to send an invalid pointer event")
示例#46
0
    def sendKeyEventUnicode(self, code, isPressed):
        """
        @summary: Send a scan code to RDP stack
        @param code: unicode
        @param isPressed: True if key is pressed and false if it's released
        """
        if not self._isReady:
            return

        try:
            event = pdu.data.UnicodeKeyEvent()
            event.unicode.value = code
            if not isPressed:
                event.keyboardFlags.value |= pdu.data.KeyboardFlag.KBDFLAGS_RELEASE

            #send event
            self._pduLayer.sendInputEvents([event])

        except InvalidValue:
            log.info("try send bad key event")
示例#47
0
文件: rdp.py 项目: ChrisTruncer/rdpy
 def sendKeyEventUnicode(self, code, isPressed):
     """
     @summary: Send a scan code to RDP stack
     @param code: unicode
     @param isPressed: True if key is pressed and false if it's released
     """
     if not self._isReady:
         return
     
     try:
         event = pdu.data.UnicodeKeyEvent()
         event.unicode.value = code
         if not isPressed:
             event.keyboardFlags.value |= pdu.data.KeyboardFlag.KBDFLAGS_RELEASE
         
         #send event
         self._pduLayer.sendInputEvents([event])
         
     except InvalidValue:
         log.info("try send bad key event")
示例#48
0
 def recvProtocolVersion(self, data):
     """
     Read handshake packet 
     If protocol receive from client is unknown
     try best version of protocol version (ProtocolVersion.RFB003008)
     @param data: Stream
     """
     self.readProtocolVersion(data)
     if self._version.value == ProtocolVersion.UNKNOWN:
         log.info("Unknown protocol version %s send 003.008"%data.getvalue())
         #protocol version is unknown try best version we can handle
         self._version.value = ProtocolVersion.RFB003008
     #send same version of 
     self.send(self._version)
     
     #next state read security
     if self._version.value == ProtocolVersion.RFB003003:
         self.expect(4, self.recvSecurityServer)
     else:
         self.expectWithHeader(1, self.recvSecurityList)
示例#49
0
 def clientConnectionFailed(self, connector, reason):
     """
     @summary: Connection failed event
     @param connector: twisted connector use for rdp connection (use reconnect to restart connection)
     @param reason: str use to advertise reason of lost connection
     """
     log.info("connection failed : %s" % reason)
     if self._dbm:
         self._dbm.open_connection()
         self._object.error_state = True
         self._dbm.update_vnc_rdp_object(self._object)
         self._dbm.close()
     print '[*] Error connecting to {0}'.format(self._object.remote_system)
     RDPScreenShotFactory.__STATE__.append(
         (connector.host, connector.port, reason))
     RDPScreenShotFactory.__INSTANCE__ -= 1
     if(RDPScreenShotFactory.__INSTANCE__ == 0):
         try:
             self._reactor.stop()
         except:
             pass
         self._app.exit()
示例#50
0
def autoDetectKeyboardLayout():
    """
    @summary: try to auto detect keyboard layout
    """
    try:
        if os.name == 'posix':    
            from subprocess import check_output
            result = check_output(["setxkbmap", "-print"])
            if "azerty" in result:
                return "fr"
        elif os.name == 'nt':
            import win32api, win32con, win32process
            from ctypes import windll
            w = windll.user32.GetForegroundWindow() 
            tid = windll.user32.GetWindowThreadProcessId(w, 0) 
            result = windll.user32.GetKeyboardLayout(tid)
            log.info(result)
            if result == 0x40c040c:
                return "fr"
    except Exception as e:
        log.info("failed to auto detect keyboard layout " + str(e))
        pass
    return "en"
示例#51
0
文件: rdp.py 项目: ChrisTruncer/rdpy
 def sendKeyEventScancode(self, code, isPressed, extended = False):
     """
     @summary: Send a scan code to RDP stack
     @param code: scan code
     @param isPressed: True if key is pressed and false if it's released
     @param extended: {boolean} extended scancode like ctr or win button
     """
     if not self._isReady:
         return
     
     try:
         event = pdu.data.ScancodeKeyEvent()
         event.keyCode.value = code
         if not isPressed:
             event.keyboardFlags.value |= pdu.data.KeyboardFlag.KBDFLAGS_RELEASE
         
         if extended:
             event.keyboardFlags.value |= pdu.data.KeyboardFlag.KBDFLAGS_EXTENDED
             
         #send event
         self._pduLayer.sendInputEvents([event])
         
     except InvalidValue:
         log.info("try send bad key event")
 def onReady(self):
     """
     @summary: Call when server is ready
     to send and receive messages
     """
     log.info("onReady")
示例#53
0
文件: x224.py 项目: ChrisTruncer/rdpy
 def recvConnectionConfirm(self, data):
     """
     @summary:  Receive connection confirm message
                 Next state is recvData 
                 Call connect on presentation layer if all is good
     @param data: Stream that contain connection confirm
     @see: response -> http://msdn.microsoft.com/en-us/library/cc240506.aspx
     @see: failure ->http://msdn.microsoft.com/en-us/library/cc240507.aspx
     """
     message = ServerConnectionConfirm()
     data.readType(message)
     
     if message.protocolNeg.failureCode._is_readed:
         pass
     
     #check presence of negotiation response
     if message.protocolNeg._is_readed:
         self._selectedProtocol = message.protocolNeg.selectedProtocol.value
     else:
         self._selectedProtocol = Protocols.PROTOCOL_RDP
     
     #NLA protocol doesn't support in actual version of RDPY
     if self._selectedProtocol in [ Protocols.PROTOCOL_HYBRID_EX ]:
         raise InvalidExpectedDataException("RDPY doesn't support PROTOCOL_HYBRID_EX security Layer")
     
     #now i'm ready to receive data
     self.setNextState(self.recvData)
     
     if self._selectedProtocol ==  Protocols.PROTOCOL_RDP:
         log.warning("*" * 43)
         log.warning("*" + " " * 10  + "RDP Security selected" + " " * 10 + "*")
         log.warning("*" * 43)
         #connection is done send to presentation
         self._presentation.connect()
         
     elif self._selectedProtocol ==  Protocols.PROTOCOL_SSL:
         log.info("*" * 43)
         log.info("*" + " " * 10  + "SSL Security selected" + " " * 10 + "*")
         log.info("*" * 43)
         self._transport.startTLS(ClientTLSContext())
         #connection is done send to presentation
         self._presentation.connect()
 
     elif self._selectedProtocol == Protocols.PROTOCOL_HYBRID:
         log.info("*" * 43)
         log.info("*" + " " * 10  + "NLA Security selected" + " " * 10 + "*")
         log.info("*" * 43)
         self._transport.startNLA(ClientTLSContext(), lambda:self._presentation.connect())
示例#54
0
    
if __name__ == '__main__':
    listen = "3389"
    privateKeyFilePath = None
    certificateFilePath = None
    rssFileSizeList = []
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hl:k:c:")
    except getopt.GetoptError:
        help()
    for opt, arg in opts:
        if opt == "-h":
            help()
            sys.exit()
        elif opt == "-l":
            listen = arg
        elif opt == "-k":
            privateKeyFilePath = arg
        elif opt == "-c":
            certificateFilePath = arg
    
    #build size map
    log.info("Build size map")
    for arg in args:
        size = readSize(arg)
        rssFileSizeList.append((size, arg))
        log.info("(%s, %s) -> %s"%(size[0], size[1], arg))
    
    reactor.listenTCP(int(listen), HoneyPotServerFactory(rssFileSizeList, privateKeyFilePath, certificateFilePath))
    reactor.run()
示例#55
0
     elif opt == "-f":
         fullscreen = True
     elif opt == "-o":
         optimized = True
     elif opt == "-k":
         keyboardLayout = arg
     elif opt == "-r":
         recodedPath = arg
         
 if ':' in args[0]:
     ip, port = args[0].split(':')
 else:
     ip, port = args[0], "3389"
 
 #create application
 app = QtGui.QApplication(sys.argv)
 
 #add qt4 reactor
 import qt4reactor
 qt4reactor.install()
 
 if fullscreen:
     width = QtGui.QDesktopWidget().screenGeometry().width()
     height = QtGui.QDesktopWidget().screenGeometry().height()
 
 log.info("keyboard layout set to %s"%keyboardLayout)
 
 from twisted.internet import reactor
 reactor.connectTCP(ip, int(port), RDPClientQtFactory(width, height, username, password, domain, fullscreen, keyboardLayout, optimized, "nego", recodedPath))
 reactor.runReturn()
 app.exec_()
示例#56
0
 def onReady(self):
     """
     @summary: callback use when RDP stack is connected (just before received bitmap)
     """
     log.info("connected %s" % addr)