Commits

Zhang Huangbin committed 3084cc0

Code cleanup.

  • Participants
  • Parent commits e32d93b

Comments (0)

Files changed (12)

 iRedAPD-1.3.9:
     * Plugin renamed:
-      block_amavisd_blacklisted_senders -> amavisd_block_blacklisted_senders
+      block_amavisd_blacklisted_senders -> ldap_amavisd_block_blacklisted_senders
     * New plugin for SQL backends: sql_user_restrictions.
       Note, it requires 4 new columns on table `vmail.mailbox`, please refer
       to iRedMail upgrade tutorials.
     def __init__(self,
                  conn,
                  plugins=[],
-                 plugins_for_sender=[],
-                 plugins_for_recipient=[],
-                 plugins_for_misc=[],
                  sender_search_attrlist=None,
                  recipient_search_attrlist=None,
                 ):
         self.set_terminator('\n')
 
         self.plugins = plugins
-        self.plugins_for_sender = plugins_for_sender
-        self.plugins_for_recipient = plugins_for_recipient
-        self.plugins_for_misc = plugins_for_misc
         self.sender_search_attrlist = sender_search_attrlist
         self.recipient_search_attrlist = recipient_search_attrlist
 
                 result = modeler.handle_data(
                     smtp_session_data=self.smtp_session_data,
                     plugins=self.plugins,
-                    plugins_for_sender=self.plugins_for_sender,
-                    plugins_for_recipient=self.plugins_for_recipient,
-                    plugins_for_misc=self.plugins_for_misc,
                     sender_search_attrlist=self.sender_search_attrlist,
                     recipient_search_attrlist=self.recipient_search_attrlist,
                 )
             except Exception, e:
                 logging.error('Error while loading plugin (%s): %s' % (plugin, str(e)))
 
-        self.plugins_for_sender = [plugin
-                                   for plugin in self.loaded_plugins
-                                   if plugin.REQUIRE_LOCAL_SENDER]
-
-        self.plugins_for_recipient = [plugin
-                                   for plugin in self.loaded_plugins
-                                   if plugin.REQUIRE_LOCAL_RECIPIENT]
-
-        self.plugins_for_misc = [plugin for plugin in self.loaded_plugins
-                                 if plugin not in self.plugins_for_sender
-                                 and plugin not in self.plugins_for_recipient]
-
         self.sender_search_attrlist = ['objectClass']
-        for plugin in self.plugins_for_sender:
+        self.recipient_search_attrlist = ['objectClass']
+        for plugin in self.loaded_plugins:
             self.sender_search_attrlist += plugin.SENDER_SEARCH_ATTRLIST
-
-        self.recipient_search_attrlist = ['objectClass']
-        for plugin in self.plugins_for_recipient:
             self.recipient_search_attrlist += plugin.RECIPIENT_SEARCH_ATTRLIST
 
     def handle_accept(self):
         PolicyChannel(
             conn,
             plugins=self.loaded_plugins,
-            plugins_for_sender=self.plugins_for_sender,
-            plugins_for_recipient=self.plugins_for_recipient,
-            plugins_for_misc=self.plugins_for_misc,
             sender_search_attrlist=self.sender_search_attrlist,
             recipient_search_attrlist=self.recipient_search_attrlist,
         )
             )
 
     # Initialize policy daemon.
-    socket_daemon = DaemonSocket((settings.listen_address, settings.listen_port))
+    DaemonSocket((settings.listen_address, settings.listen_port))
 
     # Run this program as daemon.
     if settings.run_as_daemon:

libs/ldaplib/conn_utils.py

