![]() Server : Apache/2.4.62 (Unix) OpenSSL/1.0.2k-fips System : Linux server1.richineiserver.com 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64 User : fdshops ( 1003) PHP Version : 8.2.21 Disable Function : NONE Directory : /usr/libexec/postfix/ |
#!/usr/bin/python # -*- coding: utf-8 -*- # # Check SPF results and provide recommended action back to Postfix. # # Tumgreyspf source # Copyright © 2004-2005, Sean Reifschneider, tummy.com, ltd. # <jafo@tummy.com> # # pypolicyd-spf # Copyright © 2007-15, Scott Kitterman <scott@kitterman.com> ''' Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' __version__ = "1.3.2: August 12, 2015" testing = True import syslog import os import sys import re import socket import spf maj, minor, micro = spf.__version__.split(':')[0].split('.') if int(micro) < 7: raise ImportError("At least pyspf 2.0.7 is required.") import policydspfsupp import ipaddr as ipaddress try: import authres except: pass # authres not needed in default configuration. syslog.openlog(os.path.basename(sys.argv[0]), syslog.LOG_PID, syslog.LOG_MAIL) policydspfsupp._setExceptHook() ############################################# def _cidrmatch(ip, netwrk): """Match connect IP against a CIDR network of other IP addresses.""" try: address = ipaddress.ip_address(ip) except AttributeError: address = ipaddress.IPAddress(ip) try: network = ipaddress.IPv4Network(netwrk) except ipaddress.AddressValueError: network = ipaddress.IPv6Network(netwrk) return network.__contains__(address) def _get_rdns_lookup(ip): try: address = ipaddress.ip_address(ip) except AttributeError: address = ipaddress.IPAddress(ip) if isinstance(address, ipaddress.IPv4Address): components = address.exploded.split('.') return '.'.join(components[::-1]) + '.in-addr.arpa' else: components = address.exploded.split(':') return '.'.join('.'.join(list(quad)) for quad in components)[::-1] + '.ip6.arpa' ############################################# def _get_resultcodes(configData, scope): # Parse config options for SPF results to correct Posftix actions actions = {'defer':[], 'reject':[], 'prepend':[]} local = {'local_helo': False, 'local_mfrom': False} unused_results = ['Pass', 'None', 'Neutral', 'Softfail', 'Fail', 'Temperror', 'Permerror'] helo_policy = '' mfrom_policy = '' reject_domain_list = [] sender = data.get('sender') helo = data.get('helo_name') if configData.get('Reject_Not_Pass_Domains'): reject_domains = (str(configData.get('Reject_Not_Pass_Domains'))) reject_domain_list = reject_domains.split(',') if "@" in sender: sender_domain = sender.split('@', 1)[1] else: sender_domain = '' if scope == 'helo': helo_policy = configData.get('HELO_reject') if spf.domainmatch(reject_domain_list, helo): helo_policy = 'SPF_Not_Pass' local['local_helo'] = True if helo_policy == 'SPF_Not_Pass': try: unused_results.remove('Fail') actions['reject'].append('Fail') unused_results.remove('Softfail') actions['reject'].append('Softfail') unused_results.remove('Neutral') actions['reject'].append('Neutral') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: HELO_reject') elif helo_policy == 'Softfail': try: unused_results.remove('Fail') actions['reject'].append('Fail') unused_results.remove('Softfail') actions['reject'].append('Softfail') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: HELO_reject') elif helo_policy == 'Fail' or helo_policy == 'Null': try: unused_results.remove('Fail') actions['reject'].append('Fail') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: HELO_reject') if scope == 'mfrom': mfrom_policy = configData.get('Mail_From_reject') if "@" in sender: sender_domain = sender.split('@', 1)[1] else: sender_domain = '' if spf.domainmatch(reject_domain_list, sender_domain): mfrom_policy = 'SPF_Not_Pass' local['local_mfrom'] = True if mfrom_policy == 'SPF_Not_Pass': try: unused_results.remove('Fail') actions['reject'].append('Fail') unused_results.remove('Softfail') actions['reject'].append('Softfail') unused_results.remove('Neutral') actions['reject'].append('Neutral') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: Mail_From_reject') elif mfrom_policy == 'Softfail': try: unused_results.remove('Fail') actions['reject'].append('Fail') unused_results.remove('Softfail') actions['reject'].append('Softfail') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: Mail_From_reject') elif mfrom_policy == 'Fail': try: unused_results.remove('Fail') actions['reject'].append('Fail') except: if debugLevel >= 2: syslog.syslog('Configuration File parsing error: Mail_From_reject') if (helo_policy == 'False' and scope == 'helo') or (mfrom_policy == 'False' and scope == 'mfrom'): for result in unused_results: actions['prepend'].append(result) return(actions, local) if configData.get('TempError_Defer') == 'True': actions['defer'].append('Temperror') unused_results.remove('Temperror') if configData.get('PermError_reject') == 'True': actions['reject'].append('Permerror') unused_results.remove('Permerror') for result in unused_results: actions['prepend'].append(result) return(actions, local) ############################################# def _spfbypass(data, check_type, configData): if configData.get(check_type): if configData.get('Prospective'): ip = configData.get('Prospective') else: ip = data.get('client_address') bypass_list = (str(configData.get(check_type))) bypass_list_list = bypass_list.split(',') try: spf.MAX_VOID_LOOKUPS = configData.get('Void_Limit') except AttributeError: # If pyspf is too old (prior to 2.0.9) there is no void lookup # to change, so we don't care. pass if check_type == 'skip_addresses' or check_type == 'Whitelist': for skip_network in bypass_list_list: try: if _cidrmatch(ip, skip_network): if check_type == 'skip_addresses': comment = 'SPF check N/A for local connections - ' else: comment = 'SPF skipped for whitelisted relay - ' if 'SPF' in configData.get('Header_Type'): Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s ' % ( data.get('client_address', '<UNKNOWN>'), data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'), )) elif 'AR' in configData.get('Header_Type'): try: Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'), results = [authres.NoneAuthenticationResult(comment = \ '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\ data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>')) )])) except TypeError as x: if str(x).startswith('sequence item 2'): syslog.syslog(syslog.LOG_ERR, 'Authserv_Id not set for authentication results header - invalid configuration.') raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.') if debugLevel >= 3: syslog.syslog(Header) return (True, Header) except ValueError as msg: Message = 'ERROR: {0} in {1} not IP network. Message: {2}. Aborting whitelist processing.'.format(skip_network, check_type, msg) if debugLevel: syslog.syslog(Message) return (False, 'None') return (False, 'None') elif check_type == 'Domain_Whitelist': for domain in bypass_list_list: res = spf.check2(ip, domain, domain, querytime=configData.get('Lookup_Time')) domain_res = [res[0], res[1]] domain_res[0] = domain_res[0].lower() domain_res[0] = domain_res[0].capitalize() if domain_res[0] == 'Pass': comment = 'SPF skipped for whitelisted relay domain - ' if 'SPF' in configData.get('Header_Type'): Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s ' % ( data.get('client_address', '<UNKNOWN>'), data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'), )) elif 'AR' in configData.get('Header_Type'): try: Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'), results = [authres.NoneAuthenticationResult(comment = \ '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\ data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>')) )])) except TypeError as x: if str(x).startswith('sequence item 2'): syslog.syslog(syslog.LOG_ERR, 'Authserv_Id not set for authentication results header - invalid configuration.') raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.') if debugLevel >= 3: syslog.syslog(Header) return (True, Header) return (False, 'None') elif check_type == 'Domain_Whitelist_PTR': if debugLevel >= 4: syslog.syslog ("PTR Domain Whitelist enabled.") try: # Try a reverse DNS lookup first and try and match against the domain list that way rDNSResults = spf.DNSLookup (_get_rdns_lookup(ip), 'ptr') if (len (rDNSResults) > 0): rDNSName = rDNSResults [0][1] else: # Reverse lookup didn't find any records, so don't continue with the check rDNSName = None except spf.TempError as e: # DNS timeout - continue with the base SPF check. rDNSName = None if (rDNSName is not None): for domain in bypass_list_list: if (rDNSName.endswith (domain)): comment = 'SPF skipped for PTR whitelisted relay domain - ' if 'SPF' in configData.get('Header_Type'): Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s ' % ( data.get('client_address', '<UNKNOWN>'), data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'), )) elif 'AR' in configData.get('Header_Type'): try: Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'), results = [authres.NoneAuthenticationResult(comment = \ '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\ data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>')) )])) except TypeError as x: if str(x).startswith('sequence item 2'): syslog.syslog(syslog.LOG_ERR, 'Authserv_Id not set for authentication results header - invalid configuration.') raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.') if debugLevel >= 3: syslog.syslog(Header) return (True, Header) return (False, 'None') ############################################# def _spfcheck(data, instance_dict, configData, peruser): #{{{1 debugLevel = configData.get('debugLevel', 1) if configData.get('Prospective'): ip = configData.get('Prospective') else: ip = data.get('client_address') if ip == None: if debugLevel >= 2: syslog.syslog('spfcheck: No client address, exiting') return(( None, None, instance_dict )) instance = data.get('instance') # The following if is only needed for testing. Postfix # will always provide instance. if not instance: import random instance = str(int(random.random()*100000)) # This is to prevent multiple headers being prepended # for multi-recipient mail. if instance in instance_dict: found_instance = instance_dict[instance] else: found_instance = [] # If this is not the first recipient for the message, we need to know if # there is a previous prepend to make sure we don't prepend more than once. if found_instance: if found_instance[6] != 'prepend': last_action = found_instance[3] else: last_action = found_instance[6] else: last_action = "" # start query spfResult = None spfReason = None '''Data structure for results is a list of: [0] SPF result [1] SPF reason [2] Identity (HELO/Mail From) [3] Action based on local policy [4] Header [5] Per user (stored data was based on per user policy) [6] last_action (need to know if we've prepended already)''' if debugLevel >= 4: syslog.syslog('Cached data for this instance: %s' % str(found_instance)) if not found_instance or found_instance[5] or peruser: # Do not check SPF for localhost addresses skip_check = _spfbypass(data, 'skip_addresses', configData) if skip_check[0]: skip_data = ["N/A", "Skip SPF checks on localhost", "N/A", "prepend", skip_check[1]] if last_action != 'prepend': skip_data.append(peruser) skip_data.append('prepend') if not found_instance or found_instance[5]: instance_dict[instance] = skip_data return (('prepend', skip_check[1], instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) # Whitelist designated IP addresses from SPF checks (e.g. secondary MX or # known forwarders. ip_whitelist = _spfbypass(data, 'Whitelist', configData) if ip_whitelist: if ip_whitelist[0]: skip_data = ["N/A", "Skip SPF checks for whitelisted IP addresses", "N/A", "prepend", skip_check[1]] if last_action != 'prepend': skip_data.append(peruser) skip_data.append('prepend') if not found_instance or found_instance[5]: instance_dict[instance] = skip_data if last_action != 'prepend': return (('prepend', ip_whitelist[1], instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) # Whitelist designated Domain's sending addresses from SPF checks (e.g. # known forwarders. if configData.get('Domain_Whitelist'): domain_whitelist = _spfbypass(data, 'Domain_Whitelist', configData) if domain_whitelist: if domain_whitelist[0]: skip_data = ["N/A", "Skip SPF checks for whitelisted domains", "N/A", "prepend", skip_check[1]] if last_action != 'prepend': skip_data.append(peruser) skip_data.append('prepend') if not found_instance or found_instance[5]: instance_dict[instance] = skip_data if last_action != 'prepend': return (('prepend', domain_whitelist[1], instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) # Whitelist designated Domain's sending addresses from SPF checks (e.g. # known forwarders, but based on PTR match if configData.get('Domain_Whitelist_PTR'): domain_whitelist = _spfbypass(data, 'Domain_Whitelist_PTR', configData) if domain_whitelist: if domain_whitelist[0]: skip_data = ["N/A", "Skip SPF checks for whitelisted hosts (by PTR)", "N/A", "prepend", skip_check[1]] if last_action != 'prepend': skip_data.append(peruser) skip_data.append('prepend') if not found_instance or found_instance[5]: instance_dict[instance] = skip_data if last_action != 'prepend': return (('prepend', domain_whitelist[1], instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) receiver=socket.gethostname() sender = data.get('sender') helo = data.get('helo_name') if not sender and not helo: if debugLevel >= 2: syslog.syslog('spfcheck: No sender or helo, exiting') return(( None, None, instance_dict )) Mail_From_pass_restriction = configData.get('Mail_From_pass_restriction') HELO_pass_restriction = configData.get('HELO_pass_restriction') helo_result = ['None',] # First do HELO check # if no helo name sent, use domain from sender for later use. if not helo: foo = sender.split('@', 1) if len(foo) < 2: helo = 'unknown' else: helo = foo[1] else: if configData.get('HELO_reject') != 'No_Check': helo_fake_sender = 'postmaster@' + helo res = spf.check2(ip, helo_fake_sender, helo, querytime=configData.get('Lookup_Time')) helo_result = [res[0], res[1]] helo_result.append('helo') helo_result[0] = helo_result[0].lower() helo_result[0] = helo_result[0].capitalize() helo_resultpolicy, local = _get_resultcodes(configData, 'helo') if debugLevel >= 2: syslog.syslog('spfcheck: pyspf result: "%s"' % str(helo_result)) if configData.get('HELO_reject') == 'Null' and sender: helo_result.append('dunno') else: for poss_actions in helo_resultpolicy: if helo_result[0] in helo_resultpolicy[poss_actions]: action = poss_actions helo_result.append(action) if local['local_helo']: helo_result[1] = 'Receiver policy for SPF ' + helo_result[0] if sender == '': header_sender = '<>' else: header_sender = sender if helo_result[0] == 'None': helo_result[1] = "no SPF record" spfDetail = ('identity=%s; client-ip=%s; helo=%s; envelope-from=%s; receiver=%s ' % (helo_result[2], ip, helo, header_sender, data.get('recipient', '<UNKNOWN>'))) if debugLevel >= 1: logdata = str(helo_result[0]) + "; " + spfDetail syslog.syslog(logdata) header = '' if debugLevel >= 3: headerdata = 'Header type: ' + str(configData.get('Header_Type')) + '; Authres ID (for AR): ' + str(configData.get('Authserv_Id')) syslog.syslog(headerdata) if 'SPF' in configData.get('Header_Type') and 'AR' in configData.get('Header_Type'): syslog.syslog(syslog.LOG_ERR, 'Header_Type includes both SPF and AR - invalid configuration.') raise SyntaxError('Header_Type includes both SPF and AR - invalid configuration.') if 'SPF' in configData.get('Header_Type'): header = 'Received-SPF: '+ helo_result[0] + ' (' + helo_result[1] +') ' + spfDetail elif 'AR' in configData.get('Header_Type'): if not configData.get('Authserv_Id'): raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.') header += str(authres.AuthenticationResultsHeader(authserv_id = str(configData.get('Authserv_Id')), results = [authres.SPFAuthenticationResult(result = helo_result[0], result_comment = helo_result[1], smtp_helo = helo, smtp_helo_comment = 'client-ip={0}; helo={1}; envelope-from={2}; receiver={3}'.format(ip, helo, header_sender, data.get('recipient', '<UNKNOWN>')))])) helo_result.append(header) helo_result.append(peruser) helo_result.append(helo_result[3]) if not found_instance or found_instance[5]: if found_instance and found_instance[6] == "prepend": helo_result[6] = "prepend" instance_dict[instance] = helo_result if HELO_pass_restriction and helo_result[0] == 'Pass': restrict_name = HELO_pass_restriction # Only act on the HELO result if it is authoritative. if helo_result[3] == 'reject': if configData.get('No_Mail'): # If only rejecting on "v=spf1 -all", we need to know now try: q = spf.query(i='127.0.0.1', s='localhost', h='unknown', receiver=socket.gethostname()) record = q.dns_spf(helo) except: # If the query errored some how, we know it's not "v=spf1 -all" record = '' if record != "v=spf1 -all": if last_action != 'prepend': # Prepend instead of reject if it's not a no mail record helo_result[3] = 'prepend' else: return(( 'dunno', 'Header already pre-pended', instance_dict )) if helo_result[3] == 'reject': # It may not anymore helo_result[4] = "Message rejected due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" \ + helo + ";ip=" + ip + ";r=" + data.get('recipient') return(( 'reject', helo_result[4], instance_dict )) if helo_result[3] == 'defer': helo_result[4] = "Message deferred due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" + helo + \ ";ip=" + ip + ";r=" + data.get('recipient') return(( 'defer', helo_result[4], instance_dict )) # Second do Mail From Check if sender == '': if configData.get('HELO_reject') != 'No_Check': if helo_result[3] == 'reject': if configData.get('No_Mail'): # If only rejecting on "v=spf1 -all", we need to know now try: q = spf.query(i='127.0.0.1', s='localhost', h='unknown', receiver=socket.gethostname()) record = q.dns_spf(helo) except: # If the query errored some how, we know it's not "v=spf1 -all" record = '' if record != "v=spf1 -all": if last_action != 'prepend': # Prepend instead of reject if it's not a no mail record helo_result[3] = 'prepend' else: return(( 'dunno', 'Header already pre-pended', instance_dict )) if helo_result[3] == 'reject': # It may not anymore helo_result[4] = "Message rejected due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" + helo + \ ";ip=" + ip + ";r=" + data.get('recipient') if helo_result[3] == 'defer': helo_result[4] = "Message deferred due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" + helo + \ ";ip=" + ip + ";r=" + data.get('recipient') if HELO_pass_restriction and helo_result[0] == 'Pass': restrict_name = HELO_pass_restriction return('result_only', restrict_name, instance_dict) return(( helo_result[3], helo_result[4], instance_dict )) else: if configData.get('Mail_From_reject') != 'No_Check': res = spf.check2(ip, sender, helo, querytime=configData.get('Lookup_Time')) mfrom_result = [res[0], res[1]] mfrom_result.append('mailfrom') mfrom_result[0] = mfrom_result[0].lower() mfrom_result[0] = mfrom_result[0].capitalize() mfrom_resultpolicy, local = _get_resultcodes(configData, 'mfrom') if debugLevel >= 2: syslog.syslog('spfcheck: pyspf result: "%s"' % str(mfrom_result)) for poss_actions in mfrom_resultpolicy: if mfrom_result[0] in mfrom_resultpolicy[poss_actions]: action = poss_actions mfrom_result.append(action) mfrom_result.append('') if local['local_mfrom']: mfrom_result[1] = 'Receiver policy for SPF ' + mfrom_result[0] if mfrom_result[0] == 'None': mfrom_result[1] = 'no SPF record' if mfrom_result[0] != 'None' or (mfrom_result[0] == 'None' and helo_result[0] == 'None'): spfDetail = \ ('identity=%s; client-ip=%s; helo=%s; envelope-from=%s; receiver=%s ' % (mfrom_result[2], ip, helo, sender, data.get('recipient', '<UNKNOWN>'))) if debugLevel >= 1: logdata = str(mfrom_result[0]) + "; " + spfDetail syslog.syslog(logdata) if debugLevel >= 3: headerdata = 'Header type: ' + str(configData.get('Header_Type')) + '; Authres ID (for AR): ' + str(configData.get('Authserv_Id')) syslog.syslog(headerdata) if 'SPF' in configData.get('Header_Type') and 'AR' in configData.get('Header_Type'): syslog.syslog(syslog.LOG_ERR, 'Header_Type includes both SPF and AR - invalid configuration.') raise SyntaxError('Header_Type includes both SPF and AR - invalid configuration.') header = '' if 'SPF' in configData.get('Header_Type'): header = 'Received-SPF: '+ mfrom_result[0] + ' (' + mfrom_result[1] +') ' + spfDetail elif 'AR' in configData.get('Header_Type'): if not configData.get('Authserv_Id'): raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.') header += str(authres.AuthenticationResultsHeader(authserv_id = str(configData.get('Authserv_Id')), results = [authres.SPFAuthenticationResult(result = mfrom_result[0], result_comment = mfrom_result[1], smtp_mailfrom = spf.split_email(sender,'example.com')[1], smtp_mailfrom_comment = 'client-ip={0}; helo={1}; envelope-from={2}; receiver={3}'.format(ip, helo, sender, data.get('recipient', '<UNKNOWN>')))])) mfrom_result[4] = header mfrom_result.append(peruser) mfrom_result.append(mfrom_result[3]) if not found_instance or foundinstance[5]: if found_instance and found_instance[6] == "prepend": mfrom_result[6] = "prepend" instance_dict[instance] = mfrom_result if (Mail_From_pass_restriction and mfrom_result[0] == 'Pass') or \ (HELO_pass_restriction and helo_result[0] == 'Pass'): if mfrom_result[0] == 'Pass': restrict_name = Mail_From_pass_restriction return('result_only', restrict_name, instance_dict) # Act on the Mail From result if it is authoritative. if mfrom_result[3] == 'reject': if configData.get('No_Mail'): # If only rejecting on "v=spf1 -all", we need to know now try: q = spf.query(i='127.0.0.1', s='localhost', h='unknown', receiver=socket.gethostname()) record = q.dns_spf(sender) except: # If the query errored some how, we know it's not "v=spf1 -all" record = '' if record != "v=spf1 -all": if last_action != 'prepend': # Prepend instead of reject if it's not a no mail record mfrom_result[3] = 'prepend' else: return(( 'dunno', 'Header already pre-pended', instance_dict )) if mfrom_result[3] == 'reject': # It may not be anymore mfrom_result[4] = "Message rejected due to: " + mfrom_result[1] + \ ". Please see http://www.openspf.net/Why?s=mfrom;id=" + sender + \ ";ip=" + ip + ";r=" + data.get('recipient') return(( 'reject', mfrom_result[4], instance_dict )) if mfrom_result[3] == 'defer': mfrom_result[4] = "Message deferred due to: " + mfrom_result[1] + \ ". Please see http://www.openspf.net/Why?s=mfrom;id=" + sender + \ ";ip=" + ip + ";r=" + data.get('recipient') return(( 'defer', mfrom_result[4], instance_dict )) if mfrom_result[3] != 'dunno' or helo_result[3] =='dunno': if last_action != 'prepend': if mfrom_result[4]: header = mfrom_result[4] else: header = helo_result[4] return(( 'prepend', header, instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) else: if configData.get('HELO_reject') != 'No_Check': if helo_result[3] == 'reject': if configData.get('No_Mail'): # If only rejecting on "v=spf1 -all", we need to know now try: q = spf.query(i='127.0.0.1', s='localhost', h='unknown', receiver=socket.gethostname()) record = q.dns_spf(helo) except: # If the query errored some how, we know it's not "v=spf1 -all" record = '' if record != "v=spf1 -all": if last_action != 'prepend': # Prepend instead of reject if it's not a no mail record helo_result[3] = 'prepend' else: return(( 'dunno', 'Header already pre-pended', instance_dict )) if helo_result[3] == 'reject': # It may not anymore helo_result[4] = "Message rejected due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" \ + helo + ";ip=" + ip + ";r=" + data.get('recipient') return(( 'reject', helo_result[4], instance_dict )) if helo_result[3] == 'defer': helo_result[4] = "Message deferred due to: " + helo_result[1] + \ ". Please see http://www.openspf.net/Why?s=helo;id=" + helo + \ ";ip=" + ip + ";r=" + data.get('recipient') return(( 'defer', helo_result[4], instance_dict )) if last_action != 'prepend': return(( 'prepend', helo_result[4], instance_dict )) else: return(( 'dunno', 'Header already pre-pended', instance_dict )) else: cached_instance = instance_dict[instance] if cached_instance[3] == 'prepend': return(( 'dunno', 'Header already pre-pended', instance_dict )) else: return(( cached_instance[3], cached_instance[4], instance_dict )) return(( 'None', 'None', instance_dict )) ################################################### # load config file {{{1 # Default location: configFile = '/etc/python-policyd-spf/policyd-spf.conf' if len(sys.argv) > 1: if sys.argv[1] in ( '-?', '--help', '-h' ): print('usage: policyd-spf [<configfilename>]') sys.exit(1) configFile = sys.argv[1] configGlobal = policydspfsupp._processConfigFile(filename = configFile) # loop reading data {{{1 debugLevel = configGlobal.get('debugLevel', 1) if debugLevel >= 3: syslog.syslog('Starting') instance_dict = {'0':'init',} instance_dict.clear() data = {} lineRx = re.compile(r'^\s*([^=\s]+)\s*=(.*)$') while 1: # Python readline assumes ascii here, but sometimes it's not try: lineraw = sys.stdin.buffer.readline() line = lineraw.decode('UTF-8') except AttributeError: # python2.7 compatibility, it doesn't care about ascii or not, but # lacks sys.stid.buffer line = sys.stdin.readline() if not line: break line = line.rstrip() if debugLevel >= 4: syslog.syslog('Read line: "%s"' % line) # end of entry {{{2 if not line: peruser = False if debugLevel >= 4: syslog.syslog('Found the end of entry') configData = dict(list(configGlobal.items())) if not data.get('recipient'): data['recipient'] = 'none' if configData.get('Per_User'): import policydspfuser configData, peruser = policydspfuser._datacheck(configData, data.get('recipient')) if debugLevel >= 2 and peruser: syslog.syslog('Per user configuration data in use for: %s' \ % str(data.get('recipient'))) if debugLevel >= 3: syslog.syslog('Config: %s' % str(configData)) # run the checkers {{{3 checkerValue = None checkerReason = None checkerValue, checkerReason, instance_dict = _spfcheck(data, instance_dict, configData, peruser) if configData.get('defaultSeedOnly') == 0 and checkerValue != 'prepend': checkerValue = None checkerReason = None # handle results {{{3 if debugLevel >= 3: syslog.syslog('Action: {0}: Text: {1}'.format(checkerValue, checkerReason)) if checkerValue == 'reject': sys.stdout.write('action=550 %s\n\n' % checkerReason) elif checkerValue == 'prepend': if configData.get('Prospective'): sys.stdout.write('action=dunno\n\n') else: try: sys.stdout.write('action=prepend %s\n\n' % checkerReason) except UnicodeEncodeError: sys.stdout.write('action=prepend %s\n\n' % str(checkerReason.encode("UTF-8"))[1:].strip("'")) elif checkerValue == 'defer': try: sys.stdout.write('action=defer_if_permit %s\n\n' % checkerReason) except UnicodeEncodeError: sys.stdout.write('action=defer_if_permit %s\n\n' % str(checkerReason.encode("UTF-8"))[1:].strip("'")) elif checkerValue == 'warn': try: sys.stdout.write('action=warn %s\n\n' % checkerReason) except UnicodeEncodeError: sys.stdout.write('action=warn %s\n\n' % str(checkerReason.encode("UTF-8"))[1:].strip("'")) elif checkerValue == 'result_only': try: sys.stdout.write('action=%s\n\n' % checkerReason) except UnicodeEncodeError: sys.stdout.write('action=%s\n\n' % str(checkerReason.encode("UTF-8"))[1:].strip("'")) else: sys.stdout.write('action=dunno\n\n') # end of record {{{3 sys.stdout.flush() data = {} continue # parse line {{{2 m = lineRx.match(line) if not m: syslog.syslog('ERROR: Could not match line "%s"' % line) continue # save the string {{{2 key = m.group(1) value = m.group(2) if key not in [ 'protocol_state', 'protocol_name', 'queue_id' ]: value = value.lower() data[key] = value if debugLevel >= 3: syslog.syslog('Normal exit')