Exemple #1
0
    def __init__(self, sock):
        # Create the Entity and socket
        self.auction_repository = AuctionRepositoryEntity()
        self.sock = sock

        # Create the Public key and Private key
        rsa_kg = RSAKGen()

        # Check for the existence of the directory
        if check_directory(self._server_path):

            try:
                # Get the keys from the folders
                self.auction_repository.private_key, self.auction_repository.public_key = rsa_kg.load_key_servers(
                    self._server_path, self._server_password)

                # Get the server public key
                self.auction_repository.manager_public = rsa_kg.load_public_key(
                    self._server_path, "manager_server.pem")
            except ValueError:
                # Exits
                sys.exit(
                    "The password is incorrect! All information has been deleted and the server will"
                    "now become unstable")

        else:
            # Since it doesn't exist, we create the folders
            os.mkdir(self._server_path)
            os.mkdir(os.getcwd() + "/Clients")
            self.auction_repository.private_key, self.auction_repository.public_key = rsa_kg.generate_key_pair_server(
            )
            rsa_kg.save_keys_server(self._server_path, self._server_password)
    def __init__(self, sock):
        self.sock = sock
        self.auction_manager = AuctionManagerEntity()

        # Create the Public key and Private key
        rsa_kg = RSAKGen()

        # Check for the existence of the directory
        if check_directory(self._server_path):
            try:
                self.auction_manager.private_key, self.auction_manager.public_key = rsa_kg.load_key_servers(
                    self._server_path,self._server_password)
                self.auction_manager.public_repository_key = rsa_kg.load_public_key(os.getcwd()+"/server",
                                                                                    "repository_server.pem")
            except ValueError:
                print("The password is incorrect!"
                      "All information has been deleted and the server will now become instable")
                sys.exit(0)

        else:
            os.mkdir(self._server_path)
            self.auction_manager.private_key, self.auction_manager.public_key = rsa_kg.generate_key_pair_server()
            rsa_kg.save_keys_server(self._server_path, self._server_password)

        # Create the sessionKey with the other Repository
        self.create_session_key_server()
Exemple #3
0
    def auction_to_view(self, message_json):
        username = message_json["username"]
        sk = self.auction_repository.session_key_clients[username]
        hm = base64.b64decode(message_json["hmac"])
        cr = message_json["message"].encode()

        if not HMAC_Conf.verify_integrity(hm, cr, sk):
            return base64.b64encode(
                "{ \"type\" : \"Tempered data\"}".encode('utf-8'))

        # Decrypts the message
        data = decrypt_data(sk, message_json["message"],
                            base64.b64decode(message_json["iv"]),
                            base64.b64decode(message_json["Key"]),
                            self.auction_repository.private_key)

        auction_id = unpadd_data(data, sk)

        auction = self.auction_repository.auctions[str(auction_id, "utf-8")]
        blockchain = pickle.dumps(auction.blockchain)

        # cipher first the blockchain
        enc_bl = encrypt_message_sk(
            blockchain, self.auction_repository.session_key_clients[username])

        message = "{ \"type\" : \"auction_to_view\", \n"

        message_int = "{\n\"auction_id\" : \"" + encrypt_message_sk(
            auction_id, sk) + "\" ,\n"
        message_int += "\"blockchain\" : \"" + enc_bl + "\", \n"
        message_int += "\"auct_type\" : \"" + encrypt_message_sk(
            auction.type, sk) + "\",\n"
        message_int += "\"avail\" : \"" + encrypt_message_sk(
            str(auction.open), sk) + "\"\n"
        message_int += "}"

        rsa_kg = RSAKGen()
        client_pub = rsa_kg.load_public_key(os.getcwd() + "/Clients/" +
                                            username)
        enc_json_message = encrypt_message_complete(
            base64.b64encode(message_int.encode("utf-8")), sk, client_pub)

        key = enc_json_message[0]
        iv = enc_json_message[2]
        data = enc_json_message[1]

        hmac = HMAC_Conf.integrity_control(
            data.encode(),
            self.auction_repository.session_key_clients[username])

        message += "\"message\" : \"" + data + "\",\n"
        message += "\"Key\" : \"" + str(base64.b64encode(key),
                                        'utf-8') + "\",\n"
        message += "\"hmac\" : \"" + str(base64.b64encode(hmac),
                                         'utf-8') + "\", \n"
        message += "\"iv\" : \"" + str(base64.b64encode(iv), 'utf-8') + "\"\n"
        message += "}"

        return base64.b64encode(message.encode("utf-8"))