-# Author: Zhang Huangbin <zhb _at_ iredmail.org>
-
-import logging
-import ldap
-import settings
-from libs import SMTP_ACTIONS
-
-
-def get_account_ldif(conn, account, attrlist=None):
-    logging.debug('[+] Getting LDIF data of account: %s' % account)
-
-    ldap_filter = '(&(|(mail=%s)(shadowAddress=%s))(|(objectClass=mailUser)(objectClass=mailList)(objectClass=mailAlias)))' % (account, account)
-
-    logging.debug('search filter: %s' % ldap_filter)
-    logging.debug('search attributes: %s' % str(attrlist))
-    if not isinstance(attrlist, list):
-        # Attribute list must be None or non-empty list
-        attrlist = None
-
-    try:
-        result = conn.search_s(settings.ldap_basedn,
-                               ldap.SCOPE_SUBTREE,
-                               ldap_filter,
-                               attrlist)
-
-        if len(result) == 1:
-            logging.debug('result: %s' % str(result))
-            dn, entry = result[0]
-            return (dn, entry)
-        else:
-            logging.debug('Not a local account.')
-            return (None, None)
-    except Exception, e:
-        logging.debug('!!! ERROR !!! result: %s' % str(e))
-        return (None, None)
-
-
-def get_allowed_senders_of_mail_list(conn,
-                                     base_dn,
-                                     dn_of_mail_list,
-                                     sender,
-                                     recipient,
-                                     policy):
-    """return list of allowed senders"""
-
-    logging.debug('[+] Getting allowed senders of mail list: %s' % recipient)
-    recipient_domain = recipient.split('@', 1)[-1]
-
-    # Set base dn as domain dn.
-    domaindn = 'domainName=' + recipient_domain + ',' + base_dn
-
-    # Default search scope. 2==ldap.SCOPE_SUBTREE
-    searchScope = 2
-
-    # Set search filter, attributes based on policy.
-    # Override base dn, scope if necessary.
-    if policy in ['membersonly', 'members']:
-        basedn = domaindn
-        # Filter: get mail list members.
-        searchFilter = "(&(|(objectclass=mailUser)(objectClass=mailExternalUser))(accountStatus=active)(memberOfGroup=%s))" % (recipient, )
-
-        # Get both mail and shadowAddress.
-        searchAttrs = ['mail', 'shadowAddress', ]
-
-    elif policy in ['allowedonly', 'moderatorsonly', 'moderators']:
-        # Get mail list moderators.
-        basedn = dn_of_mail_list
-        searchScope = 0     # Use ldap.SCOPE_BASE to improve performance.
-        searchFilter = "(&(objectclass=mailList)(mail=%s))" % (recipient, )
-        searchAttrs = ['listAllowedUser']
-
-    else:
-        basedn = domaindn
-        # Policy: policy==membersAndModeratorsOnly or not set.
-        # Filter used to get both members and moderators.
-        searchFilter = "(|(&(|(objectClass=mailUser)(objectClass=mailExternalUser))(memberOfGroup=%s))(&(objectclass=mailList)(mail=%s)))" % (recipient, recipient, )
-        searchAttrs = ['mail', 'shadowAddress', 'listAllowedUser', ]
-
-    logging.debug('base dn: %s' % basedn)
-    logging.debug('search scope: %s' % searchScope)
-    logging.debug('search filter: %s' % searchFilter)
-    logging.debug('search attributes: %s' % ', '.join(searchAttrs))
-
-    try:
-        result = conn.search_s(basedn, searchScope, searchFilter, searchAttrs)
-        userList = []
-        for obj in result:
-            for k in searchAttrs:
-                if k in obj[1].keys():
-                    # Example of result data:
-                    # [('dn', {'listAllowedUser': ['user@domain.ltd']})]
-                    userList += obj[1][k]
-
-        # Exclude mail list itself.
-        if recipient in userList:
-            userList.remove(recipient)
-
-        logging.debug('result: %s' % str(userList))
-
-        # Query once more to get 'shadowAddress'.
-        if len(userList) > 0 and policy in ['allowedonly',
-                                            'moderatorsonly',
-                                            'moderators']:
-            logging.debug('Addition query to get user aliases...')
-
-            basedn = 'ou=Users,' + domaindn
-            searchFilter = '(&(objectClass=mailUser)(enabledService=shadowaddress)(|'
-            for i in userList:
-                searchFilter += '(mail=%s)' % i
-            searchFilter += '))'
-
-            searchAttrs = ['shadowAddress', ]
-
-            logging.debug('base dn: %s' % basedn)
-            logging.debug('search scope: 2 (ldap.SCOPE_SUBTREE)')
-            logging.debug('search filter: %s' % searchFilter)
-            logging.debug('search attributes: %s' % ', '.join(searchAttrs))
-
-            try:
-                resultOfShadowAddresses = conn.search_s(
-                    'ou=Users,' + domaindn,
-                    2,  # ldap.SCOPE_SUBTREE
-                    searchFilter,
-                    ['mail', 'shadowAddress', ],
-                )
-
-                for obj in resultOfShadowAddresses:
-                    for k in searchAttrs:
-                        if k in obj[1].keys():
-                            # Example of result data:
-                            # [('dn', {'listAllowedUser': ['user@domain.ltd']})]
-                            userList += obj[1][k]
-                        else:
-                            pass
-
-                logging.debug('final result: %s' % str(userList))
-
-            except Exception, e:
-                logging.debug('Error: %s' % str(e))
-
-        return [u.lower() for u in userList]
-    except Exception, e:
-        logging.debug('Error: %s' % str(e))
-        return []
-
-
-def apply_plugin(plugin, **kwargs):
-    action = SMTP_ACTIONS['default']
-
-    logging.debug('--> Apply plugin: %s' % plugin.__name__)
-    try:
-        action = plugin.restriction(**kwargs)
-        logging.debug('<-- Result: %s' % action)
-    except Exception, e:
-        logging.debug('<!> Error: %s' % str(e))
-
-    return action

