예제 #1
0
    def processNew(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data_error = ""

        user = -1
        if 'id' in data.keys():
            user = int(data['id'])

        if user < 0:
            log(
                logging.ERROR, "No valid \"id\" field in \"new\" message: " +
                json.dumps(data))
            data_error = {"error": "wrong message format"}

        if client.id != data["id"]:
            log(
                logging.ERROR,
                "No valid \"id\" field in \"all\" message, (not your mail box): "
                + json.dumps(data))
            data_error = {"error": "Not your mail box"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        payload = {"result": self.registry.userNewMessages(user)}
        payload = load_payload(payload)
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #2
0
    def processList(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data = unload_payload(data)
        user = 0  # 0 means all users
        userStr = "all users"
        if 'id' in data.keys():
            user = int(data['id'])
            userStr = "user%d" % user

        log(logging.DEBUG, "List %s" % userStr)

        userList = self.registry.listUsers(user)
        if userList == None:
            log(logging.ERROR, "User does not exist: " + json.dumps(data))
            data_error = {"error": "user does not exist"}
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        payload = load_payload({"result": userList})
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #3
0
    def processSend(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data_error = ""

        if not set(data.keys()).issuperset(set({'src', 'dst', 'msg', 'copy'})):
            log(logging.ERROR,
                "Badly formated \"send\" message: " + json.dumps(data))
            data_error = load_payload({"error": "wrong message format"})
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        srcId = int(data['src'])
        dstId = int(data['dst'])
        msg = str("\n".join([data['msg']['text'], data['msg']['signature']]))
        copy = str("\n".join([data['copy']['copy'],
                              data['copy']['signature']]))

        if not self.registry.userExists(srcId):
            log(logging.ERROR,
                "Unknown source id for \"send\" message: " + json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if not self.registry.userExists(dstId):
            log(
                logging.ERROR,
                "Unknown destination id for \"send\" message: " +
                json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if client.id != srcId or srcId == None:
            log(
                logging.ERROR,
                "No valid \"src id\" field in \"send\" message, (not your mail box): "
                + json.dumps(data))
            data_error = {
                "error": "Cant send msg from other person, user your source ID"
            }

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        # Save message and copy
        payload = {
            "result": self.registry.sendMessage(srcId, dstId, msg, copy)
        }
        payload = load_payload(payload)
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #4
0
    def processRecv(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))

        data_error = ""
        if not set({'id', 'msg'}).issubset(set(data.keys())):
            log(logging.ERROR,
                "Badly formated \"recv\" message: " + json.dumps(data))
            data_error = {"error": "wrong parameters"}
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        fromId = int(data['id'])
        msg = recvBytes(data['msg']).decode('utf-8')
        if not self.registry.userExists(fromId):
            log(logging.ERROR,
                "Unknown source id for \"recv\" message: " + json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if client.id != fromId:
            log(
                logging.ERROR,
                "No valid \"id\" field in \"recv\" message, (not your mail box): "
                + json.dumps(data))
            data_error = {"error": "Not your mail box"}

        if not self.registry.messageExists(fromId, msg):
            log(logging.ERROR,
                "Unknown mail box for \"recv\" message: " + json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        # Read message

        response = self.registry.recvMessage(fromId, msg)

        payload = {"payload": response}
        payload = load_payload(payload)
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #5
0
    def All(self, uid):
        payload = {'type': 'all', 'id': uid}
        payload = load_payload(payload)

        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)
        self.send_to_server(payload)

        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))

        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)
        #verificar o msgID se esta na lista de enviados? e verificar assinatura
        response = response["payload"]
        response = unload_payload(response)

        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))

        else:
            received = ""
            for x in response.get('result')[0]:
                received += x.decode(ENCODING) + "; "
            log_success(
                "Received Message: %s" %
                str(received if received != "" else "No received messages"))
            sended = ""

            for x in response.get('result')[1]:
                sended += x.decode(ENCODING) + "; "
            log_success("Sended Message: %s" %
                        str(sended if sended != "" else "No sended messages"))
예제 #6
0
    def New(self, uid):
        payload = {'type': 'new', 'id': uid}
        payload = load_payload(payload)

        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)
        self.send_to_server(payload)

        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))
        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)
        response = response["payload"]
        response = unload_payload(response)

        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))

        elif len(response.get('result')) == 0:
            log_info("No new messages to show")

        else:
            log_success("New messages: ")
            for x in response.get('result'):
                print("\tmessage: " + x.decode(ENCODING))
