Ejemplo n.º 1
0
    def exists(self, user, memo=None):
        """
        Check whether a user exists in this domain or an alias of it.

        @type user: L{User}
        @param user: A user.

        @type memo: L{NoneType <types.NoneType>} or L{dict} of L{AliasBase}
        @param memo: A record of the addresses already considered while
            resolving aliases. The default value should be used by all
            external code.

        @rtype: no-argument callable which returns L{IMessage <smtp.IMessage>}
            provider.
        @return: A function which takes no arguments and returns a message
            receiver for the user.

        @raises SMTPBadRcpt: When the given user does not exist in this domain
            or an alias of it.
        """
        if self.userDirectory(user.dest.local) is not None:
            return lambda: self.startMessage(user)
        try:
            a = self.alias[user.dest.local]
        except:
            raise smtp.SMTPBadRcpt(user)
        else:
            aliases = a.resolve(self.alias, memo)
            if aliases:
                return lambda: aliases
            log.err("Bad alias configuration: " + str(user))
            raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 2
0
    def validateTo(self, user):
        print "validateTo:", user
        if str(user) in ['*****@*****.**', '*****@*****.**']:
            raise smtp.SMTPBadRcpt(user)
        if user.dest.domain in self.postman.valid_domains:

            def emailcallback(incoming):
                return self.postman.new_email(incoming, self.email_element,
                                              user.dest.domain)

            return lambda: ScewptMessage(emailcallback)
        elif user.dest.domain in self.postman.invalid_domains:
            raise smtp.SMTPBadRcpt(user)
        else:

            def handleCheckDomain(isvalid):
                print 'isvalid:', isvalid, user.dest.domain
                if isvalid or user.dest.domain == 'localhost':
                    self.postman.valid_domains.append(user.dest.domain)
                else:
                    self.postman.invalid_domains.append(user.dest.domain)

            d = self.postman.check_domain(user.dest.domain)
            d.addBoth(handleCheckDomain)
            d.addBoth(lambda ign: self.validateTo(user))
            return d
Ejemplo n.º 3
0
 def exists(self, user, memo=None):
     """Check for existence of user in the domain
     """
     if self.userDirectory(user.dest.local) is not None:
         return lambda: self.startMessage(user)
     try:
         a = self.alias[user.dest.local]
     except:
         raise smtp.SMTPBadRcpt(user)
     else:
         aliases = a.resolve(self.alias, memo)
         if aliases:
             return lambda: aliases
         log.err("Bad alias configuration: " + str(user))
         raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 4
0
 def validateTo(self, user):
     # Accept recipients @localhost.
     if user.dest.domain == "localhost":
         return lambda: MaildirMessage(self._getAddressDir(str(user.dest)))
     else:
         log.msg("Received email for invalid recipient %s" % user)
         raise smtp.SMTPBadRcpt(user)
 def validateTo(self, user):
     # Accept recipients @localhost.
     if user.dest.domain == "localhost":
         return StdoutMessage
     else:
         log.msg("Received email for invalid recipient %s" % (user), )
         raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 6
0
 def validateFrom(self, helo, origin):
     #valida que el dominio solo sea el del server de quien envia el mensaje
     if origin.domain in domain_aux:
         return origin
     else:
         log.msg("Invalid domain %s" % origin.domain)
         raise smtp.SMTPBadRcpt(origin.domain)
Ejemplo n.º 7
0
 def validateTo(self, user):
     # Only messages directed to configured users are accepted
     logging.info("validating to %s", user)
     if self.db.validUser(user.dest):
         logging.info("ok")
         return lambda: ImmudbMessage(self.db, user.dest)
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 8
0
    def validateTo(self, user):
        if '-' in user.dest.local:
            ml_id, recipient_id = user.dest.local.split('-', 1)

            return lambda: ReturnPathMessage(ml_id, recipient_id)
        logging.getLogger('smtpd').warn(
            "Recipient '%s' refused: badly formated.", user)
        raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 9