libs/ldaplib/modeler.py

 import logging
 import settings
 from libs import SMTP_ACTIONS
-from libs.ldaplib import conn_utils
+from libs.ldaplib import utils
 
 
 class Modeler:
     def handle_data(self,
                     smtp_session_data,
                     plugins=[],
-                    plugins_for_sender=[],
-                    plugins_for_recipient=[],
-                    plugins_for_misc=[],
                     sender_search_attrlist=[],
                     recipient_search_attrlist=[],
                    ):
         if not plugins:
             return 'DUNNO'
 
-        # Check whether we should get sender/recipient LDIF data first
-        get_sender_ldif = False
-        get_recipient_ldif = False
-        if plugins_for_sender:
-            get_sender_ldif = True
-
-        if plugins_for_recipient:
-            get_recipient_ldif = True
-
         # Get account dn and LDIF data.
         plugin_kwargs = {'smtp_session_data': smtp_session_data,
                          'conn': self.conn,
                          'recipient_ldif': None,
                         }
 
-        if get_sender_ldif:
-            senderDn, senderLdif = conn_utils.get_account_ldif(
-                conn=self.conn,
-                account=smtp_session_data['sender'],
-                attrlist=sender_search_attrlist,
-            )
-            plugin_kwargs['sender_dn'] = senderDn
-            plugin_kwargs['sender_ldif'] = senderLdif
+        for plugin in plugins:
+            # Get LDIF data of sender if required
+            if plugin.REQUIRE_LOCAL_SENDER \
+               and plugin_kwargs['sender_dn'] is None:
+                sender_dn, sender_ldif = utils.get_account_ldif(
+                    conn=self.conn,
+                    account=smtp_session_data['sender'],
+                    attrlist=sender_search_attrlist,
+                )
+                plugin_kwargs['sender_dn'] = sender_dn
+                plugin_kwargs['sender_ldif'] = sender_ldif
 
-        if get_recipient_ldif:
-            recipientDn, recipientLdif = conn_utils.get_account_ldif(
-                conn=self.conn,
-                account=smtp_session_data['recipient'],
-                attrlist=recipient_search_attrlist,
-            )
-            plugin_kwargs['recipient_dn'] = recipientDn
-            plugin_kwargs['recipient_ldif'] = recipientLdif
+            # Get LDIF data of recipient if required
+            if plugin.REQUIRE_LOCAL_RECIPIENT \
+               and plugin_kwargs['recipient_dn'] is None:
+                recipient_dn, recipient_ldif = utils.get_account_ldif(
+                    conn=self.conn,
+                    account=smtp_session_data['recipient'],
+                    attrlist=recipient_search_attrlist,
+                )
+                plugin_kwargs['recipient_dn'] = recipient_dn
+                plugin_kwargs['recipient_ldif'] = recipient_ldif
 
-        for plugin in plugins:
-            action = conn_utils.apply_plugin(plugin, **plugin_kwargs)
+            # Apply plugin
+            action = utils.apply_plugin(plugin, **plugin_kwargs)
             if not action.startswith('DUNNO'):
                 return action
 

