示例#1
0
    def handleUserInput(self, line):
        if line == "\n":
            self.running = 0

        # request list of online users
        elif str.split(line)[0] == "list":
            if self.username:
                listMessage = ListMessage(self.clientPort, self.username)
                self.sendEncrypted(listMessage.encode(), self.withKey(self.serverPublicKey), self.serverSocket)
                self.debug("list request encoded and sent to server")
            else:
                print "You are not currently logged in. \nPlease enter your username and password in the format: <username> <password>"

        # select user
        elif str.split(line)[0] == "send":
            if len(str.split(line)) < 3:
                print "Invalid send format. Please try again."

            if self.username:
                lineArray = str.split(line)
                toUser = lineArray[1]
                toUserMessage = " ".join(lineArray[2:])

                if toUser in self.currentConnections:
                    userInfo = self.currentConnections[toUser]
                    privateMessage = PrivateMessage(self.clientPort, self.username, userInfo["port"], toUserMessage)
                    self.sendPrivateEncrypted(
                        privateMessage.encode(),
                        self.withKey(userInfo["publicKey"]),
                        userInfo["sessionKey"],
                        userInfo["socket"],
                    )

                    self.sanitizeInput()

                else:
                    self.messageQueue.append((toUser, toUserMessage))
                    self.nonceSent = self.genNonce()
                    self.usernameSent = toUser

                    selectUserMessage = SelectUserMessage(self.username, toUser, self.nonceSent)
                    self.sendEncrypted(
                        selectUserMessage.encode(), self.withKey(self.serverPublicKey), self.serverSocket
                    )
                    self.sanitizeInput()
                    self.debug("selectUserMessage encoded and sent to server")
                    print "Attempting to start session with " + toUser + ".\n"

        # login
        elif len(str.split(line)) == 2:
            if self.username == None:
                usernameInput = str.split(line)[0]
                passwordInput = str.split(line)[1]
                loginMessage = (usernameInput, passwordInput)
                self.messageQueue.append(loginMessage)
                self.loginAuthNonce = self.genNonce()
                loginAuthMessage = LoginAuth(self.clientPort, self.loginAuthNonce, self.genTime(), self.clientPublicKey)
                self.sendEncrypted(loginAuthMessage.encode(), self.withKey(self.serverPublicKey), self.serverSocket)
                self.debug("login information sent to server")

                self.sanitizeInput()
            else:
                print "You are already logged in as " + self.username + "!"

        elif self.username:
            print "Invalid command. Please try again."

        else:
            print "You are not currently logged in. \n\nPlease enter your username and password in the format: <username> <password>"