0
 def validateTo(self, user):
     # Only messages directed to mailhooks.com are accepted.
     callbacks = self.factory.callbacks
     if user.dest.domain in callbacks.keys():
         return lambda: Message(callbacks[user.dest.domain])
     elif '*' in callbacks.keys():
         return lambda: Message(callbacks['*'])
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 10
0
        def not_found(failure):
            failure.trap(KeyNotFound)

            # if key was not found, check config to see if will send anyway
            if self._encrypted_only:
                emit(catalog.SMTP_RECIPIENT_REJECTED, user.dest.addrstr)
                raise smtp.SMTPBadRcpt(user.dest.addrstr)
            log.msg("Warning: will send an unencrypted message (because "
                    "encrypted_only' is set to False).")
            emit(catalog.SMTP_RECIPIENT_ACCEPTED_UNENCRYPTED,
                 user.dest.addrstr)
Ejemplo n.º 11
0
    def exists(self, user):
        """
        Raise an exception to indicate that the user does not exist in this
        domain.

        @type user: L{User}
        @param user: A user.

        @raise SMTPBadRcpt: When the given user does not exist in this domain.
        """
        raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 12
0
    def exists(self, user):
        """Check whether we will relay

        Call overridable willRelay method
        """
        if self.willRelay(user.dest, user.protocol):
            # The most cursor form of verification of the addresses
            orig = filter(None, str(user.orig).split('@', 1))
            dest = filter(None, str(user.dest).split('@', 1))
            if len(orig) == 2 and len(dest) == 2:
                return lambda: self.startMessage(user)
        raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 13
0
    def validateTo(self, user):
        """Validate the SMTP ``RCPT TO:`` address for the incoming connection.

        The local username and domain name to which this SMTP message is
        addressed, after being stripped of any ``'+'`` aliases, **must** be
        identical to those in the email address set our
        ``EMAIL_SMTP_FROM_ADDR`` configuration file option.

        :type user: :api:`twisted.mail.smtp.User`
        :param user: Information about the user this SMTP message was
            addressed to.
        :raises: A :api:`twisted.mail.smtp.SMTPBadRcpt` if any of the above
            conditions weren't met.
        :rtype: callable
        :returns: A parameterless function which returns an instance of
            :class:`SMTPMessage`.
        """
        logging.debug("Validating SMTP 'RCPT TO:' email address...")

        recipient = user.dest
        ourAddress = smtp.Address(self.context.smtpFromAddr)

        if not ((ourAddress.domain in recipient.domain) or
                (recipient.domain == b"bridgedb")):
            logging.debug(("Not our domain (%s) or subdomain, skipping"
                           " SMTP 'RCPT TO' address: %s")
                          % (ourAddress.domain.decode('utf-8'), str(recipient)))
            raise smtp.SMTPBadRcpt(str(recipient))
        # The recipient's username should at least start with ours,
        # but it still might be a '+' address.
        if not recipient.local.startswith(ourAddress.local):
            logging.debug(("Username doesn't begin with ours, skipping"
                           " SMTP 'RCPT TO' address: %s") % str(recipient))
            raise smtp.SMTPBadRcpt(str(recipient))
        # Ignore everything after the first '+', if there is one.
        beforePlus = recipient.local.split(b'+', 1)[0]
        if beforePlus != ourAddress.local:
            raise smtp.SMTPBadRcpt(str(recipient))

        return lambda: SMTPMessage(self.context, self.fromCanonicalSMTP)
Ejemplo n.º 14
0
    def validateTo(self, user):
        # Only messages directed to the "console" user are accepted.
        try:
            token = Canarytoken(value=user.dest.local)
            self.canarydrop = Canarydrop(**get_canarydrop(
                canarytoken=token.value()))
            return lambda: CanaryMessage(esmtp=self)
        except (NoCanarytokenPresent, NoCanarytokenFound):
            log.warn('No token in recipient address: {address}'\
                     .format(address=user.dest.local))
        except Exception as e:
            log.error(e)

        raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 15
