示例#1
0
def answer_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = connection.recv_bytes(256)  # reject large message
    assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
    message = message[len(CHALLENGE):]
    digest = hmac.new(authkey, message).digest()
    connection.send_bytes(digest)
    response = connection.recv_bytes(256)  # reject large message
    if response != WELCOME:
        raise AuthenticationError('digest sent was rejected')
示例#2
0
def deliver_challenge(connection, authkey):
    import hmac
    message = os.urandom(MESSAGE_LENGTH)
    connection.send_bytes(CHALLENGE + message)
    digest = hmac.new(authkey, message).digest()
    response = connection.recv_bytes(256)
    if response == digest:
        connection.send_bytes(WELCOME)
    else:
        connection.send_bytes(FAILURE)
        raise AuthenticationError('digest received was wrong')
示例#3
0
def answer_challenge(connection, authkey):
    import hmac
    raise isinstance(authkey, bytes) or AssertionError
    message = connection.recv_bytes(256)
    if not message[:len(CHALLENGE)] == CHALLENGE:
        raise AssertionError('message = %r' % message)
        message = message[len(CHALLENGE):]
        digest = hmac.new(authkey, message).digest()
        connection.send_bytes(digest)
        response = connection.recv_bytes(256)
        raise response != WELCOME and AuthenticationError('digest sent was rejected')
示例#4
0
def deliver_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = os.urandom(MESSAGE_LENGTH)
    connection.send_bytes(CHALLENGE + message)
    digest = hmac.new(authkey, message, get_digestmod_for_hmac()).digest()
    response = connection.recv_bytes(256)  # reject large message
    if response == digest:
        connection.send_bytes(WELCOME)
    else:
        connection.send_bytes(FAILURE)
        raise AuthenticationError('digest received was wrong')
示例#5
0
    async def challengeReply(self) -> None:
        """Server replies to client challenges"""
        message = await self.reader.readexactly(CHALLENGE_SEND_LEN)
        assert message[: len(CHALLENGE)] == CHALLENGE, f"message = {message!r}"
        message = message[len(CHALLENGE) :]

        digest = hmac.new(self.authKey, message, HASH_ALGO).digest()

        self.writer.write(digest)
        await self.writer.drain()
        response = await self.reader.readexactly(len(WELCOME))

        if response != WELCOME:
            raise AuthenticationError("digest sent was rejected")
 async def deliver_challenge(self, authkey: bytes):
     import hmac
     if not isinstance(authkey, bytes):
         raise ValueError("Authkey must be bytes, not {0!s}".format(
             type(authkey)))
     message = os.urandom(MESSAGE_LENGTH)
     await self.send_bytes(CHALLENGE + message)
     digest = hmac.new(authkey, message, 'md5').digest()
     response = await self.recv_bytes(256)  # reject large message
     if response == digest:
         await self.send_bytes(WELCOME)
     else:
         await self.send_bytes(FAILURE)
         raise AuthenticationError('digest received was wrong')
示例#7
0
    async def challengeSend(self) -> None:
        """Client sends challenge to server when client connects"""
        message = os.urandom(RANDBYTES_LEN)
        self.writer.write(CHALLENGE + message)
        await self.writer.drain()

        digest = hmac.new(self.authKey, message, HASH_ALGO).digest()

        response = await self.reader.readexactly(CHALLENGE_REPLY_LEN)
        if response == digest:
            self.writer.write(WELCOME)
            await self.writer.drain()
        else:
            self.writer.write(FAILURE)
            await self.writer.drain()
            raise AuthenticationError("digest received didn't verify?")
