This file is indexed.

/usr/bin/policyd-spf is in postfix-policyd-spf-python 2.0.2-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
#!/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.
#  <jafo@tummy.com>
#
#  pypolicyd-spf
#  Copyright © 2007-16, Scott Kitterman <scott@kitterman.com>
'''
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
'''

__version__ = "2.0.2"
__date__ = "2017-12-14"

testing = True

import syslog
import os
import sys
import re
import socket
import ipaddress # needs python3.3, python2 backport doesn't work
# import random - Only needed for testing, so imported in line if needed.

import spf
# import authres - not needed in default configuration, imported if needed in
# main program loop.

import policydspfsupp
# import policydspfuser - Only imported if per-user settings are activated for
# efficiency.

if int(sys.version_info.major) < 3 or (int(sys.version_info.major) == 3 and \
    int(sys.version_info.minor) < 3):
    raise ImportError("Python 3.3 or later is required")
maj, minor, micro = spf.__version__.split(':')[0].split('.')
if int(micro) < 9:
    raise ImportError("At least pyspf 2.0.9 is required.")

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."""

    address = ipaddress.ip_address(ip)
    try:
        network = ipaddress.IPv4Network(netwrk)
    except ipaddress.AddressValueError:
        network = ipaddress.IPv6Network(netwrk)
    return network.__contains__(address)

def _ipmatch(ip1, ip2):
    """Non-string matching of two IP addresses"""
    addr1 = ipaddress.ip_address(ip1)
    addr2 = ipaddress.ip_address(ip2)
    if addr1 == addr2:
        return True
    else:
        return False

def _get_rdns_lookup(ip):
    address = ipaddress.ip_address(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 debugLevel >= 5: syslog.syslog('_get_resultcodes: scope: {0}, Reject_Not_Pass_Domains: {1}, helo_policy: {2}, mfrom_policy: {3}'.format(scope, configData.get('Reject_Not_Pass_Domains'), configData.get('HELO_reject'),configData.get('Mail_From_reject')))
    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 debugLevel >= 5: syslog.syslog('Scope helo unused results: {0}'.format(unused_results))
    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 debugLevel >= 5: syslog.syslog('Scope mfrom unused results: {0}'.format(unused_results))

    if (helo_policy == 'False' and scope == 'helo') or (mfrom_policy == 'False' and scope == 'mfrom'):
        for result in unused_results:
            actions['prepend'].append(result)
        if debugLevel >= 5: syslog.syslog('{0} policy false results: actions: {1} local {2}'.format(scope,actions,local))
        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)
    if debugLevel >= 5: syslog.syslog('{0} policy true results: actions: {1} local {2}'.format(scope,actions,local))
    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(',')
        if check_type == 'skip_addresses' or check_type == 'Whitelist':
            if debugLevel >= 4: syslog.syslog ("{0} enabled.".format(check_type))
            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 'AR' in configData.get('Header_Type'):
                            try:
                                Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'),
                                    results = [authres.NoneAuthenticationResult(comment = \
                                    '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\
                                        data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'))
                                        )]))
                            except TypeError as x:
                                if str(x).startswith('sequence item 2'):
                                    if debugLevel >= 0:  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.')
                        else:
                            Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                                % ( data.get('client_address', '<UNKNOWN>'),
                                    data.get('helo_name', '<UNKNOWN>'),
                                    data.get('sender', '<UNKNOWN>'),
                                    data.get('recipient', '<UNKNOWN>'),
                                    ))
                        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 >= 0: syslog.syslog(Message)
                    return (False, 'None')
            return (False, 'None')
        if check_type == 'Domain_Whitelist':
            if debugLevel >= 4: syslog.syslog ("Domain Whitelist enabled.")
            for domain in bypass_list_list:
                res = spf.check2(ip, domain, domain, querytime=configData.get('Whitelist_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 'AR' in configData.get('Header_Type'):
                        try:
                            Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'),
                                results = [authres.NoneAuthenticationResult(comment = \
                                '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\
                                    data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'))
                                    )]))
                        except TypeError as x:
                            if str(x).startswith('sequence item 2'):
                                if debugLevel >= 0: 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.')
                    else:
                        Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                            % ( data.get('client_address', '<UNKNOWN>'),
                                data.get('helo_name', '<UNKNOWN>'),
                                data.get('sender', '<UNKNOWN>'),
                                data.get('recipient', '<UNKNOWN>'),
                                ))
                    if debugLevel >= 3: syslog.syslog(Header)
                    return (True, Header)
            return (False, 'None')
        if 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', timeout=configData.get('Whitelist_Lookup_Time'))
                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 'AR' in configData.get('Header_Type'):
                            try:
                                Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'),
                                    results = [authres.NoneAuthenticationResult(comment = \
                                    '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\
                                        data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'))
                                        )]))
                            except TypeError as x:
                                if str(x).startswith('sequence item 2'):
                                    if debugLevel >= 0: 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.')
                        else:
                            Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                                % ( data.get('client_address', '<UNKNOWN>'),
                                    data.get('helo_name', '<UNKNOWN>'),
                                    data.get('sender', '<UNKNOWN>'),
                                    data.get('recipient', '<UNKNOWN>'),
                                    ))
                        if debugLevel >= 3: syslog.syslog(Header)
                        return (True, Header)
            return (False, 'None')
        if check_type == 'HELO_Whitelist':
            if debugLevel >= 4: syslog.syslog ("HELO Domain Whitelist enabled.")
            # Collect the IP addresses from the A/AAAA records of all HELO_Whitelist domains
            connectip = ipaddress.ip_address(ip)
            answerlist = []
            for domain in bypass_list_list:
                if domain == data.get('helo_name'):
                    try:
                        if debugLevel >= 5: syslog.syslog ("HELO Domain Whitelist domain match: {0}.".format(domain))
                        if isinstance(connectip,ipaddress.IPv4Address):
                            if debugLevel >= 5: syslog.syslog ("HELO Domain Whitelist domain: {0} is IPv4: {1}.".format(domain,connectip))
                            # DNS A lookup for IPv4 first: If A doesn't match connect IP, then skip
                            DNSAResults = spf.DNSLookup (domain, 'a', timeout=configData.get('Whitelist_Lookup_Time'))
                            if (len (DNSAResults) > 0):
                                for answer in DNSAResults:
                                    answerlist.append(answer[1])
                        if isinstance(connectip,ipaddress.IPv6Address):
                            if debugLevel >= 5: syslog.syslog ("HELO Domain Whitelist domain: {0} is IPv6: {1}.".format(domain,connectip))
                            # DNS AAAA lookup for IPv6
                            DNSAAAAResults = spf.DNSLookup (domain, 'aaaa', timeout=configData.get('Whitelist_Lookup_Time'))
                            if (len (DNSAAAAResults) > 0):
                                for answer in DNSAAAAResults:
                                    answerlist.append(answer[1])
                    except spf.TempError as e:
                        # DNS timeout - continue with the base SPF check.
                        pass
            if (answerlist is not None):
                for ipans in answerlist:
                    if _ipmatch(ipans,ip):
                        comment = 'SPF skipped for whitelisted HELO domain - '
                        if 'AR' in configData.get('Header_Type'):
                            try:
                                Header = str(authres.AuthenticationResultsHeader(authserv_id = configData.get('Authserv_Id'),
                                    results = [authres.NoneAuthenticationResult(comment = \
                                    '{0} client-ip={1}; helo={2}; envelope-from={3}; receiver={4}'.format(comment, data.get('client_address', '<UNKNOWN>'),\
                                        data.get('helo_name', '<UNKNOWN>'), data.get('sender', '<UNKNOWN>'), data.get('recipient', '<UNKNOWN>'))
                                        )]))
                            except TypeError as x:
                                if str(x).startswith('sequence item 2'):
                                    syslog.syslog(syslog.LOG_ERR, 'Authserv_Id not set for authentication results header - invalid configuration.')
                                    raise SyntaxError('Authserv_Id not set for authentication results header - invalid configuration.')
                        else:
                            Header = ('X-Comment: ' + comment + 'client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                                % ( data.get('client_address', '<UNKNOWN>'),
                                    data.get('helo_name', '<UNKNOWN>'),
                                    data.get('sender', '<UNKNOWN>'),
                                    data.get('recipient', '<UNKNOWN>'),
                                    ))
                        if debugLevel >= 3: syslog.syslog(Header)
                        return (True, Header)
            return (False, 'None')
#############################################
def _rejectmessage(result, type, info, ip, recipient):
    if result[3] == 'reject':
        rejectdefer = "rejected"
    elif result[3] == 'defer':
        rejectdefer = "deferred"
    url = ("http://www.openspf.net/Why?s={0};id={1};ip={2};r={3}"
              .format(type, info, ip, recipient))
    msg = configData.get('Reason_Message')
    return msg.format(
            rejectdefer=rejectdefer,
            spf=result[1],
            url=url,
    )

#############################################
def _spfcheck(data, instance_dict, configData, peruser, peruserconfigData):  #{{{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, None))
    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[5] != 'prepend':
            last_action = found_instance[3]
        else:
            last_action = found_instance[5]
    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] 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 peruser:
        # Do not check SPF for localhost addresses
        if not peruser:
            skip_check = _spfbypass(data, 'skip_addresses', configData)
        else:
            skip_check = _spfbypass(data, 'skip_addresses', peruserconfigData)
            if debugLevel >= 4: syslog.syslog('skip_addresses check used peruser data')
        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('prepend')
                if not found_instance and not peruser:
                    instance_dict[instance] = skip_data
                return (('prepend', skip_check[1], instance_dict, None))
            else:
                return(( 'dunno', 'Header already pre-pended', instance_dict, None))
        # Whitelist designated IP addresses from SPF checks (e.g. secondary MX or 
        # known forwarders.
        if not peruser:
            ip_whitelist = _spfbypass(data, 'Whitelist', configData)
        else:
            ip_whitelist = _spfbypass(data, 'Whitelist', peruserconfigData)
            if debugLevel >= 4: syslog.syslog('Whitelist check used peruser data')
        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('prepend')
                    if not found_instance and not peruser:
                        instance_dict[instance] = skip_data
                if last_action != 'prepend':
                    return (('prepend', ip_whitelist[1], instance_dict, None))
                else:
                    return(( 'dunno', 'Header already pre-pended', instance_dict, None))
        # Whitelist designated Domain's sending addresses from SPF checks (e.g. 
        # known forwarders.
        if not peruser:
            domain_whitelist = _spfbypass(data, 'Domain_Whitelist', configData)
        else:
            domain_whitelist = _spfbypass(data, 'Domain_Whitelist', peruserconfigData)
            if debugLevel >= 4: syslog.syslog('Domain_Whitelist check used peruser data')
        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('prepend')
                    if not found_instance and not peruser:
                        instance_dict[instance] = skip_data
                if last_action != 'prepend':
                    return (('prepend', domain_whitelist[1], instance_dict, None))
                else:
                    return(( 'dunno', 'Header already pre-pended', instance_dict, None))
        # Whitelist designated HELO/EHLO Domain's sending addresses from SPF
        # checks (e.g. known forwarders and hosts with broken SPF records).
        if not peruser:
            helo_whitelist = _spfbypass(data, 'HELO_Whitelist', configData)
        else:
            helo_whitelist = _spfbypass(data, 'HELO_Whitelist', peruserconfigData)
            if debugLevel >= 4: syslog.syslog('HELO_Whitelist check used peruser data')
        if helo_whitelist:
            if helo_whitelist[0]:
                skip_data = ["N/A", "Skip SPF checks for whitelisted HELO/EHLO names", "N/A", "prepend", skip_check[1]]
                if last_action != 'prepend':
                    skip_data.append('prepend')
                    if not found_instance and not peruser:
                        instance_dict[instance] = skip_data
                if last_action != 'prepend':
                    return (('prepend', helo_whitelist[1], instance_dict, None))
                else:
                    return(( 'dunno', 'Header already pre-pended', instance_dict, None))
        # Whitelist designated Domain's sending addresses from SPF checks (e.g.
        # known forwarders, but based on PTR match
        if not peruser:
            domain_whitelist = _spfbypass(data, 'Domain_Whitelist_PTR', configData)
        else:
            domain_whitelist = _spfbypass(data, 'Domain_Whitelist_PTR', peruserconfigData)
        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('prepend')
                    if not found_instance and not peruser:
                        instance_dict[instance] = skip_data
                if last_action != 'prepend':
                    return (('prepend', domain_whitelist[1], instance_dict, None))
                else:
                    return(( 'dunno', 'Header already pre-pended', instance_dict, None))
        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, None))
        if not peruser:
            Mail_From_pass_restriction = configData.get('Mail_From_pass_restriction')
            HELO_pass_restriction = configData.get('HELO_pass_restriction')
            HELO_reject = configData.get('HELO_reject')
            Mail_From_reject = configData.get('Mail_From_reject')
            if configData.get('No_Mail') == 'True':
                No_Mail = True
            else: No_Mail = False
        else:
            Mail_From_pass_restriction = peruserconfigData.get('Mail_From_pass_restriction')
            HELO_pass_restriction = peruserconfigData.get('HELO_pass_restriction')
            HELO_reject = peruserconfigData.get('HELO_reject')
            Mail_From_reject = peruserconfigData.get('Mail_From_reject')
            if peruserconfigData.get('No_Mail') == 'True':
                No_Mail = True
            else: No_Mail = False
        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]
        if HELO_reject != 'No_Check':
            helo_fake_sender = 'postmaster@' + helo
            heloquery = spf.query(i=ip, s=helo_fake_sender, h=helo, querytime=configData.get('Lookup_Time'))
            res = heloquery.check()
            helo_result = [res[0], res[2]]
            helo_result.append('helo') 
            helo_result[0] = helo_result[0].lower()
            helo_result[0] = helo_result[0].capitalize()
            if (helo_result[0] == 'Permerror') or (helo_result[0] == 'Temperror'):
                isheloerror = True
            else:
                isheloerror = False
            if not peruser:
                helo_resultpolicy, local = _get_resultcodes(configData, 'helo')
            else:
                helo_resultpolicy, local = _get_resultcodes(peruserconfigData, 'helo')
            if debugLevel >= 2:
                syslog.syslog('spfcheck: pyspf result: "%s"' % str(helo_result))
            if 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[2] = 'Receiver policy for SPF ' + helo_result[0]
            if sender == '':
                header_sender = '<>'
            else:
                header_sender = sender
            if helo_result[0] == 'None':
                helo_result[2] = "no SPF record"
            spfDetail = ('identity=%s; client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                % (helo_result[2], ip, helo, header_sender, data.get('recipient', '<UNKNOWN>')))
            if debugLevel >= 2:
                logdata = str(helo_result[0]) + "; " + spfDetail
                syslog.syslog(logdata)
            header = ''
            if 'SPF' in configData.get('Header_Type') and 'AR' in configData.get('Header_Type'):
                if debugLevel >= 0: 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 '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 = configData.get('Authserv_Id'),
                    results = [authres.SPFAuthenticationResult(result = helo_result[0],
                    result_comment = helo_result[2],
                    smtp_helo = helo, smtp_helo_comment =
                    'client-ip={0}; helo={1}; envelope-from={2}; receiver={3}'.format(ip, helo, header_sender, data.get('recipient', '<UNKNOWN>')))]))
            else:
                header = 'Received-SPF: '+ helo_result[0] + ' (' + helo_result[2] +') ' + spfDetail
            if helo_result[3] != 'reject' and helo_result[3] != 'defer':
                helo_result.append(header)
                helo_result.append(helo_result[3])
                if HELO_pass_restriction and helo_result[0] == 'Pass':
                    restrict_name = HELO_pass_restriction
                    helo_result[3] = 'result_only'
                    helo_result[4] = restrict_name
                    helo_result[5] = 'restriction'
                if not peruser:
                    instance_dict[instance] = helo_result
            # Only act on the HELO result if it is authoritative.
            else:
                if helo_result[3] == 'reject':
                    if No_Mail:
                        # If only rejecting on "v=spf1 -all", we need to know now
                        if debugLevel >= 5: syslog.syslog('Pyspf Cached SPF record before HELO No_Mail check: {0}'.format(str(heloquery.cache[helo, 'TXT'][0][0])))
                        record = str(heloquery.cache[helo, 'TXT'][0][0])
                        if record != str("b'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, None))
                if helo_result[3] in ('reject', 'defer'): # It may not be reject anymore
                    header = _rejectmessage(helo_result, 'helo', helo, ip, data.get('recipient'))
                    helo_result.append(header)
                    helo_result.append(helo_result[3])
                    if not peruser:
                        instance_dict[instance] = helo_result
                    return((helo_result[3], header, instance_dict, isheloerror ))
        # Second do Mail From Check
        if sender == '':
            if HELO_reject != 'No_Check':
                helo_result.append(header)
                helo_result.append(helo_result[3])
                if HELO_pass_restriction and helo_result[0] == 'Pass':
                    restrict_name = HELO_pass_restriction
                    helo_result[3] = 'result_only'
                    helo_result[4] = restrict_name
                    helo_result[5] = 'restriction'
                    if not peruser:
                        instance_dict[instance] = helo_result
                    return('result_only', restrict_name, instance_dict, None)
                if not peruser:
                    instance_dict[instance] = helo_result
                return(( helo_result[3], header, instance_dict, isheloerror ))
        else:
            if Mail_From_reject != 'No_Check':
                mfromquery = spf.query(i=ip, s=sender, h=helo, querytime=configData.get('Lookup_Time'))
                mres = mfromquery.check()
                mfrom_result = [mres[0], mres[2]]
                mfrom_result.append('mailfrom')
                mfrom_result[0] = mfrom_result[0].lower()
                mfrom_result[0] = mfrom_result[0].capitalize()
                if (mfrom_result[0] == 'Permerror') or (mfrom_result[0] == 'Temperror'):
                    ismfromerror = True
                else:
                    ismfromerror = False
                if not peruser:
                    mfrom_resultpolicy, local = _get_resultcodes(configData, 'mfrom')
                else:
                    mfrom_resultpolicy, local = _get_resultcodes(peruserconfigData, '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)
                if local['local_mfrom']:
                    mfrom_result[1] = 'Receiver policy for SPF ' + mfrom_result[0]
                if mfrom_result[0] == 'None':
                    mfrom_result[1] = 'no SPF record'
                if mfrom_result[0] != 'None' or (mfrom_result[0] == 'None' and helo_result[0] == 'None'):
                    spfDetail = \
                        ('identity=%s; client-ip=%s; helo=%s; envelope-from=%s; receiver=%s '
                        % (mfrom_result[2], ip, helo, sender, data.get('recipient', '<UNKNOWN>')))
                    if debugLevel >= 2:
                        logdata = str(mfrom_result[0]) + "; " + spfDetail
                        syslog.syslog(logdata)
                    header = ''
                    if 'SPF' in configData.get('Header_Type') and 'AR' in configData.get('Header_Type'):
                        if debugLevel >= 0: 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 '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 = configData.get('Authserv_Id'),
                            results = [authres.SPFAuthenticationResult(result = mfrom_result[0],
                            result_comment = mfrom_result[2],
                            smtp_mailfrom = spf.split_email(sender,'example.com')[1], smtp_mailfrom_comment =
                            'client-ip={0}; helo={1}; envelope-from={2}; receiver={3}'.format(ip, helo, sender, data.get('recipient', '<UNKNOWN>')))]))
                    else:
                        header = 'Received-SPF: '+ mfrom_result[0] + ' (' + mfrom_result[2] +') ' + spfDetail
                    if mfrom_result[3] != 'reject' and mfrom_result[3] != 'defer':
                        mfrom_result.append(header)
                        mfrom_result.append(mfrom_result[3])
                        if not peruser:
                            if debugLevel >= 4:syslog.syslog('not peruser')
                            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
                        mfrom_result[3] = 'result_only'
                        mfrom_result[4] = restrict_name
                        mfrom_result[5] = 'restriction'
                        if not peruser:
                            instance_dict[instance] = mfrom_result
                    return('result_only', restrict_name, instance_dict, None)
                # Act on the Mail From result if it is authoritative.
                if mfrom_result[3] == 'reject' or mfrom_result[3] == 'defer':
                    if mfrom_result[3] == 'reject':
                        if No_Mail:
                            # If only rejecting on "v=spf1 -all", we need to know now
                            senderdomain = sender.split('@')[1]
                            if debugLevel >= 5: syslog.syslog('Pyspf Cached SPF record before mfrom No_Mail check: {0}'.format(str(mfromquery.cache[senderdomain, 'TXT'][0][0])))
                            mrecord = str(mfromquery.cache[senderdomain, 'TXT'][0][0])
                            if mrecord != str("b'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, None ))
                    if mfrom_result[3] in ('reject', 'defer'): # It may not be reject anymore
                        header = _rejectmessage(mfrom_result, 'mfrom', sender, ip, data.get('recipient'))
                        mfrom_result.append(header)
                        mfrom_result.append(mfrom_result[3])
                        if not peruser:
                            instance_dict[instance] = mfrom_result
                        return(( mfrom_result[3], header, instance_dict, ismfromerror ))
                if mfrom_result[3] != 'dunno' or helo_result[3] == 'dunno':
                    if last_action != 'prepend':
                        return(( 'prepend', header, instance_dict, None ))
                    else:
                        return(( 'dunno', 'Header already pre-pended', instance_dict, None ))
            else:
                if HELO_reject != 'No_Check':
                    if helo_result[3] == 'reject':
                        if No_Mail:
                            # If only rejecting on "v=spf1 -all", we need to know now
                            if debugLevel >= 5: syslog.syslog('Pyspf Cached SPF record before HELO No_Mail check: {0}'.format(str(heloquery.cache[helo, 'TXT'][0][0])))
                            record = str(heloquery.cache[helo, 'TXT'][0][0])
                            if record != str("b'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, None ))
                    if helo_result[3] in ('reject', 'defer'): # It may not anymore
                        header = _rejectmessage(helo_result, 'helo', helo, ip, data.get('recipient'))
                        if helo_result[3] == 'reject': # It may not anymore
                            return(( 'reject', header, instance_dict, isheloerror ))
                        if helo_result[3] == 'defer':
                            return(( 'defer', header, instance_dict, isheloerror ))
                    if last_action != 'prepend':
                        return(( 'prepend', header, instance_dict, None ))
                    else:
                        return(( 'dunno', 'Header already pre-pended', instance_dict, None ))
    else:
        cached_instance = instance_dict[instance]
        if cached_instance[3] == 'prepend':
            return(( 'dunno', 'Header already pre-pended', instance_dict, None ))
        else:
            return(( cached_instance[3], cached_instance[4], instance_dict, None ))
    return(( 'None', 'None', instance_dict, None ))

###################################################
#  load config file  {{{1
#  Default location:
configFile = '/etc/postfix-policyd-spf-python/policyd-spf.conf'
if len(sys.argv) > 1:
    if sys.argv[1] in ( '-?', '--help', '-h' ):
        print('usage: policyd-spf [<configfilename>]')
        sys.exit(1)
    configFile = sys.argv[1]

configGlobal = policydspfsupp._processConfigFile(filename = configFile)

if configGlobal.get('Header_Type') == 'AR':
    try:
        import authres
    except ImportError:
        syslog.syslog(syslog.LOG_ERR,'ERROR: Configured for Authentication Results header type, but authres module missing')
        raise ImportError("Configured for Authentication Results, but authres missing..")

#  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
    lineraw = sys.stdin.buffer.readline()
    line = lineraw.decode('UTF-8',errors='replace')
    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
        peruserconfigData = []
        rejectAction = ''
        deferAction = ''
        if debugLevel >= 4: syslog.syslog('Found the end of entry')
        configData = dict(list(configGlobal.items()))
        if configData.get('defaultSeedOnly') is not None:
            syslog.syslog(syslog.LOG_ERR,'WARNING: Deprecated Config Option defaultSeedOnly in use in: {0}'.format(configFile ))

        if configData.get('Authserv_Id') == 'HOSTNAME':
                configData['Authserv_Id'] = socket.gethostname()
        if configData.get('Mock'):
            sys.stdout.write('action=dunno mock header field that should be ignored\n\n')
            continue
        if not data.get('recipient'):
            data['recipient'] = 'none'
        if configData.get('Per_User'):
            import policydspfuser
            peruserconfigData, 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 configData.get('Hide_Receiver') != 'No':
            data['recipient'] = '<UNKNOWN>'
        if not peruser:
            Void_Limit = configData.get('Void_Limit')
        else:
            Void_Limit = peruserconfigData.get('Void_Limit')
        spf.MAX_VOID_LOOKUPS = Void_Limit
        if debugLevel >= 3: syslog.syslog('Config: %s' % str(configData))
        #  run the checkers  {{{3
        checkerValue = None
        checkerReason = None
        checkerValue, checkerReason, instance_dict, iserror = _spfcheck(data, 
                    instance_dict, configData, peruser, peruserconfigData)

        if not peruser:
            TestOnly = configData.get('defaultSeedOnly')
            TestOnly = configData.get('TestOnly')
        else:
            TestOnly = peruserconfigData.get('defaultSeedOnly')
            TestOnly = peruserconfigData.get('TestOnly')
        if TestOnly == 0 and checkerValue != 'prepend':
            checkerValue = None
            checkerReason = None

        if configData.get('SPF_Enhanced_Status_Codes') == 'No':
            rejectAction = '550'
            deferAction = 'defer_if_permit'
        else:
            if iserror:
                rejectAction = '550 5.7.24'
                deferAction = 'defer_if_permit 4.7.24'
            else:
                rejectAction = '550 5.7.23'
                deferAction = 'defer_if_permit 4.7.24'

        #  handle results  {{{3
        if debugLevel >= 3: syslog.syslog('Action: {0}: Text: {1} Reject action: {2}'.format(checkerValue, checkerReason, rejectAction))
        if checkerValue == 'reject':
            if debugLevel >= 1: syslog.syslog('{0} {1}'.format(rejectAction, checkerReason))
            sys.stdout.write('action={0} {1}\n\n'.format(rejectAction, checkerReason))

        elif checkerValue == 'prepend':
            if configData.get('Prospective'):
                sys.stdout.write('action=dunno\n\n')
            else:
                if configData.get('Header_Type') != 'None':
                    if debugLevel >= 1: syslog.syslog('prepend {0}'.format(checkerReason))
                    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("'"))
                else:
                    if debugLevel >= 1: syslog.syslog('Header field not prepended: {0}'.format(checkerReason))
                    sys.stdout.write('action=dunno\n\n')

        elif checkerValue == 'defer':
            if debugLevel >= 1: syslog.syslog('{0} {1}'.format(deferAction, checkerReason))
            try:
                sys.stdout.write('action={0} {1}\n\n'.format(deferAction, checkerReason))
            except UnicodeEncodeError:
                sys.stdout.write('action={0} {1}\n\n'.format(deferAction, 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':
            if debugLevel >= 1: syslog.syslog('result_only {0}'.format(checkerReason))
            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: 
        if debugLevel >= 0: 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')