0
 def verify_if_can_encrypt_for_recipient(can_encrypt):
     if can_encrypt:
         self.log.debug('Accepting mail for %s...' % user.dest.addrstr)
         emit_async(catalog.SMTP_RECIPIENT_ACCEPTED_ENCRYPTED,
                    self._userid, user.dest.addrstr)
     elif self._encrypted_only:
         emit_async(catalog.SMTP_RECIPIENT_REJECTED, self._userid,
                    user.dest.addrstr)
         raise smtp.SMTPBadRcpt(user.dest.addrstr)
     else:
         self.log.warn(
             'Warning: will send an unencrypted message (because '
             '"encrypted_only" is set to False).')
         emit_async(catalog.SMTP_RECIPIENT_ACCEPTED_UNENCRYPTED,
                    self._userid, user.dest.addrstr)
Ejemplo n.º 16
0
 def localValidateTo(self, user):
     """
     Determine whether the given user exists locally.  If they do not,
     reject the address as invalid.  If they do, return a delivery object
     appropriate for that user.  Currently this delivery object is the same
     as the remote delivery object, but at some point it may make sense to
     optimize this codepath and skip the network for local<->local delivery.
     """
     siteStore = self.avatar.store.parent
     loginSystem = siteStore.findUnique(userbase.LoginSystem)
     account = loginSystem.accountByAddress(
         user.dest.local.decode('ascii'), user.dest.domain.decode('ascii'))
     if account is None:
         return defer.fail(smtp.SMTPBadRcpt(user))
     else:
         # XXX TODO - We could skip the network here.
         return self.remoteValidateTo(user)
Ejemplo n.º 17
0
    def validateTo(self, user):
        """
        Validate the address of C{user}, a recipient of the message.

        This method is called once for each recipient and validates the
        C{user}'s address against the RFC 2822 definition. If the
        configuration option ENCRYPTED_ONLY_KEY is True, it also asserts the
        existence of the user's key.

        In the end, it returns an encrypted message object that is able to
        send itself to the C{user}'s address.

        :param user: The user whose address we wish to validate.
        :type: twisted.mail.smtp.User

        @return: A Deferred which becomes, or a callable which takes no
            arguments and returns an object implementing IMessage. This will
            be called and the returned object used to deliver the message when
            it arrives.
        @rtype: no-argument callable

        @raise SMTPBadRcpt: Raised if messages to the address are not to be
            accepted.
        """
        # try to find recipient's public key
        try:
            address = validate_address(user.dest.addrstr)
            # verify if recipient key is available in keyring
            self._km.get_key(address, OpenPGPKey)  # might raise KeyNotFound
            log.msg("Accepting mail for %s..." % user.dest.addrstr)
            signal(proto.SMTP_RECIPIENT_ACCEPTED_ENCRYPTED, user.dest.addrstr)
        except KeyNotFound:
            # if key was not found, check config to see if will send anyway.
            if self._encrypted_only:
                signal(proto.SMTP_RECIPIENT_REJECTED, user.dest.addrstr)
                raise smtp.SMTPBadRcpt(user.dest.addrstr)
            log.msg("Warning: will send an unencrypted message (because "
                    "encrypted_only' is set to False).")
            signal(proto.SMTP_RECIPIENT_ACCEPTED_UNENCRYPTED,
                   user.dest.addrstr)
        return lambda: EncryptedMessage(self._origin, user, self._km, self.
                                        _host, self._port, self._cert, self.
                                        _key)
Ejemplo n.º 18
0
def validate_address(address):
    """
    Validate C{address} as defined in RFC 2822.

    :param address: The address to be validated.
    :type address: str

    @return: A valid address.
    @rtype: str

    @raise smtp.SMTPBadRcpt: Raised if C{address} is invalid.
    """
    leap_assert_type(address, str)
    # in the following, the address is parsed as described in RFC 2822 and
    # ('', '') is returned if the parse fails.
    _, address = parseaddr(address)
    if address == '':
        raise smtp.SMTPBadRcpt(address)
    return address