예제 #7
0
    def processReceipt(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data_error = {}

        fromId = int(data['id'])
        if client.id != fromId:
            log(
                logging.ERROR,
                "No valid \"id\" field in \"recv\" message, (not your mail box): "
                + json.dumps(data))
            data_error = {"error": "Not your mail box"}

        if not set({'id', 'msg', 'receipt'}).issubset(set(data.keys())):
            log(logging.ERROR,
                "Badly formated \"receipt\" message: " + json.dumps(data))
            data_error = {"error": "wrong request format"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        fromId = int(data["id"])
        msg = get_bytes(base64.b64decode(data['msg']))
        receipt = str("\n".join([data['receipt'], data['date']]))

        if not self.registry.messageWasRed(str(fromId), msg):
            log(
                logging.ERROR,
                "Unknown, or not yet red, message for \"receipt\" request " +
                json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        self.registry.storeReceipt(fromId, msg, receipt)
예제 #8
0
    def List(self, uid=None, get_response=False):
        #falta a parte de assinal este msgID

        payload = {}

        if uid == None:
            payload = {'type': 'list'}
        else:
            payload = {'type': 'list', 'id': uid}

        payload = load_payload(payload)

        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)
        self.send_to_server(payload)

        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))
        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)
        #verificar o msgID se esta na lista de enviados? e verificar assinatura

        response = response["payload"]

        if response.get('error'):
            response = get_bytes(unload_payload(response))
            log_error(response.get('error'))
            return
        else:
            response = response["result"]
            response = unload_payload(response)
            if get_response:
                return response
            try:
                print("-----------\n USER LIST \n-----------")
                for x in response:
                    if x.get("description") != None:
                        print(
                            "\nID: {0}\nName: {1}\nUUID: {2}\n-----------".
                            format(
                                x.get("id"),
                                get_bytes(
                                    x.get("description").get("subject_name")),
                                x.get("description").get("uuid")))
                    else:
                        print("\nID: {0}\nName: {1}\nUUID: {2}\n-----------".
                              format(uid, get_bytes(x.get("subject_name")),
                                     x.get("uuid")))
            except Exception as e:
                raise e
                log_info("Id does not exist")
예제 #9
0
    def processAll(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data_error = ""

        user = -1
        if 'id' in data.keys():
            user = int(data['id'])

        if user < 0:
            log(
                logging.ERROR, "No valid \"id\" field in \"new\" message: " +
                json.dumps(data))
            data_error = {"error": "wrong message format"}
            # removi return's aqui e no if abaixo para garantir que não retorna. Só deve retornar no if data_error

        if client.id != data["id"]:
            log(
                logging.ERROR,
                "No valid \"id\" field in \"all\" message, (not your mail box): "
                + json.dumps(data))
            data_error = {"error": "Not your mail box"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        payload = {
            "result": [
                self.registry.userAllMessages(user),
                self.registry.userSentMessages(user)
            ]
        }
        payload = load_payload(payload)

        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #10
0
    def processStatus(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))
        data_error = {}

        fromId = int(data['id'])
        if client.id != fromId:
            log(
                logging.ERROR,
                "No valid \"id\" field in \"recv\" message, (not your mail box): "
                + json.dumps(data))

        if not set({'id', 'msg'}).issubset(set(data.keys())):
            log(logging.ERROR,
                "Badly formated \"receipt\" message: " + json.dumps(data))
            data_error = {"error": "wrong request format"}

        fromId = int(data['id'])
        msg = str(data["msg"])

        if (not self.registry.copyExists(fromId, msg)):
            log(logging.ERROR,
                "Unknown message for \"status\" request: " + json.dumps(data))
            data_error = {"error": "wrong parameters"}

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        response = self.registry.getReceipts(fromId, msg)

        payload = {"payload": response}

        payload = load_payload(payload)
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)
예제 #11
0
    def handleRequest(self, s, request, client):
        """Handle a request from a client socket.
        """
        try:
            logging.info("HANDLING message from %s: %r" %
                         (client, repr(request)))

            try:
                req = json.loads(request)
            except:
                logging.exception("Invalid message from client")
                return

            if not isinstance(req, dict):
                log(logging.ERROR, "Invalid message format from client")
                return

            if 'type' not in req:
                ok, client.blockChain, req = ourCrypto.verify_integrity(
                    req, client.sessionKeys, client.blockChain)

                if ok is not True:
                    payload = {
                        "error":
                        "No integrity in package or package malformed",
                        "last_hash": sendBytes(client.blockChain.currentHash)
                    }
                    payload, client.blockChain = ourCrypto.generate_integrity(
                        payload, client.sessionKeys, client.blockChain)
                    client.sendResult(payload)
                    return

                req = req["payload"]

                if 'type' not in req:
                    log(logging.ERROR, "Message has no TYPE field")
                    return

            if req['type'] in self.messageTypes:
                self.messageTypes[req['type']](req, client)
            else:
                log(
                    logging.ERROR,
                    "Invalid message type: " + str(req['type']) +
                    " Should be one of: " + str(self.messageTypes.keys()))
                client.sendResult({"error": "unknown request"})

        except Exception as e:
            logging.exception("Could not handle request")
