Esempio n. 1
0
async def is_authenticated(reader: StreamReader, writer: StreamWriter) -> bool:
    challenge = create_random_challenge()

    request_id = RequestIDGenerator.generate_request_id(
    ) % CONNECTION_COUNTER_LIMIT
    frame = AuthenticationChallengeFrame(challenge, request_id)
    await send_over_stream_async(frame, writer, settings.CONCENT_PRIVATE_KEY)
    logger.info(f"Challenge has been sent for request ID: {request_id}.")
    received_frame = await handle_frame_receive_async(
        reader, settings.SIGNING_SERVICE_PUBLIC_KEY)
    logger.info(f"Response has been received for request ID: {request_id}.")
    is_successful = True
    message_to_log = f'Authentication unsuccessful. Request ID: {request_id}. '
    if not isinstance(received_frame, AuthenticationResponseFrame):
        is_successful = False
        message_to_log += f'Received_frame is not AuthenticationResponseFrame instance. It is {type(received_frame)} instance.'
    elif received_frame.request_id != request_id:
        is_successful = False
        message_to_log += f'Received_frame ID should be {request_id}, but it is {received_frame.request_id}. '
    else:
        try:
            ecdsa_verify(settings.SIGNING_SERVICE_PUBLIC_KEY,
                         received_frame.payload, challenge)
        except InvalidSignature:
            is_successful = False
            message_to_log += 'Invalid ECDSA signature'
    if not is_successful:
        logger.debug(message_to_log)
    return is_successful
Esempio n. 2
0
    def test_message_sig(self):
        """Signed message inside a signed message"""

        concent_keys = cryptography.ECCx(None)
        provider_keys = cryptography.ECCx(None)
        requestor_keys = cryptography.ECCx(None)

        report_computed_task = factories.tasks.ReportComputedTaskFactory()

        # Dump TaskToCompute to make it signed
        s_rct = shortcuts.dump(
            report_computed_task,
            requestor_keys.raw_privkey,
            provider_keys.raw_pubkey,
        )

        # Load TaskToCompute back to its original format
        # Task TaskToCompute is verified correctly
        report_computed_task = shortcuts.load(
            s_rct,
            provider_keys.raw_privkey,
            requestor_keys.raw_pubkey,
        )

        first_sig = report_computed_task.sig
        first_hash = report_computed_task.get_short_hash()

        force_report = message.ForceReportComputedTask()
        force_report.report_computed_task = report_computed_task

        s_force_report = shortcuts.dump(
            force_report,
            provider_keys.raw_privkey,
            concent_keys.raw_pubkey,
        )

        force_report = shortcuts.load(
            s_force_report,
            concent_keys.raw_privkey,
            provider_keys.raw_pubkey,
        )

        second_sig = force_report.report_computed_task.sig
        second_hash = force_report.report_computed_task.get_short_hash()

        self.assertEqual(first_sig, second_sig)
        self.assertEqual(first_hash, second_hash)

        # Now, attached TaskToCompute should still be verified using
        # original key. ecdsa_verify will raise InvalidSignature on
        # failure.
        cryptography.ecdsa_verify(
            requestor_keys.raw_pubkey,
            force_report.report_computed_task.sig,
            force_report.report_computed_task.get_short_hash(),
        )
Esempio n. 3
0
 def _validate_signature(cls, raw_signed_part_of_the_frame: bytes, signature: bytes, public_key: bytes) -> None:
     try:
         ecdsa_verify(
             pubkey=public_key,
             signature=signature,
             message=raw_signed_part_of_the_frame,
         )
     except InvalidSignature:
         raise SignatureInvalidMiddlemanProtocolError(
             'Frame signature does not match its content.'
         )
    def test_signature(self):
        bob = get_ecc('secret2')

        # sign
        message = sha3("Hello Alice")
        signature = bob.sign(message)

        # verify signature
        assert ecdsa_verify(bob.raw_pubkey, signature, message) is True

        # wrong signature
        message = sha3("Hello Alicf")
        with self.assertRaises(exceptions.InvalidSignature):
            ecdsa_verify(bob.raw_pubkey, signature, message)
