-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathtests.py
More file actions
executable file
·1711 lines (1506 loc) · 67.5 KB
/
tests.py
File metadata and controls
executable file
·1711 lines (1506 loc) · 67.5 KB
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/env python3
# -*- coding: utf-8 -*-https://github.com/domainaware/checkdmarc
"""Automated tests"""
import json
import os
import unittest
from unittest.mock import patch
import dns.resolver
import checkdmarc
import checkdmarc.bimi
import checkdmarc.dmarc
import checkdmarc.dnssec
import checkdmarc.mta_sts
import checkdmarc.smtp_tls_reporting
import checkdmarc.soa
import checkdmarc.spf
import checkdmarc.utils
from typing import Any, cast
from checkdmarc.spf import ParsedSPFMXMechanism, SPFAMechanism
from checkdmarc.soa import SOARecordSuccessful
# Detect if running in GitHub Actions to skip DNS lookups
OFFLINE_MODE = os.environ.get("GITHUB_ACTIONS", "false").lower() == "true"
known_good_domains = ["fbi.gov", "pm.me", "ssa.gov"]
class Test(unittest.TestCase):
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testKnownGood(self):
"""Domains with known good, SPF and DMARC records"""
results = checkdmarc.check_domains(known_good_domains)
if not isinstance(results, list):
results = [results]
for result in results:
spf_result = cast(Any, result["spf"])
dmarc_result = result["dmarc"]
spf_error = None
dmarc_error = None
if "error" in spf_result:
spf_error = spf_result["error"]
if "error" in dmarc_result:
dmarc_error = dmarc_result["error"]
self.assertEqual(
spf_result["valid"],
True,
"Known good domain {0} failed SPF check:\n\n{1}".format(
result["domain"], spf_error
),
)
self.assertEqual(
dmarc_result["valid"],
True,
"Known good domain {0} failed DMARC check:\n\n{1}".format(
result["domain"], dmarc_error
),
)
def testDMARCMixedFormatting(self):
"""DMARC records with extra spaces and mixed case are still valid"""
examples = [
"v=DMARC1;p=ReJect",
"v = DMARC1;p=reject;",
"v = DMARC1\t;\tp=reject\t;",
"v = DMARC1\t;\tp\t\t\t=\t\t\treject\t;",
"V=DMARC1;p=reject;",
]
for example in examples:
parsed_record = checkdmarc.dmarc.parse_dmarc_record(example, "")
self.assertIsInstance(parsed_record, dict)
def testGetBaseDomain(self):
subdomain = "foo.example.com"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "example.com"
# Test reserved domains
subdomain = "_dmarc.nonauth-rua.invalid.example"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "invalid.example"
subdomain = "_dmarc.nonauth-rua.invalid.test"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "invalid.test"
subdomain = "_dmarc.nonauth-rua.invalid.invalid"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "invalid.invalid"
subdomain = "_dmarc.nonauth-rua.invalid.localhost"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "invalid.localhost"
# Test newer PSL entries
subdomain = "e3191.c.akamaiedge.net"
result = checkdmarc.utils.get_base_domain(subdomain)
assert result == "c.akamaiedge.net"
def testUppercaseSPFMechanism(self):
"""Treat uppercase SPF mechanisms as valid"""
spf_record = "v=spf1 IP4:147.75.8.208 -ALL"
domain = "example.no"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 0)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testSplitSPFRecord(self):
"""Split SPF records are parsed properly"""
rec = '"v=spf1 ip4:147.75.8.208 " "include:_spf.salesforce.com -all"'
parsed_record = checkdmarc.spf.parse_spf_record(rec, "example.com")
self.assertEqual(parsed_record["parsed"]["all"], "fail")
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testJunkAfterAll(self):
"""Ignore any mechanisms after the all mechanism, but warn about it"""
rec = "v=spf1 ip4:213.5.39.110 -all MS=83859DAEBD1978F9A7A67D3"
domain = "avd.dk"
warning = (
"Any text after the all mechanism other than an exp modifier is ignored."
)
parsed_record = checkdmarc.spf.parse_spf_record(rec, domain)
self.assertIn(warning, parsed_record["warnings"])
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testDNSSEC(self):
"""Test known good DNSSEC"""
self.assertEqual(checkdmarc.dnssec.test_dnssec("fbi.gov"), True)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testIncludeMissingSPF(self):
"""A warning is included for SPF records that include domains that are missing SPF records"""
spf_record = "v=spf1 include:example.doesnotexist ~all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertTrue(
"example.doesnotexist: The domain does not exist." in results["warnings"]
)
self.assertEqual(results["dns_lookups"], 1)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testTooManySPFDNSLookups(self):
"""SPF records with > 10 SPF mechanisms that cause DNS lookups raise
SPFTooManyDNSLookups"""
spf_record = (
"v=spf1 a include:_spf.salesforce.com "
"include:spf.protection.outlook.com "
"include:spf.constantcontact.com "
"include:_spf.elasticemail.com "
"include:servers.mcsv.net "
"include:_spf.google.com "
"include:service-now.com "
"~all"
)
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFTooManyDNSLookups,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testTooManySPFVoidDNSLookups(self):
"""SPF records with > 2 void DNS lookups"""
spf_record = (
"v=spf1 a:13Mk4olS9VWhQqXRl90fKJrD.example.com "
"mx:SfGiqBnQfRbOMapQJhozxo2B.example.com "
"a:VAFeyU9N2KJX518aGsN3w6VS.example.com "
"~all"
)
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFTooManyVoidDNSLookups,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFSyntaxErrors(self):
"""SPF record syntax errors raise SPFSyntaxError"""
spf_record = (
'"v=spf1 mx a:mail.cohaesio.net include: trustpilotservice.com ~all"'
)
domain = "2021.ai"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv4(self):
"""Invalid ipv4 SPF mechanism values raise SPFSyntaxError"""
spf_record = (
"v=spf1 ip4:78.46.96.236 +a +mx +ip4:138.201.239.158 "
"+ip4:78.46.224.83 "
"+ip4:relay.mailchannels.net +ip4:138.201.60.20 ~all"
)
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv6inIPv4(self):
"""Invalid ipv4 SPF mechanism values raise SPFSyntaxError"""
spf_record = "v=spf1 ip4:1200:0000:AB00:1234:0000:2552:7777:1313 ~all"
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv4Range(self):
"""Invalid ipv4 SPF mechanism values raise SPFSyntaxError"""
spf_record = "v=spf1 ip4:78.46.96.236/99 ~all"
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv6(self):
"""Invalid ipv6 SPF mechanism values raise SPFSyntaxError"""
spf_record = "v=spf1 ip6:1200:0000:AB00:1234:O000:2552:7777:1313 ~all"
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv4inIPv6(self):
"""Invalid ipv6 SPF mechanism values raise SPFSyntaxError"""
spf_record = "v=spf1 ip6:78.46.96.236 ~all"
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFInvalidIPv6Range(self):
"""Invalid ipv6 SPF mechanism values raise SPFSyntaxError"""
record = "v=spf1 ip6:1200:0000:AB00:1234:0000:2552:7777:1313/130 ~all"
domain = "surftown.dk"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
record,
domain,
)
def testSPFInvalidMissingSpaceBeforeAllMechanism(self):
"""There is not a space between the IP4 and all mechanism in the SPF record."""
spf_record = "v=spf1 ip4:8.8.8.8~all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFIncludeLoop(self):
"""SPF record with include loop raises SPFIncludeLoop"""
spf_record = '"v=spf1 include:example.com"'
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFIncludeLoop,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testSPFMissingMXRecord(self):
"""A warning is issued if an SPF record contains a mx mechanism
pointing to a domain that has no MX records"""
spf_record = '"v=spf1 mx ~all"'
domain = "seanthegeek.net"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn(
"{0}: An mx mechanism points to {0}, but that domain/subdomain does not have any MX records.".format(
domain
),
results["warnings"],
)
self.assertEqual(results["dns_lookups"], 1)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testSPFMissingARecord(self):
"""A warning is issued if an SPF record contains an a mechanism
pointing to a domain that has no A records"""
spf_record = '"v=spf1 a ~all"'
domain = "cardinalhealth.net"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
snipit = "that domain/subdomain does not have any A/AAAA records."
self.assertTrue(any(snipit in s for s in results["warnings"]))
self.assertEqual(results["dns_lookups"], 1)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testSPFMXMechanism(self):
"""Addresses are included in the output for SPF records with an mx lookup"""
spf_record = "v=spf1 mx:proton.me ~all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
for mechanism in results["parsed"]["mechanisms"]:
if mechanism["mechanism"] == "mx":
mx_mechanism = cast(ParsedSPFMXMechanism, mechanism)
self.assertTrue(len(mx_mechanism["hosts"]) > 0)
for host in mx_mechanism["hosts"]:
self.assertTrue(len(host) > 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFMacrosExists(self):
"""SPF macros can be used with the exists mechanism"""
record = "v=spf1 exists:exists:%{i}.spf.hc0000-xx.iphmx.com ~all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(record, domain)
self.assertTrue(len(results["parsed"]["mechanisms"]) > 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFMacrosInclude(self):
"""SPF macros can be used with the exists mechanism"""
record = "v=spf1 include:include:%{ir}.%{v}.%{d}.spf.has.pphosted.com ~all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(record, domain)
self.assertTrue(len(results["parsed"]["mechanisms"]) > 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFAMechanism(self):
"""Addresses are included in the output for SPF records with an a lookup"""
spf_record = "v=spf1 a ~all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
for mechanism in results["parsed"]["mechanisms"]:
if mechanism["mechanism"] == "a":
a_mechanism = cast(SPFAMechanism, mechanism)
self.assertTrue(len(a_mechanism["addresses"]) > 0)
self.assertEqual(results["dns_lookups"], 1)
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testDMARCPctLessThan100Warning(self):
"""A warning is issued if the DMARC pct value is less than 100"""
snipit = "pct value is less than 100"
dmarc_record = (
"v=DMARC1; p=none; sp=none; fo=1; pct=50; adkim=r; "
"aspf=r; rf=afrf; ri=86400; "
"rua=mailto:eits.dmarcrua@energy.gov; "
"ruf=mailto:eits.dmarcruf@energy.gov"
)
domain = "energy.gov"
results = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(any(snipit in s for s in results["warnings"]))
def testInvalidDMARCURI(self):
"""An invalid DMARC report URI raises InvalidDMARCReportURI"""
dmarc_record = (
"v=DMARC1; p=none; rua=reports@dmarc.cyber.dhs.gov,"
"mailto:dmarcreports@usdoj.gov"
)
domain = "dea.gov"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCReportURI,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
dmarc_record = (
"v=DMARC1; p=none; rua=__"
"mailto:reports@dmarc.cyber.dhs.gov,"
"mailto:dmarcreports@usdoj.gov"
)
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCReportURI,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testInvalidDMARCPolicyValue(self):
"""An invalid DMARC policy value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=foo; rua=mailto:dmarc@example.com"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCbisNewTagNp(self):
"""DMARCbis np tag is parsed correctly"""
dmarc_record = "v=DMARC1; p=reject; np=quarantine"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["np"]["value"], "quarantine")
self.assertTrue(result["tags"]["np"]["explicit"])
def testDMARCbisNewTagPsd(self):
"""DMARCbis psd tag is parsed correctly"""
dmarc_record = "v=DMARC1; p=reject; psd=n"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["psd"]["value"], "n")
self.assertTrue(result["tags"]["psd"]["explicit"])
def testDMARCbisNewTagT(self):
"""DMARCbis t tag is parsed correctly"""
dmarc_record = "v=DMARC1; p=reject; t=y"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["t"]["value"], "y")
self.assertTrue(result["tags"]["t"]["explicit"])
def testDMARCbisInvalidNpValue(self):
"""An invalid np tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; np=invalid"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCbisInvalidPsdValue(self):
"""An invalid psd tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; psd=x"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCbisInvalidTValue(self):
"""An invalid t tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; t=x"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCbisPctRemovedWarning(self):
"""A warning is issued when the removed pct tag is used"""
dmarc_record = "v=DMARC1; p=reject; pct=100"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(
any("pct tag was removed in DMARCbis" in w for w in result["warnings"])
)
def testDMARCbisRfRemovedWarning(self):
"""A warning is issued when the removed rf tag is used"""
dmarc_record = "v=DMARC1; p=reject; rf=afrf"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(
any("rf tag was removed in DMARCbis" in w for w in result["warnings"])
)
def testDMARCbisRiRemovedWarning(self):
"""A warning is issued when the removed ri tag is used"""
dmarc_record = "v=DMARC1; p=reject; ri=3600"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(
any("ri tag was removed in DMARCbis" in w for w in result["warnings"])
)
@unittest.skip(reason="This test will be used once DMARCbis is released")
def testDMARCbisMissingPTagWarning(self):
"""A missing p tag results in a warning and defaults to none"""
dmarc_record = "v=DMARC1; rua=mailto:dmarc@example.com"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["p"]["value"], "none")
self.assertFalse(result["tags"]["p"]["explicit"])
warning = (
"A missing p tag is equivalent to p=none in DMARCbis, "
"but a p tag is required in older versions of DMARC."
)
self.assertTrue(any(warning in w for w in result["warnings"]))
def testDMARCbisNpDefaultsToSp(self):
"""The np tag defaults to the sp tag value when not explicit"""
dmarc_record = "v=DMARC1; p=reject; sp=quarantine"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["np"]["value"], "quarantine")
self.assertFalse(result["tags"]["np"]["explicit"])
def testDMARCbisNpDefaultsToP(self):
"""The np tag defaults to the p tag value when sp is also absent"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["np"]["value"], "reject")
self.assertFalse(result["tags"]["np"]["explicit"])
def testDMARCbisPsdDefaultsToU(self):
"""The psd tag defaults to u when not explicit"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["psd"]["value"], "u")
self.assertFalse(result["tags"]["psd"]["explicit"])
def testDMARCbisTDefaultsToN(self):
"""The t tag defaults to n when not explicit"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertEqual(result["tags"]["t"]["value"], "n")
self.assertFalse(result["tags"]["t"]["explicit"])
def testDMARCbisRemovedTagImplicitNoWarning(self):
"""No warning is issued for implicit (default) removed tags"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
removed_warnings = [w for w in result["warnings"] if "removed in DMARCbis" in w]
self.assertEqual(len(removed_warnings), 0)
def testDMARCbisBackwardCompatibility(self):
"""Old RFC 7489 records with all tags are still valid"""
dmarc_record = (
"v=DMARC1; p=none; sp=none; fo=1; pct=50; adkim=r; "
"aspf=r; rf=afrf; ri=86400; "
"rua=mailto:eits.dmarcrua@energy.gov; "
"ruf=mailto:eits.dmarcruf@energy.gov"
)
domain = "energy.gov"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertIsInstance(result, dict)
self.assertIn("tags", result)
def testDMARCbisTreeWalkDiscovery(self):
"""DNS tree walk discovers DMARC records for parent domains"""
# This tests that the tree walk works by using a mock
with patch("checkdmarc.dmarc._query_dmarc_record") as mock_query:
with patch("checkdmarc.dmarc.query_dns") as mock_root_dns:
mock_root_dns.return_value = []
# First call for sub.example.com returns None
# Walk: example.com returns a record
mock_query.side_effect = [
None, # _dmarc.sub.example.com
"v=DMARC1; p=reject", # _dmarc.example.com
]
result = checkdmarc.dmarc.query_dmarc_record("sub.example.com")
self.assertEqual(result["location"], "example.com")
self.assertEqual(result["record"], "v=DMARC1; p=reject")
@unittest.skipIf(OFFLINE_MODE, "No network access in GitHub Actions")
def testBIMI(self):
"""Test BIMI checks"""
domain = "chase.com"
results = checkdmarc.bimi.check_bimi(domain)
self.assertEqual(len(cast(Any, results)["warnings"]), 0)
def testSPFValidAMechanismMacro(self):
"""SPF records with valid macros are accepted"""
spf_record = "v=spf1 a:%{l}.example.com -all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("mechanisms", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenAMechanismMacro(self):
"""SPF records with invalid macros raise SPFSyntaxError"""
spf_record = "v=spf1 a:%{?} -all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidMXMechanismMacro(self):
"""SPF records with valid macros in mx mechanism are accepted"""
spf_record = "v=spf1 mx:%{d} -all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("mechanisms", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenMXMechanismMacro(self):
"""SPF records with invalid macros in mx mechanism raise SPFSyntaxError"""
spf_record = "v=spf1 mx:%{?} -all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidPTRMechanismMacro(self):
"""SPF records with valid macros in ptr mechanism are accepted (but warn about ptr usage)"""
spf_record = "v=spf1 ptr:%{d} -all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("mechanisms", results["parsed"])
# PTR mechanism always raises a warning in checkdmarc
self.assertTrue(
any("ptr mechanism should not be used" in w for w in results["warnings"])
)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenPTRMechanismMacro(self):
"""SPF records with invalid macros in ptr mechanism raise SPFSyntaxError"""
spf_record = "v=spf1 ptr:%{?} -all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidIncludeMechanismMacro(self):
"""SPF records with valid macros in include mechanism are accepted"""
spf_record = "v=spf1 include:%{d}._spf.example.com -all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("mechanisms", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenIncludeMechanismMacro(self):
"""SPF records with invalid macros in include mechanism raise SPFSyntaxError"""
spf_record = "v=spf1 include:%{?}._spf.example.com -all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidExistsMechanismMacro(self):
"""SPF records with valid macros in exists mechanism are accepted"""
spf_record = "v=spf1 exists:%{i}._spf.example.com -all"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("mechanisms", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenExistsMechanismMacro(self):
"""SPF records with invalid macros in exists mechanism raise SPFSyntaxError"""
spf_record = "v=spf1 exists:%{?}._spf.example.com -all"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidRedirectModifierMacro(self):
"""SPF records with valid macros in redirect modifier are accepted"""
spf_record = "v=spf1 redirect=%{d}._spf.example.com"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("redirect", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 1)
def testSPFBrokenRedirectModifierMacro(self):
"""SPF records with invalid macros in redirect modifier raise SPFSyntaxError"""
spf_record = "v=spf1 redirect=%{?}._spf.example.com"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testSPFValidExpModifierMacro(self):
"""SPF records with valid macros in exp modifier are accepted"""
spf_record = "v=spf1 -all exp=%{d}"
domain = "example.com"
results = checkdmarc.spf.parse_spf_record(spf_record, domain)
self.assertIn("exp", results["parsed"])
self.assertEqual(len(results["warnings"]), 0)
self.assertEqual(results["dns_lookups"], 0)
def testSPFBrokenExpModifierMacro(self):
"""SPF records with invalid macros in exp modifier raise SPFSyntaxError"""
spf_record = "v=spf1 -all exp=%{?}"
domain = "example.com"
self.assertRaises(
checkdmarc.spf.SPFSyntaxError,
checkdmarc.spf.parse_spf_record,
spf_record,
domain,
)
def testUndecodableCharactersInNonSPFRecord(self):
"""Non-SPF TXT records with undecodable characters should be ignored with a warning"""
domain = "example.com"
# Mock query_dns to return:
# 1. An undecodable non-SPF TXT record
# 2. A valid SPF record
with patch("checkdmarc.spf.query_dns") as mock_query_dns:
# First call for SPF type records (returns empty)
# Second call for TXT records (returns undecodable + valid SPF)
mock_query_dns.side_effect = [
[], # No SPF type records
[
"Undecodable characters", # TXT record with undecodable chars
'"v=spf1 include:spf.smtp2go.com -all"', # Valid SPF record
],
]
# This should succeed and return the valid SPF record
result = checkdmarc.spf.get_spf_record(domain)
# Verify the SPF record was found
self.assertIsNotNone(result["record"])
self.assertIn("v=spf1", cast(str, result["record"]))
# Verify a warning was added for the undecodable record
self.assertTrue(len(result["warnings"]) > 0)
self.assertTrue(
any(
"TXT record" in w and "undecodable" in w.lower()
for w in result["warnings"]
)
)
# ================================================================
# DMARC additional tests
# ================================================================
def testDMARCSyntaxError(self):
"""An invalid DMARC fo tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; fo=invalid_value"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCDuplicateTags(self):
"""Duplicate DMARC tags raise InvalidDMARCTag"""
dmarc_record = "v=DMARC1; p=reject; p=none"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTag,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCInvalidTag(self):
"""An invalid DMARC tag raises InvalidDMARCTag"""
dmarc_record = "v=DMARC1; p=reject; xyz=foo"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTag,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCSPFInDMARC(self):
"""An SPF record where a DMARC record should be raises SPFRecordFoundWhereDMARCRecordShouldBe"""
record = "v=spf1 include:example.com -all"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.SPFRecordFoundWhereDMARCRecordShouldBe,
checkdmarc.dmarc.parse_dmarc_record,
record,
domain,
)
def testDMARCPctZero(self):
"""pct=0 produces a warning about disabling enforcement"""
dmarc_record = "v=DMARC1; p=reject; pct=0"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(any("pct value of 0" in w for w in result["warnings"]))
def testDMARCPctOutOfRange(self):
"""pct value out of range raises DMARCSyntaxError"""
dmarc_record = "v=DMARC1; p=reject; pct=150"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.DMARCSyntaxError,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCPctNegative(self):
"""Negative pct value raises DMARCSyntaxError"""
dmarc_record = "v=DMARC1; p=reject; pct=-1"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.DMARCSyntaxError,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCPctNonInteger(self):
"""Non-integer pct value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; pct=abc"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCRiNonInteger(self):
"""Non-integer ri value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; ri=abc"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCFoRedundancy(self):
"""fo=0:1 produces a warning about redundancy"""
dmarc_record = "v=DMARC1; p=reject; fo=0:1"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(any("redundant" in w.lower() for w in result["warnings"]))
def testDMARCInvalidFoValue(self):
"""Invalid fo tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; fo=x"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCInvalidRfValue(self):
"""Invalid rf tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; rf=invalid"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCSpNoneWarning(self):
"""Explicit sp=none produces a warning"""
dmarc_record = "v=DMARC1; p=reject; sp=none"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(any("sp tag value of none" in w for w in result["warnings"]))
def testDMARCParkedDomainPolicyWarning(self):
"""Parked domains with p!=reject produce warnings"""
dmarc_record = "v=DMARC1; p=none"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain, parked=True)
self.assertTrue(any("parked" in w.lower() for w in result["warnings"]))
def testDMARCParkedDomainSpWarning(self):
"""Parked domains with sp!=reject produce warnings"""
dmarc_record = "v=DMARC1; p=reject; sp=none"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain, parked=True)
self.assertTrue(
any(
"subdomain policy" in w.lower() and "parked" in w.lower()
for w in result["warnings"]
)
)
def testDMARCMissingRuaWarning(self):
"""Missing rua tag produces a best practice warning"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(dmarc_record, domain)
self.assertTrue(any("rua" in w.lower() for w in result["warnings"]))
def testDMARCPTagPosition(self):
"""p tag not immediately after v raises DMARCSyntaxError"""
dmarc_record = "v=DMARC1; sp=none; p=reject"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.DMARCSyntaxError,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCTagDescriptions(self):
"""Tag descriptions are included when requested"""
dmarc_record = "v=DMARC1; p=reject"
domain = "example.com"
result = checkdmarc.dmarc.parse_dmarc_record(
dmarc_record, domain, include_tag_descriptions=True
)
for tag in result["tags"]:
self.assertIn("description", result["tags"][tag])
self.assertIn("name", result["tags"][tag])
def testDMARCGetTagDescriptionString(self):
"""get_dmarc_tag_description returns value-specific descriptions"""
details = checkdmarc.dmarc.get_dmarc_tag_description("p", "reject")
self.assertIn("reject", details["description"].lower())
def testDMARCGetTagDescriptionList(self):
"""get_dmarc_tag_description handles list values (fo tag)"""
details = checkdmarc.dmarc.get_dmarc_tag_description("fo", ["0", "d"])
self.assertIn("0:", details["description"])
self.assertIn("d:", details["description"])
def testDMARCGetTagDescriptionDefault(self):
"""get_dmarc_tag_description returns default value"""
details = checkdmarc.dmarc.get_dmarc_tag_description("pct")
self.assertEqual(details["default"], 100)
def testDMARCGetTagDescriptionNoDefault(self):
"""get_dmarc_tag_description returns None for tags without default"""
details = checkdmarc.dmarc.get_dmarc_tag_description("v")
self.assertIsNone(details["default"])
def testDMARCInvalidSpValue(self):
"""Invalid sp tag value raises InvalidDMARCTagValue"""
dmarc_record = "v=DMARC1; p=reject; sp=invalid"
domain = "example.com"
self.assertRaises(
checkdmarc.dmarc.InvalidDMARCTagValue,
checkdmarc.dmarc.parse_dmarc_record,
dmarc_record,
domain,
)
def testDMARCRecordStartsWithWhitespace(self):
"""DMARC record with leading whitespace raises DMARCRecordStartsWithWhitespace"""
with patch("checkdmarc.dmarc.query_dns") as mock_dns:
mock_dns.return_value = [" v=DMARC1; p=reject"]
self.assertRaises(
checkdmarc.dmarc.DMARCRecordStartsWithWhitespace,
checkdmarc.dmarc._query_dmarc_record,