libs/ldaplib/utils.py

+# Author: Zhang Huangbin <zhb _at_ iredmail.org>
+
+import logging
+import ldap
+import settings
+from libs import SMTP_ACTIONS
+
+
+def get_account_ldif(conn, account, attrlist=None):
+    logging.debug('[+] Getting LDIF data of account: %s' % account)
+
+    ldap_filter = '(&(|(mail=%(account)s)(shadowAddress=%(account)s))(|(objectClass=mailUser)(objectClass=mailList)(objectClass=mailAlias)))' % {'account': account}
+
+    logging.debug('search filter: %s' % ldap_filter)
+    logging.debug('search attributes: %s' % str(attrlist))
+    if not isinstance(attrlist, list):
+        # Attribute list must be None or non-empty list
+        attrlist = None
+
+    try:
+        result = conn.search_s(settings.ldap_basedn,
+                               ldap.SCOPE_SUBTREE,
+                               ldap_filter,
+                               attrlist)
+
+        if len(result) == 1:
+            logging.debug('result: %s' % str(result))
+            dn, entry = result[0]
+            return (dn, entry)
+        else:
+            logging.debug('Not a local account.')
+            return (None, None)
+    except Exception, e:
+        logging.debug('<!> ERROR, result: %s' % str(e))
+        return (None, None)
+
+
+def get_allowed_senders_of_mail_list(conn,
+                                     base_dn,
+                                     dn_of_mail_list,
+                                     sender,
+                                     recipient,
+                                     policy):
+    """return list of allowed senders"""
+
+    logging.debug('[+] Getting allowed senders of mail list: %s' % recipient)
+    recipient_domain = recipient.split('@', 1)[-1]
+
+    # Set base dn as domain dn.
+    domaindn = 'domainName=' + recipient_domain + ',' + base_dn
+
+    # Default search scope. 2==ldap.SCOPE_SUBTREE
+    searchScope = 2
+
+    # Set search filter, attributes based on policy.
+    # Override base dn, scope if necessary.
+    if policy in ['membersonly', 'members']:
+        basedn = domaindn
+        # Filter: get mail list members.
+        searchFilter = "(&(|(objectclass=mailUser)(objectClass=mailExternalUser))(accountStatus=active)(memberOfGroup=%s))" % (recipient, )
+
+        # Get both mail and shadowAddress.
+        searchAttrs = ['mail', 'shadowAddress', ]
+
+    elif policy in ['allowedonly', 'moderatorsonly', 'moderators']:
+        # Get mail list moderators.
+        basedn = dn_of_mail_list
+        searchScope = 0     # Use ldap.SCOPE_BASE to improve performance.
+        searchFilter = "(&(objectclass=mailList)(mail=%s))" % (recipient, )
+        searchAttrs = ['listAllowedUser']
+
+    else:
+        basedn = domaindn
+        # Policy: policy==membersAndModeratorsOnly or not set.
+        # Filter used to get both members and moderators.
+        searchFilter = "(|(&(|(objectClass=mailUser)(objectClass=mailExternalUser))(memberOfGroup=%s))(&(objectclass=mailList)(mail=%s)))" % (recipient, recipient, )
+        searchAttrs = ['mail', 'shadowAddress', 'listAllowedUser', ]
+
+    logging.debug('base dn: %s' % basedn)
+    logging.debug('search scope: %s' % searchScope)
+    logging.debug('search filter: %s' % searchFilter)
+    logging.debug('search attributes: %s' % ', '.join(searchAttrs))
+
+    try:
+        result = conn.search_s(basedn, searchScope, searchFilter, searchAttrs)
+        userList = []
+        for obj in result:
+            for k in searchAttrs:
+                if k in obj[1].keys():
+                    # Example of result data:
+                    # [('dn', {'listAllowedUser': ['user@domain.ltd']})]
+                    userList += obj[1][k]
+
+        # Exclude mail list itself.
+        if recipient in userList:
+            userList.remove(recipient)
+
+        logging.debug('result: %s' % str(userList))
+
+        # Query once more to get 'shadowAddress'.
+        if len(userList) > 0 and policy in ['allowedonly',
+                                            'moderatorsonly',
+                                            'moderators']:
+            logging.debug('Addition query to get user aliases...')
+
+            basedn = 'ou=Users,' + domaindn
+            searchFilter = '(&(objectClass=mailUser)(enabledService=shadowaddress)(|'
+            for i in userList:
+                searchFilter += '(mail=%s)' % i
+            searchFilter += '))'
+
+            searchAttrs = ['shadowAddress', ]
+
+            logging.debug('base dn: %s' % basedn)
+            logging.debug('search scope: 2 (ldap.SCOPE_SUBTREE)')
+            logging.debug('search filter: %s' % searchFilter)
+            logging.debug('search attributes: %s' % ', '.join(searchAttrs))
+
+            try:
+                resultOfShadowAddresses = conn.search_s(
+                    'ou=Users,' + domaindn,
+                    2,  # ldap.SCOPE_SUBTREE
+                    searchFilter,
+                    ['mail', 'shadowAddress', ],
+                )
+
+                for obj in resultOfShadowAddresses:
+                    for k in searchAttrs:
+                        if k in obj[1].keys():
+                            # Example of result data:
+                            # [('dn', {'listAllowedUser': ['user@domain.ltd']})]
+                            userList += obj[1][k]
+                        else:
+                            pass
+
+                logging.debug('final result: %s' % str(userList))
+
+            except Exception, e:
+                logging.debug('Error: %s' % str(e))
+
+        return [u.lower() for u in userList]
+    except Exception, e:
+        logging.debug('Error: %s' % str(e))
+        return []
+
+
+def apply_plugin(plugin, **kwargs):
+    action = SMTP_ACTIONS['default']
+
+    logging.debug('--> Apply plugin: %s' % plugin.__name__)
+    try:
+        action = plugin.restriction(**kwargs)
+        logging.debug('<-- Result: %s' % action)
+    except Exception, e:
+        logging.debug('<!> Error: %s' % str(e))
+
+    return action

