tdnssec.py - electrum - Electrum Bitcoin wallet
HTML git clone https://git.parazyd.org/electrum
DIR Log
DIR Files
DIR Refs
DIR Submodules
---
tdnssec.py (5983B)
---
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2015 Thomas Voegtlin
5 #
6 # Permission is hereby granted, free of charge, to any person
7 # obtaining a copy of this software and associated documentation files
8 # (the "Software"), to deal in the Software without restriction,
9 # including without limitation the rights to use, copy, modify, merge,
10 # publish, distribute, sublicense, and/or sell copies of the Software,
11 # and to permit persons to whom the Software is furnished to do so,
12 # subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 # SOFTWARE.
25
26 # Check DNSSEC trust chain.
27 # Todo: verify expiration dates
28 #
29 # Based on
30 # http://backreference.org/2010/11/17/dnssec-verification-with-dig/
31 # https://github.com/rthalley/dnspython/blob/master/tests/test_dnssec.py
32
33
34 # import traceback
35 # import sys
36 import time
37 import struct
38 import hashlib
39
40
41 import dns.name
42 import dns.query
43 import dns.dnssec
44 import dns.message
45 import dns.resolver
46 import dns.rdatatype
47 import dns.rdtypes.ANY.NS
48 import dns.rdtypes.ANY.CNAME
49 import dns.rdtypes.ANY.DLV
50 import dns.rdtypes.ANY.DNSKEY
51 import dns.rdtypes.ANY.DS
52 import dns.rdtypes.ANY.NSEC
53 import dns.rdtypes.ANY.NSEC3
54 import dns.rdtypes.ANY.NSEC3PARAM
55 import dns.rdtypes.ANY.RRSIG
56 import dns.rdtypes.ANY.SOA
57 import dns.rdtypes.ANY.TXT
58 import dns.rdtypes.IN.A
59 import dns.rdtypes.IN.AAAA
60
61 from .logging import get_logger
62
63
64 _logger = get_logger(__name__)
65
66
67 # hard-coded trust anchors (root KSKs)
68 trust_anchors = [
69 # KSK-2017:
70 dns.rrset.from_text('.', 1 , 'IN', 'DNSKEY', '257 3 8 AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU='),
71 # KSK-2010:
72 dns.rrset.from_text('.', 15202, 'IN', 'DNSKEY', '257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQbSEW0O8gcCjF FVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh/RStIoO8g0NfnfL2MTJRkxoX bfDaUeVPQuYEhg37NZWAJQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaD X6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpz W5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relS Qageu+ipAdTTJ25AsRTAoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulq QxA+Uk1ihz0='),
73 ]
74
75
76 def check_query(ns, sub, _type, keys):
77 q = dns.message.make_query(sub, _type, want_dnssec=True)
78 response = dns.query.tcp(q, ns, timeout=5)
79 assert response.rcode() == 0, 'No answer'
80 answer = response.answer
81 assert len(answer) != 0, ('No DNS record found', sub, _type)
82 assert len(answer) != 1, ('No DNSSEC record found', sub, _type)
83 if answer[0].rdtype == dns.rdatatype.RRSIG:
84 rrsig, rrset = answer
85 elif answer[1].rdtype == dns.rdatatype.RRSIG:
86 rrset, rrsig = answer
87 else:
88 raise Exception('No signature set in record')
89 if keys is None:
90 keys = {dns.name.from_text(sub):rrset}
91 dns.dnssec.validate(rrset, rrsig, keys)
92 return rrset
93
94
95 def get_and_validate(ns, url, _type):
96 # get trusted root key
97 root_rrset = None
98 for dnskey_rr in trust_anchors:
99 try:
100 # Check if there is a valid signature for the root dnskey
101 root_rrset = check_query(ns, '', dns.rdatatype.DNSKEY, {dns.name.root: dnskey_rr})
102 break
103 except dns.dnssec.ValidationFailure:
104 # It's OK as long as one key validates
105 continue
106 if not root_rrset:
107 raise dns.dnssec.ValidationFailure('None of the trust anchors found in DNS')
108 keys = {dns.name.root: root_rrset}
109 # top-down verification
110 parts = url.split('.')
111 for i in range(len(parts), 0, -1):
112 sub = '.'.join(parts[i-1:])
113 name = dns.name.from_text(sub)
114 # If server is authoritative, don't fetch DNSKEY
115 query = dns.message.make_query(sub, dns.rdatatype.NS)
116 response = dns.query.udp(query, ns, 3)
117 assert response.rcode() == dns.rcode.NOERROR, "query error"
118 rrset = response.authority[0] if len(response.authority) > 0 else response.answer[0]
119 rr = rrset[0]
120 if rr.rdtype == dns.rdatatype.SOA:
121 continue
122 # get DNSKEY (self-signed)
123 rrset = check_query(ns, sub, dns.rdatatype.DNSKEY, None)
124 # get DS (signed by parent)
125 ds_rrset = check_query(ns, sub, dns.rdatatype.DS, keys)
126 # verify that a signed DS validates DNSKEY
127 for ds in ds_rrset:
128 for dnskey in rrset:
129 htype = 'SHA256' if ds.digest_type == 2 else 'SHA1'
130 good_ds = dns.dnssec.make_ds(name, dnskey, htype)
131 if ds == good_ds:
132 break
133 else:
134 continue
135 break
136 else:
137 raise Exception("DS does not match DNSKEY")
138 # set key for next iteration
139 keys = {name: rrset}
140 # get TXT record (signed by zone)
141 rrset = check_query(ns, url, _type, keys)
142 return rrset
143
144
145 def query(url, rtype):
146 # 8.8.8.8 is Google's public DNS server
147 nameservers = ['8.8.8.8']
148 ns = nameservers[0]
149 try:
150 out = get_and_validate(ns, url, rtype)
151 validated = True
152 except BaseException as e:
153 _logger.info(f"DNSSEC error: {repr(e)}")
154 out = dns.resolver.resolve(url, rtype)
155 validated = False
156 return out, validated