pypolicyd-spf-1.3.2/0000775000175000017500000000000012563005271016004 5ustar kittermakitterma00000000000000pypolicyd-spf-1.3.2/setup.py0000775000175000017500000000262212562722107017526 0ustar kittermakitterma00000000000000from distutils.core import setup import os import sys DESC = """pypolicyd-spf SPF Postfix policy server implemented in Python.""" setup(name='pypolicyd-spf', version='1.3.2', description=DESC, author='Scott Kitterman', author_email='scott@kitterman.com', url='https://launchpad.net/pypolicyd-spf', py_modules=['policydspfsupp', 'policydspfuser'], keywords = ['Postfix','spf','email'], scripts = ['policyd-spf'], data_files=[(os.path.join('share', 'man', 'man1'), ['policyd-spf.1']), (os.path.join('share', 'man', 'man5'), ['policyd-spf.conf.5']), (os.path.join('/etc', 'python-policyd-spf'), ['policyd-spf.conf']), (os.path.join('share', 'man', 'man5'), ['policyd-spf.peruser.5'])], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Email :: Mail Transport Agents', 'Topic :: Communications :: Email :: Filters', ] ) if sys.version_info < (2, 6): raise Exception("pypolicyd-spf requires python2.6/2.7 or python3.2 and later.") pypolicyd-spf-1.3.2/README0000664000175000017500000000532512562722171016675 0ustar kittermakitterma00000000000000Python Postfix Policy for SPF (python-policy-spf) 1.3.2 Python based policy daemon for Postfix SPF checking Tumgreyspf source Copyright © 2004-2005, Sean Reifschneider, tummy.com, ltd. python-policyd-spf changes Copyright © 2007-2014 Scott Kitterman Documentation inputs: Copyright © 2004-2005, Sean Reifschneider, tummy.com, ltd. 2003-2004 Meng Weng Wong from postfix-policyd-spf-perl Copyright © 2007-2014 Scott Kitterman 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. ================= This is python-policyd-spf, an external policy checker for the postfix mail server. It will use pyspf to check SPF records to determine if email should be rejected by your server. To install from the tar.gz (if this software has been packaged for your distribution, the packaged version is recommended and should be installed using your normal distribution packaging tools): 1. Extract the package from the tarball (tar -xvvzf ...) 2. Enter the package directory (cd ...) 3. python setup.py build 4. As root python setup.py install It requires Python (python2.6, python2.7, or python3.2+), the pyspf (python-spf) library version 2.0.7 or higher (2.0.9 is required for all changes related to the RFC 7208 updates to the SPF design), and (for Python versions before python3.3, the ipaddr module (version 2.1.10 or later) - for python3.3 and later the built-in ipaddress module is used). If pyspf not available through your packaging system, it can be downloaded from: http://sourceforge.net/projects/pymilter/ If ipaddr not available through your packaging system, it can be downloaded from: http://code.google.com/p/ipaddr-py/downloads/list To use the optional RFC 7001 Authentication-Results header, the authres module is also needed. It is also need to run some tests. It can be downloaded from pypi or from: https://launchpad.net/authentication-results-python Nothing is configured by default, so this will not interact with Postfix until it has been set up. See man 1 policyd-spf for information on setting up and using this policy server. See man 5 policyd-spf.conf for configuration file information. pypolicyd-spf-1.3.2/policyd-spf.peruser.50000664000175000017500000001745412343533115022021 0ustar kittermakitterma00000000000000\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "policy-spf.peruser 5" .TH policy-spf.peruser 5 "2012-03-17" .SH "NAME" python-policyd-spf \- pure-Python Postfix policy daemon for SPF checking .SH "VERSION" .IX Header "VERSION" 1\.3 .SH "USAGE" .IX Header "USAGE" Usage: policyd-spf [/etc/policyd-spf/policyd-spf.conf] .SH "OTHER DOCUMENTATION" .IX Header "OTHER DOCUMENTATION" This documentation assumes you have read Postfix's README_FILES/ SMTPD_POLICY_README and are generally familiar with Sender Policy Framework (SPF). See RFC 7208 for details. man 1 policyd-spf provides general operation documentation for this package. See man 5 policyd-spf.conf for configuration file information. .SH "SYNOPSIS" .IX Header "SYNOPSIS" python-policyd-spf operates with a default installed configuration file and set of default configuration options that are used if the configuration file cannot be found. These options can be changed by changing the installed configuration files or through giving a path to an alternate configuration file. Additionally, different configurations can be provided on a per user basis. This man page describes setup and user of per user (mail recipient) configurations. Currently these configurations can either be stored in a text file or a Berkeley DB (libdb) datase. If there is sufficient interest, other data storage methods may be supported in the future. .SH "DESCRIPTION" .IX Header "DESCRIPTION" Use of per-user configuration is defined in the application configuration file with the setting "Per_User". The value of the setting gives the type and location of the per-user configuration information. Currently supported types are text and bsddb. User is defined an email address of a recipient of the message. All options available at the application level (See man 5 policyd-spf.conf) can be adjusted on a per-user basis. Per-user checks can only be done as part of smtpd_recipient_restrictions. Per-user actions are not possible at other stages of the SMTP dialogue. The user is not yet known for smtpd_client_restrictions, smtpd_helo_restrictions, or smtpd_sender_restrictions. If used during smtpd_data_restrictions or smtpd_end_of_data_restrictions, the entire message will be available only if the message was only to a single recipient. If per-user configurations are used when recipient information is not available, warnings will be logged and the per-user information will be ignored. In addition to specifying individual users, regular expression matching is also available, but may have performance implications since the entire user table has to be traversed for each message recipient. .SH "OPTIONS" .IX Header "OPTIONS" .SH "Text Per-User Configuration File" .IX Header "Text" The text file option is useful for testing and when only a small number of users require per-user configurations. It is specified in the main configuration file: "Per_User = text,/etc/pypolicyd-spf/userconf" Lines beginning with "#" are treated as comments and ignored. The location of the file is determined by the system administrator. No default file is provided in or installed by the package. The configuration of the file is a comma separated combination of user and configuration information, with one line per user's configuration information (NOTE: due to man page formating requirements, these lines are wrapped - in the config file, it must be one line per user): postmaster@example.com,Mail_From_reject=No_Check|PermError_reject=\ False|HELO_reject=SPF_Not_Pass|defaultSeedOnly=1|debugLevel=5|\ skip_addresses=127.0.0.0/8,::ffff:127.0.0.0//104,::1//128|TempError_Defer=False strict@example.com,PermError_rejec=True|HELO_reject=SPF_Not_Pass|\ TempError_Defer=True It is not necessary to specify all configuration parameters for each user, only those that are different than the overall configuration need to be specified. If the specified per user configuration file is missing, an error is logged and the global configuration is used instead. .SH "SEE ALSO" .IX Header "SEE ALSO" man 1 policyd-spf, man 5 policyd-spf.conf, python-spf, , RFC 7208 .SH "AUTHORS" .IX Header "AUTHORS" This version of \fBpypolicyd-spf\fR was written by Copyright © 2007-2011, Scott Kitterman . It is derived from Tumgreyspf, written by Sean Reifschneider, tummy.com, ltd . .PP This man-page was created by Scott Kitterman . pypolicyd-spf-1.3.2/policydspfsupp.py0000664000175000017500000001253512562720035021451 0ustar kittermakitterma00000000000000# -*- coding: utf-8 -*- # # Tumgreyspf # Copyright © 2004-2005, Sean Reifschneider, tummy.com, ltd. # # pypolicyd-spf changes # Copyright © 2007-12 Scott Kitterman ''' 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. ''' import syslog import os import sys import re import stat # default values defaultConfigData = { 'debugLevel' : 5, 'HELO_reject' : 'SPF_Not_Pass', 'Mail_From_reject' : 'Fail', 'PermError_reject' : 'False', 'TempError_Defer' : 'False', 'skip_addresses' : '127.0.0.0/8,::ffff:127.0.0.0/104,::1', 'defaultSeedOnly' : 1, 'Header_Type' : 'SPF', 'Lookup_Time' : 20, 'Void_Limit' : 2 } ################################# class ConfigException(Exception): '''Exception raised when there's a configuration file error.''' pass #################################################################### def _processConfigFile(filename = None, config = None, useSyslog = 1, useStderr = 0): '''Load the specified config file, exit and log errors if it fails, otherwise return a config dictionary.''' import policydspfsupp if config == None: config = policydspfsupp.defaultConfigData if filename != None: try: _readConfigFile(filename, config) except Exception as e: if useSyslog: syslog.syslog(e.args[0]) if useStderr: sys.stderr.write('%s\n' % e.args[0]) sys.exit(1) return(config) ################# class ExceptHook: def __init__(self, useSyslog = 1, useStderr = 0): self.useSyslog = useSyslog self.useStderr = useStderr def __call__(self, etype, evalue, etb): import traceback tb = traceback.format_exception(*(etype, evalue, etb)) tb = list([a.rstrip('\n') for a in tb]) tb = '\n'.join([c for c in tb]) for line in tb.split('\n'): if self.useSyslog: syslog.syslog(line) if self.useStderr: sys.stderr.write(line + '\n') #################### def _setExceptHook(): sys.excepthook = ExceptHook(useSyslog = 1, useStderr = 1) ############################################################### commentRx = re.compile(r'^(.*)#.*$') def _readConfigFile(path, configData = None, configGlobal = {}): '''Reads a configuration file from the specified path, merging it with the configuration data specified in configData. Returns a dictionary of name/value pairs based on configData and the values read from path.''' debugLevel = configGlobal.get('debugLevel', 0) if debugLevel >= 5: syslog.syslog('readConfigFile: Loading "%s"' % path) if configData == None: configData = {} nameConversion = { 'debugLevel' : int, 'HELO_reject' : str, 'Mail_From_reject' : str, 'PermError_reject' : str, 'TempError_Defer' : str, 'Mail_From_pass_restriction' : str, 'HELO_pass_restriction' : str, 'Prospective' : str, 'Whitelist' : str, 'skip_addresses': str, 'Domain_Whitelist' : str, 'Domain_Whitelist_PTR': str, 'No_Mail': str, 'Reject_Not_Pass_Domains' : str, 'Per_User' : str, 'defaultSeedOnly' : int, 'Header_Type' : str, 'Authserv_Id' : str, 'Lookup_Time' : int, 'Void_Limit' : int } # check to see if it's a file try: mode = os.stat(path)[0] except OSError as e: syslog.syslog(syslog.LOG_ERR,'ERROR stating "%s": %s' % ( path, e.strerror )) return(configData) if not stat.S_ISREG(mode): syslog.syslog(syslog.LOG_ERR,'ERROR: is not a file: "%s", mode=%s' % ( path, oct(mode) )) return(configData) # load file fp = open(path, 'r') while 1: line = fp.readline() if not line: break # parse line line = (line.split('#', 1)[0]).strip() if not line: continue data = [q.strip() for q in line.split('=')] if len(data) != 2: if len(data) == 1: if debugLevel >= 1: syslog.syslog('Configuration item "%s" not defined in file "%s"' % ( line, path )) else: syslog.syslog('ERROR parsing line "%s" from file "%s"' % ( line, path )) continue name, value = data # check validity of name conversion = nameConversion.get(name) if conversion == None: syslog.syslog('ERROR: Unknown name "%s" in file "%s"' % ( name, path )) continue if debugLevel >= 5: syslog.syslog('readConfigFile: Found entry "%s=%s"' % ( name, value )) configData[name] = conversion(value) fp.close() return(configData) pypolicyd-spf-1.3.2/policyd-spf0000775000175000017500000011717112563002264020172 0ustar kittermakitterma00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Check SPF results and provide recommended action back to Postfix. # # Tumgreyspf source # Copyright © 2004-2005, Sean Reifschneider, tummy.com, ltd. # # # pypolicyd-spf # Copyright © 2007-15, Scott Kitterman ''' 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 try: import ipaddress except ImportError: 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', ''), data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', ''), )) 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', ''),\ data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', '')) )])) 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', ''), data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', ''), )) 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', ''),\ data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', '')) )])) 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', ''), data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', ''), )) 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', ''),\ data.get('helo_name', ''), data.get('sender', ''), data.get('recipient', '')) )])) 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', ''))) 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', '')))])) 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', ''))) 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', '')))])) 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 []') 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') pypolicyd-spf-1.3.2/MANIFEST.in0000664000175000017500000000017412343533115017543 0ustar kittermakitterma00000000000000include COPYING include CHANGES include MANIFEST.in include README.per_user_whitelisting include policyd-spf.conf.commented pypolicyd-spf-1.3.2/README.per_user_whitelisting0000664000175000017500000000510712343533115023303 0ustar kittermakitterma00000000000000This document illustrates applying different SMTPD Access Restrictions for different recipients depending upon whether a message gets SPF Pass. An understanding of at least the following Postfix documents and associated man pages is required. RESTRICTION_CLASS_README SMTPD_ACCESS_README SMTPD_POLICY_README The Postfix RESTRICTION_CLASS_README opens with the following example illustrating the use of different restrictions for different recipients. /etc/postfix/main.cf: smtpd_restriction_classes = restrictive, permissive # With Postfix < 2.3 specify reject_unknown_client. restrictive = reject_unknown_sender_domain reject_unknown_client_hostname ... permissive = permit smtpd_recipient_restrictions permit_mynetworks reject_unauth_destination check_recipient_access hash:/etc/postfix/recipient_access /etc/postfix/recipient_access: joe@my.domain permissive jane@my.domain restrictive The example below illustrates using this policy-spf daemon with the Postfix "check_policy_service" access restriction to apply the "permissive" restriction only to messages getting SPF Pass. /etc/python-policyd-spf/policyd-spf.conf: HELO_pass_restriction = spf_fin, passed_spf Mail_From_pass_restriction = spf_fin, passed_spf /etc/python-policyd-spf/policyd-spf-fin.conf: HELO_reject = False Mail_From_reject = False /etc/postfix/master.cf: policyd-spf unix - n n - 0 spawn user=nobody argv=/usr/bin/policyd-spf policyd-spf-fin unix - n n - 0 spawn user=nobody argv=/usr/bin/policyd-spf /etc/python-policyd-spf/policyd-spf-fin.conf /etc/postfix/main.cf: spf_fin = check_policy_service unix:private/policyd-spf-fin smtpd_restriction_classes = restrictive, permissive, spf_fin, passed_spf restrictive = reject_unknown_sender_domain reject_unknown_client_hostname ... permissive = permit passed_spf check_recipient_access hash:/etc/postfix/recipient_access restrictive smtpd_recipient_restrictions permit_mynetworks reject_unauth_destination check_policy_service unix:private/policyd-spf restrictive policyd-spf_time_limit = 3600 policyd-spf-fin_time_limit = 3600 /etc/postfix/recipient_access: joe@my.domain permissive jane@my.domain restrictive pypolicyd-spf-1.3.2/COPYING0000664000175000017500000002613612343533115017046 0ustar kittermakitterma00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. pypolicyd-spf-1.3.2/CHANGES0000664000175000017500000002654112563002442017004 0ustar kittermakitterma00000000000000# Legend: # --- = A new release # + = Added a feature (in a backwards compatible way) # ! = Changed something significant, or removed a feature # * = Fixed a bug, or made a minor improvement --- 1.3.2 (2015-08-12) * Fix python3 incompatibility in cases where HELO name is somehow missing (LP: #1184102) * Updated README to mention the minimum ipaddr version, if needed, is 2.1.10 (LP: #1229862) * Fix up header caching (LP: #1422325) * Fix and refactor for simplicity detection of Authserv_Id missing from configuration (LP: #1484239) * Add try/except around SPF record queries of No_Mail option to avoid errors on bogus TXT records --- 1.3.1 (2014-06-14) * Fix case where, when run with python3 the policy server would choke on email addresses that contained non-ascii characters (LP: #1325579) --- 1.3 (2014-05-09) ! Updates related to the new SPF RFC, RFC 7208 - Added new config option, Lookup_Time, to adjust SPF record timeout limit (default 20 seconds per RFC 7208) Requires at least pyspf 2.0.7 - Added new config option, Void_Limit, to enable the new void lookup limit instroduced in RFC 7208 to be adjusted - Default is 2 as recommended in RFC 7208, section 4.6.4. Has no effect on pyspf before 2.0.9. - Updated documentation to refer to RFC 7208 (and RFC 7001 for authentication results) - Updated descriptions in documentation to describe spec compliance relative to RFC 7208 instead of RFC 4408 * Guard against crashes when forming header field contents if the receiver is somehow missing --- 1.2 (2013-07-25) ! Added external dependency on ipaddr module for python versions < 3.3 * Fix PTR whitelist to work with IPv6 connections (patch from Frank Hunszinger) - LP: #1179266 * Replace custom code with use of ipaddr/ipaddress to perform CIDR matching ! CIDR network definitions are now more limited to correct networks - Double slashes are no longer allowed - Updated defaults and documentation for skip_addresses to match --- 1.1.2 (2013-05-10 13:13 -0400) Brown paper bag release * Add MANIFEST.in and rename in setup.py to make package compatible with using sdist (fixes missing files in 1.1.1) --- 1.1.1 (2013-05-10 12:23 -0400) * Fixed documentation to be more compatible with running with Python3. --- 1.1 (2012-07-21 21:30 -0400) + Ported to Python 3. Tested on python3.2, python2.7, and python2.6. Versions previous to python2.6 will not work. --- 1.0 (2012-03-17 23:34 -0400) * Fixed missing authentication results headers for no authentication performed cases (when authres is enabled) * Fixed ambiguous config file warning in per user processing * Make functions private (leading underscore) * Fixed erroneous use of syslog.LOG_ERR in per user processing --- 0.9 (2012-01-10 22:35 -0500) + Add support for optionally generating RFC 5451 authentication results headers + Add new Header_Type configuration option to support generating RFC 4408 Received-SPF and/or RFC 5451 Authentication-Results headers (default is Received-SPF) ! Changed license from GPL version 2 to Apache 2.0 with agreement from all copyright holders * Log message to the error facility for all OSErrors * Instead of crashing if per user configuration is missing, continue with global configuration * Use openspf.net instead of openspf.org for Why text in reject/defer messages due to extended openspf.org downtime * Fix install location of standard config file when installed with distutils * Fix example syntax in policyd-spf.peruser.5 * Update and clarify inconsistencies in policyd-spf.conf.5 --- 0.8.1 (2010-11-27 22:41 -0500) * Prepend headers even when defaultSeedOnly = 0 (now does what's documented) * Fix typos in policyd-spf.conf(5) --- 0.8 (2010-02-17 01:38 -0500) + Add Domain_Whitelist_PTR to allow whitelisting from SPF tests based on rDNS PTR match (patch from Colin Stewart ) * Only check Domain_Whitelist if it actually exists in the configuration + Add No_Mail option to allow for only rejecting from hosts/domains that send no mail ("v=spf1 -all") + Add ability to provide per user (per recipient) settings * Fixed a bug so that skipping SPF checks due to localhost or any whitelist settings does not prepend multiple headers per message for multi recipient messages * Fixed a bug so that non-reject HELO results are correctly used when Mail From checks are disabled (No_Check) * Clean up unused code in policydspfsupp.py --- 0.7.3 (2010-01-07 01:00 -0500) * No longer require Python 2.5 (Thanks to Matthew Munsey ) * Update copyright for new year * Update for new project location * Clean up imports (PEP-8 style, remove redundancy, removed unused) * Remove deprecated licence distribution option from setup.py --- 0.7.2 (2009-10-22 02:54 -0400) ! Require at least Python 2.5 * Fix to not crash on invalid senders that lack a domain part * Remove unused imports of deprecated popen2 module --- 0.7.1 (2008-07-25 23:54 -0400) * Fix default log level in policyd-spf.conf.commented to match default * Update configuration recommendations in policyd-spf.1 --- 0.7 (2008-06-22 13:45 -0400) + Reject option for Mail From not pass or none (parallel HELO option) + Reject on Softfail for HELO and Mail From + Add receiver policy options per sender domain to reject non-SPF Pass mail for specific domains + Update policyd-spf(5) for new options ! Refactor result processing for better scalability and easier testing ! Move commented config file to a new file and use/install an uncommented minimal config file to reduce future churn in the operational config file * Fix prepend only (no action) options to work * Clarify in policyd-spf(5) that permerror and temperror setting affect both HELO and Mail From checks when those checks are enabled --- 0.6.1 (2008-04-05 01:23 -0400) * Pre-initialize helo_result to None to avoid crash if HELO checking is disabled --- 0.6 (2008-02-20 16:35 -0500) ! Logging redesign: - Change default loglevel to 1 and readjust loglevel 1 and 2 to 2 and 3 - Loglevel 0 changed to no logging - Move all non-error config file related logging to level 5 - Don't log SPF result comments - Updated policyd-spf(5) debugLevel description - Don't log errors for known config options * Added exit log message promised in policyd-spf(5) * Removed adding policyd-spf to %PYTHONPATH + Added prospective SPF checks to see if mail sent from current IP would Fail SPF after being sent. Don't add SPF Received headers for these. * Fixed IP whitelisting to work with multiple IP ranges (patch from Nicolas Litchinko) * Fixed 'seed only' option to work (patch from Nicolas Litchinko) * Fixed domain whitelist to work * Fixed domain whitelist to work with multiple domains (patch from Nicolas Litchinko) * Correctly detect IPv6 addresses in skip and white lists and use correct implicit CIDR for IPv6 * Correct examples and policyd-spf(5) to not have spaces in IP and domain lists + Log error if IP whitelist or skip list have non-IP address items in the lists and then don't crash ! Install man pages and config files in FHS compliant locations. ! Removed spec files since I'm not qualified to maintain them --- 0.5.2 (2007-10-26 15:30 -0400) * Corrected regression so appending a header on Permerror works (introduced in 0.4) - Thanks to "John A. Martin" for the bug report. * Log and prepend Mail From result instead of HELO result if both are None. * Provide default explanation for None results (so header and log fields are not left empty * Use correct RFC 4408 identity names (mailfrom/helo) in headers, logging, and SMTP replies * Use package installed config file if none is specified and related documentation updates * Fix default installation location for man pages and config file * Revised README.per_user_whitelisting --- 0.5.1 (2007-10-17 14:47 -0400) * Corrected regression so reject on Permerror works (introduced in 0.4) Thanks to "John A. Martin" for the bug report. * Fixed Restriction Class option to be useful. + Made restriction class names configurable + Added per user whitelisting README to explain how it's useful Thanks to "John A. Martin" for the contribution. * Corrected SPF-Recieved header to us <> for null sender * Corrected Postfix integration section of policyd-spf(1) to reflect correct policy service time limit name. * Corrected installed config file locations in both man pages. * Header and logging cleanup (removed trailing ';' and adjusted whitespace). --- 0.5 (2007-10-03 13:39 -0400) + Added man page for configuration file formatting (man 5 policyd-spf.conf) * Moved explicit logging of the result headers for HELO and Mail From from debug level 1 to debug level 2 (SPF results are already logged at debug level 1) * Moved config file item logging to a new debug level 5. This should only be needed for development and not for operational use. ! Shifted list of local addresses to skip SPF from hard coded to a config option. * Changed default (no config file) TempError defer to False to match docs and default in config file. ! Refactored Whitelisting/SPF skipping code for reduced size and better extensibility and maintainability. + Added Forwarder Domain SPF Whitelist + Added Restriction Class mode to return only SPF result to Postfix + Return link to SPF "Why" page for reject/defer actions. --- 0.4.1 (2007-08-13 11:00 -0400) * Correct multi-recipient caching to work for multi-recipient rejections --- 0.4 (2007-07-09 17:24) + Process HELO first and reject if allowed before looking up Mail From + Log failure to find SPF library ! Rationalize text of logging and comments back to Postfix - any script that parses logs from this program automatically will need to be updated. * Remove obsolete code for using non-Python SPF libraries + Activate support for config files (refactored legacy code) ! Change PermError default from Reject to Prepend - Reject on PermError was inconsistent with traditional SPF usage. ! Remove obsolete undistributed files from SVN trunk ! Remove INSTALL file (redundant to man 1 policyd-spf) * Adjust master.cf recommendations in INSTALL for new recommendations from Weitse Venema (postfix-users mailing list). * Change indentation from tabs to spaces in legacy code + Support case insensitive SPF results as required by RFC 4408. + SPF results reported with initial capitalization. + Add SPF whitelist facility in config file --- 0.3 (2007-02-23 11:54) * Refactored and simplified SPF results reporting/logging * Changed logging to match RFC 4408 SPF-Received: terminology * Fixed processing to skip SPF for localhost connections to work for IPv6 + Implemented prepending of SPF-Received: header. + Added man page (man 1 policyd-spf) --- 0.2 (2007-02-07 16:50) * Changed skip local connections to use CIDR match rather than string. * Log non-fail/error results to syslog --- 0.1 (2007-01-17 18:00) ! Initial release ! Removed greylisting ! Stubbed out config files until they can be updated and integrated + Defer on temperror + Reject on permerror + Check HELO for null Sender (Mail From) --- 0.0 Source from Tumgreyspf (2007-01-11 00:00) ! Source Tumgreyspf Version 1.24 pypolicyd-spf-1.3.2/policyd-spf.10000664000175000017500000002302712343533115020322 0ustar kittermakitterma00000000000000\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "policy-spf 1" .TH policy-spf 1 "2012-03-17" .SH "NAME" python-policyd-spf \- pure-Python Postfix policy daemon for SPF checking .SH "VERSION" .IX Header "VERSION" 1\.3 .SH "USAGE" .IX Header "USAGE" NOTE: Depending on the packaging and distribution, the exact path to the executable may vary. $ policyd-spf (Start using installed config file) $ policyd-spf \-h (Display usage message) $ policyd-spf /etc/policyd-spf/policyd-spf.conf (Config file name to use) Configuration options are described in the sample configuration file provided with the package (policyd-spf.conf.commented) and in policyd-spf.conf(5). The provided setup.py installs an uncommented configuration file in /etc/policyd-spf/. Additionally, whitelisting certain IP addresses or IP addresses used by listed domains from SPF checks is supported. Skipping SPF checks for local submission or trusted relays is also provided. The sample configuration file and policyd-spf.conf(5) shows the format to use. .SH "OTHER DOCUMENTATION" .IX Header "OTHER DOCUMENTATION" This documentation assumes you have read Postfix's README_FILES/ SMTPD_POLICY_README and are generally familiar with Sender Policy Framework (SPF). See RFC 7208 for details. See man 5 policyd-spf.conf for configuration file information. man 5 policyd-spf.peruser provides documentation on setting up and using different configuration options on a per user (mail reciepient) basis. .SH "SYNOPSIS" .IX Header "SYNOPSIS" python-policyd-spf is a Postfix SMTPd policy daemon for SPF checking. It is implemented in pure Python and uses the pyspf module. The SPF web site is http://www.openspf.org/. The Postfix configuration must be changed to check SPF. .SH "DESCRIPTION" .IX Header "DESCRIPTION" Logging is sent to syslogd. Each time a Postfix SMTP server process is started it connects to the policy service socket and Postfix runs one instance of this Python script. By default, a Postfix SMTP server process terminates after 100 seconds of idle time, or after serving 100 clients. Thus, the cost of starting this Python script is smoothed over time The default policy_time_limit is 1000 seconds. This may be too short for some SMTP transactions to complete. As recommended in SMTPD_POLICY_README, this should be extended to 3600 seconds. To do so, set "policy_time_limit = 3600" in /etc/postfix/main.cf. Messages that get a Fail SPF result will be rejected. Messages that get a Permerror are, by default, treated as if they had no SPF record. Messages that get a Temperror result are, by default, treated as if they had no SPF record, but can (and probably should) be deferred if otherwise permitted. Messages that get other SPF results (Pass, None, Neutral, Softfail) will have the SPF Received header prepended. Note: Spamasassisn 3.2 and follow will use this header for spam scoring so there is no need to configure a separate SPF check in these Spamassassin versions. See Spamassassin documentation for details. Default Mail From rejection/deferal criteria are, by design, conservative. Default HELO check actions are to reject mail with other than Pass/None. HELO records are much simpler than Mail From records and rejecting based on HELO checking does not present a false positive risk. These settings are a matter of local policy and should be adjusted to meet the requirements of site administrators. See policyd-spf.conf(5) for configuration file details. .SH "LOGGING" .IX Header "LOGGING" Policyd-spf will log messages to syslog about it's activities. The "debugLevel" value in "policyd-spf.conf" can be increased to get additional information to be logged. When set to a value of "0", only test results (SPF hits/misses) are logged. Results will be returned to Postfix and logged as a warning by Postfix also. For logging by this policy server, look for "policyd-spf" in your mail log files. .SH "TESTING THE POLICY DAEMON" .IX Header "TESTING THE POLICY DAEMON" Testing the policy daemon To test the policy daemon by hand, execute: policyd-spf Each query is a bunch of attributes. Order does not matter, and the daemon uses only a few of all the attributes shown below: request=smtpd_access_policy protocol_state=RCPT protocol_name=SMTP helo_name=some.domain.tld queue_id=8045F2AB23 instance=12345.6789 sender=foo@bar.tld recipient=bar@foo.tld client_address=1.2.3.4 client_name=another.domain.tld [empty line] The policy daemon will answer in the same style, with an attribute list followed by a empty line: action=dunno [empty line] .SH "POSTFIX INTEGRATION" .IX Header "POSTFIX INTEGRATION" 1. Add the following to /etc/postfix/master.cf: policyd-spf unix - n n - 0 spawn user=nobody argv=/usr/bin/policyd-spf NOTE: Check the path to both the installed Python interpreter and policyd-spf. These vary from system to system. To use non-default settings, you must also add the config file (see above and policyd-spf.conf(5) for details). If you run other services with user nobody, create a dedicated user for this policy server and use that instead. 2. Configure the Postfix policy service in /etc/postfix/main.cf: smtpd_recipient_restrictions = ... reject_unauth_destination check_policy_service unix:private/policyd-spf ... policyd-spf_time_limit = 3600 NOTE: Specify check_policy_service AFTER reject_unauth_destination or else your system can become an open relay. 3. Reload Postfix. .SH "SEE ALSO" .IX Header "SEE ALSO" policyd-spf.conf(5), policyd-spf.peruser(5), python-spf, , RFC 7208 .SH "AUTHORS" .IX Header "AUTHORS" This version of \fBpython-policyd-spf\fR was written by Copyright © 2007-2012 Scott Kitterman . It is derived from Tumgreyspf, written by Sean Reifschneider, tummy.com, ltd . Portions of the documentation were written by Meng Weng Wong . .PP This man-page was created by Scott Kitterman . pypolicyd-spf-1.3.2/policyd-spf.conf.50000664000175000017500000005041312343533115021251 0ustar kittermakitterma00000000000000\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "policy-spf.conf 5" .TH policy-spf.conf 5 "2012-03-17" .SH "NAME" python-policyd-spf \- pure-Python Postfix policy daemon for SPF checking .SH "VERSION" .IX Header "VERSION" 1\.3 .SH "USAGE" .IX Header "USAGE" Usage: policyd-spf [/etc/policyd-spf/policyd-spf.conf] .SH "OTHER DOCUMENTATION" .IX Header "OTHER DOCUMENTATION" This documentation assumes you have read Postfix's README_FILES/ SMTPD_POLICY_README and are generally familiar with Sender Policy Framework (SPF). See RFC 7208 for details. man 1 policyd-spf provides general operation documentation for this package. man 5 policyd-spf.peruser provides documentation on setting up and using different configuration options on a per user (mail reciepient) basis. .SH "SYNOPSIS" .IX Header "SYNOPSIS" python-policyd-spf operates with a default installed configuration file and set of default configuration options that are used if the configuration file cannot be found. These options can be changed by changing the installed configuration files or through giving a path to an alternate configuration file. .SH "DESCRIPTION" .IX Header "DESCRIPTION" Configuration options are described here and in the configuration file provided with the package. The provided setup.py installs this configuration file in /etc/policyd-spf/. Additionally, whitelisting certain IP addresses from SPF checks is supported. This man page and the sample configuration file show the format to use. These options can be adjusted on a per user (mail recipient) basis. Details on per user settings can be found in policyd-spf.peruser(5). .SH "OPTIONS" .IX Header "OPTIONS" .SH "LOGGING" .IX Header "LOGGING" "debugLevel" controls the amount of information logged by the policy server. The default, 1, logs no debugging messages, just basic SPF results and errors generated through the policy server. This value can be increased up to 5 (values higher than 5 will not cause an error, but will not log any additional information). debug level 2 adds a log message if no client address (IP address from which the connection was made), Mail From addresss, or HELO/EHLO name is received by the policy server, and logs SPF results for each Mail From and HELO check. debug level 3 generates a log message each time the policy server starts and each time it exits, as well as logging a copy of the exact header returned to Postfix to be prepended into the message. Each time the policy server starts, debug level 3 also logs the configuration information used by the policy server. debug level 4 logs the complete data set received by Postfix via the policy interface and when the end of the entry is read. debug level 5 is used to debug config file processing and can only be set in code and not via the config file. If debug level is 0, then the policy server logs errors only. Default: debugLevel = 1 .SH "TEST OPERATION" .IX Header "TEST OPERATION" The policy server can operate in a test only mode. This allows you to see the potential impact of SPF checking in your mail logs without rejecting mail. Headers are prepended in messages, but message delivery is not affected. This mode is not enabled by default. To enable it, set defaultSeedOnly = 0. Default: defaultSeedOnly = 1 .SH "HELO/EHLO CHECKING" .IX Header "HELO/EHLO CHECKING" HELO check rejection policy options are: SPF_Not_Pass (default) - Reject if result not Pass, None, or Temperror (alternatively put, reject if the SPF result is Fail, Softfail, Neutral, PermError). Unlike Mail From checking, there are no standard e-mail use cases where a HELO check should not Pass if there is an SPF record for the HELO name (transparent forwarding, for example, is not an issue). HELO/EHLO is known first in the SMTP dialogue and there is no practical reason to waste resources on Mail From checks if the HELO check will already cause the message to be rejected. This should not cause interoperability problems when used for HELO. Softfail - Reject on HELO Softfail or Fail. HELO/EHLO is known first in the SMTP dialogue and there is no practical reason to waste resources on Mail From checks if the HELO check will already cause the message to be rejected. This should not cause interoperability problems when used for HELO. Fail - Reject only on HELO Fail. HELO/EHLO is known first in the SMTP dialogue and there is no practical reason to waste resources on Mail From checks if the HELO check will already cause the message to be rejected. This should not cause interoperability problems when used for HELO. Null - Only reject HELO Fail for Null sender (SPF Classic). This is the approach used by the pre-RFC 4408 reference implementation and many of the pre- RFC specifications. Use of at least this option (SPF_Not_Pass or Fail) are preferred) is highly recommended. False - Never reject on HELO, append header only. This is useful for post-SMTP spam filters such as SpamAssassin. No_Check - Never check HELO. This is only recommended if you are calling the policy server twice (once for HELO checks and once for Mail From) with two different configuration files. This approach is useful to get both the HELO and Mail From headers prepended to a message. Default: HELO_reject = SPF_Not_Pass .SH "HELO/EHLO PASS RESTRICTION" .IX Header "HELO/EHLO PASS RESTRICTION" HELO Pass Restriction allows integration with other Postfix access controls by provding a user supplied name of a postfix access restriction to be applied to a message when the HELO checking result is Pass. The indicated restriction must be an action as defined for a Postfix SMTP server access table access(5) and explained in the Postfix RESTRICTION CLASS README. The README.per_user_whitelisting file provided with this distribution provides examples. Note: A helo pass restriction will be the returned result even if the mail from result would cause the message to be rejected. Example: HELO_pass_restriction = helo_passed_spf Default: None .SH "Mail From CHECKING" .IX Header "Mail From CHECKING" Mail From rejection policy options are: SPF_Not_Pass - Reject if result not Pass/None/Tempfail. This option is not RFC 7208 compliant since the mail with an SPF Neutral result is treated differently than mail with no SPF record and Softfail results are not supposed to cause mail rejection. Global use of this option is not recommended. Use per-domain if needed (per-domain usage described below). Softfail - Reject on Mail From Softfail or Fail. Global use of this option is not recommended. Use per-domain if needed (per-domain usage described below). Fail (default) - Reject on Mail From Fail. False - Never reject on Mail From, append header only. This is useful for post-SMTP spam filters such as SpamAssassin. No_Check - Never check Mail From/Return Path. This is only recommended if you are calling the policy server twice (once for HELO checks and once for Mail From) with two different configuration files. This approach is useful to get both the HELO and Mail From headers prepended to a message. It could also be used to do HELO checking only (because HELO checking has a lower false positive risk than Mail From checking), but this approach may not be fully RFC 7208 compliant since the Mail From identity is mandatory if HELO checking does not reach a definitive result. Default: Mail_From_reject = Fail .SH "Mail From PASS RESTRICTION" .IX Header "Mail From PASS RESTRICTION" Mail From Pass Restriction allows integration with other Postfix access contlols by provding a user supplied name of a postfix access restriction to be applied to a message when the HELO checking result is Pass. The indicated restriction must be an action as defined for a Postfix SMTP server access table access(5) and explained in the Postfix RESTRICTION CLASS README. Note: A mail from pass restriction will be the returned result even if the helo result would cause the message to be rejected. Example: mail_from_pass_restriction = mfrom_passed_spf Default: None .SH "Limit Rejections To Domains That Send No Mail" .IX Header "Limit Rejections To Domains That Send No Mail" No_Mail - Only reject when SPF indicates the host/domain sends no mail. This option will only cause mail to be rejected if the HELO/Mail From record is "v=spf1 \-all". This option is useful for rejecting mail in situations where the tolerance for rejecting wanted mail is very low. It operates on both HELO and Mail From identities if set. Default: No_Mail = False .SH "Domain Specific Receiver Policy" .IX Header "Domain Specific Receiver Policy" Using this option, a list of domains can be defined for special processing when messages do not Pass SPF. This can be useful for commonly spoofed domains that are not yet publishing SPF records with \-all. Specifically, if mail from a domain in this list has a Neutral/Softfail result, it will be rejected (as if it had a Fail result). If needed, it is better to do it on a per-domain basis rather than globally. Example: Reject_Not_Pass_Domains = aol.com,hotmail.com Default: None .SH "Permanent Error Processing" .IX Header "Permanent Error Processing" Policy for rejecting due to SPF PermError options are: True - Reject the message if the SPF result (for HELO or Mail From) is PermError. This has a higher short-term false positive risk, but does result in senders getting feedback that they have a problem with their SPF record. False - Treat PermError the same as no SPF record at all. This is consistet with the pre-RFC usage (the pre-RFC name for this error was "Unknown"). This is a global option that affects both HELO and Mail From scopes when checks for that scope are enabled. The only per scope setting that can over-ride this is Mail_From/HELO_reject = False/ Default: PermError_reject = False .SH "Temporary Error Processing" .IX Header "Temporary Error Processing" Policy for deferring messages due to SPF TempError options are: True - Defer the message if the SPF result (for HELO or Mail From) is TempError. This is the traditional usage and has proven useful in reducing acceptance of unwanted messages. Sometimes spam senders do not retry. Sometimes by the time a message is retried the sending IP has made it onto a DNS RBL and can then be rejected. This is not the default because it is possible for some DNS errors that are classified as "Temporary" per RFC 7208 to be permanent in the sense that they require operator intervention to correct. This is a global option that affects both HELO and Mail From scopes when checks for that scope are enabled. The only per scope setting that can over-ride this is Mail_From/HELO_reject = False/ False - Treat TempError the same as no SPF record at all. This is the default to minimize false positive risk. Default: TempError_Defer = False .SH "Prospective SPF Check" .IX Header "Prospective SPF Check" Prospective SPF checking - Check to see if mail sent from the defined IP address would pass. This is useful for outbound MTAs to avoid sending mail that would Fail SPF checks when received. Disable HELO checking when using this option. It's only potentially useful for Mail From checking. SPF Received headers are not added when this option is used. Prospective = 192.168.0.4 Default: None .SH "LOCAL SPF BYPASS LIST" .IX Header "LOCAL SPF BYPASS LIST" Do not check SPF for localhost addresses - add to skip addresses to skip SPF for internal networks if desired. Defaults are standard IPv4 and IPv6 localhost addresses. This can also be used, to allow mail from local clients submitting mail to an MTA also acting as a Mail Submission Agent (MSA) to be skipped. An x-header is prepended indicating SPF checks were skipped due to a local address. This is a trace header only. Note the lack of spaces in the list. Default: skip_addresses = 127.0.0.0/8,::ffff:127.0.0.0/104,::1 .SH "SPF IP WHITELIST" .IX Header "SPF IP WHITELIST" A comma separated CIDR Notation list of IP addresses to skip SPF checks for. Use this list to whitelist trusted relays (such as a secondary MX and trusted forwarders). An x-header is prepended indicating the IP was whitelisted against SPF checks. This is a trace header only. Note the lack of spaces in the list. Example: Whitelist = 192.168.0.0/31,192.168.1.0/30 Default: None .SH "SPF DOMAIN WHITELIST" .IX Header "SPF DOMAIN WHITELIST" Domain_Whitelist: List of domains whose sending IPs should be whitelisted from SPF checks. Use this to list trusted forwarders by domain name. Client IP addresses are tested against SPF records published by the listed domains. This is useful for large forwarders with complex outbound infrastructures and SPF records. This option is less scalable than the SPF IP Whitelist. An x-header is prepended indicating the IP was whitelisted against SPF checks. This is a trace header only. This option does nothing if the domain does not have an SPF record. In this case use the SPF IP Whitelist described above or Domain_Whitelist_PTR (below). Note the lack of spaces in the list. Example: Domain_Whitelist = pobox.com,trustedforwarder.org Default: None .SH "PTR DOMAIN WHITELIST" .IX Header "PTR DOMAIN WHITELIST" Domain_Whitelist_PTR: List of domains (and subdomains) whose sending IPs should be whitelisted from SPF checks based on PTR match of the domain. Use this to list trusted forwarders by domain name if they do not publish SPF records. Client IP addresses PTR names are tested to see if they match the listed domains. This is useful for large forwarders with complex outbound infrastructures, but no SPF records and predictable host naming. Matching is done using the same rules as the SPF PTR mechanism as described in RFC 7208. List the parent domain and all subdomains will match. This option is less scalable than the SPF IP Whitelist. An x-header is prepended indicating the IP was whitelisted against SPF checks. This is a trace header only. This option does nothing if the host does not have a PTR record record. In this case use the SPF IP Whitelist described above. Note the lack of spaces in the list. Example: Domain_Whitelist_PTR = yahoo.com,yahoogroups.com Default: None .SH "RESULTS HEADER" .IX Header "RESULTS HEADER" The standard method for documenting SPF results in a message (for consumption by downstream processes) is the Received-SPF header defined in RFC 7208. This is the default header to use. Results can also be documented in the Authentication-Results header, which is also covered in RFC 7208. The default is Received-SPF (SPF), but inclusion of Authentication-Results (AR) headers as an alternative to Received-SPF can be specified. If there is a requirement to prepend both Received-SPF and Authentication- Results headers, then it must be done by processing the message with more than one instance of the policy server using different configuration files with different Header_Type settings. Examples: Header_Type = SPF or Header_Type = AR Default: SPF .SH "Authentications Results Authentication Identifier" .IX Header "Authentications Results Authentication Identifier" Every Authentication-Results header field has an authentication identifier field ('Authserv_Id'). This is similar in syntax to a fully-qualified domain name. See policyd-spf.conf.5 and RFC 7001 paragraph 2.4 for details. Default is None. Authserv-Id must be provided if Header_Type 'AR' is used. The authentication identifier field provides a unique identifier that refers to the authenticating service within a given administrative domain. The identifier MUST be unique to that domain. This identifier is intended to be machine-readable and not necessarily meaningful to users. Example: Authserv_Id = mx.example.com .SH "DNS Timeout Limit" .IX Header "DNS Timeout Limit RFC 7208 recommends an elapsed time limit for SPF checks of at least 20 seconds. Lookup_Time allows the maximum time (seconds) to be adjusted. 20 seconds is the default. Example: Lookup_Time = 20 Default 20 (seconds) .SH "DNS Void Lookup Limit" .IX Header "DNS Void Lookup Limit" RFC 7208 adds a new processing limit called "void lookup limit" (See section 4.6.4). Void lookups are DNS queries within an SPF record for which DNS queries return either a positive answer (RCODE 0) with an answer count of 0, or a "Name Error" (RCODE 3) answer. This should not need to be changed. Although new in an RFC in RFC 7208, this limit has been widely deployed in the Mail::SPF perl library without issue. Default is 2, but it can be adjusted. Only relevant for pyspf 2.0.9 and later. Ignored for earlier releases. Example: Void_Limit = 2 Default 2 .SH "SEE ALSO" .IX Header "SEE ALSO" man 1 policyd-spf, man 5 policyd-spf.peruser, python-spf, , RFC 7208, RFC 7001 .SH "AUTHORS" .IX Header "AUTHORS" This version of \fBpypolicyd-spf\fR was written by Copyright © 2007-2012, Scott Kitterman . It is derived from Tumgreyspf, written by Sean Reifschneider, tummy.com, ltd . Portions of the documentation were written by Meng Weng Wong . .PP This man-page was created by Scott Kitterman . pypolicyd-spf-1.3.2/policyd-spf.conf.commented0000664000175000017500000001055612343533115023064 0ustar kittermakitterma00000000000000# Amount of debugging information logged. 0 logs no debugging messages # 5 includes all debug messages. debugLevel = 1 # If set to 0, no messages are rejected by SPF. This allows you to see the # potential impact of SPF checking in your mail logs without rejecting mail. defaultSeedOnly = 1 # HELO check rejection policy. Options are: # HELO_reject = SPF_Not_Pass (default) - Reject if result not Pass/None/Tempfail. # HELO_reject = Softfail - Reject if result Softfail and Fail # HELO_reject = Fail - Reject on HELO Fail # HELO_reject = Null - Only reject HELO Fail for Null sender (SPF Classic) # HELO_reject = False - Never reject/defer on HELO, append header only. # HELO_reject = No_Check - Never check HELO. HELO_reject = SPF_Not_Pass # HELO pass restriction policy. # HELO_pass_restriction = helo_passed_spf - Apply the given restriction when # the HELO checking result is Pass. The given restriction must be an # action as defined for a Postfix SMTP server access table access(5). #HELO_pass_restriction # Mail From rejection policy. Options are: # Mail_From_reject = SPF_Not_Pass - Reject if result not Pass/None/Tempfail. # Mail_From_reject = Softfail - Reject if result Softfail and Fail # Mail_From_reject = Fail - Reject on Mail From Fail (default) # Mail_From_reject = False - Never reject/defer on Mail From, append header only # Mail_From_reject = No_Check - Never check Mail From/Return Path. Mail_From_reject = Fail # Reject only from domains that send no mail. Options are: # No_Mail = False - Normal SPF record processing (default) # No_Mail = True - Only reject for "v=spf1 -all" records # Mail From pass restriction policy. # Mail_From_pass_restriction = mfrom_passed_spf - Apply the given # restriction when the Mail From checking result is Pass. The given # restriction must be an action as defined for a Postfix SMTP server # access table access(5). #Mail_From_pass_restriction # Reject mail for Netural/Softfail results for these domains. # Recevier policy option to reject mail from certain domains when SPF is not # Pass/None even if their SPF record does not produce a Fail result. This # Option does not change the effect of PermError_reject or TempError_Defer # Reject_Not_Pass_Domains = aol.com,hotmail.com # Policy for rejecting due to SPF PermError. Options are: # PermError_reject = True # PermError_reject = False PermError_reject = False # Policy for deferring messages due to SPF TempError. Options are: # TempError_Defer = True # TempError_Defer = False TempError_Defer = False # Prospective SPF checking - Check to see if mail sent from the defined IP # address would pass. # Prospective = 192.168.0.4 # Do not check SPF for localhost addresses - add to skip addresses to # skip SPF for internal networks if desired. Defaults are standard IPv4 and # IPv6 localhost addresses. skip_addresses = 127.0.0.0/8,::ffff:127.0.0.0/104,::1 # Whitelist: CIDR Notation list of IP addresses not to check SPF for. # Example (default is no whitelist): # Whitelist = 192.168.0.0/31,192.168.1.12 # Domain_Whitelist: List of domains whose sending IPs (defined by passing # their SPF check should be whitelisted from SPF. # Example (default is no domain whitelist): # Domain_Whitelist = pobox.com,trustedforwarder.org # Domain_Whitelist_PTR: List of domains to whitelist against SPF checks base # on PTR match. # Example (default is no PTR whitelist) # Domain_Whitelist_PTR = yahoo.com # Type of header to insert to document SPF result. Can be Received-SPF (SPF) # or Authentication Results (AR). It cannot be both. # Examples: (default is Received-SPF): # Header_Type = AR # Header_Type = SPF # Every Authentication-Results header field has an authentication identifier # field ('Authserv_Id'). This is similar in syntax to a fully-qualified domain # name. See policyd-spf.conf.5 and RFC 7001 paragraph 2.4 for details. # Default is None. Authserv-Id must be provided if Header_Type 'AR' is used. # Authserv_Id = mx.example.com # RFC 7208 recommends an elapsed time limit for SPF checks of at least 20 # seconds. Lookup_Time allows the maximum time (seconds) to be adjusted. 20 # seconds is the default. # Lookup_Time = 20 # RFC 7208 adds a new processing limit called "void lookup limit" (See section # 4.6.4). Default is 2, but it can be adjusted. Only relevant for pyspf # 2.0.9 and later. Ignored for earlier releases. # Void_Limit = 2 pypolicyd-spf-1.3.2/PKG-INFO0000664000175000017500000000147412563005271017107 0ustar kittermakitterma00000000000000Metadata-Version: 1.1 Name: pypolicyd-spf Version: 1.3.2 Summary: pypolicyd-spf SPF Postfix policy server implemented in Python. Home-page: https://launchpad.net/pypolicyd-spf Author: Scott Kitterman Author-email: scott@kitterman.com License: UNKNOWN Description: UNKNOWN Keywords: Postfix,spf,email Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: No Input/Output (Daemon) Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Natural Language :: English Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications :: Email :: Mail Transport Agents Classifier: Topic :: Communications :: Email :: Filters pypolicyd-spf-1.3.2/policydspfuser.py0000664000175000017500000000761312562720035021441 0ustar kittermakitterma00000000000000# -*- coding: utf-8 -*- # # pypolicyd-spf # Copyright © 2010-2012 Scott Kitterman ''' 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. ''' import syslog import re import os ############################################################### commentRx = re.compile(r'^(.*)#.*$') def _readUserConfigFile(path, recipient, configData): '''Reads a configuration file from the specified path, merging it with the configuration data specified in configData for the identified recipient. Returns updated configData for the user.''' debugLevel = configData.get('debugLevel', 0) if debugLevel >= 4: syslog.syslog('readUserConfigFile: Loading "%s"' % path) if configData == None: configData = {} nameConversion = { 'debugLevel' : int, 'HELO_reject' : str, 'Mail_From_reject' : str, 'PermError_reject' : str, 'TempError_Defer' : str, 'Mail_From_pass_restriction' : str, 'HELO_pass_restriction' : str, 'Prospective' : str, 'Whitelist' : str, 'skip_addresses': str, 'Domain_Whitelist' : str, 'Domain_Whitelist_PTR': str, 'No_Mail': str, 'Reject_Not_Pass_Domains' : str, 'defaultSeedOnly' : int, 'Header_Type' : str, 'Authserv-Id' : str, 'Lookup_Time' : int, 'Void_Limit' : int } # check to see if it's a file try: os.stat(path)[0] except OSError as e: syslog.syslog(syslog.LOG_ERR,'ERROR stating "%s": %s' % ( path, e.strerror )) return(configData, False) # load file fp = open(path, 'r') while 1: line = fp.readline() if not line: break # parse line line = (line.split('#', 1)[0]).strip() if not line: continue data = [q.strip() for q in line.split(',', 1)] user, value = data if user != recipient: peruser = False continue values = {} valuelist = value.split('|') for valuepair in valuelist: key, item = valuepair.split('=') values[key] = item for config in values.items(): # check validity of name conversion = nameConversion.get(config[0]) name, value = config if conversion == None: syslog.syslog(syslog.LOG_ERR,'ERROR: Unknown name "%s" in file "%s"' % ( name, path )) continue if debugLevel >= 5: syslog.syslog('readUserConfigFile: Found entry "%s=%s"' % ( name, value )) configData[name] = conversion(value) peruser = True fp.close() return configData, peruser def _datacheck(configData, recipient): debugLevel = configData.get('debugLevel', 1) if debugLevel >= 3: syslog.syslog('Starting to process per-user settings') userdata = configData.get('Per_User') if debugLevel >= 3: syslog.syslog('User data: '+ str(userdata)) usertype, userlocation = userdata.split(',') if usertype == "text": if debugLevel >= 4: syslog.syslog('Reading per user data (type text) from: "%s"' % userlocation) configData, peruser = _readUserConfigFile(userlocation, recipient, configData) if debugLevel >= 4: syslog.syslog('Per-user settings for "%s": "%s"' % (recipient, str(configData))) return configData, peruser pypolicyd-spf-1.3.2/policyd-spf.conf0000664000175000017500000000041612343533115021104 0ustar kittermakitterma00000000000000# For a fully commented sample config file see policyd-spf.conf.commented debugLevel = 1 defaultSeedOnly = 1 HELO_reject = SPF_Not_Pass Mail_From_reject = Fail PermError_reject = False TempError_Defer = False skip_addresses = 127.0.0.0/8,::ffff:127.0.0.0/104,::1