plugins/amavisd_block_blacklisted_senders.py

-# Author: Zhang Huangbin <zhb _at_ iredmail.org>
-
-# Priority: whitelist first, then blacklist.
-
-import logging
-from libs import SMTP_ACTIONS
-
-REQUIRE_LOCAL_SENDER = False
-REQUIRE_LOCAL_RECIPIENT = False
-SENDER_SEARCH_ATTRLIST = []
-RECIPIENT_SEARCH_ATTRLIST = ['amavisBlacklistSender', 'amavisWhitelistSender']
-
-
-def restriction(**kwargs):
-    smtp_session_data = kwargs['smtp_session_data']
-    recipient_ldif = kwargs['recipient_ldif']
-
-    if not 'amavisAccount' in recipient_ldif['objectClass']:
-        return 'DUNNO (Not a amavisdAccount object)'
-
-    sender = smtp_session_data.get('sender').lower()
-
-    # Get valid Amavisd sender, sender domain and sub-domain(s).
-    # - Sample user: user@sub2.sub1.com.cn
-    # - Valid Amavisd senders:
-    #   -> user@sub2.sub1.com.cn
-    #   -> @sub2.sub1.com.cn
-    #   -> @.sub2.sub1.com.cn
-    #   -> @.sub1.com.cn
-    #   -> @.com.cn
-    #   -> @.cn
-    splited_sender_domain = str(sender.split('@', 1)[-1]).split('.')
-
-    # Default senders (user@domain.ltd):
-    # ['@.', 'user@domain.ltd', @domain.ltd']
-    valid_amavisd_senders = set(['@.', sender, '@' + sender.split('@', 1)[-1], ])
-    for counter in range(len(splited_sender_domain)):
-        # Append domain and sub-domain.
-        valid_amavisd_senders.update(['@.' + '.'.join(splited_sender_domain)])
-        splited_sender_domain.pop(0)
-
-    # Get list of amavisBlacklistedSender.
-    blSenders = set([v.lower() for v in recipient_ldif.get('amavisBlacklistSender', [])])
-
-    # Get list of amavisWhitelistSender.
-    wlSenders = set([v.lower() for v in recipient_ldif.get('amavisWhitelistSender', [])])
-
-    logging.debug('Sender: %s' % sender)
-    logging.debug('Whitelisted senders: %s' % str(wlSenders))
-    logging.debug('Blacklisted senders: %s' % str(blSenders))
-
-    # Bypass whitelisted senders.
-    if len(valid_amavisd_senders & wlSenders) > 0:
-        return SMTP_ACTIONS['accept']
-
-    # Reject blacklisted senders.
-    if len(valid_amavisd_senders & blSenders) > 0:
-        return 'REJECT Blacklisted'
-
-    # Neither blacklisted nor whitelisted.
-    return 'DUNNO (No white/blacklist records found)'