예제 #12
0
    def Receipt(self, box, msg):
        if self.id == None:
            log_error("No user id, pls create a user\n")
            return

        log_info("Sending receipt for message number %s " % str(box))

        date = str(int(time.mktime(datetime.utcnow().timetuple())))

        msg = msg + "\n" + sendBytes(date)

        signature = self.cc.sign(msg)

        payload = {
            'type': 'receipt',
            'id': self.id,
            'msg': str(box),
            'receipt': signature,
            'date': date,
        }

        payload = load_payload(payload)
        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)
        self.send_to_server(payload)

        self.socket.settimeout(2)

        try:
            response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))
            ok, self.blockChain, response = ourCrypto.verify_integrity(
                response, self.sessionKeys, self.blockChain)

            if not ok:
                print("No integrity of message. Exiting...")
                sys.exit(-1)
            response = response["payload"]
            response = get_bytes(unload_payload(response))
            log_error(response.get('error'))

        except Exception as e:
            log_success("Receipt was sent\n")

        self.socket.settimeout(None)
예제 #13
0
    def Create(self):
        payload = {
            'uuid': self.uuid,
            'publicKey': self.AsyCypher.getPub(),
            'cert': self.cc.cert.dump_certificate(),
            'subject_name': self.cc.cert.get_subject(),

            #'randomId': msgID
        }

        payload = load_payload(payload)

        signature = self.cc.sign(json.dumps(payload, sort_keys=True))

        payload["signature"] = sendBytes(signature)
        payload["type"] = "create"

        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)
        self.send_to_server(payload)

        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))

        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)
        #verificar o msgID se esta na lista de enviados? e verificar assinatura
        response = response["payload"]
        response = unload_payload(response)
        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))

        elif response.get('login'):
            self.id = response.get('result')
            log_info(response.get('login').decode(ENCODING))

        else:
            self.id = response.get('result')
            log_success("Message box with created successfully (ID: %s)" %
                        str(response.get('result')))
예제 #14
0
    def Recv(self, box):
        if self.id == None:
            log_error("No user id, pls create/login a user\n")
            return
        payload = {
            'type': 'recv',
            'id': self.id,
            'msg': str(box),
        }

        payload = load_payload(payload)
        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)

        self.send_to_server(payload)
        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))
        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)

        response = response["payload"]
        response = unload_payload(response)

        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))
        else:
            intermidiate_data = response["payload"][1].split(
                bytes("\n", "utf-8"))

            plaintext, padd = self.AsyCypher.decyph(intermidiate_data[0])
            log_success("\nMessage: %s \n" % str(plaintext.decode(ENCODING)))

            self.Receipt(box,
                         plaintext.decode(ENCODING) + "\n" + sendBytes(padd))