示例#2
0
    def handleMessageType(self, serverSocket, jsonMessage):
        # TODO: ADD TRY-CATCH TO HANDLE: ValueError: No JSON object could be decoded

        if jsonMessage["messageType"] == "loginAuthResponse":
            self.validateNonce(self.loginAuthNonce, jsonMessage["nonce"])
            self.validateTimestamp(time.time(), jsonMessage["timestamp"])

            messageToSend = self.messageQueue.pop()

            loginMessage = LoginMessage(self.clientPort, messageToSend[0], messageToSend[1], self.clientPublicKey)
            self.sendEncrypted(loginMessage.encode(), self.withKey(self.serverPublicKey), self.serverSocket)

        elif jsonMessage["messageType"] == "loginResponse":
            self.debug("received login response")
            if jsonMessage["status"] == "success":
                self.username = jsonMessage["username"]
                print "Login succeeded. Type `list` to see a list of online users to message!"
            elif jsonMessage["status"] == "alreadyLoggedIn":
                print "You are already logged in in another session. \nPlease logout the other session to start a new session."
            elif jsonMessage["status"] == "fail":
                print "Invalid username or password."
            else:
                print "Invalid command"

        elif jsonMessage["messageType"] == "listResponse":
            print "Users currently online:"
            for element in jsonMessage["userList"]:
                # print 'Users currently online: ' + jsonMessage['userList']
                print "  * " + str(element)

        elif jsonMessage["messageType"] == "selectUserResponse":

            self.debug("received selectUserResponse")
            """
      self.debug("received: " + str(jsonMessage['toUser']))
      self.debug("received: " + str(jsonMessage['toUserPubKey']))
      self.debug("received: " + str(jsonMessage['toUserPort']))
      self.debug("received: " + str(jsonMessage['sessionKey']))
      self.debug("received: " + str(jsonMessage['nonceReturned']))
      self.debug("received: " + str(jsonMessage['timestamp']))
      self.debug("received: " + str(jsonMessage['forwardBlock']))
      """

            self.validateUsername(self.usernameSent, jsonMessage["toUser"])
            self.validateNonce(self.nonceSent, jsonMessage["nonceReturned"])
            self.validateTimestamp(time.time(), jsonMessage["timestamp"])

            if jsonMessage["toUserPort"] != "":
                self.setPrivateMessageMode(
                    jsonMessage["toUser"],
                    jsonMessage["toUserPubKey"],
                    jsonMessage["sessionKey"],
                    jsonMessage["toUserPort"],
                    jsonMessage["forwardBlock"],
                )
            else:
                print jsonMessage["toUser"] + " is unavailable. Please try a different user."

        elif jsonMessage["messageType"] == "establishPrivateMessage":
            nsBlockEncrypted = binascii.a2b_base64(jsonMessage["forwardBlock"])
            nsBlockDecrypted = json.loads(self.decrypt(self.withKey(self.clientPrivateKey), nsBlockEncrypted))

            self.validateUsername(self.username, nsBlockDecrypted["destinationUsername"])
            self.validateTimestamp(time.time(), nsBlockDecrypted["serverTimestamp"])

            currentPrivateConnection = {
                "socket": socket.socket(socket.AF_INET, socket.SOCK_STREAM),
                "port": jsonMessage["srcPort"],
                "publicKey": jsonMessage["srcPublicKey"],
                "sessionKey": nsBlockDecrypted["sessionKey"],
            }

            self.currentConnections[jsonMessage["srcUsername"]] = currentPrivateConnection

            currentPrivateConnection["socket"].connect((self.host, jsonMessage["srcPort"]))

            establishPrivateMessageResponse = EstablishPrivateMessageResponse(self.username, jsonMessage["nonce"])
            self.sendEncrypted(
                establishPrivateMessageResponse.encode(),
                self.withKey(jsonMessage["srcPublicKey"]),
                currentPrivateConnection["socket"],
            )

        elif jsonMessage["messageType"] == "establishPrivateMessageResponse":
            self.validateNonce(self.privateMessageEstablishmentNonce, jsonMessage["nonce"])

            for msg in self.messageQueue:
                if msg[0] == jsonMessage["username"]:
                    toPort = self.currentConnections[jsonMessage["username"]]["port"]
                    toPublicKey = self.currentConnections[jsonMessage["username"]]["publicKey"]
                    toSocket = self.currentConnections[jsonMessage["username"]]["socket"]
                    toSessionKey = self.currentConnections[jsonMessage["username"]]["sessionKey"]

                    privateMessage = PrivateMessage(self.clientPort, self.username, toPort, msg[1])
                    self.sendPrivateEncrypted(
                        privateMessage.encode(), self.withKey(toPublicKey), toSessionKey, toSocket
                    )

            self.messageQueue = filter(lambda x: x[0] != jsonMessage["username"], self.messageQueue)

        elif jsonMessage["messageType"] == "logoutMessage":
            user = jsonMessage["username"]
            self.currentConnections[user]["socket"].close()
            del self.currentConnections[user]

            print user + " has logged out."

        # encrypted private message
        elif len(jsonMessage) > 0:
            data_decrypted = json.loads(self.decryptPrivateMessage(jsonMessage))

            if data_decrypted["messageType"] == "privateMessage":
                fromUser = self.currentConnections[data_decrypted["srcUsername"]]
                print data_decrypted["srcUsername"] + " >>>  " + str(data_decrypted["message"])
                privateMessageResponse = PrivateMessageResponse(
                    self.clientPort, fromUser["port"], data_decrypted["message"]
                )
                self.debug("setting currentPrivateConnection")
                self.sendPrivateEncrypted(
                    privateMessageResponse.encode(),
                    self.withKey(fromUser["publicKey"]),
                    fromUser["sessionKey"],
                    fromUser["socket"],
                )

            elif data_decrypted["messageType"] == "privateMessageResponse":
                print "YOU" + " >>>  " + str(data_decrypted["message"])