forked from mgeeky/decode-spam-headers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode-spam-headers.py
6931 lines (5586 loc) · 268 KB
/
decode-spam-headers.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
#
# This script attempts to decode SMTP headers that may contain Anti-Spam related information, clues,
# scores and other characteristics. Intention is to extract reason why the message was considered a spam,
# by combining flags and values for different headers from all around the Internet and documentation.
#
# The script might be used by System Administrators to help them understand mail deliverability obstacles,
# but also by the Offensive security consultants performing Phishing Awareness Trainings, before sending
# a campaign to analyse negative constructs in their e-mails.
#
# The script can decode 67+ different SPAM related headers (and others bringing valuable information):
# - X-forefront-antispam-report
# - X-exchange-antispam
# - X-exchange-antispam-mailbox-delivery
# - X-exchange-antispam-message-info
# - X-microsoft-antispam-report-cfa-test
# - Received
# - From
# - To
# - Subject
# - Thread-topic
# - Received-spf
# - X-mailer
# - X-originating-ip
# - User-agent
# - X-forefront-antispam-report
# - X-microsoft-antispam-mailbox-delivery
# - X-microsoft-antispam
# - X-exchange-antispam-report-cfa-test
# - X-spam-status
# - X-spam-level
# - X-spam-flag
# - X-spam-report
# - X-vr-spamcause
# - X-ovh-spam-reason
# - X-vr-spamscore
# - X-virus-scanned
# - X-spam-checker-version
# - X-ironport-av
# - X-ironport-anti-spam-filtered
# - X-ironport-anti-spam-result
# - X-mimecast-spam-score
# - Spamdiagnosticmetadata
# - X-ms-exchange-atpmessageproperties
# - X-msfbl
# - X-ms-exchange-transport-endtoendlatency
# - X-ms-oob-tlc-oobclassifiers
# - X-ip-spam-verdict
# - X-amp-result
# - X-ironport-remoteip
# - X-ironport-reputation
# - X-sbrs
# - X-ironport-sendergroup
# - X-policy
# - X-ironport-mailflowpolicy
# - X-remote-ip
# - X-sea-spam
# - X-fireeye
# - X-antiabuse
# - X-tmase-version
# - X-tm-as-product-ver
# - X-tm-as-result
# - X-imss-scan-details
# - X-tm-as-user-approved-sender
# - X-tm-as-user-blocked-sender
# - X-tmase-result
# - X-tmase-snap-result
# - X-imss-dkim-white-list
# - X-tm-as-result-xfilter
# - X-tm-as-smtp
# - X-scanned-by
# - X-mimecast-spam-signature
# - X-mimecast-bulk-signature
# - X-sender-ip
# - X-forefront-antispam-report-untrusted
# - X-microsoft-antispam-untrusted
# - X-sophos-senderhistory
# - X-sophos-rescan
# - X-MS-Exchange-CrossTenant-Id
# - X-OriginatorOrg
# - IronPort-Data
# - IronPort-HdrOrdr
# - X-DKIM
# - DKIM-Filter
# - X-SpamExperts-Class
# - X-SpamExperts-Evidence
# - X-Recommended-Action
# - X-AppInfo
# - X-TM-AS-MatchedID
# - X-MS-Exchange-EnableFirstContactSafetyTip
# - X-MS-Exchange-Organization-BypassFocusedInbox
# - X-MS-Exchange-SkipListedInternetSender
# - X-MS-Exchange-ExternalOriginalInternetSender
# - X-CNFS-Analysis
# - X-Authenticated-Sender
# - X-Apparently-From
# - X-Env-Sender
# - Sender
#
# Usage:
# ./decode-spam-headers [options] <smtp-headers.txt>
#
# NOTICE:
# Parts of this code contain fragments copied from the following places:
#
# 1) testEmailIntelligence():
# source: https://github.com/nquinlan/Email-Intelligence
# authored by: Nick Quinlan ([email protected])
#
# Requirements:
# - python-dateutil
# - tldextract
# - packaging
# - dnspython
# - colorama
#
# Mariusz Banach / mgeeky, '21-'22
# <mb [at] binary-offensive.com>
#
import os, sys, re
import string
import argparse
import json
import textwrap
import socket
import textwrap
import time
import atexit
import base64
from html import escape
from email import header as emailheader
from datetime import *
from dateutil.tz import *
try:
from dateutil import parser
except ImportError:
print('''
[!] You need to install python-dateutil:
# pip3 install python-dateutil
''')
sys.exit(1)
try:
import colorama
except ImportError:
print('''
[!] You need to install colorama:
# pip3 install colorama
''')
sys.exit(1)
try:
import packaging.version
except ImportError:
print('''
[!] You need to install packaging:
# pip3 install packaging
''')
sys.exit(1)
try:
import requests
except ImportError:
print('''
[!] You need to install requests:
# pip3 install requests
''')
sys.exit(1)
try:
import tldextract
except ImportError:
print('''
[!] You need to install tldextract:
# pip3 install tldextract
''')
sys.exit(1)
try:
import dns.resolver
except ImportError:
print('''
[!] You need to install dnspython:
# pip3 install dnspython
If problem remains, re-install dnspython:
# pip3 uninstall dnspython
# pip3 install dnspython
''')
sys.exit(1)
colorama.init()
options = {
'debug': False,
'verbose': False,
'nocolor' : False,
'log' : sys.stderr,
'format' : 'text',
'dont_resolve' : False,
}
class Logger:
colors_map = {
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
'grey': 38,
}
html_colors_map = {
'background':'rgb(40, 44, 52)',
'grey': 'rgb(132, 139, 149)',
'cyan' : 'rgb(86, 182, 194)',
'blue' : 'rgb(97, 175, 239)',
'red' : 'rgb(224, 108, 117)',
'magenta' : 'rgb(198, 120, 221)',
'yellow' : 'rgb(229, 192, 123)',
'white' : 'rgb(220, 223, 228)',
'green' : 'rgb(108, 135, 94)',
}
colors_dict = {
'error': colors_map['red'],
'info ': colors_map['green'],
'debug': colors_map['grey'],
'other': colors_map['grey'],
}
options = {}
def __init__(self, opts = None):
self.options.update(Logger.options)
if opts != None and len(opts) > 0:
self.options.update(opts)
@staticmethod
def with_color(c, s):
#return "\x1b[%dm%s\x1b[0m" % (c, s)
return f'__COLOR_{c}__|{s}|__END_COLOR__'
@staticmethod
def replaceColors(s, colorizingFunc):
pos = 0
while pos < len(s):
if s[pos:].startswith('__COLOR_'):
pos += len('__COLOR_')
pos1 = s[pos:].find('__|')
assert pos1 != -1, "Output colors mismatch - could not find pos of end of color number!"
c = int(s[pos:pos+pos1])
pos += pos1 + len('__|')
pos2 = s[pos:].find('|__END_COLOR__')
assert pos2 != -1, "Output colors mismatch - could not find end of color marker!"
txt = s[pos:pos+pos2]
pos += pos2 + len('|__END_COLOR__')
patt = f'__COLOR_{c}__|{txt}|__END_COLOR__'
colored = colorizingFunc(c, txt)
assert len(colored) > 0, f"Could not strip colors from phrase: ({patt})!"
s = s.replace(patt, colored)
pos = 0
continue
pos += 1
return s
@staticmethod
def noColors(s):
return Logger.replaceColors(s, lambda c, txt: txt)
return out
def ansiColors(s):
return Logger.replaceColors(s, lambda c, txt: f'\x1b[{c}m{txt}\x1b[0m')
@staticmethod
def htmlColors(s):
def get_col(c, txt):
text = escape(txt)
for k, v in Logger.colors_map.items():
if v == c:
htmlCol = Logger.html_colors_map[k]
return f'<font class="text-{k}">{text}</font>'
return text
return Logger.replaceColors(s, get_col)
def colored(self, txt, col):
if self.options['nocolor']:
return txt
return Logger.with_color(Logger.colors_map[col], txt)
# Invocation:
# def out(txt, mode='info ', fd=None, color=None, noprefix=False, newline=True):
@staticmethod
def out(txt, fd, mode='info ', **kwargs):
if txt == None or fd == 'none':
return
elif fd == None:
raise Exception('[ERROR] Logging descriptor has not been specified!')
args = {
'color': None,
'noprefix': False,
'newline': True,
'nocolor' : False
}
args.update(kwargs)
if type(txt) != str:
txt = str(txt)
txt = txt.replace('\t', ' ' * 4)
if args['nocolor']:
col = ''
elif args['color']:
col = args['color']
if type(col) == str and col in Logger.colors_map.keys():
col = Logger.colors_map[col]
else:
col = Logger.colors_dict.setdefault(mode, Logger.colors_map['grey'])
prefix = ''
if mode:
mode = '[%s] ' % mode
if not args['noprefix']:
if args['nocolor']:
prefix = mode.upper()
else:
prefix = Logger.with_color(Logger.colors_dict['other'], '%s'
% (mode.upper()))
nl = ''
if 'newline' in args:
if args['newline']:
nl = '\n'
if 'force_stdout' in args:
fd = sys.stdout
to_write = ''
if type(fd) == str:
prefix2 = ''
if mode:
prefix2 = '%s' % (mode.upper())
prefix2 + txt + nl
else:
if args['nocolor']:
to_write = prefix + txt + nl
else:
to_write = prefix + Logger.with_color(col, txt) + nl
to_write = Logger.ansiColors(to_write)
if type(fd) == str:
with open(fd, 'a') as f:
f.write(to_write)
f.flush()
else:
fd.write(to_write)
# Info shall be used as an ordinary logging facility, for every desired output.
def info(self, txt, forced = False, **kwargs):
kwargs['nocolor'] = self.options['nocolor']
if forced or (self.options['verbose'] or \
self.options['debug'] ) \
or (type(self.options['log']) == str and self.options['log'] != 'none'):
Logger.out(txt, self.options['log'], 'info', **kwargs)
def text(self, txt, **kwargs):
kwargs['noPrefix'] = True
kwargs['nocolor'] = self.options['nocolor']
Logger.out(txt, self.options['log'], '', **kwargs)
def dbg(self, txt, **kwargs):
if self.options['debug']:
if self.options['format'] == 'html':
txt = f'<!-- {txt} -->'
kwargs['nocolor'] = self.options['nocolor']
Logger.out(txt, self.options['log'], 'debug', **kwargs)
def err(self, txt, **kwargs):
kwargs['nocolor'] = self.options['nocolor']
Logger.out(txt, self.options['log'], 'error', **kwargs)
def fatal(self, txt, **kwargs):
kwargs['nocolor'] = self.options['nocolor']
Logger.out(txt, self.options['log'], 'error', **kwargs)
os._exit(1)
logger = Logger(options)
class Verstring(object):
def __init__(self, name, date, *versions):
self.name = name
self.date = date
self.version = versions[0].split(' ')[0]
def __eq__(self, other):
if isinstance(other, Verstring):
return packaging.version.parse(self.version) == packaging.version.parse(other.version) \
and self.name == other.name
elif isinstance(other, str):
return packaging.version.parse(self.version) == packaging.version.parse(other)
def __lt__(self, other):
return packaging.version.parse(self.version) < packaging.version.parse(other.version)
def __str__(self):
return f'{self.name}; {self.date}; {self.version}'
class SMTPHeadersAnalysis:
bad_keywords = (
'gophish', 'phishingfrenzy', 'frenzy', 'king-phisher', 'phisher',
'speedphishing',
)
Dodgy_User_Names = (
'action', 'postmaster', 'root', 'admin', 'administrator', 'offer',
'test', 'it', 'account', 'hr', 'job', 'relay', 'robot', 'help', 'catchall',
'guest', 'spam', 'abuse', 'all', 'contact', 'nobody', 'auto', 'db', 'web', 'no-reply', 'noreply',
'anonymous', 'amazon', 'microsoft', 'google', 'mailbox', 'group',
)
Header_Keywords_That_May_Contain_Spam_Info = (
'spam', 'phishing', 'bulk', 'attack', 'defend', 'assassin', 'virus', 'scan', 'mimecast',
'ironport', 'forefront', '360totalsecurity', 'acronis', 'adaware', 'adsbot-google',
'aegislab', 'ahnlab', 'altavista', 'anti-virus', 'antivirus', 'antiy', 'apexone',
'appengine-google', 'arcabit', 'avast', 'avg', 'avira', 'baidu', 'baiduspider',
'barracuda', 'bingbot', 'bitdefender', 'bitdefender', 'bluvector', 'carbon',
'carbonblack', 'check point', 'checkpoint', 'clamav', 'code42', 'comodo', 'countercept',
'countertack', 'crowdstrike', 'crowdstrike', 'curl', 'cybereason', 'cybereason',
'cylance', 'cylance', 'cynet360', 'cyren', 'defender', 'druva', 'drweb', 'duckduckbot',
'egambit', 'emsisoft', 'emsisoft', 'encase', 'endgame', 'endgame', 'ensilo', 'escan',
'eset', 'exabot', 'f-secure', 'facebookexternalhit', 'falcon', 'fidelis', 'fireeye',
'forcepoint', 'fortigate', 'fortil', 'fortinet', 'gdata', 'gdata', 'googlebot',
'gravityzone', 'huntress', 'ia_archiver', 'ikarussecurity', 'ivanti', 'juniper',
'k7antivirus', 'k7computing', 'kaspersky', 'kingsoft', 'lightcyber', 'lynx',
'malwarebytes', 'mcafee', 'mj12bot', 'msnbot', 'nanoav', 'netwitness', 'paloalto',
'paloaltonetworks', 'panda', 'proofpoint', 'python-urllib', 'scanner', 'scanning',
'secureage', 'secureworks', 'security', 'sentinelone', 'sentinelone', 'simplepie',
'slackbot-linkexpanding', 'slurp', 'sogou', 'sonicwall', 'sophos', 'superantispyware',
'symantec', 'tachyon', 'tencent', 'totaldefense', 'trapmine', 'trend micro', 'trendmicro',
'trusteer', 'trustlook', 'virusblokada', 'virustotal', 'virustotalcloud', 'webroot',
'yandex', 'yandexbot', 'zillya', 'zonealarm', 'zscaler', '-sea-', 'perlmx', 'trustwave',
'mailmarshal', 'tmase', 'startscan', 'fe-etp', 'jemd', 'suspicious', 'grey', 'infected', 'unscannable',
'dlp-', 'sanitize', 'mailscan', 'barracuda', 'clearswift', 'messagelabs', 'msw-jemd', 'fe-etp', 'symc-ess',
'starscan', 'mailcontrol', 'spamexpert', 'X-Fuglu',
)
Interesting_Headers = (
'mailgun', 'sendgrid', 'mailchimp', 'x-ses', 'x-avas', 'X-Gmail-Labels', 'X-vrfbldomain',
'mandrill', 'bulk', 'sendinblue', 'amazonses', 'mailjet', 'postmark', 'postfix', 'dovecot', 'roundcube',
'seg', '-IP', 'crosspremises', 'brightmail', 'check', 'exim', 'postfix', 'exchange', 'microsoft', 'office365',
'dovecot', 'sendmail', 'report', 'status', 'benchmarkemail', 'bronto', 'X-Complaints-To',
'X-Roving-ID', 'X-DynectEmail-Msg', 'X-elqPod', 'X-EMV-MemberId', 'e2ma', 'fishbowl', 'eloop', 'X-Google-Appengine-App-Id',
'X-ICPINFO', 'x-locaweb-id', 'X-MC-User', 'mailersend', 'MailiGen', 'Mandrill', 'MarketoID', 'X-Messagebus-Info',
'Mixmax', 'X-PM-Message-Id', 'postmark', 'X-rext', 'responsys', 'X-SFDC-User', 'salesforce', 'x-sg-', 'x-sendgrid-',
'silverpop', '.mkt', 'X-SMTPCOM-Tracking-Number', 'X-vrfbldomain', 'verticalresponse',
'yesmail', 'logon', 'safelink', 'safeattach', 'appinfo', 'X-XS4ALL-', 'client-ip', 'porn',
'X-Newsletter'
)
Security_Appliances_And_Their_Headers = \
(
('Barracuda Email Security' , 'X-Barracuda-'),
('Cisco Advanced Malware Protection (AMP)' , 'X-Amp-'),
('Cisco IronPort / Email Security Appliance (ESA)' , 'X-Policy'),
('Cisco IronPort / Email Security Appliance (ESA)' , 'X-SBRS'),
('Cisco IronPort' , 'X-IronPort-'),
('Office365' , 'X-.+Tenant.+'),
('Office365' , 'X-MS-Exchange-Organization'),
('Office365' , 'X-MS-Exchange-CrossTenant-Id'),
('Exchange Online Protection' , 'X-EOP'),
('Exchange Online Protection' , 'X-MS-Exchange-'),
('Exchange Online Protection - First Contact Safety' , 'X-.+-EnableFirstContactSafetyTip'),
('Exchange Online Protection - Enhanced Filtering' , 'X-.+-SkipListedInternetSender'),
('Exchange Online Protection - Enhanced Filtering' , 'X-.+-ExternalOriginalInternetSender'),
('Exchange Server 2016 Anti-Spam' , 'SpamDiagnostic'),
('FireEye Email Security Solution' , 'X-FE-'),
('FireEye Email Security Solution' , 'X-FEAS-'),
('FireEye Email Security Solution' , 'X-FireEye'),
('Mimecast' , 'X-Mimecast-'),
('Fuglu - mail scanner for postfix' , 'X-Fuglu'),
('MS Defender Advanced Threat Protection - Safe Links' , '-ATPSafeLinks'),
('MS Defender Advanced Threat Protection' , 'X-MS.+-Atp'),
('MS Defender for Office365' , '-Safelinks'),
('MS ForeFront Anti-Spam' , 'X-Forefront-Antispam'),
('MS ForeFront Anti-Spam' , 'X-Microsoft-Antispam'),
('n-able Mail Assure (SpamExperts)' , 'SpamExperts-'),
('OVH Anti-Spam' , 'X-Ovh-'),
('OVH Anti-Spam' , 'X-VR-'),
('Proofpoint Email Protection' , 'X-Proofpoint'),
('Sophos Email Appliance (PureMessage)' , 'X-SEA-'),
('SpamAssassin' , 'X-IP-Spam-'),
('SpamAssassin' , 'X-Spam-'),
('Symantec Email Security' , 'X-SpamInfo'),
('Symantec Email Security' , 'X-SpamReason'),
('Symantec Email Security' , 'X-Brightmail-Tracker'),
('Symantec Email Security' , 'X-StarScan'),
('Symantec Email Security' , 'X-SYMC-'),
('Trend Micro Anti-Spam' , 'X-TM-AS-'),
('Trend Micro Anti-Spam' , 'X-TMASE-'),
('Trend Micro InterScan Messaging Security' , 'X-IMSS-'),
('Cloudmark Security Platform' , 'X-CNFS-'),
('Cloudmark Security Platform' , 'X-CMAE-'),
('VIPRE Email Security' , 'X-Vipre-'),
('Sunbelt Software Ninja Email Security' , 'X-Ninja-'),
('WP.pl / o2.pl Email Scanner' , 'X-WP-AV-'),
)
Security_Appliances_And_Their_Values = \
(
('Exchange Online Protection' , '.protection.outlook.com'),
)
Headers_Known_For_Breaking_Line = (
'Received',
'Authentication-Results',
'Received-SPF',
'DKIM-Signature',
'X-Google-DKIM-Signature',
'X-GM-Message-State',
'Subject',
'X-MS-Exchange-Organization-ExpirationStartTime',
'X-MS-Exchange-Organization-Network-Message-Id',
'X-Forefront-Antispam-Report',
'X-MS-Exchange-CrossTenant-OriginalArrivalTime',
'X-Microsoft-Antispam-Mailbox-Delivery',
'X-Microsoft-Antispam-Message-Info'
)
#
# This array will be (partially) dynamically adjusted by the script by SMTPHeadersAnalysis.getHeader method.
#
# Add here header names that are processed by the script, but not passed to `getHeader` method
# in order to skip them from "Other Interesting Headers" sweep scan.
#
Handled_Spam_Headers = [
'X-Forefront-Antispam-Report',
'X-Exchange-Antispam',
'X-Exchange-Antispam-Mailbox-Delivery',
'X-Exchange-Antispam-Message-Info',
'X-Microsoft-Antispam-Report-CFA-Test',
]
auth_result = {
'none': 'The message was not signed.',
'pass': logger.colored('The message was signed, the signature or signatures were acceptable to the ADMD, and the signature(s) passed verification tests.', 'green'),
'fail': logger.colored('The message was signed and the signature or signatures were acceptable to the ADMD, but they failed the verification test(s).', 'red'),
'policy': 'The message was signed, but some aspect of the signature or signatures was not acceptable to the ADMD.',
'neutral': logger.colored('The message was signed, but the signature or signatures contained syntax errors or were not otherwise able to be processed.', 'magenta'),
'temperror': logger.colored('The message could not be verified due to some error that is likely transient in nature, such as a temporary inability to retrieve a public key.', 'red'),
'permerror': logger.colored('The message could not be verified due to some error that is unrecoverable, such as a required header field being absent.', 'red'),
}
IronPort_AV = {
'i' : (
'Version Information',
(
'Product Version',
'Number of IDEs',
'IDE Serial '
)
),
'E' : (
'AV scanning engine',
''
),
'e' : (
'Errors',
{
"i" : 'ignored',
"u" : logger.colored('unscannable', 'red'),
"e" : 'encrypted',
"t" : 'timeout',
"f" : 'fatal',
"j" : 'savi-bug (ignored)',
"s" : 'savi-bug (unscannable)',
"z" : 'unknown',
}
),
'v' : (
'Virus List',
(
'extension',
'type code list'
)
),
'd' : (
'File details',
(
'extension',
'type code list'
)
),
'a' : (
'Message actions',
{
'_map' : {
'N' : 'notification',
'H' : 'headers',
'T' : 'time',
':' : 'action'
},
'action' : {
"a" : 'archived ?',
"s" : logger.colored('sent', 'green'),
"d" : logger.colored('dropped', 'red'),
"f" : 'forwarded',
"x" : 'certain errors (timed-out, rpc conn fails, etc)',
},
'notification' : {
"s" : 'sender',
"r" : 'recipient',
"o" : 'other',
},
'headers' : {
"s" : 'subject modified',
"h" : 'custom header modified',
},
'time' : {
},
}
)
}
Aterisk_Risk_Score = {
'*' : logger.colored('lowest risk associated', 'green'),
'**' : logger.colored('low risk associated', 'green'),
'***' : logger.colored('moderately low risk associated', 'yellow'),
'****' : logger.colored('moderately high risk associated', 'yellow'),
'*****' : logger.colored('high risk associated', 'red'),
'******' : logger.colored('highest risk associated', 'red'),
}
AMP_Results = {
'CLEAN' : logger.colored('No malware detected.', "green"),
'MALICIOUS' : logger.colored('Malware detected.', "red"),
'UNKNOWN' : logger.colored('Could not categorize the message.', "magenta"),
'UNSCANNABLE' : logger.colored('Could not scan the message.', "yellow"),
}
Forefront_Antispam_Report = {
'ARC' : (
'ARC Protocol',
{
'AAR': 'Records the content of the Authentication-results header from DMARC.',
'AMS': 'Includes cryptographic signatures of the message.',
'AS': 'Includes cryptographic signatures of the message headers'
}
),
'CAT' : (
'The category of protection policy',
{
'BULK': logger.colored('Bulk', 'red'),
'DIMP': logger.colored('Domain Impersonation', 'red'),
'GIMP': logger.colored('Mailbox intelligence based impersonation', 'red'),
'HPHSH': logger.colored('High confidence phishing', 'red'),
'HPHISH': logger.colored('High confidence phishing', 'red'),
'HSPM': logger.colored('High confidence spam', 'red'),
'MALW': logger.colored('Malware', 'red'),
'PHSH': logger.colored('Phishing', 'red'),
'SPM': logger.colored('Spam', 'red'),
'SPOOF': logger.colored('Spoofing', 'red'),
'UIMP': logger.colored('User Impersonation', 'red'),
'AMP': logger.colored('Anti-malware', 'red'),
'SAP': logger.colored('Safe attachments', 'green'),
'OSPM': logger.colored('Outbound spam', 'red'),
'NONE': logger.colored('Clean message', 'green'),
}
),
'CTRY' : (
'The source country as determined by the connecting IP address',
''
),
'H' : (
'The HELO or EHLO string of the connecting email server.',
''
),
'IPV' : (
'Ingress Peer Verification status',
{
'CAL' : logger.colored('Source IP address was Configured in Allowed List (CAL)', 'green'),
'NLI' : 'The IP address was not found on any IP reputation list.',
}
),
'EFV' : (
'Egress F(?) Verification status',
{
'CAL' : logger.colored('Source IP address was Configured in Allowed List (CAL)', 'green'),
'NLI' : 'The IP address was not found on any IP reputation list.',
}
),
'DIR' : (
'Direction of email verification',
{
'INB' : 'Inbound email verification',
'OUT' : 'Outbound email verification',
'OUB' : 'Outbound email verification',
'OTB' : 'Outbound email verification',
}
),
'LANG' : (
'The language in which the message was written',
''
),
'PTR' : (
'Reverse DNS of the Connecting IP peer\'s address',
''
),
'SFTY' : (
'The message was identified as phishing',
{
'9.19': logger.colored('Domain impersonation. The sending domain is attempting to impersonate a protected domain', 'red'),
'9.20' : logger.colored('User impersonation. The sending user is attempting to impersonate a user in the recipient\'s organization', 'red'),
}
),
'SRV' : (
'Bulk Email analysis results',
{
'BULK' : logger.colored('The message was identified as bulk email by spam filtering and the bulk complaint level (BCL) threshold', 'red'),
}
),
'SFV' : (
'Message Filtering',
{
'BLK' : logger.colored('Filtering was skipped and the message was blocked because it was sent from an address in a user\'s Blocked Senders list.', 'red'),
'NSPM' : logger.colored('Spam filtering marked the message as non-spam and the message was sent to the intended recipients.', 'green'),
'SFE' : logger.colored('Filtering was skipped and the message was allowed because it was sent from an address in a user\'s Safe Senders list.', 'green'),
'SKA' : logger.colored('The message skipped spam filtering and was delivered to the Inbox because the sender was in the allowed senders list or allowed domains list in an anti-spam policy.', 'green'),
'SKB' : logger.colored('The message was marked as spam because it matched a sender in the blocked senders list or blocked domains list in an anti-spam policy.', 'red'),
'SKI' : 'Similar to SFV:SKN, the message skipped spam filtering for another reason (for example, an intra-organizational email within a tenant).',
'SKN' : logger.colored('The message was marked as non-spam prior to being processed by spam filtering. For example, the message was marked as SCL -1 or Bypass spam filtering by a mail flow rule.', 'green'),
'SKQ' : logger.colored('The message was released from the quarantine and was sent to the intended recipients.', 'cyan'),
'SKS' : logger.colored('The message was marked as spam prior to being processed by spam filtering. For example, the message was marked as SCL 5 to 9 by a mail flow rule.', 'red'),
'SPM' : logger.colored('The message was marked as spam by spam filtering.', 'red'),
}
),
}
Barracuda_Score_Thresholds = [
[0.0, 2.99, logger.colored('Delivered to Inbox', 'green')],
[3.0, 4.99, logger.colored('Delivered to Inbox. Subject line tagged with [Suspected SPAM]', 'yellow')],
[5.0, 6.99, logger.colored('Delivered to Barracuda Quarantine Inbox', 'red')],
[7.0, 10.0, logger.colored('Blocked from delivery', 'red')],
]
Barracuda_Aggressive_Score_Thresholds = [
[0.0, 1.99, logger.colored('Delivered to Inbox', 'green')],
[2.0, 3.49, logger.colored('Delivered to Inbox. Subject line tagged with [SPAM?]', 'yellow')],
[3.5, 5.00, logger.colored('Delivered to Barracuda Quarantine Inbox', 'red')],
[5.1, 10.0, logger.colored('Blocked from delivery', 'red')],
]
Trend_Type_AntiSpam = {
1 : logger.colored('Spam', 'red'),
2 : logger.colored('Phishing', 'red'),
}
Spam_Diagnostics_Metadata = {
'NSPM' : logger.colored('Not Spam', 'green'),
'SPAM' : logger.colored('SPAM', 'red'),
}
#
# Below rules were collected solely in a trial-and-error manner or by scraping any
# pieces of information from all around the Internet.
#
# They do not represent the actual Anti-Spam rule name or context and surely represent
# something close to what is understood (or they may have totally different meaning).
#
# Until we'll be able to review anti-spam rules documention, there is no viable mean to map
# rule ID to its meaning.
#
Anti_Spam_Rules_ReverseEngineered = \
{
'35100500006' : logger.colored('(SPAM) Message contained embedded image.', 'red'),
# https://docs.microsoft.com/en-us/answers/questions/416100/what-is-meanings-of-39x-microsoft-antispam-mailbox.html
'520007050' : logger.colored('(SPAM) Moved message to Spam and created Email Rule to move messages from this particular sender to Junk.', 'red'),
# triggered on an empty mail with subject being: "test123 - viagra"
'162623004' : 'Subject line contained suspicious words (like Viagra).',
# triggered on mail with subject "test123" and body being single word "viagra"
'19618925003' : 'Mail body contained suspicious words (like Viagra).',
# triggered on mail with empty body and subject "Click here"
'28233001' : 'Subject line contained suspicious words luring action (ex. "Click here"). ',
# triggered on a mail with test subject and 1500 words of http://nietzsche-ipsum.com/
'30864003' : 'Mail body contained a lot of text (more than 10.000 characters).',
# mails that had simple message such as "Hello world" triggered this rule, whereas mails with
# more than 150 words did not.
'564344004' : 'HTML mail body with less than 150 words of text (not sure how much less though)',
# message was sent with a basic html and only one <u> tag in body.
'67856001' : 'HTML mail body contained underline <u> tag.',
# message with html,head,body and body containing simple text with no b/i/u formatting.
'579124003' : 'HTML mail body contained text, but no text formatting (<b>, <i>, <u>) was present',
# This is a strong signal. Mails without <a> doesnt have this rule.
'166002' : 'HTML mail body contained URL <a> link.',
# Message contained <a href="https://something.com/file.html?parameter=value" - GET parameter with value.
'21615005' : 'Mail body contained <a> tag with URL containing GET parameter: ex. href="https://foo.bar/file?aaa=bbb"',
# Message contained <a href="https://something.com/file.html?parameter=https://another.com/website"
# - GET parameter with value, being a URL to another website
'45080400002' : 'Something about <a> tag\'s URL. Possibly it contained GET parameter with value of another URL: ex. href="https://foo.bar/file?aaa=https://baz.xyz/"',
# Message contained <a> with href pointing to a file with dangerous extension, such as file.exe
'460985005' : 'Mail body contained HTML <a> tag with href URL pointing to a file with dangerous extension (such as .exe)',
#
# Message1: GoPhish -> VPS 587/tcp redirector -> smtp.gmail.com:587 -> target
# Message2: GoPhish -> VPS 587/tcp redirector -> smtp-relay.gmail.com:587 -> target
#
# These were the only differences I spotted:
# Message1 - FirstHop Gmail SMTP Received with ESMTPS.
# Message2 - FirstHop Gmail SMTP-Relay Received with ESMTPSA.
#
'121216002' : 'First Hop MTA SMTP Server used as a SMTP Relay. It\'s known to originate e-mails, but here it acted as a Relay. Or maybe due to use of "with ESMTPSA" instead of ESMTPS?',
# Triggered on message with <a> added to HTML: <a href="https://support.spotify.com/is-en/">https://www.reddit.com/</a>
'966005' : 'Mail body contained link tag with potentially masqueraded URL: <a href="https://attacker.com">https://example.com</a>',
#
# Message1: GoPhish EC2 -> another EC2 with socat to smtp.gmail.com:587 (authenticated) -> Target
# Message2: GoPhish EC2 -> Gsuite -> Target
#
# Subject, mail body were exactly the same.
#
# Below two rules were added to the second message. My understanding is that they're somehow referring
# to the reputation of the first-hop server, maybe reverse-DNS resolution.
#
'5002400100002' : "(GUESSING) Somehow related to First Hop server reputation, it's reverse-PTR resolution or domain impersonation",
'58800400005' : "(GUESSING) Somehow related to First Hop server reputation, it's reverse-PTR resolution or domain impersonation",
'19625305002' : '(GUESSING) Something to do with the HTML code and used tags/structures',
'43540500002' : '(GUESSING) Something to do with the HTML code and used tags/structures',
'460985005' : '(GUESSING) Something to do with either more-complex HTML code or with the <a> tag and its URL.',
# Triggered on an empty text message, subject "test" - that was marked with "Domain Impersonation", however
# ForeFront Anti-Spam headers did not support that Domain Impersonation. Weird.
'22186003' : '(GUESSING) Something to do with either Text message (non-HTML) or probable Domain Impersonation',
# Found by @ipSlav (https://github.com/mgeeky/decode-spam-headers/issues/15)
'42882007' : 'Missing Reply-To Address. Might be fixed by adding -ReplyTo flag to Send-MailMessage',
'78352004' : 'Missing Reply-To Address. Might be fixed by adding -ReplyTo flag to Send-MailMessage',
}
ForeFront_Spam_Confidence_Levels = {
-1 : (False, logger.colored('The message skipped spam filtering. WHITELISTED.', 'green')),
0 : (False, logger.colored('Spam filtering determined the message was not spam.', 'green')),
1 : (False, 'The message skipped spam filtering'),
5 : (True, logger.colored('Spam filtering marked the message as Spam', 'red')),
6 : (True, logger.colored('Spam filtering marked the message as Spam', 'red')),
9 : (True, logger.colored('Spam filtering marked the message as High confidence spam', 'red')),
}
ForeFront_Phishing_Confidence_Levels = {
1 : (False, 'The message content isn\'t likely to be phishing'),
2 : (False, 'The message content isn\'t likely to be phishing'),
3 : (False, 'The message content isn\'t likely to be phishing'),
4 : (True, logger.colored('The message content is likely to be phishing.', 'red')),
5 : (True, logger.colored('The message content is likely to be phishing.', 'red')),
6 : (True, logger.colored('The message content is likely to be phishing.', 'red')),
7 : (True, logger.colored('The message content is likely to be phishing.', 'red')),
8 : (True, logger.colored('The message content is likely to be phishing.', 'red')),
}
ForeFront_Bulk_Confidence_Levels = {
0 : logger.colored('The message isn\'t from a bulk sender.', 'green'),
1 : logger.colored('The message is from a bulk sender that generates few complaints.', 'yellow'),
2 : logger.colored('The message is from a bulk sender that generates few complaints.', 'yellow'),
3 : logger.colored('The message is from a bulk sender that generates few complaints.', 'yellow'),
4 : logger.colored('The message is from a bulk sender that generates a mixed number of complaints.', 'red'),
5 : logger.colored('The message is from a bulk sender that generates a mixed number of complaints.', 'red'),
6 : logger.colored('The message is from a bulk sender that generates a mixed number of complaints.', 'red'),
7 : logger.colored('The message is from a bulk sender that generates a mixed number of complaints.', 'red'),
8 : logger.colored('The message is from a bulk sender that generates a high number of complaints.', 'red'),
9 : logger.colored('The message is from a bulk sender that generates a high number of complaints.', 'red'),
}
ATP_Message_Properties = {
'SA' : 'Safe Attachments',
'SL' : 'Safe Links',
}
TLCOOBClassifiers = {
'OLM' : (
'',
{
}
)
}
SpamExperts_Classes = {
'spam' : logger.colored("system was not confident enough to block the message", "red"),
'unsure' : logger.colored("system was not confident enough to block the message", "magenta"),
'ham' : logger.colored("", "yellow"),
}
SpamExperts_Actions = {
'accept' : logger.colored("Message is accepted.", "green"),
'drop' : logger.colored("Message is dropped.", "red"),
}
SEA_Spam_Fields = {
'gauge' : 'Spam Message Gauge result',
'probability' : 'Spam Probability (100% - certain spam)',
'report' : 'Anti-Spam rules that matched the message along with their probability',
}
SpamAssassin_Spam_Status = (
'SpamAssassin spam evaluation status report',
{
'_result' : 'Whether the message is Spam',
'score' : 'Total score for the message (negative if whitelisted)',
'required' : 'The score that would be required to be classed as spam',
'tests' : 'List of tests that returned non-zero value',
'autolearn' : 'Whether autolearn learned the message as spam or ham',
'version' : 'Version of SpamAssassin used',
'hits' : 'Number of characteristics considering this message as Spam',
'tagged_above' : 'Tag message with SpamAssassin report if above threshold',
}
)
Cisco_Predefined_MailFlow_Policies = {
'$TRUSTED' : logger.colored('Mails from this sender are TRUSTED and will not be scanned by Anti-Spam or Anti-Virus.', 'green'),
'$BLOCKED' : logger.colored('Mails from this sender are BLOCKED', 'red'),
'$THROTTLED' : logger.colored('Mails from this sender are slowed down because they were considered suspicious. Messages will be scanned.', 'magenta'),
'$ACCEPTED' : logger.colored('Mail flow policies were undecided about the sender so they accepted the message. Message will be scanned and reputation evaluated.', 'green'),
}
Forefront_Antispam_Delivery = {
'dest' : (
'Destination where message should be placed',
{
'I' : logger.colored('Inbox directory', 'green'),
'J' : logger.colored('JUNK directory', 'red'),