plugins/ldap_amavisd_block_blacklisted_senders.py

+# Author: Zhang Huangbin <zhb _at_ iredmail.org>
+
+# Priority: whitelist first, then blacklist.
+
+import logging
+from libs import SMTP_ACTIONS
+
+REQUIRE_LOCAL_SENDER = False
+REQUIRE_LOCAL_RECIPIENT = False
+SENDER_SEARCH_ATTRLIST = []
+RECIPIENT_SEARCH_ATTRLIST = ['amavisBlacklistSender', 'amavisWhitelistSender']
+
+
+def restriction(**kwargs):
+    smtp_session_data = kwargs['smtp_session_data']
+    recipient_ldif = kwargs['recipient_ldif']
+
+    if not 'amavisAccount' in recipient_ldif['objectClass']:
+        return 'DUNNO (Not a amavisdAccount object)'
+
+    sender = smtp_session_data.get('sender').lower()
+
+    # Get valid Amavisd sender, sender domain and sub-domain(s).
+    # - Sample user: user@sub2.sub1.com.cn
+    # - Valid Amavisd senders:
+    #   -> user@sub2.sub1.com.cn
+    #   -> @sub2.sub1.com.cn
+    #   -> @.sub2.sub1.com.cn
+    #   -> @.sub1.com.cn
+    #   -> @.com.cn
+    #   -> @.cn
+    splited_sender_domain = str(sender.split('@', 1)[-1]).split('.')
+
+    # Default senders (user@domain.ltd):
+    # ['@.', 'user@domain.ltd', @domain.ltd']
+    valid_amavisd_senders = set(['@.', sender, '@' + sender.split('@', 1)[-1], ])
+    for counter in range(len(splited_sender_domain)):
+        # Append domain and sub-domain.
+        valid_amavisd_senders.update(['@.' + '.'.join(splited_sender_domain)])
+        splited_sender_domain.pop(0)
+
+    # Get list of amavisBlacklistedSender.
+    blSenders = set([v.lower() for v in recipient_ldif.get('amavisBlacklistSender', [])])
+
+    # Get list of amavisWhitelistSender.
+    wlSenders = set([v.lower() for v in recipient_ldif.get('amavisWhitelistSender', [])])
+
+    logging.debug('Sender: %s' % sender)
+    logging.debug('Whitelisted senders: %s' % str(wlSenders))
+    logging.debug('Blacklisted senders: %s' % str(blSenders))
+
+    # Bypass whitelisted senders.
+    if len(valid_amavisd_senders & wlSenders) > 0:
+        return SMTP_ACTIONS['accept']
+
+    # Reject blacklisted senders.
+    if len(valid_amavisd_senders & blSenders) > 0:
+        return 'REJECT Blacklisted'
+
+    # Neither blacklisted nor whitelisted.
+    return 'DUNNO (No white/blacklist records found)'

plugins/ldap_domain_wblist.py

 
 def restriction(**kwargs):
     conn = kwargs['conn']
-    base_dn = kwargs['baseDn']
+    base_dn = kwargs['base_dn']
     smtp_session_data = kwargs['smtp_session_data']
 
     sender = smtp_session_data['sender'].lower()

plugins/ldap_expired_password.py

 EXPIRED_DAYS = 90
 
 def restriction(**kwargs):
-    ldapSenderLdif = kwargs['senderLdif']
+    sender_ldif = kwargs['sender_ldif']
+
+    if not 'mailUser' in sender_ldif['objectClass']:
+        return 'DUNNO Not a mail user'
 
     # Check password last change days
