forked from domainaware/checkdmarc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkdmarc.py
executable file
·2664 lines (2315 loc) · 106 KB
/
checkdmarc.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/env python3
# -*- coding: utf-8 -*-
"""Validates and parses SPF amd DMARC DNS records"""
import logging
from collections import OrderedDict
from re import compile, IGNORECASE
import json
from csv import DictWriter
from argparse import ArgumentParser
import os
from time import sleep
from datetime import datetime, timedelta
import socket
import smtplib
import tempfile
import platform
import shutil
import atexit
import requests
from ssl import SSLError, CertificateError, create_default_context
from io import StringIO
from expiringdict import ExpiringDict
import publicsuffix2
import dns.resolver
import dns.exception
import timeout_decorator
from pyleri import (Grammar,
Regex,
Sequence,
List,
Repeat
)
import ipaddress
"""Copyright 2019 Sean Whalen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""
__version__ = "4.3.1"
DMARC_VERSION_REGEX_STRING = r"v=DMARC1;"
BIMI_VERSION_REGEX_STRING = r"v=BIMI1;"
DMARC_TAG_VALUE_REGEX_STRING = r"([a-z]{1,5})=([\w.:@/+!,_\- ]+)"
BIMI_TAG_VALUE_REGEX_STRING = r"([a-z]{1})=(.*)"
MAILTO_REGEX_STRING = r"^(mailto):" \
r"([\w\-!#$%&'*+-/=?^_`{|}~]" \
r"[\w\-.!#$%&'*+-/=?^_`{|}~]*@[\w\-.]+)(!\w+)?"
SPF_VERSION_TAG_REGEX_STRING = "v=spf1"
SPF_MECHANISM_REGEX_STRING = r"([+\-~?])?(mx|ip4|ip6|exists|include|all|a|" \
r"redirect|exp|ptr)[:=]?([\w+/_.:\-{%}]*)"
AFTER_ALL_REGEX_STRING = "all .*"
DMARC_TAG_VALUE_REGEX = compile(DMARC_TAG_VALUE_REGEX_STRING)
BIMI_TAG_VALUE_REGEX = compile(BIMI_TAG_VALUE_REGEX_STRING)
MAILTO_REGEX = compile(MAILTO_REGEX_STRING)
SPF_MECHANISM_REGEX = compile(SPF_MECHANISM_REGEX_STRING, IGNORECASE)
AFTER_ALL_REGEX = compile(AFTER_ALL_REGEX_STRING, IGNORECASE)
USER_AGENT = "Mozilla/5.0 (({0} {1})) parsedmarc/{2}".format(
platform.system(),
platform.release(),
__version__
)
DNS_CACHE = ExpiringDict(max_len=200000, max_age_seconds=1800)
TLS_CACHE = ExpiringDict(max_len=200000, max_age_seconds=1800)
STARTTLS_CACHE = ExpiringDict(max_len=200000, max_age_seconds=1800)
TMPDIR = tempfile.mkdtemp()
def _cleanup():
"""Remove temporary files"""
shutil.rmtree(TMPDIR)
atexit.register(_cleanup)
class SMTPError(Exception):
"""Raised when n SMTP error occurs"""
class SPFError(Exception):
"""Raised when a fatal SPF error occurs"""
def __init__(self, msg, data=None):
"""
Args:
msg (str): The error message
data (dict): A dictionary of data to include in the output
"""
self.data = data
Exception.__init__(self, msg)
class _SPFWarning(Exception):
"""Raised when a non-fatal SPF error occurs"""
class _SPFMissingRecords(_SPFWarning):
"""Raised when a mechanism in a ``SPF`` record is missing the requested
A/AAAA or MX records"""
class _SPFDuplicateInclude(_SPFWarning):
"""Raised when a duplicate SPF include is found"""
class _DMARCWarning(Exception):
"""Raised when a non-fatal DMARC error occurs"""
class _BIMIWarning(Exception):
"""Raised when a non-fatal BIMI error occurs"""
class _DMARCBestPracticeWarning(_DMARCWarning):
"""Raised when a DMARC record does not follow a best practice"""
class DNSException(Exception):
"""Raised when a general DNS error occurs"""
def __init__(self, error):
if isinstance(error, dns.exception.Timeout):
error.kwargs["timeout"] = round(error.kwargs["timeout"], 1)
class DMARCError(Exception):
"""Raised when a fatal DMARC error occurs"""
def __init__(self, msg, data=None):
"""
Args:
msg (str): The error message
data (dict): A dictionary of data to include in the results
"""
self.data = data
Exception.__init__(self, msg)
class SPFRecordNotFound(SPFError):
"""Raised when an SPF record could not be found"""
def __init__(self, error):
if isinstance(error, dns.exception.Timeout):
error.kwargs["timeout"] = round(error.kwargs["timeout"], 1)
class MultipleSPFRTXTRecords(SPFError):
"""Raised when multiple TXT spf1 records are found"""
class SPFSyntaxError(SPFError):
"""Raised when an SPF syntax error is found"""
class SPFTooManyDNSLookups(SPFError):
"""Raised when an SPF record requires too many DNS lookups (10 max)"""
def __init__(self, *args, **kwargs):
data = dict(dns_lookups=kwargs["dns_lookups"])
SPFError.__init__(self, args[0], data=data)
class SPFRedirectLoop(SPFError):
"""Raised when a SPF redirect loop is detected"""
class SPFIncludeLoop(SPFError):
"""Raised when a SPF include loop is detected"""
class DMARCRecordNotFound(DMARCError):
"""Raised when a DMARC record could not be found"""
def __init__(self, error):
if isinstance(error, dns.exception.Timeout):
error.kwargs["timeout"] = round(error.kwargs["timeout"], 1)
class DMARCSyntaxError(DMARCError):
"""Raised when a DMARC syntax error is found"""
class InvalidDMARCTag(DMARCSyntaxError):
"""Raised when an invalid DMARC tag is found"""
class InvalidDMARCTagValue(DMARCSyntaxError):
"""Raised when an invalid DMARC tag value is found"""
class InvalidDMARCReportURI(InvalidDMARCTagValue):
"""Raised when an invalid DMARC reporting URI is found"""
class UnrelatedTXTRecordFoundAtDMARC(DMARCError):
"""Raised when a TXT record unrelated to DMARC is found"""
class SPFRecordFoundWhereDMARCRecordShouldBe(UnrelatedTXTRecordFoundAtDMARC):
"""Raised when a SPF record is found where a DMARC record should be;
most likely, the ``_dmarc`` subdomain
record does not actually exist, and the request for ``TXT`` records was
redirected to the base domain"""
class DMARCRecordInWrongLocation(DMARCError):
"""Raised when a DMARC record is found at the root of a domain"""
class DMARCReportEmailAddressMissingMXRecords(DMARCError):
"""Raised when a email address in a DMARC report URI is missing MX
records"""
class UnverifiedDMARCURIDestination(DMARCError):
"""Raised when the destination of a DMARC report URI does not indicate
that it accepts reports for the domain"""
class MultipleDMARCRecords(DMARCError):
"""Raised when multiple DMARC records are found, in violation of
RFC 7486, section 6.6.3"""
class BIMIError(Exception):
"""Raised when a fatal BIMI error occurs"""
def __init__(self, msg, data=None):
"""
Args:
msg (str): The error message
data (dict): A dictionary of data to include in the results
"""
self.data = data
Exception.__init__(self, msg)
class BIMIRecordNotFound(BIMIError):
"""Raised when a BIMI record could not be found"""
def __init__(self, error):
if isinstance(error, dns.exception.Timeout):
error.kwargs["timeout"] = round(error.kwargs["timeout"], 1)
class BIMISyntaxError(BIMIError):
"""Raised when a BIMI syntax error is found"""
class InvalidBIMITag(BIMISyntaxError):
"""Raised when an invalid BIMI tag is found"""
class InvalidBIMITagValue(BIMISyntaxError):
"""Raised when an invalid BIMI tag value is found"""
class InvalidBIMIIndicatorURI(InvalidBIMITagValue):
"""Raised when an invalid BIMI indicator URI is found"""
class UnrelatedTXTRecordFoundAtBIMI(BIMIError):
"""Raised when a TXT record unrelated to BIMI is found"""
class SPFRecordFoundWhereBIMIRecordShouldBe(UnrelatedTXTRecordFoundAtBIMI):
"""Raised when a SPF record is found where a BIMI record should be;
most likely, the ``selector_bimi`` subdomain
record does not actually exist, and the request for ``TXT`` records was
redirected to the base domain"""
class BIMIRecordInWrongLocation(BIMIError):
"""Raised when a BIMI record is found at the root of a domain"""
class MultipleBIMIRecords(BIMIError):
"""Raised when multiple BIMI records are found"""
class _SPFGrammar(Grammar):
"""Defines Pyleri grammar for SPF records"""
version_tag = Regex(SPF_VERSION_TAG_REGEX_STRING)
mechanism = Regex(SPF_MECHANISM_REGEX_STRING, IGNORECASE)
START = Sequence(version_tag, Repeat(mechanism))
class _DMARCGrammar(Grammar):
"""Defines Pyleri grammar for DMARC records"""
version_tag = Regex(DMARC_VERSION_REGEX_STRING)
tag_value = Regex(DMARC_TAG_VALUE_REGEX_STRING)
START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))
class _BIMIGrammar(Grammar):
"""Defines Pyleri grammar for BIMI records"""
version_tag = Regex(BIMI_VERSION_REGEX_STRING)
tag_value = Regex(BIMI_TAG_VALUE_REGEX_STRING)
START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))
tag_values = OrderedDict(adkim=OrderedDict(name="DKIM Alignment Mode",
default="r",
description='In relaxed mode, '
'the Organizational '
'Domains of both the '
'DKIM-authenticated '
'signing domain (taken '
'from the value of the '
'"d=" tag in the '
'signature) and that '
'of the RFC 5322 '
'From domain '
'must be equal if the '
'identifiers are to be '
'considered aligned.'),
aspf=OrderedDict(name="SPF alignment mode",
default="r",
description='In relaxed mode, '
'the SPF-authenticated '
'domain and RFC5322 '
'From domain must have '
'the same '
'Organizational Domain. '
'In strict mode, only '
'an exact DNS domain '
'match is considered to '
'produce Identifier '
'Alignment.'),
fo=OrderedDict(name="Failure Reporting Options",
default="0",
description='Provides requested '
'options for generation '
'of failure reports. '
'Report generators MAY '
'choose to adhere to the '
'requested options. '
'This tag\'s content '
'MUST be ignored if '
'a "ruf" tag (below) is '
'not also specified. '
'The value of this tag is '
'a colon-separated list '
'of characters that '
'indicate failure '
'reporting options.',
values={
"0": 'Generate a DMARC failure '
'report if all underlying '
'authentication mechanisms '
'fail to produce an aligned '
'"pass" result.',
"1": 'Generate a DMARC failure '
'report if any underlying '
'authentication mechanism '
'produced something other '
'than an aligned '
'"pass" result.',
"d": 'Generate a DKIM failure '
'report if the message had '
'a signature that failed '
'evaluation, regardless of '
'its alignment. DKIM-'
'specific reporting is '
'described in AFRF-DKIM.',
"s": 'Generate an SPF failure '
'report if the message '
'failed SPF evaluation, '
'regardless of its alignment.'
' SPF-specific reporting is '
'described in AFRF-SPF'
}
),
p=OrderedDict(name="Requested Mail Receiver Policy",
description='Specifies the policy to '
'be enacted by the '
'Receiver at the '
'request of the '
'Domain Owner. The '
'policy applies to '
'the domain and to its '
'subdomains, unless '
'subdomain policy '
'is explicitly described '
'using the "sp" tag.',
values={
"none": 'The Domain Owner requests '
'no specific action be '
'taken regarding delivery '
'of messages.',
"quarantine": 'The Domain Owner '
'wishes to have '
'email that fails '
'the DMARC mechanism '
'check be treated by '
'Mail Receivers as '
'suspicious. '
'Depending on the '
'capabilities of the '
'MailReceiver, '
'this can mean '
'"place into spam '
'folder", '
'"scrutinize '
'with additional '
'intensity", and/or '
'"flag as '
'suspicious".',
"reject": 'The Domain Owner wishes '
'for Mail Receivers to '
'reject '
'email that fails the '
'DMARC mechanism check. '
'Rejection SHOULD '
'occur during the SMTP '
'transaction.'
}
),
pct=OrderedDict(name="Percentage",
default=100,
description='Integer percentage of '
'messages from the '
'Domain Owner\'s '
'mail stream to which '
'the DMARC policy is to '
'be applied. '
'However, this '
'MUST NOT be applied to '
'the DMARC-generated '
'reports, all of which '
'must be sent and '
'received unhindered. '
'The purpose of the '
'"pct" tag is to allow '
'Domain Owners to enact '
'a slow rollout of '
'enforcement of the '
'DMARC mechanism.'
),
rf=OrderedDict(name="Report Format",
default="afrf",
description='A list separated by '
'colons of one or more '
'report formats as '
'requested by the '
'Domain Owner to be '
'used when a message '
'fails both SPF and DKIM '
'tests to report details '
'of the individual '
'failure. Only "afrf" '
'(the auth-failure report '
'type) is currently '
'supported in the '
'DMARC standard.',
values={
"afrf": ' "Authentication Failure '
'Reporting Using the '
'Abuse Reporting Format", '
'RFC 6591, April 2012,'
'<http://www.rfc-'
'editor.org/info/rfc6591>'
}
),
ri=OrderedDict(name="Report Interval",
default=86400,
description='Indicates a request to '
'Receivers to generate '
'aggregate reports '
'separated by no more '
'than the requested '
'number of seconds. '
'DMARC implementations '
'MUST be able to provide '
'daily reports and '
'SHOULD be able to '
'provide hourly reports '
'when requested. '
'However, anything other '
'than a daily report is '
'understood to '
'be accommodated on a '
'best-effort basis.'
),
rua=OrderedDict(name="Aggregate Feedback Addresses",
description=' A comma-separated list '
'of DMARC URIs to which '
'aggregate feedback '
'is to be sent.'
),
ruf=OrderedDict(name="Forensic Feedback Addresses",
description=' A comma-separated list '
'of DMARC URIs to which '
'forensic feedback '
'is to be sent.'
),
sp=OrderedDict(name="Subdomain Policy",
description='Indicates the policy to '
'be enacted by the '
'Receiver at the request '
'of the Domain Owner. '
'It applies only to '
'subdomains of the '
'domain queried, and not '
'to the domain itself. '
'Its syntax is identical '
'to that of the "p" tag '
'defined above. If '
'absent, the policy '
'specified by the "p" '
'tag MUST be applied '
'for subdomains.'
),
v=OrderedDict(name="Version",
description='Identifies the record '
'retrieved as a DMARC '
'record. It MUST have the '
'value of "DMARC1". The '
'value of this tag MUST '
'match precisely; if it '
'does not or it is absent, '
'the entire retrieved '
'record MUST be ignored. '
'It MUST be the first '
'tag in the list.')
)
spf_qualifiers = {
"": "pass",
"?": "neutral",
"+": "pass",
"-": "fail",
"~": "softfail"
}
bimi_tags = OrderedDict(
v=OrderedDict(name="Version",
description='Identifies the record '
'retrieved as a BIMI '
'record. It MUST have the '
'value of "BIMI1". The '
'value of this tag MUST '
'match precisely; if it '
'does not or it is absent, '
'the entire retrieved '
'record MUST be ignored. '
'It MUST be the first '
'tag in the list.')
)
def get_base_domain(domain, use_fresh_psl=False):
"""
Gets the base domain name for the given domain
.. note::
Results are based on a list of public domain suffixes at
https://publicsuffix.org/list/public_suffix_list.dat.
Args:
domain (str): A domain or subdomain
use_fresh_psl (bool): Download a fresh Public Suffix List
Returns:
str: The base domain of the given domain
"""
psl_path = os.path.join(TMPDIR, "public_suffix_list.dat")
def download_psl():
url = "https://publicsuffix.org/list/public_suffix_list.dat"
# Use a browser-like user agent string to bypass some proxy blocks
headers = {"User-Agent": USER_AGENT}
fresh_psl = requests.get(url, headers=headers).text
with open(psl_path, "w", encoding="utf-8") as fresh_psl_file:
fresh_psl_file.write(fresh_psl)
domain = domain.lower()
if domain.endswith(".test") or domain.endswith(
".example") or domain.endswith(".invalid") or domain.endswith(
".localhost"):
parts = domain.strip(".").split(".")
if len(parts) == 1:
return parts[0]
else:
return ".".join(parts[-2::])
if use_fresh_psl:
if not os.path.exists(psl_path):
download_psl()
else:
psl_age = datetime.now() - datetime.fromtimestamp(
os.stat(psl_path).st_mtime)
if psl_age > timedelta(hours=24):
try:
download_psl()
except Exception as error:
logging.warning(
"Failed to download an updated PSL {0}".format(error))
with open(psl_path, encoding="utf-8") as psl_file:
psl = publicsuffix2.PublicSuffixList(psl_file)
return psl.get_public_suffix(domain)
else:
return publicsuffix2.get_sld(domain)
def _query_dns(domain, record_type, nameservers=None, timeout=2.0,
cache=None):
"""
Queries DNS
Args:
domain (str): The domain or subdomain to query about
record_type (str): The record type to query for
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeout (float): Sets the DNS timeout in seconds
cache (ExpiringDict): Cache storage
Returns:
list: A list of answers
"""
domain = str(domain).lower()
record_type = record_type.upper()
cache_key = "{0}_{1}".format(domain, record_type)
if cache is None:
cache = DNS_CACHE
if cache:
records = cache.get(cache_key, None)
if records:
return records
resolver = dns.resolver.Resolver()
timeout = float(timeout)
if nameservers is None:
nameservers = ["1.1.1.1", "1.0.0.1",
"2606:4700:4700::1111", "2606:4700:4700::1001",
]
resolver.nameservers = nameservers
resolver.timeout = timeout
resolver.lifetime = timeout
if record_type == "TXT":
resource_records = list(map(
lambda r: r.strings,
resolver.query(domain, record_type, lifetime=timeout)))
_resource_record = [
resource_record[0][:0].join(resource_record)
for resource_record in resource_records if resource_record]
records = [r.decode() for r in _resource_record]
else:
records = list(map(
lambda r: r.to_text().replace('"', '').rstrip("."),
resolver.query(domain, record_type, lifetime=timeout)))
if cache:
cache[cache_key] = records
return records
def _get_nameservers(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for a list of nameservers
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
Returns:
list: A list of ``OrderedDicts``; each containing a ``preference``
integer and a ``hostname``
Raises:
:exc:`checkdmarc.DNSException`
"""
answers = []
try:
answers = _query_dns(domain, "NS", nameservers=nameservers,
timeout=timeout)
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
pass
except Exception as error:
raise DNSException(error)
return answers
def _get_mx_hosts(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for a list of Mail Exchange hosts
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
Returns:
list: A list of ``OrderedDicts``; each containing a ``preference``
integer and a ``hostname``
Raises:
:exc:`checkdmarc.DNSException`
"""
hosts = []
try:
logging.debug("Checking for MX records on {0}".format(domain))
answers = _query_dns(domain, "MX", nameservers=nameservers,
timeout=timeout)
for record in answers:
record = record.split(" ")
preference = int(record[0])
hostname = record[1].rstrip(".").strip().lower()
hosts.append(OrderedDict(
[("preference", preference), ("hostname", hostname)]))
hosts = sorted(hosts, key=lambda h: (h["preference"], h["hostname"]))
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
pass
except Exception as error:
raise DNSException(error)
return hosts
def _get_a_records(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for A and AAAA records
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an answer from DNS
Returns:
list: A sorted list of IPv4 and IPv6 addresses
Raises:
:exc:`checkdmarc.DNSException`
"""
qtypes = ["A", "AAAA"]
addresses = []
for qt in qtypes:
try:
addresses += _query_dns(domain, qt, nameservers=nameservers,
timeout=timeout)
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
# Sometimes a domain will only have A or AAAA records, but not both
pass
except Exception as error:
raise DNSException(error)
addresses = sorted(addresses)
return addresses
def _get_reverse_dns(ip_address):
"""
Queries for an IP addresses reverse DNS hostname(s)
Args:
ip_address (str): An IPv4 or IPv6 address
Returns:
list: A list of reverse DNS hostnames
Raises:
:exc:`checkdmarc.DNSException`
"""
try:
results = socket.gethostbyaddr(ip_address)
hostnames = [results[0]] + results[1]
except socket.herror:
return []
except Exception as error:
raise DNSException(error)
return hostnames
def _get_txt_records(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for TXT records
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an answer from DNS
Returns:
list: A list of TXT records
Raises:
:exc:`checkdmarc.DNSException`
"""
try:
records = _query_dns(domain, "TXT", nameservers=nameservers,
timeout=timeout)
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
raise DNSException(
"The domain {0} does not have any TXT records".format(domain))
except Exception as error:
raise DNSException(error)
return records
def _query_dmarc_record(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for a DMARC record
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an record from DNS
Returns:
str: A record string or None
"""
target = "_dmarc.{0}".format(domain.lower())
dmarc_record = None
dmarc_record_count = 0
unrelated_records = []
try:
records = _query_dns(target, "TXT", nameservers=nameservers,
timeout=timeout)
for record in records:
if record.startswith("v=DMARC1"):
dmarc_record_count += 1
else:
unrelated_records.append(record)
if dmarc_record_count > 1:
raise MultipleDMARCRecords(
"Multiple DMARC policy records are not permitted - "
"https://tools.ietf.org/html/rfc7489#section-6.6.3")
if len(unrelated_records) > 0:
raise UnrelatedTXTRecordFoundAtDMARC(
"Unrelated TXT records were discovered. These should be "
"removed, as some receivers may not expect to find "
"unrelated TXT records "
"at {0}\n\n{1}".format(target, "\n\n".join(unrelated_records)))
dmarc_record = records[0]
except dns.resolver.NoAnswer:
try:
records = _query_dns(domain.lower(), "TXT",
nameservers=nameservers,
timeout=timeout)
for record in records:
if record.startswith("v=DMARC1"):
raise DMARCRecordInWrongLocation(
"The DMARC record must be located at "
"{0}, not {1}".format(target, domain.lower()))
except dns.resolver.NoAnswer:
pass
except dns.resolver.NXDOMAIN:
raise DMARCRecordNotFound(
"The domain {0} does not exist".format(domain))
except Exception as error:
DMARCRecordNotFound(error)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
pass
except Exception as error:
raise DMARCRecordNotFound(error)
return dmarc_record
def _query_bmi_record(domain, selector="default", nameservers=None,
timeout=2.0):
"""
Queries DNS for a BIMI record
Args:
domain (str): A domain name
selector: the BIMI selector
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an record from DNS
Returns:
str: A record string or None
"""
target = "{0}._bimi.{1}".format(selector, domain.lower())
bimi_record = None
bmi_record_count = 0
unrelated_records = []
try:
records = _query_dns(target, "TXT", nameservers=nameservers,
timeout=timeout)
for record in records:
if record.startswith("v=BIMI1"):
bmi_record_count += 1
else:
unrelated_records.append(record)
if bmi_record_count > 1:
raise MultipleBIMIRecords(
"Multiple BMI records are not permitted")
if len(unrelated_records) > 0:
raise UnrelatedTXTRecordFoundAtDMARC(
"Unrelated TXT records were discovered. These should be "
"removed, as some receivers may not expect to find "
"unrelated TXT records "
"at {0}\n\n{1}".format(target, "\n\n".join(unrelated_records)))
bimi_record = records[0]
except dns.resolver.NoAnswer:
try:
records = _query_dns(domain.lower(), "TXT",
nameservers=nameservers,
timeout=timeout)
for record in records:
if record.startswith("v=BIMI1"):
raise BIMIRecordInWrongLocation(
"The BIMI record must be located at "
"{0}, not {1}".format(target, domain.lower()))
except dns.resolver.NoAnswer:
pass
except dns.resolver.NXDOMAIN:
raise BIMIRecordNotFound(
"The domain {0} does not exist".format(domain))
except Exception as error:
BIMIRecordNotFound(error)
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
pass
except Exception as error:
raise BIMIRecordNotFound(error)
return bimi_record
def query_dmarc_record(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for a DMARC record
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an record from DNS
Returns:
OrderedDict: An ``OrderedDict`` with the following keys:
- ``record`` - the unparsed DMARC record string
- ``location`` - the domain where the record was found
- ``warnings`` - warning conditions found
Raises:
:exc:`checkdmarc.DMARCRecordNotFound`
:exc:`checkdmarc.DMARCRecordInWrongLocation`
:exc:`checkdmarc.MultipleDMARCRecords`
:exc:`checkdmarc.SPFRecordFoundWhereDMARCRecordShouldBe`
"""
logging.debug("Checking for a DMARC record on {0}".format(domain))
warnings = []
base_domain = get_base_domain(domain)
location = domain.lower()
record = _query_dmarc_record(domain, nameservers=nameservers,
timeout=timeout)
try:
root_records = _query_dns(domain.lower(), "TXT",
nameservers=nameservers,
timeout=timeout)
for root_record in root_records:
if root_record.startswith("v=DMARC1"):
warnings.append("DMARC record at root of {0} "
"has no effect".format(domain.lower()))
except Exception:
pass