示例#1
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")
示例#2
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"))
示例#3
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))
示例#4
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)
示例#5
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)
示例#6
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')))
示例#7
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))
示例#8
0
    def Status(self, box):
        if self.id == None:
            log_error("No user id, pls create a user\n")
            return
        message = {
            'type': 'status',
            'id': self.id,
            'msg': box,
        }

        self.send_to_server(message)
        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)

        valido = False
        if response.get('error'):
            log_error(response.get('error').decode(ENCODING))
        else:

            response = response["payload"]
            msg = response["msg"]
            receipt = response["receipts"]

            receiptID = ""
            valido = False
            validoCert = False
            for x in receipt:
                if receiptID != x["id"]:
                    receiptID = x["id"]
                    list_result = (self.List(receiptID, get_response=True)[0])

                    signature = recvBytes(
                        list_result["signature"].decode(ENCODING))
                    del list_result["signature"]
                    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 certificate\n")
                        validoCert = self.certCertificate.validate_signature(
                            json.dumps(list_result, sort_keys=True), signature)
                    except Exception as e:
                        pass
                if validoCert:
                    intermidiate_data = msg.split(bytes("\n", "utf-8"))

                    plaintext, padd = self.AsyCypher.decyph(
                        intermidiate_data[0])
                    try:
                        receipt_splited = x["receipt"].split(
                            bytes("\n", "utf-8"))

                        time_to_validate = time.gmtime(
                            float(
                                recvBytes(
                                    receipt_splited[1].decode(ENCODING))))
                        time_to_validate = datetime.fromtimestamp(
                            time.mktime(time_to_validate))

                        signature = recvBytes(
                            receipt_splited[0].decode(ENCODING))
                        plaintext = plaintext.decode(
                            ENCODING) + "\n" + sendBytes(
                                padd) + "\n" + receipt_splited[1].decode(
                                    ENCODING)
                        valido = self.certCertificate.validate_signature(
                            plaintext,
                            signature,
                            time_to_validate=time_to_validate)
                    except Exception as e:
                        raise e

                    if valido:
                        valido = False
                        log_success(
                            "Authenticated receipt. ID-%s\nClient_Date-%s\nServer_Date-%s \n"
                            % (str(x["id"].decode(ENCODING)),
                               str(
                                   datetime.fromtimestamp(
                                       int(
                                           recvBytes(receipt_splited[1].decode(
                                               ENCODING))))),
                               str(
                                   datetime.fromtimestamp(
                                       int(
                                           int(x["date"].decode(ENCODING)) /
                                           1000)))))
                    else:
                        log_error(
                            "Unauthenticated receipt. ID-%s\nClient_Date-%s\nServer_Date-%s \n"
                            % (str(x["id"].decode(ENCODING)),
                               str(
                                   datetime.fromtimestamp(
                                       int(
                                           recvBytes(receipt_splited[1].decode(
                                               ENCODING))))),
                               str(
                                   datetime.fromtimestamp(
                                       int(
                                           int(x["date"].decode(ENCODING)) /
                                           1000)))))
                else:
                    log_error(
                        "Information in the description is not reliable \n")
示例#9
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))))