-    last_changed_day = int(ldapSenderLdif.get('shadowLastChange', [0])[0])
+    last_changed_day = int(sender_ldif.get('shadowLastChange', [0])[0])
 
     # Convert today to shadowLastChange
     today = datetime.date.today()
     changed_days_of_today = (datetime.date(today.year, today.month, today.day) - datetime.date(1970, 1, 1)).days
 
     if (last_changed_day + EXPIRED_DAYS) < changed_days_of_today:
-        return 'REJECT Password expired, please change the password before sending email.'
+        return 'REJECT Password expired, please change your password before sending email.'
 
     return SMTP_ACTIONS['default']
 

plugins/ldap_maillist_access_policy.py

 
 import logging
 from libs import SMTP_ACTIONS, LDAP_ACCESS_POLICIES_OF_MAIL_LIST
-from libs.ldaplib import conn_utils
+from libs.ldaplib import utils
 
 REQUIRE_LOCAL_SENDER = False
 REQUIRE_LOCAL_RECIPIENT = True
                     'moderatorsonly', 'moderators',
                     'allowedonly', 'membersandmoderatorsonly']:
         # Handle other access policies: membersOnly, allowedOnly, membersAndModeratorsOnly.
-        allowedSenders = conn_utils.get_allowed_senders_of_mail_list(
+        allowedSenders = utils.get_allowed_senders_of_mail_list(
             conn=conn,
             base_dn=base_dn,
             dn_of_mail_list=recipient_dn,

plugins/ldap_recipient_restrictions.py

 RECIPIENT_SEARCH_ATTRLIST = []
 
 def restriction(**kwargs):
-    ldapSenderLdif = kwargs['senderLdif']
+    sender_ldif = kwargs['sender_ldif']
     smtp_session_data = kwargs['smtp_session_data']
 
     # Get recipient address.
-    smtpRecipient = smtp_session_data.get('recipient').lower()
-    splited_recipient_domain = str(smtpRecipient.split('@')[-1]).split('.')
+    recipient = smtp_session_data.get('recipient').lower()
+    splited_recipient_domain = str(recipient.split('@')[-1]).split('.')
 
     # Get correct domain name and sub-domain name.
     # Sample recipient domain: sub2.sub1.com.cn
     #   -> .sub1.com.cn
     #   -> .com.cn
     #   -> .cn
-    recipients = ['@.', smtpRecipient, '@' + smtpRecipient.split('@')[-1],]
+    allowed_recipients = ['@.', recipient, '@' + recipient.split('@')[-1],]
     for counter in range(len(splited_recipient_domain)):
         # Append domain and sub-domain.
-        recipients += ['@.' + '.'.join(splited_recipient_domain)]
+        allowed_recipients += ['@.' + '.'.join(splited_recipient_domain)]
         splited_recipient_domain.pop(0)
 
     # Get value of mailBlacklistedRecipient, mailWhitelistRecipient.
-    blacklisted_rcpts = [v.lower() for v in ldapSenderLdif.get('mailBlacklistRecipient', [])]
-    whitelisted_rcpts = [v.lower() for v in ldapSenderLdif.get('mailWhitelistRecipient', [])]
+    blacklisted_rcpts = [v.lower() for v in sender_ldif.get('mailBlacklistRecipient', [])]
+    whitelisted_rcpts = [v.lower() for v in sender_ldif.get('mailWhitelistRecipient', [])]
 
     # Bypass whitelisted recipients if has intersection set.
-    if len(set(recipients) & set(whitelisted_rcpts)) > 0:
+    if len(set(allowed_recipients) & set(whitelisted_rcpts)) > 0:
         return 'DUNNO (Whitelisted)'
 
     # Reject blacklisted recipients if has intersection set.
-    if len(set(recipients) & set(blacklisted_rcpts)) > 0 \
+    if len(set(allowed_recipients) & set(blacklisted_rcpts)) > 0 \
        or '@.' in blacklisted_rcpts:
         return 'REJECT Permission denied'
 

settings.py.sample

 # Enabled plugins.
 #   - Plugin name is file name which placed under 'plugins/' directory.
 #   - Plugin names MUST be seperated by comma.
-plugins = ['ldap_maillist_access_policy', 'amavisd_block_blacklisted_senders']
+plugins = ['ldap_maillist_access_policy', 'ldap_amavisd_block_blacklisted_senders']
 
 #
 # For ldap backend.