示例#8
0
    def send_message(
        self,
        recipients: Optional[Union[List[str], str]] = None,
        subject: Optional[str] = "",
        body: Optional[str] = "",
        attachments: Optional[Union[List[str], str]] = None,
        html: Optional[bool] = False,
        images: Optional[Union[List[str], str]] = None,
        cc: Optional[Union[List[str], str]] = None,
        bcc: Optional[Union[List[str], str]] = None,
        save: Optional[bool] = False,
    ) -> None:
        """Keyword for sending message through connected Exchange account.

        :param recipients: list of email addresses
        :param subject: message subject, defaults to ""
        :param body: message body, defaults to ""
        :param attachments: list of filepaths to attach, defaults to `None`
        :param html: if message content is in HTML, default `False`
        :param images: list of filepaths for inline use, defaults to `None`
        :param cc: list of email addresses
        :param bcc: list of email addresses
        :param save: is sent message saved to Sent messages folder or not,
            defaults to False

        Email addresses can be prefixed with ``ex:`` to indicate an Exchange
        account address.

        At least one target needs to exist for `recipients`, `cc` or `bcc`.
        """
        if not self.account:
            raise AuthenticationError("Not authorized to any Exchange account")
        recipients, cc, bcc, attachments, images = self._handle_message_parameters(
            recipients, cc, bcc, attachments, images)
        if not recipients and not cc and not bcc:
            raise NoRecipientsError(
                "Atleast one address is required for 'recipients', 'cc' or 'bcc' parameter"  # noqa: E501
            )
        self.logger.info("Sending message to %s", ",".join(recipients))

        m = Message(
            account=self.account,
            subject=subject,
            body=body,
            to_recipients=recipients,
            cc_recipients=cc,
            bcc_recipients=bcc,
        )

        self._add_attachments_to_msg(attachments, m)
        self._add_images_inline_to_msg(images, html, body, m)

        if html:
            m.body = HTMLBody(body)
        else:
            m.body = body

        # TODO. The exchangelib does not seem to provide any straightforward way of
        # verifying if message was sent or not
        if save:
            m.folder = self.account.sent
            m.send_and_save()
        else:
            m.send()
示例#9
0
文件: pool.py 项目: tzoiker/aiomisc
        async def handler(start_event: asyncio.Event) -> None:
            log.debug("Starting to handle client")

            packet_type, salt = await receive()
            assert packet_type == PacketTypes.AUTH_SALT

            packet_type, digest = await receive()
            assert packet_type == PacketTypes.AUTH_DIGEST

            hasher = HASHER()
            hasher.update(salt)
            hasher.update(self.__cookie)

            if digest != hasher.digest():
                exc = AuthenticationError("Invalid cookie")
                await send(PacketTypes.EXCEPTION, exc)
                raise exc

            await send(PacketTypes.AUTH_OK, True)

            log.debug("Client authorized")

            packet_type, identity = await receive()
            assert packet_type == PacketTypes.IDENTITY
            process = self.__spawning.pop(identity)
            starting: asyncio.Future = self.__starting.pop(identity)

            if self.initializer is not None:
                initializer_done = self.__create_future()

                await step(self.initializer, self.initializer_args,
                           dict(self.initializer_kwargs), initializer_done)

                try:
                    await initializer_done
                except Exception as e:
                    starting.set_exception(e)
                    raise
                else:
                    starting.set_result(None)
                finally:
                    start_event.set()
            else:
                starting.set_result(None)
                start_event.set()

            while True:
                func: Callable
                args: Tuple[Any, ...]
                kwargs: Dict[str, Any]
                result_future: asyncio.Future
                process_future: asyncio.Future

                (
                    func,
                    args,
                    kwargs,
                    result_future,
                    process_future,
                ) = await self.tasks.get()

                try:
                    if process_future.done():
                        continue

                    process_future.set_result(process)

                    if result_future.done():
                        continue

                    await step(func, args, kwargs, result_future)
                except asyncio.IncompleteReadError:
                    await self.__wait_process(process)
                    self.__on_exit(process)

                    result_future.set_exception(
                        ProcessError(
                            "Process {!r} exited with code {!r}".format(
                                process,
                                process.returncode,
                            ), ), )
                    break
                except Exception as e:
                    if not result_future.done():
                        self.loop.call_soon(result_future.set_exception, e)

                    if not writer.is_closing():
                        self.loop.call_soon(writer.close)

                    await self.__wait_process(process)
                    self.__on_exit(process)

                    raise