Exemple #4
0
    def create_session_key_server(self, message_json, address):

        # decode the params
        parameters = pickle.loads(
            codecs.decode(message_json["params"].encode(), "base64"))
        par = load_pem_parameters(parameters, backend=default_backend())

        # Get the server public key
        manager_pub = message_json["public"].encode()
        save_server_key_client(self._server_path, manager_pub,
                               "/manager_server.pem")

        # Load the key
        r = RSAKGen()
        self.auction_repository.manager_public = r.load_public_key(
            self._server_path, "manager_server.pem")

        # Generate our public/private key
        private_key = par.generate_private_key()
        public_key = private_key.public_key()

        # Get the public key from the user
        peer_public_key_bytes = message_json["pk"].encode()
        peer_public_key = serialization.load_pem_public_key(
            peer_public_key_bytes, default_backend())
        shared_key = private_key.exchange(peer_public_key)

        calendar_date = str(datetime.datetime.now())

        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=DH_HKDF_KEY,
                           salt=None,
                           info=calendar_date.encode(),
                           backend=default_backend()).derive(shared_key)

        # Construct the message with the keys
        message = "{ \"type\" : \"session_server\" ,\n"

        # Now send our DH public key to the client
        pk_dh = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo).decode(
                'utf-8')

        message += "\"pk\" : \"" + pk_dh + "\" ,\n"
        message += "\"info\" : \"" + calendar_date + "\",\n"
        message += "\"server_key\" : \"" + self.auction_repository.public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo).decode(
                'utf-8') + "\""

        message += "}"

        # Set the sessionKey as the bytes of the derived_key
        self.auction_repository.session_key_server = derived_key
        return base64.b64encode(message.encode('utf-8'))
    def create_session_key_server(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Our parameters
        parameters = dh.generate_parameters(generator=5, key_size=utils_app.DH_KEY_SIZE, backend=default_backend())

        # Our private key and public key
        private_key = parameters.generate_private_key()
        public_key = private_key.public_key()

        message = codecs.encode(
            pickle.dumps(parameters.parameter_bytes(encoding=Encoding.PEM, format=ParameterFormat.PKCS3)),
            "base64").decode()

        # message construction
        json_message = "{ " + "\n"
        json_message += "\"type\" : \"session_server\"," + "\n"
        json_message += "\"params\" : \"" + message + "\", \n"
        json_message += "\"pk\" : \"" + public_key.public_bytes(encoding=serialization.Encoding.PEM,
                                                                format=serialization.PublicFormat.SubjectPublicKeyInfo)\
            .decode('utf-8') + "\","
        json_message += "\"public\" : \"" + self.auction_manager.public_key.\
            public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)\
            .decode('utf-8') + "\""
        json_message += "}"

        try:
            # send type
            sock.sendto(base64.b64encode(json_message.encode('utf-8')), utils_app.AR_ADDRESS)

            # Receive type
            data, server = sock.recvfrom(utils_app.SOCKET_BYTES)
            json_message = json.loads(base64.b64decode(data), strict=False)

            # derivate the key
            peer_public_key_bytes = json_message["pk"].encode()
            peer_public_key = serialization.load_pem_public_key(peer_public_key_bytes, default_backend())
            shared_key = private_key.exchange(peer_public_key)

            derived_key = cryptography.hazmat.primitives.kdf.hkdf.HKDF(algorithm=hashes.SHA256(),
                                                                       length=utils_app.DH_HKDF_KEY,
                                                                       salt=None, info=json_message["info"].encode(),
                                                                       backend=default_backend()).derive(shared_key)
            self.auction_manager.session_key_repository = derived_key

            save_server_key_client(self._server_path, json_message["server_key"].encode(), "/repository_server.pem")

            #Load the key
            r = RSAKGen()
            self.auction_manager.public_repository_key = r.load_public_key(os.getcwd()+"/server",
                                                                           "repository_server.pem")
            print("Session Set with repository")
        finally:
            sock.close()