Ejemplo n.º 19
0
    def exists(self, user):
        """
        Check whether mail can be relayed to a user.

        @type user: L{User}
        @param user: A user.

        @rtype: no-argument callable which returns L{IMessage <smtp.IMessage>}
            provider
        @return: A function which takes no arguments and returns a message
            receiver for the user.

        @raise SMTPBadRcpt: When mail cannot be relayed to the user.
        """
        if self.willRelay(user.dest, user.protocol):
            # The most cursor form of verification of the addresses
            orig = filter(None, str(user.orig).split('@', 1))
            dest = filter(None, str(user.dest).split('@', 1))
            if len(orig) == 2 and len(dest) == 2:
                return lambda: self.startMessage(user)
        raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 20
0
	def validateTo(self, user):
		# Only messages directed to either a valid forward or a mailinglist are
		# accepted
		ip = user.protocol.transport.getPeer()[1]
		addr = None
		try:
			addr = MailingList.objects.get(listaddress__iexact='%s' % user.dest)
			print >>sys.stderr, 'list addr: %s' % (addr)
			return lambda: ListMessage(user, addr)
		except MailingList.DoesNotExist:
			pass
		try:
			addr = Forward.objects.get(forward__iexact='%s' % user.dest )
			print >>sys.stderr, 'forward addr: %s' % (addr)
			return lambda: ForwardMessage(user, addr)
		except Forward.DoesNotExist:
			pass
		if ip in self.local_ips:
			return lambda: LocalMessage(user)
		 
		raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 21
0
 def validateTo(self, user):
     # Only messages directed to the "console" user are accepted.
     if (user.dest.local == "benb" and user.dest.domain == 'benb.org'):
         return lambda: ConsoleMessage()
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 22
0
 def notLoggedIn(err):
     err.trap(userbase.NoSuchUser)
     return defer.fail(smtp.SMTPBadRcpt(user))
Ejemplo n.º 23
0
 def validateTo(self, user):
     # Only accept mail for our domains -- if set. Otherwise, anything goes.
     if not MY_DOMAINS or user.dest.domain in MY_DOMAINS:
         return lambda: TempMailMessage(user)
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 24
0
 def validateTo(self, user):
     if not str(user.dest).lower() == self.googleSearchAddress:
         raise smtp.SMTPBadRcpt(user.dest)
     else:
         return lambda: ReplyFromGoogle(self.googleSearchAddress, self.
                                        upstreamServer)
Ejemplo n.º 25
0
Archivo: smtp.py Proyecto: shoosen/ibid
 def validateTo(self, user):
     if str(user) == self.factory.address or str(user) in self.factory.accept:
         return lambda: Message(self.factory.name)
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 26
0
 def exists(self, user):
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 27
0
 def validateTo(self, user):
     if not user.dest.domain in self.validDomains:
         raise smtp.SMTPBadRcpt(user)
     print "Accepting mail for %s..." % user.dest
     return lambda: MaildirMessageWriter(self._getAddressDir(str(user.dest))
                                         )
Ejemplo n.º 28
0
 def validateTo(self, user):
     # Only messages directed to the "console" user are accepted.
     if user.dest.local == "console":
         return lambda: CanaryMessage()
     raise smtp.SMTPBadRcpt(user)
Ejemplo n.º 29
0
 def exists(self, user):
     if user.dest.local in self.messages:
         return defer.succeed(lambda: self.startMessage(user))
     return defer.fail(smtp.SMTPBadRcpt(user))
Ejemplo n.º 30
0
 def validateTo(self, user):
     # Only messages directed to the "console" user are accepted.
     if user.dest.local == "blog":
         return lambda: BlogMessage(self.store)
     raise smtp.SMTPBadRcpt(user)