Debian Codegraph @

examples/doh-json.py

raw
1 #!/usr/bin/env python3
2
3 import copy
4 import json
5
6 import httpx
7
8 import dns.flags
9 import dns.message
10 import dns.rdataclass
11 import dns.rdatatype
12 import dns.resolver
13
14 # This shows how to convert to/from dnspython's message object and the
15 # DNS-over-HTTPS (DoH) JSON form used by Google and Cloudflare, and
16 # described here:
17 #
18 # https://developers.google.com/speed/public-dns/docs/doh/json
19 #
20 # There's no need to do this for DoH as dnspython supports the
21 # standard RFC 8484 protocol which all DoH providers implement. The
22 # conversion to/from JSON is useful, however, so we show a way to do
23 # it.
24 #
25 # "simple" below means "simple python data types", i.e. things made of
26 # combinations of dictionaries, lists, strings, and numbers.
27
28
29 def make_rr(simple, rdata):
30 csimple = copy.copy(simple)
31 csimple["data"] = rdata.to_text()
32 return csimple
33
34
35 def flatten_rrset(rrs):
36 simple = {
37 "name": str(rrs.name),
38 "type": rrs.rdtype,
39 }
40 if len(rrs) > 0:
41 simple["TTL"] = rrs.ttl
42 return [make_rr(simple, rdata) for rdata in rrs]
43 else:
44 return [simple]
45
46
47 def to_doh_simple(message):
48 simple = {"Status": message.rcode()}
49 for f in dns.flags.Flag:
50 if f != dns.flags.Flag.AA and f != dns.flags.Flag.QR:
51 # DoH JSON doesn't need AA and omits it. DoH JSON is only
52 # used in replies so the QR flag is implied.
53 simple[f.name] = (message.flags & f) != 0
54 for i, s in enumerate(message.sections):
55 k = dns.message.MessageSection.to_text(i).title()
56 simple[k] = []
57 for rrs in s:
58 simple[k].extend(flatten_rrset(rrs))
59 # we don't encode the ecs_client_subnet field
60 return simple
61
62
63 def from_doh_simple(simple, add_qr=False):
64 message = dns.message.QueryMessage()
65 flags = 0
66 for f in dns.flags.Flag:
67 if simple.get(f.name, False):
68 flags |= f
69 if add_qr: # QR is implied
70 flags |= dns.flags.QR
71 message.flags = flags
72 message.set_rcode(simple.get("Status", 0))
73 for i, sn in enumerate(dns.message.MessageSection):
74 rr_list = simple.get(sn.name.title(), [])
75 for rr in rr_list:
76 rdtype = dns.rdatatype.RdataType(rr["type"])
77 rrs = message.find_rrset(
78 i,
79 dns.name.from_text(rr["name"]),
80 dns.rdataclass.IN,
81 rdtype,
82 create=True,
83 )
84 if "data" in rr:
85 rrs.add(
86 dns.rdata.from_text(dns.rdataclass.IN, rdtype, rr["data"]),
87 rr.get("TTL", 0),
88 )
89 # we don't decode the ecs_client_subnet field
90 return message
91
92
93 a = dns.resolver.resolve("www.dnspython.org", "a")
94 p = to_doh_simple(a.response)
95 print(json.dumps(p, indent=4))
96 response = httpx.get(
97 "https://dns.google/resolve?",
98 verify=True,
99 params={"name": "www.dnspython.org", "type": 1},
100 )
101 p = json.loads(response.text)
102 m = from_doh_simple(p, True)
103 print(m)