Esempio n. 5
0
    def test_that_authenticate_should_send_authentication_response_if_authentication_challenge_is_correct(
            self):
        middleman_message = AuthenticationChallengeFrame(
            payload=self.authentication_challenge,
            request_id=99,
        )
        raw_message = middleman_message.serialize(
            private_key=CONCENT_PRIVATE_KEY)

        raw_message_received = self._prepare_and_execute_handle_connection(
            raw_message, )

        deserialized_message = AbstractFrame.deserialize(
            raw_message=raw_message_received,
            public_key=SIGNING_SERVICE_PUBLIC_KEY,
        )

        assertpy.assert_that(deserialized_message).is_instance_of(
            AuthenticationResponseFrame)
        assertpy.assert_that(
            deserialized_message.payload).is_instance_of(bytes)
        assertpy.assert_that(
            ecdsa_verify(
                SIGNING_SERVICE_PUBLIC_KEY,
                deserialized_message.payload,
                self.authentication_challenge,
            )).is_true()
    def test_that_get_authentication_challenge_signature_should_return_signature_of_passed_bytes(self):
        authentication_challenge = bytes(os.urandom(1000))

        signature = self.signing_service._get_authentication_challenge_signature(authentication_challenge)

        self.assertIsInstance(signature, bytes)
        self.assertTrue(
            ecdsa_verify(
                self.signing_service.signing_service_public_key,
                signature,
                authentication_challenge,
            )
        )
Esempio n. 7
0
    def verify_signature(self,
                         public_key: bytes,
                         msg_hash: bytes = None) -> bool:
        """
        Verify the message's signature using the provided public key.
        Ensures that the message's content is intact and that it has been
        indeed signed by the expected party.

        :param public_key: the public key of the expected sender
        :param msg_hash: if provided, a call to `get_short_hash()`
                         will be skipped and the provided hash used instead
        :return: `True` if the signature is correct.
        :raises: `exceptions.InvalidSignature` if the signature is corrupted
        """
        return cryptography.ecdsa_verify(pubkey=public_key,
                                         signature=self.sig,
                                         message=msg_hash
                                         or self.get_short_hash())
    def test_message_sig(self):
        """Signed message inside a signed message"""

        concent_keys = cryptography.ECCx(None)
        provider_keys = cryptography.ECCx(None)
        requestor_keys = cryptography.ECCx(None)

        task_to_compute = message.TaskToCompute()
        ctd = message.ComputeTaskDef({
            'task_id': 20,
        })
        task_to_compute.compute_task_def = ctd

        # Dump TaskToCompute to make it signed
        s_task_to_compute = shortcuts.dump(
            task_to_compute,
            requestor_keys.raw_privkey,
            provider_keys.raw_pubkey,
        )

        # Load TaskToCompute back to its original format
        task_to_compute = shortcuts.load(
            s_task_to_compute,
            provider_keys.raw_privkey,
            requestor_keys.raw_pubkey,
        )

        first_sig = task_to_compute.sig
        first_hash = task_to_compute.get_short_hash()

        # Task TaskToCompute is verified correctly
        cryptography.ecdsa_verify(
            requestor_keys.raw_pubkey,
            task_to_compute.sig,
            task_to_compute.get_short_hash(),
        )

        force_report = message.ForceReportComputedTask()
        force_report.task_to_compute = task_to_compute

        s_force_report = shortcuts.dump(
            force_report,
            provider_keys.raw_privkey,
            concent_keys.raw_pubkey,
        )

        force_report = shortcuts.load(
            s_force_report,
            concent_keys.raw_privkey,
            provider_keys.raw_pubkey,
        )

        second_sig = force_report.task_to_compute.sig
        second_hash = force_report.task_to_compute.get_short_hash()

        self.assertEqual(first_sig, second_sig)
        self.assertEqual(first_hash, second_hash)

        # Now, attached TaskToCompute should still be verified using
        # original key. ecdsa_verify will raise InvalidSignature on
        # failure.
        cryptography.ecdsa_verify(
            requestor_keys.raw_pubkey,
            force_report.task_to_compute.sig,
            force_report.task_to_compute.get_short_hash(),
        )