Exemple #6
0
    def list_auctions(self, message_json):

        sk = self.auction_repository.session_key_clients[
            message_json["username"]]

        # VERIFYES THE message integrity
        if not HMAC_Conf.verify_function("username", message_json, sk):
            return base64.b64encode(
                "{ \"type\" : \"Tempered data\"}".encode('utf-8'))

        # gets the list of auctions and serializes it
        auction_list = self.auction_repository.listAuctions()
        serialized = pickle.dumps(auction_list)

        # loads the shared secret between the server and the user
        username = message_json["username"]
        session_key = self.auction_repository.session_key_clients[username]

        list_auc = encrypt_message_sk(serialized, session_key)

        rsa_kg = RSAKGen()
        client_pub = rsa_kg.load_public_key(os.getcwd() + "/Clients/" +
                                            username)

        enc_json_message = encrypt_message_complete(
            base64.b64encode(list_auc.encode("utf-8")), sk, client_pub)

        message = "{ \"type\" : \"list_auctions\" ,\n"

        key = enc_json_message[0]
        iv = enc_json_message[2]
        data = enc_json_message[1]

        hmac = HMAC_Conf.integrity_control(
            data.encode(),
            self.auction_repository.session_key_clients[username])

        message += "\"list\" : \"" + data + "\", \n"
        message += "\"Key\" : \"" + str(base64.b64encode(key),
                                        'utf-8') + "\",\n"
        message += "\"hmac\" : \"" + str(base64.b64encode(hmac),
                                         'utf-8') + "\", \n"
        message += "\"iv\" : \"" + str(base64.b64encode(iv), 'utf-8') + "\"\n"
        message += "}"

        print("auction_repos", message)
        return base64.b64encode(message.encode("utf-8"))
Exemple #7
0
    def make_bid(self, message_json):
        sk = self.auction_repository.session_key_clients[
            message_json["username"]]

        # VERIFIES THE message integrity
        if not HMAC_Conf.verify_function("message", message_json, sk):
            return base64.b64encode(
                "{ \"type\" : \"Tempered data\"}".encode('utf-8'))

        # Decrypts the message
        username = message_json["username"]
        data = decrypt_data(
            self.auction_repository.session_key_clients[username],
            message_json["message"], base64.b64decode(message_json["iv"]),
            base64.b64decode(message_json["Key"]),
            self.auction_repository.private_key)
        # Loads the message to json
        message_json = json.loads(data, strict="False")

        auction_id = unpadd_data(
            message_json["auction_id"],
            self.auction_repository.session_key_clients[username])
        bidder = unpadd_data(
            message_json["bidder"],
            self.auction_repository.session_key_clients[username])
        amount = unpadd_data(
            message_json["amount"],
            self.auction_repository.session_key_clients[username])
        signature = unpadd_data(
            message_json["signature"],
            self.auction_repository.session_key_clients[username])

        certificate = unpadd_data(
            message_json["certificate"],
            self.auction_repository.session_key_clients[username])

        # validate certificate and signature
        cert = x509.load_pem_x509_certificate(certificate, default_backend())
        citizen = CitizenCard()
        if not citizen.check_signature(cert, signature, amount):
            return base64.b64encode(
                "{ \"type\" : \"No valid signature\"}".encode('utf-8'))

        if not citizen.validate_certificate(cert):
            return base64.b64encode(
                "{ \"type\" : \"No valid certificate\"}".encode('utf-8'))

        auction = self.auction_repository.auctions[str(auction_id, "utf-8")]
        response = auction.makeBid(bidder, amount, signature, certificate)

        if not response:
            return base64.b64encode(
                "{ \"type\" : \"No success\"}".encode('utf-8'))

        # create receipt
        rsa_kg = RSAKGen()

        block = auction.blockchain[-1]
        server_signature = rsa_kg.sign_message(
            block.hash, self.auction_repository.private_key)
        server_signature = encrypt_message_sk(server_signature, sk)

        uuids = encrypt_message_sk(str(uuid.uuid1()), sk)

        last = encrypt_message_sk(block.hash, sk)
        bidder = encrypt_message_sk(bidder, sk)

        receipt = create_receipt(encrypt_message_sk(str(block.timestamp), sk),
                                 encrypt_message_sk(str(auction_id),
                                                    sk), server_signature,
                                 encrypt_message_sk(amount, sk),
                                 encrypt_message_sk(signature, sk), uuids,
                                 last, bidder)

        # cipher receipt with pub_key
        client_pub = rsa_kg.load_public_key(os.getcwd() + "/Clients/" +
                                            username)
        enc_json_message = encrypt_message_complete(
            base64.b64encode(receipt.encode("utf-8")), sk, client_pub)

        key = enc_json_message[0]
        iv = enc_json_message[2]
        data = enc_json_message[1]

        hmac = HMAC_Conf.integrity_control(
            data.encode(),
            self.auction_repository.session_key_clients[username])

        message = "{ \"type\" : \"receipt\", \n"
        message += "\"message\" : \"" + data + "\",\n"
        message += "\"Key\" : \"" + str(base64.b64encode(key),
                                        'utf-8') + "\",\n"
        message += "\"hmac\" : \"" + str(base64.b64encode(hmac),
                                         'utf-8') + "\", \n"
        message += "\"iv\" : \"" + str(base64.b64encode(iv), 'utf-8') + "\"\n"
        message += "}"

        return base64.b64encode(message.encode("utf-8"))