예제 #15
0
    def Send(self, dst, msg):

        if self.id == None:
            log_error("No user id, pls create/login a user")
            return
        list_result = self.List(dst, get_response=True)
        if list_result == None:
            log_error("No destination user ID")
            return
        list_result = list_result[0]
        signature = recvBytes(list_result["signature"].decode(ENCODING))
        del list_result["signature"]
        valido = False
        try:
            self.certCertificate = Certificate(
                recvBytes(list_result["cert"].decode(ENCODING)))
            list_result["cert"] = list_result["cert"].decode(ENCODING)
            list_result["publicKey"] = list_result["publicKey"].decode(
                ENCODING)
            list_result["subject_name"] = list_result["subject_name"].decode(
                ENCODING)
            log_info("Validating public key of the recipient")
            valido = self.certCertificate.validate_signature(
                json.dumps(list_result, sort_keys=True), signature)
        except Exception as e:
            pass

        if not valido:
            log_error("Information in the description is not reliable")
            return
        list_result = get_bytes(self.List(dst, get_response=True))[0]

        signature = self.cc.sign(msg)

        padd = os.urandom(32)  # padding

        text = self.AsyCypher.cyph(bytes(msg, 'utf-8'),
                                   public_key=list_result["publicKey"],
                                   padd=padd)
        copy = self.AsyCypher.cyph(bytes(msg, 'utf-8'), padd=padd)

        payload = {
            'type': 'send',
            'src': self.id,
            'dst': dst,
            'msg': {
                "text": text,
                "signature": signature
            },
            'copy': {
                "copy": copy,
                "signature": signature
            },
        }

        payload = load_payload(payload)
        payload, self.blockChain = ourCrypto.generate_integrity(
            payload, self.sessionKeys, self.blockChain)

        self.send_to_server(payload)

        response = json.loads(self.socket.recv(BUFSIZE).decode('utf-8'))

        ok, self.blockChain, response = ourCrypto.verify_integrity(
            response, self.sessionKeys, self.blockChain)
        if not ok:
            print("No integrity of message. Exiting...")
            sys.exit(-1)
        #verificar o msgID se esta na lista de enviados? e verificar assinatura
        response = response["payload"]
        response = unload_payload(response)

        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))
        else:
            log_success("Message identifier: %s; Receipt identifier %s" %
                        (str(response["result"][0].decode(ENCODING)),
                         str(response["result"][1].decode(ENCODING))))
예제 #16
0
    def processCreate(self, data, client):
        log(logging.DEBUG, "%s" % json.dumps(data))

        signature = recvBytes(data["signature"])

        del data["signature"]
        del data["type"]

        try:

            client.clientCertificate = Certificate(recvBytes(data["cert"]))
            valido = client.clientCertificate.validate_signature(
                json.dumps(data, sort_keys=True), signature)
            print(valido)
        except Exception as e:
            raise e

        data["signature"] = sendBytes(signature)

        data_error = ""
        if 'uuid' not in data.keys():
            print("no data.keys")
            log(logging.ERROR,
                "No \"uuid\" field in \"create\" message: " + json.dumps(data))
            data_error = {"error": "wrong message format"}

        uuid = data['uuid']
        if not isinstance(uuid, int):  # is it an error ?
            log(
                logging.ERROR,
                "No valid \"uuid\" field in \"create\" message: " +
                json.dumps(data))
            data_error = {"error": "wrong message format"}

        #esta a usar a userExists para verificar o uuid e o id
        if self.registry.userExistsUuid(uuid):
            #do lado do servidor agora os clientes tem uuid e id associados
            client.id, client.uuid = self.registry.userExistsUuid(uuid)

            # Comparing certificates just to be sure :)
            cert_stored = recvBytes(
                self.registry.listUsers(client.id)[0]['cert'])
            cert_recived = recvBytes(data["cert"])

            if cert_stored == cert_recived:
                data_error = {"login": "******", "result": client.id}
            else:
                data_error = {
                    "error": "You are not who you say you are :) Get Rekt m8"
                }

        if data_error:
            data_error = load_payload(data_error)
            payload, client.blockChain = ourCrypto.generate_integrity(
                data_error, client.sessionKeys, client.blockChain)
            client.sendResult(payload)
            return

        me = self.registry.addUser(data)

        client.id = me.id
        client.uuid = uuid

        payload = {"result": me.id}
        payload = load_payload(payload)
        payload, client.blockChain = ourCrypto.generate_integrity(
            payload, client.sessionKeys, client.blockChain)
        client.sendResult(payload)