-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbms.py
2481 lines (2337 loc) · 91.7 KB
/
bms.py
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
from __future__ import print_function
# A simple milter that has grown quite a bit.
#
# See ChangeLog
#
# Author: Stuart D. Gathman <[email protected]>
# Copyright 2001,2002,2003,2004,2005-2013 Business Management Systems, Inc.
# Copyright 2013-2015 Stuart D. Gathman
# This code is under the GNU General Public License. See COPYING for details.
import sys
import os
import os.path
import ipaddress
try:
from io import BytesIO
from email import errors
from email.message import Message
from email.utils import getaddresses
except:
from StringIO import StringIO as BytesIO
from email import Errors as errors
from email.Message import Message
from email.Utils import getaddresses
import mime
import Milter
import tempfile
import time
import socket
import re
import shutil
import gc
import smtplib
import urllib
import Milter.dsn as dsn
from Milter.dynip import is_dynip as dynip
from Milter.utils import \
iniplist,parse_addr,parse_header,ip4re,addr2bin,parseaddr
from Milter.config import MilterConfigParser
from Milter.greysql import Greylist
from Milter.policy import MTAPolicy
from fnmatch import fnmatchcase
from glob import glob
# Import gossip if available
try:
import gossip
import gossip.client
import gossip.server
gossip_node = None
except: gossip = None
# Import pysrs if available
try:
import SRS
srsre = re.compile(r'^SRS[01][+-=]',re.IGNORECASE)
except: SRS = None
try:
import SES
except: SES = None
# Import spf if available
try: import spf
except: spf = None
# Import dkim if available
try: import dkim
except: dkim = None
# Import authres if available
try: import authres
except: authres = None
# Sometimes, MTAs reply to our DSN. We recognize this type of reply/DSN
# and check for the original recipient SRS encoded in Message-ID.
# If found, we blacklist that recipient.
_subjpats = (
r'^failure notice',
r'^subjectbounce',
r'^returned mail',
r'^undeliver',
r'\bdelivery\b.*\bfail',
r'\bdelivery problem',
r'\bnot\s+be\s+delivered',
r'\buser unknown\b',
r'^failed', r'^mail failed',
r'^echec de distribution',
r'\berror\s+sending\b',
r'^fallo en la entrega',
r'\bfehlgeschlagen\b'
)
refaildsn = re.compile('|'.join(_subjpats),re.IGNORECASE)
# We don't want to whitelist recipients of Autoreplys and other robots.
# There doesn't seem to be a foolproof way to recognize these, so
# we use this heuristic. The worst that can happen is someone won't get
# whitelisted when they should, or we'll whitelist some spammer for a while.
_autopats = (
r'^read:',
r'\bautoreply:\b',
r'^return receipt',
r'^Your message\b.*\bawaits moderator approval'
)
reautoreply = re.compile('|'.join(_autopats),re.IGNORECASE)
import logging
# Thanks to Chris Liechti for config parsing suggestions
class Config(object):
def __init__(self):
## True if greylisting is activated
self.greylist = False
## List email providers which should have mailboxes banned, not domain.
self.email_providers = (
'yahoo.com','gmail.com','aol.com','hotmail.com','me.com',
'googlegroups.com', 'att.net', 'nokiamail.com'
)
self.access_file = None
self.access_file_nulls = False
self.access_file_colon = True
## List of executable extensions to be removed from incoming emails
# Executable email attachments is the most common Windows malware
# vector in my experience.
self.banned_exts = mime.extlist.split(',')
## Remove scripts from HTML attachments
self.scan_html = True
## Scan email attachments
self.scan_rfc822 = True
## Check filenames in ZIP attachments
self.scan_zip = False
## Option to block subjects with chinese characters.
# This does not prevent corresponding with Chinese people,
# or block Chinese in other parts of the email. Chinese
# chars in the subject sent to someone who does not speak the language
# is almost certainly spam.
self.block_chinese = False
## URL of CGI to display enhanced error diagnostics via web.
self.errors_url = "http://bmsi.com/cgi-bin/errors.cgi"
self.dkim_domain = None
self.dkim_key = None
self.dkim_selector = 'default'
## List of networks considered internal.
self.internal_connect = ()
## Banned case sensitive Subject keywords
self.spam_words = ()
## Banned case insensitive Subject keywords
self.porn_words = ()
## Banned keywords in From: header
self.from_words = ()
## Internal senders which should whitelist recipients
self.whitelist_senders = {}
## Send whitelisted recipients to this MX for consolidation
self.whitelist_mx = ()
## Ban these HELO names (usually local domains)
self.hello_blacklist = ()
## Treat these MAIL FROM mailboxes as DSNs - for braindead MTAs.
self.banned_users = ()
## Log header fields
self.log_headers = False
## Data directory, or '' to use logdir
self.datadir = ''
## Option to heuristically guess a sender policy for domains lacking one.
self.spf_best_guess = False
## Socket for talking to MTA as proto:address
# If proto is missing, it defaults to unix domain socket.
# Examples:
# <pre>
# 'unix:/var/run/pythonfilter' Unix domain socket
# 'local:/var/run/pythonfilter' named pipe
# 'inet:8800' port 8800 on ANY IP4 interface
# 'inet:8800@hostname' port 8800 on hostname
# 'inet6:8801' port 8801 on ANY IP6 interface
# 'inet6:8802@[2001:db8:1234::1]' port 8802 on IP6 interface
# </pre>
# See <a href="http://pythonhosted.org/pymilter/namespacemilter.html#a266a6e09897499d8b1ae0e20f0d2be73">milter.setconn()</a>
self.socketname = "/tmp/pythonsock"
## Milter protocol timeout.
# If the MTA doesn't respond within this timeout, we assume something
# went wrong and abort the connection. This is currently also used
# when sending DSNs.
self.timeout = 600
## List of non-SRS domains that can be trusted to forward to us.
# If the connectip gets an SPF Pass with any of these domains,
# we treat the email as SPF Pass for the forwarder domain.
# Don't make this list too long, as this is an inefficient process.
self.trusted_forwarder = ()
## List of trusted relays such as MX hosts for our domain.
# Connections from a trusted relay can trust the first Received header.
# SPF checks are bypassed for internal connections and trusted relays.
self.trusted_relay = ()
## True to continue until DATA when a REJECT decision is made.
# This allows logging intended recipients, which can be very useful.
self.delayed_reject = True
## Set of domains to reject executables.
# Normally, executable attachments are sequestered where the mail
# admin can recover them if needed, and replaced
# with a notice. For these MAIL FROM domains, the message is
# rejected instead.
self.reject_virus_from = ()
## List of localparts by domain to wiretap.
# Wiretapping copies messages to another user or alias for
# archiving or monitoring.
self.wiretap_users = {}
## List of localparts by domain to silently discard.
# Allows an administrator to intercept instead of monitor mail
# from a suspect employee. Approved emails can be redirected
# to approved recipients. Helps prevents "leaks" of confidential
# info like customer lists from unethical employees.
self.discard_users = {}
## Address to send wiretapped emails to.
self.wiretap_dest = None
## Filename to append all emails to.
self.mail_archive = None
## Wiretap acts like Bcc: if True.
# When False, wiretap adds wiretap_dest to the Cc: header field.
self.blind_wiretap = True
## Smart alias dictionary.
# A smart alias is matched on both sender and recipient, unlike
# traditional aliases, which match on the recipient only.
# The key is a sender,recipient tuple. The values is a list of
# recipients to replace the original recipient.
self.smart_alias = {}
## True if smart alias local parts are case sensitive.
# The SMTP internet standard says the localpart is case sensitive.
# Maddeningly, Microsoft programmers routinely ignore the specification
# and convert local parts to upper case - end users have no way to
# enter correct emails. If you want smart alias to match emails
# from the evil empire (and your mailboxes are not all upper case), you
# need to set this to false.
self.case_sensitive_localpart = False
def getGreylist(self):
if not self.greylist: return None
greylist = getattr(local,'greylist',None)
if not greylist:
grey_db = os.path.join(self.datadir,self.grey_db)
greylist = Greylist(grey_db,self.grey_time,
self.grey_expire,self.grey_days)
local.greylist = greylist
return greylist
config = Config()
_archive_lock = None
# Global configuration defaults suitable for test framework.
check_user = {}
block_forward = {}
hide_path = ()
internal_policy = False
private_relay = ()
internal_mta = ()
internal_domains = ()
dspam_dict = None
dspam_users = {}
dspam_train = {}
dspam_userdir = None
dspam_exempt = {}
dspam_whitelist = {}
dspam_screener = ()
dspam_internal = True # True if internal mail should be dspammed
dspam_reject = ()
dspam_sizelimit = 180000
srs = None
ses = None
srs_reject_spoofed = False
srs_domain = ()
spf_reject_neutral = ()
spf_accept_softfail = ()
spf_accept_fail = ()
spf_reject_noptr = False
supply_sender = False
banned_ips = set()
banned_domains = set()
UNLIMITED = 0x7fffffff
max_demerits = UNLIMITED
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format='%(asctime)s %(message)s',
datefmt='%Y%b%d %H:%M:%S'
)
milter_log = logging.getLogger('milter')
import threading
local = threading.local()
## Read config files.
# Only some configs are returned in a Config object. Most are still
# globals set as a side effect. The intent is to migrate them over time.
# @param list List of config file pathnames to check in order
# @return Config
def read_config(list):
cp = MilterConfigParser({
'tempdir': "/var/log/milter/save",
'datadir': "/var/lib/milter",
'socket': "/var/run/milter/pythonsock",
'errors_url': "http://bmsi.com/cgi-bin/errors.cgi",
'scan_html': 'no',
'scan_rfc822': 'yes',
'scan_zip': 'no',
'block_chinese': 'no',
'log_headers': 'no',
'blind_wiretap': 'yes',
'reject_spoofed': 'no',
'reject_noptr': 'no',
'supply_sender': 'no',
'best_guess': 'no',
'dspam_internal': 'yes',
'case_sensitive_localpart': 'no',
'internal_policy': 'no'
})
try:
cp.read(list)
except UnicodeDecodeError:
print("Using latin1 for compatibility - consider using utf-8.")
cp.read(list,encoding='latin1')
config = Config()
# old configs have datadir for both logging and data
config.datadir = cp.getdefault('milter','datadir','')
config.logdir = cp.getdefault('milter','logdir',config.datadir)
# config reference files are in datadir by default
if config.datadir:
print("chdir:",config.datadir)
os.chdir(config.datadir)
# milter section
tempfile.tempdir = cp.get('milter','tempdir')
global check_user
global internal_domains
global private_relay, internal_mta, max_demerits
config.socketname = cp.get('milter','socket')
config.timeout = cp.getintdefault('milter','timeout',600)
check_user = cp.getaddrset('milter','check_user')
config.log_headers = cp.getboolean('milter','log_headers')
config.internal_connect = cp.getlist('milter','internal_connect')
internal_domains = cp.getlist('milter','internal_domains')
config.trusted_relay = cp.getlist('milter','trusted_relay')
private_relay = cp.getlist('milter','private_relay')
internal_mta = cp.getlist('milter','internal_mta')
config.hello_blacklist = cp.getlist('milter','hello_blacklist')
config.case_sensitive_localpart = cp.getboolean('milter','case_sensitive_localpart')
max_demerits = cp.getintdefault('milter','max_demerits',UNLIMITED)
config.errors_url = cp.get('milter','errors_url')
if cp.has_option('milter','email_providers'):
config.email_providers = cp.get('milter','email_providers')
# defang section
global block_forward
if cp.has_section('defang'):
section = 'defang'
# for backward compatibility,
# banned extensions defaults to empty only when defang section exists
config.banned_exts = cp.getlist(section,'banned_exts')
else: # use milter section if no defang section for compatibility
section = 'milter'
config.scan_rfc822 = cp.getboolean(section,'scan_rfc822')
config.scan_zip = cp.getboolean(section,'scan_zip')
config.scan_html = cp.getboolean(section,'scan_html')
config.block_chinese = cp.getboolean(section,'block_chinese')
block_forward = cp.getaddrset(section,'block_forward')
config.porn_words = [x for x in cp.getlist(section,'porn_words')
if len(x) > 1]
config.spam_words = [x for x in cp.getlist(section,'spam_words')
if len(x) > 1]
from_words = [x for x in cp.getlist(section,'from_words')
if len(x) > 1]
if len(from_words) == 1 and from_words[0].startswith("file:"):
with open(from_words[0][5:],'r') as fp:
from_words = [s.strip() for s in fp.readlines()]
from_words = [s for s in from_words if len(s) > 2]
config.from_words = from_words
# scrub section
global hide_path, internal_policy
hide_path = cp.getlist('scrub','hide_path')
config.reject_virus_from = cp.getlist('scrub','reject_virus_from')
internal_policy = cp.getboolean('scrub','internal_policy')
# wiretap section
config.blind_wiretap = cp.getboolean('wiretap','blind')
config.wiretap_users = cp.getaddrset('wiretap','users')
config.discard_users = cp.getaddrset('wiretap','discard')
config.wiretap_dest = cp.getdefault('wiretap','dest')
if config.wiretap_dest: config.wiretap_dest = '<%s>' % config.wiretap_dest
config.mail_archive = cp.getdefault('wiretap','archive')
for sa,v in [
(k,cp.get('wiretap',k)) for k in cp.getlist('wiretap','smart_alias')
] + (cp.has_section('smart_alias') and cp.items('smart_alias',True) or []):
print(sa,v)
sm = [q.strip() for q in v.split(',')]
if len(sm) < 2:
milter_log.warning('malformed smart alias: %s',sa)
continue
if len(sm) == 2: sm.append(sa)
if config.case_sensitive_localpart:
key = (sm[0],sm[1])
else:
key = (sm[0].lower(),sm[1].lower())
config.smart_alias[key] = sm[2:]
# dspam section
global dspam_dict, dspam_users, dspam_userdir, dspam_exempt, dspam_internal
global dspam_screener,dspam_whitelist,dspam_reject,dspam_sizelimit
config.whitelist_senders = cp.getaddrset('dspam','whitelist_senders')
config.whitelist_mx = cp.getlist('dspam','whitelist_mx')
dspam_dict = cp.getdefault('dspam','dspam_dict')
dspam_exempt = cp.getaddrset('dspam','dspam_exempt')
dspam_whitelist = cp.getaddrset('dspam','dspam_whitelist')
dspam_users = cp.getaddrdict('dspam','dspam_users')
dspam_userdir = cp.getdefault('dspam','dspam_userdir')
dspam_screener = cp.getlist('dspam','dspam_screener')
dspam_train = set(cp.getlist('dspam','dspam_train'))
dspam_reject = cp.getlist('dspam','dspam_reject')
dspam_internal = cp.getboolean('dspam','dspam_internal')
if cp.has_option('dspam','dspam_sizelimit'):
dspam_sizelimit = cp.getint('dspam','dspam_sizelimit')
# spf section
global spf_reject_neutral,SRS,spf_reject_noptr
global spf_accept_softfail,spf_accept_fail,supply_sender
if spf:
spf.DELEGATE = cp.getdefault('spf','delegate')
spf_reject_neutral = cp.getlist('spf','reject_neutral')
spf_accept_softfail = cp.getlist('spf','accept_softfail')
spf_accept_fail = cp.getlist('spf','accept_fail')
config.spf_best_guess = cp.getboolean('spf','best_guess')
spf_reject_noptr = cp.getboolean('spf','reject_noptr')
supply_sender = cp.getboolean('spf','supply_sender')
config.access_file = cp.getdefault('spf','access_file')
config.trusted_forwarder = cp.getlist('spf','trusted_forwarder')
srs_config = cp.getdefault('srs','config')
if srs_config: cp.read([srs_config])
srs_secret = cp.getdefault('srs','secret')
if SRS and srs_secret:
global ses,srs,srs_reject_spoofed,srs_domain
database = cp.getdefault('srs','database')
srs_reject_spoofed = cp.getboolean('srs','reject_spoofed')
maxage = cp.getintdefault('srs','maxage',8)
hashlength = cp.getintdefault('srs','hashlength',8)
separator = cp.getdefault('srs','separator','=')
if database:
import SRS.DB
srs = SRS.DB.DB(database=database,secret=srs_secret,
maxage=maxage,hashlength=hashlength,separator=separator)
else:
srs = SRS.Guarded.Guarded(secret=srs_secret,
maxage=maxage,hashlength=hashlength,separator=separator)
if SES:
ses = SES.new(secret=srs_secret,expiration=maxage)
srs_domain = set(cp.getlist('srs','ses'))
srs_domain.update(cp.getlist('srs','srs'))
else:
srs_domain = set(cp.getlist('srs','srs'))
srs_domain.update(cp.getlist('srs','sign'))
srs_domain.add(cp.getdefault('srs','fwdomain'))
config.banned_users = cp.getlist('srs','banned_users')
if gossip:
global gossip_node, gossip_ttl
if cp.has_option('gossip','server'):
server = cp.get('gossip','server')
host,port = gossip.splitaddr(server)
gossip_node = gossip.client.Gossip(host,port)
else:
gossip_db = os.path.join(config.datadir,'gossip4.db')
gossip_node = gossip.server.Gossip(gossip_db,1000)
for p in cp.getlist('gossip','peers'):
host,port = gossip.splitaddr(p)
try:
gossip_node.peers.append(gossip.server.Peer(host,port))
except socket.gaierror as x:
milter_log.error("gossip peers: %s",x,exc_info=True)
gossip_ttl = cp.getintdefault('gossip','ttl',1)
# greylist section
if cp.has_option('greylist','dbfile'):
config.grey_db = cp.getdefault('greylist','dbfile')
config.grey_days = cp.getintdefault('greylist','retain',36)
config.grey_expire = cp.getintdefault('greylist','expire',6)
config.grey_time = cp.getintdefault('greylist','time',5)
config.greylist = True
# DKIM section
if cp.has_option('dkim','privkey'):
dkim_keyfile = cp.getdefault('dkim','privkey')
config.dkim_selector = cp.getdefault('dkim','selector','default')
config.dkim_domain = cp.getdefault('dkim','domain')
if dkim_keyfile and config.dkim_domain:
try:
with open(dkim_keyfile,'r') as kf:
config.dkim_key = kf.read()
except:
milter_log.error('Unable to read: %s',dkim_keyfile)
return config
def maskip(ip):
n = ipaddress.ip_network(ip)
if n.version == 4:
hostbits = 8
else:
hostbits = 64
return str(n.supernet(hostbits).network)
def findsrs(fp):
lastln = None
for ln in fp:
if lastln:
c = chr(ln[0])
if c.isspace() and c != '\n':
lastln += ln
continue
try:
name,val = lastln.rstrip().split(None,1)
pos = val.find(b'<SRS')
if pos >= 0:
end = val.find(b'>',pos+4)
return srs.reverse(val[pos+1:end].decode())
except: pass
lnl = ln.lower()
if lnl.startswith(b'action:'):
if lnl.split()[-1] != b'failed': break
for k in (b'message-id:',b'x-mailer:',b'sender:',b'references:'):
if lnl.startswith(k):
lastln = ln
break
def inCharSets(v,*encs):
try: u = unicode(v,'utf8')
except: return True
for enc in encs:
try:
s = u.encode(enc,'backslashreplace')
return s.count(r'\u') < 3
except: UnicodeError
return False
def param2dict(str):
pairs = [x.split('=',1) for x in str]
for e in pairs:
if len(e) < 2: e.append(None)
return dict([(k.upper(),v) for k,v in pairs])
class SPFPolicy(MTAPolicy):
"Get SPF/DKIM policy by result from sendmail style access file."
def getFailPolicy(self):
policy = self.getPolicy('spf-fail')
if not policy:
if self.domain in spf_accept_fail:
policy = 'CBV'
else:
policy = 'REJECT'
return policy
def getNonePolicy(self):
policy = self.getPolicy('spf-none')
if not policy:
if spf_reject_noptr:
policy = 'REJECT'
else:
policy = 'CBV'
return policy
def getSoftfailPolicy(self):
policy = self.getPolicy('spf-softfail')
if not policy:
if self.domain in spf_accept_softfail:
policy = 'OK'
elif self.domain in spf_reject_neutral:
policy = 'REJECT'
else:
policy = 'CBV'
return policy
def getNeutralPolicy(self):
policy = self.getPolicy('spf-neutral')
if not policy:
if self.domain in spf_reject_neutral:
policy = 'REJECT'
policy = 'OK'
return policy
def getPermErrorPolicy(self):
policy = self.getPolicy('spf-permerror')
if not policy:
policy = 'REJECT'
return policy
def getTempErrorPolicy(self):
policy = self.getPolicy('spf-temperror')
if not policy:
policy = 'REJECT'
return policy
def getPassPolicy(self):
policy = self.getPolicy('spf-pass')
if not policy:
policy = 'OK'
return policy
from Milter.cache import AddrCache
cbv_cache = AddrCache(renew=7)
auto_whitelist = AddrCache(renew=60)
blacklist = AddrCache(renew=30)
def isbanned(dom,s):
if dom in s: return True
a = dom.split('.')
if a[0] == '*': a = a[1:]
if len(a) < 2: return False
a[0] = '*'
return isbanned('.'.join(a),s)
RE_MULTIMX = re.compile(r'^(mail|smtp|mx)[0-9]{1,3}[.]')
def write_header(fp,name,val):
fp.write(b"%s: %s\n" % (name.encode(),val.encode('utf-8')))
class bmsMilter(Milter.Base):
"""Milter to replace attachments poisonous to Windows with a WARNING message,
check SPF, and other anti-forgery features, and implement wiretapping
and smart alias redirection."""
def log(self,*msg):
milter_log.info('[%d] %s',self.id,' '.join([str(m) for m in msg]))
def logstream(outerself):
"Return a file like object that call self.log for each line"
class LineWriter(object):
def __init__(self):
self._buf = ''
def write(self,s):
s = self._buf + s
pos = s.find('\n')
while pos >= 0:
outerself.log(s[:pos])
s = s[pos+1:]
pos = s.find('\n')
self._buf = s
return LineWriter()
def __init__(self):
self.tempname = None
self.mailfrom = None # sender in SMTP form
self.canon_from = None # sender in end user form
self.fp = None
self.pristine_headers = None
self.enhanced_headers = None
self.bodysize = 0
self.id = Milter.uniqueID()
self.config = config # get reference to current global config
# delrcpt can only be called from eom(). This accumulates recipient
# changes which can then be applied by alter_recipients()
def del_recipient(self,rcpt):
rcpt = rcpt.lower()
if not rcpt in self.discard_list:
self.discard_list.append(rcpt)
# addrcpt can only be called from eom(). This accumulates recipient
# changes which can then be applied by alter_recipients()
def add_recipient(self,rcpt):
rcpt = rcpt.lower()
if not rcpt in self.redirect_list:
self.redirect_list.append(rcpt)
# addheader can only be called from eom(). This accumulates added headers
# which can then be applied by alter_headers()
def add_header(self,name,val,idx=-1):
if idx < 0:
self.enhanced_headers.append((name,val))
else:
self.enhanced_headers.insert(idx,(name,val))
self.new_headers.append((name,val,idx))
self.log('%s: %s' % (name,val))
def apply_headers(self):
"Send accumulated milter generated headers to MTA"
for name,val,idx in self.new_headers:
try:
try:
self.addheader(name,val,idx)
except TypeError:
val = val.replace('\x00',r'\x00')
self.addheader(name,val,idx)
except Milter.error:
self.addheader(name,val) # older sendmail can't insheader
def delay_reject(self,*args,**kw):
if self.config.delayed_reject:
self.reject = (args,kw)
return Milter.CONTINUE
self.htmlreply(*args,**kw)
return Milter.REJECT
def connect(self,hostname,unused,hostaddr):
self.internal_connection = False
self.trusted_relay = False
self.reject = None
self.offenses = 0
# sometimes people put extra space in sendmail config, so we strip
self.receiver = self.getsymval('j').strip()
dport = self.getsymval('{daemon_port}')
if dport:
self.dport = int(dport)
else:
self.dport = 0
if hostaddr and len(hostaddr) > 0:
config = self.config
ipaddr = hostaddr[0]
if iniplist(ipaddr,config.internal_connect):
self.internal_connection = True
if iniplist(ipaddr,config.trusted_relay):
self.trusted_relay = True
else: ipaddr = ''
self.connectip = ipaddr
self.missing_ptr = dynip(hostname,self.connectip)
self.localhost = iniplist(ipaddr,('127.*','::1'))
if self.internal_connection:
connecttype = 'INTERNAL'
else:
connecttype = 'EXTERNAL'
if self.trusted_relay:
connecttype += ' TRUSTED'
if self.missing_ptr:
connecttype += ' DYN'
self.log("connect from %s at %s:%s %s" %
(hostname,hostaddr,dport,connecttype))
self.hello_name = None
self.connecthost = hostname
# Sendmail is normally configured so that only authenticated senders
# are allowed to proceed to MAIL FROM on port 587.
if self.dport != 587 and addr2bin(ipaddr) in banned_ips:
self.log("REJECT: BANNED IP")
return self.delay_reject('550','5.7.1', 'Banned for dictionary attacks')
if hostname == 'localhost' and not self.localhost or hostname == '.':
self.log("REJECT: PTR is",hostname)
return self.delay_reject('550','5.7.1',
'"%s" is not a reasonable PTR name'%hostname)
return Milter.CONTINUE
def hello(self,hostname):
self.hello_name = hostname
self.log("hello from %s" % hostname)
if not self.internal_connection:
# Allow illegal HELO from internal network, some email enabled copier/fax
# type devices (Toshiba) have broken firmware.
if ip4re.match(hostname):
self.log("REJECT: numeric hello name:",hostname)
self.setreply('550','5.7.1','hello name cannot be numeric ip')
return Milter.REJECT
if hostname in self.config.hello_blacklist:
self.log("REJECT: spam from self:",hostname)
self.setreply('550','5.7.1',
'Your mail server lies. Its name is *not* %s.' % hostname)
return self.offense(inc=4)
if hostname == 'GC':
n = gc.collect()
self.log("gc:",n,' unreachable objects')
self.log("auto-whitelist:",len(auto_whitelist),' entries')
self.log("cbv_cache:",len(cbv_cache),' entries')
self.setreply('550','5.7.1','%d unreachable objects'%n)
return Milter.REJECT
# HELO not allowed after MAIL FROM
if self.mailfrom: self.offense(inc=2)
return Milter.CONTINUE
def smart_alias(self,to):
config = self.config
smart_alias = config.smart_alias
if smart_alias:
if config.case_sensitive_localpart:
t = parse_addr(to)
else:
t = parse_addr(to.lower())
if len(t) == 2:
ct = '@'.join(t)
else:
ct = t[0]
if config.case_sensitive_localpart:
cf = self.efrom
else:
cf = self.efrom.lower()
cf0 = cf.split('@',1)
if len(cf0) == 2:
cf0 = '@' + cf0[1]
else:
cf0 = cf
for key in ((cf,ct),(cf0,ct)):
if key in smart_alias:
self.del_recipient(to)
for t in smart_alias[key]:
self.add_recipient('<%s>'%t)
def offense(self,inc=1,min=0):
self.offenses += inc
if self.offenses < min:
self.offenses = min
if self.offenses > max_demerits and not self.trusted_relay:
try:
ip = addr2bin(self.connectip)
if ip not in banned_ips:
banned_ips.add(ip)
with open('banned_ips','at') as fp:
print(self.connectip,file=fp)
self.log("BANNED IP:",self.connectip)
except: pass
return Milter.REJECT
# multiple messages can be received on a single connection
# envfrom (MAIL FROM in the SMTP protocol) seems to mark the start
# of each message.
def envfrom(self,f,*str):
self.log("mail from",f,str)
#param = param2dict(str)
#self.envid = param.get('ENVID',None)
#self.mail_param = param
self.fp = BytesIO()
self.pristine_headers = BytesIO()
self.enhanced_headers = []
if self.tempname:
os.remove(self.tempname) # remove any leftover from previous message
self.tempname = None
self.mailfrom = f
self.forward = True
self.bodysize = 0
self.hidepath = False
self.discard = False
self.dspam = True
self.whitelist = False
self.blacklist = False
self.greylist = False
self.reject_spam = True
self.data_allowed = True
self.delayed_failure = None
self.trust_received = self.trusted_relay
self.trust_spf = self.trusted_relay or self.internal_connection
self.external_spf = None
self.trust_dkim = self.trust_spf
self.external_dkim = None
self.redirect_list = []
self.discard_list = []
self.new_headers = []
self.recipients = []
self.confidence = None
self.cbv_needed = None
self.whitelist_sender = False
self.postmaster_reply = False
self.orig_from = None
self.has_dkim = False
self.dkim_domain = None
self.arresults = []
config = self.config
if f == '<>' and internal_mta and self.internal_connection:
if not iniplist(self.connectip,internal_mta):
self.log("REJECT: pretend MTA at ",self.connectip,
" sending MAIL FROM ",f)
self.setreply('550','5.7.1',
'Your PC is trying to send a DSN even though it is not an MTA.',
'If you are running MS Outlook, it is broken. If you want to',
'send return receipts, use a more standards compliant email client.'
)
return Milter.REJECT
if authres and not self.missing_ptr: self.arresults.append(
authres.IPRevAuthenticationResult(result = 'pass',
policy_iprev=self.connectip,policy_iprev_comment=self.connecthost)
)
if self.canon_from:
self.reject = None # reset delayed reject seen after mail from
t = parse_addr(f)
if len(t) == 2: t[1] = t[1].lower()
self.canon_from = '@'.join(t)
self.efrom = self.canon_from
# Some braindead MTAs can't be relied upon to properly flag DSNs.
# This heuristic tries to recognize such.
self.is_bounce = (f == '<>' or t[0].lower() in config.banned_users
#and t[1] == self.hello_name
)
# Check SMTP AUTH, also available:
# auth_authen authenticated user
# auth_author (ESMTP AUTH= param)
# auth_ssf (connection security, 0 = unencrypted)
# auth_type (authentication method, CRAM-MD5, DIGEST-MD5, PLAIN, etc)
# cipher_bits SSL encryption strength
# cert_subject SSL cert subject
# verify SSL cert verified
self.user = self.getsymval('{auth_authen}')
if self.user:
# Very simple SMTP AUTH policy by default:
# any successful authentication is considered INTERNAL
# Detailed authorization policy is configured in the access file below.
self.internal_connection = True
self.trust_dkim = self.trust_spf = True
auth_type = self.getsymval('{auth_type}')
ssl_bits = self.getsymval('{cipher_bits}')
self.log(
"SMTP AUTH:",self.user,"sslbits =",ssl_bits, auth_type,
"ssf =",self.getsymval('{auth_ssf}'), "INTERNAL"
)
# Detailed authorization policy is configured in the access file below.
if auth_type and authres: self.arresults.append(
authres.SMTPAUTHAuthenticationResult(result = 'pass',
result_comment = auth_type+' sslbits=%s'%ssl_bits,
smtp_auth = self.user
)
)
if self.getsymval('{verify}'):
self.log("SSL AUTH:",
self.getsymval('{cert_subject}'),
"verify =",self.getsymval('{verify}')
)
if self.reject:
self.log("REJECT CANCELED")
self.reject = None
From = 'From %s %s\n' % (self.canon_from,time.ctime())
self.fp.write(From.encode('utf-8'))
self.internal_domain = False
self.umis = None
if len(t) == 2:
user,domain = t
for pat in internal_domains:
if fnmatchcase(domain,pat):
self.internal_domain = True
break
if srs and domain in srs_domain and user.lower().startswith('srs0'):
try:
newaddr = srs.reverse(self.canon_from)
self.orig_from = newaddr
self.efrom = newaddr
self.log("Original MFROM:",newaddr)
except:
self.log("REJECT: bad MFROM signature",self.canon_from)
self.setreply('550','5.7.1','Bad MFROM signature')
return Milter.REJECT
if self.internal_connection:
if self.user:
with SPFPolicy('%s@%s'%(self.user,domain),conf=self.config) as p:
policy = p.getPolicy('smtp-auth')
print("smtp-auth: ",p.sender,policy,p.use_nulls)
else:
policy = None
# trust ourself not to be a zombie
if self.trusted_relay or self.localhost:
policy = 'OK'
if policy:
if policy == 'WHITELIST':
self.whitelist = True
elif policy != 'OK':
self.log("REJECT: unauthorized user",self.user,
"at",self.connectip,"sending MAIL FROM",self.canon_from)
self.setreply('550','5.7.1',
'SMTP user %s is not authorized to use MAIL FROM %s.' %
(self.user,self.canon_from)
)
return Milter.REJECT
elif internal_domains and not self.internal_domain:
self.log("REJECT: zombie PC at ",self.connectip,
" sending MAIL FROM ",self.canon_from)
self.setreply('550','5.7.1',
'Your PC is using an unauthorized MAIL FROM.',
'It is either badly misconfigured or controlled by organized crime.'
)
return Milter.REJECT
# effective from
if self.orig_from:
user,domain = self.orig_from.split('@')
if isbanned(domain,banned_domains):
self.log("REJECT: banned domain",domain)
return self.delay_reject('550','5.7.1',template='bandom',domain=domain)
if self.internal_connection:
wl_users = config.whitelist_senders.get(domain,())
if user in wl_users or '' in wl_users:
self.whitelist_sender = True
self.rejectvirus = domain in config.reject_virus_from
if user in config.wiretap_users.get(domain,()):
self.add_recipient(config.wiretap_dest)
self.smart_alias(config.wiretap_dest)
if user in config.discard_users.get(domain,()):
self.discard = True
exempt_users = dspam_whitelist.get(domain,())
if user in exempt_users or '' in exempt_users:
self.dspam = False
else:
self.rejectvirus = False
domain = None
if not self.hello_name:
self.log("REJECT: missing HELO")
self.setreply('550','5.7.1',"It's polite to say HELO first.")