Debian Codegraph @

dns/edns.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2009-2017 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 """EDNS Options"""
19
20 import binascii
21 import math
22 import socket
23 import struct
24 from typing import Any, Dict
25
26 import dns.enum
27 import dns.inet
28 import dns.ipv4
29 import dns.ipv6
30 import dns.name
31 import dns.rdata
32 import dns.wire
33
34
35 class OptionType(dns.enum.IntEnum):
36 """EDNS option type codes"""
37
38 #: NSID
39 NSID = 3
40 #: DAU
41 DAU = 5
42 #: DHU
43 DHU = 6
44 #: N3U
45 N3U = 7
46 #: ECS (client-subnet)
47 ECS = 8
48 #: EXPIRE
49 EXPIRE = 9
50 #: COOKIE
51 COOKIE = 10
52 #: KEEPALIVE
53 KEEPALIVE = 11
54 #: PADDING
55 PADDING = 12
56 #: CHAIN
57 CHAIN = 13
58 #: EDE (extended-dns-error)
59 EDE = 15
60 #: REPORTCHANNEL
61 REPORTCHANNEL = 18
62
63 @classmethod
64 def _maximum(cls):
65 return 65535
66
67
68 class Option:
69 """Base class for all EDNS option types."""
70
71 def __init__(self, otype: OptionType | str):
72 """Initialize an option.
73
74 *otype*, a ``dns.edns.OptionType``, is the option type.
75 """
76 self.otype = OptionType.make(otype)
77
78 def to_wire(self, file: Any | None = None) -> bytes | None:
79 """Convert an option to wire format.
80
81 Returns a ``bytes`` or ``None``.
82
83 """
84 raise NotImplementedError # pragma: no cover
85
86 def to_text(self) -> str:
87 raise NotImplementedError # pragma: no cover
88
89 def to_generic(self) -> "GenericOption":
90 """Creates a dns.edns.GenericOption equivalent of this rdata.
91
92 Returns a ``dns.edns.GenericOption``.
93 """
94 wire = self.to_wire()
95 assert wire is not None # for mypy
96 return GenericOption(self.otype, wire)
97
98 @classmethod
99 def from_wire_parser(cls, otype: OptionType, parser: "dns.wire.Parser") -> "Option":
100 """Build an EDNS option object from wire format.
101
102 *otype*, a ``dns.edns.OptionType``, is the option type.
103
104 *parser*, a ``dns.wire.Parser``, the parser, which should be
105 restructed to the option length.
106
107 Returns a ``dns.edns.Option``.
108 """
109 raise NotImplementedError # pragma: no cover
110
111 def _cmp(self, other):
112 """Compare an EDNS option with another option of the same type.
113
114 Returns < 0 if < *other*, 0 if == *other*, and > 0 if > *other*.
115 """
116 wire = self.to_wire()
117 owire = other.to_wire()
118 if wire == owire:
119 return 0
120 if wire > owire:
121 return 1
122 return -1
123
124 def __eq__(self, other):
125 if not isinstance(other, Option):
126 return False
127 if self.otype != other.otype:
128 return False
129 return self._cmp(other) == 0
130
131 def __ne__(self, other):
132 if not isinstance(other, Option):
133 return True
134 if self.otype != other.otype:
135 return True
136 return self._cmp(other) != 0
137
138 def __lt__(self, other):
139 if not isinstance(other, Option) or self.otype != other.otype:
140 return NotImplemented
141 return self._cmp(other) < 0
142
143 def __le__(self, other):
144 if not isinstance(other, Option) or self.otype != other.otype:
145 return NotImplemented
146 return self._cmp(other) <= 0
147
148 def __ge__(self, other):
149 if not isinstance(other, Option) or self.otype != other.otype:
150 return NotImplemented
151 return self._cmp(other) >= 0
152
153 def __gt__(self, other):
154 if not isinstance(other, Option) or self.otype != other.otype:
155 return NotImplemented
156 return self._cmp(other) > 0
157
158 def __str__(self):
159 return self.to_text()
160
161
162 class GenericOption(Option): # lgtm[py/missing-equals]
163 """Generic Option Class
164
165 This class is used for EDNS option types for which we have no better
166 implementation.
167 """
168
169 def __init__(self, otype: OptionType | str, data: bytes | str):
170 super().__init__(otype)
171 self.data = dns.rdata.Rdata._as_bytes(data, True)
172
173 def to_wire(self, file: Any | None = None) -> bytes | None:
174 if file:
175 file.write(self.data)
176 return None
177 else:
178 return self.data
179
180 def to_text(self) -> str:
181 return f"Generic {self.otype}"
182
183 def to_generic(self) -> "GenericOption":
184 return self
185
186 @classmethod
187 def from_wire_parser(
188 cls, otype: OptionType | str, parser: "dns.wire.Parser"
189 ) -> Option:
190 return cls(otype, parser.get_remaining())
191
192
193 class ECSOption(Option): # lgtm[py/missing-equals]
194 """EDNS Client Subnet (ECS, RFC7871)"""
195
196 def __init__(self, address: str, srclen: int | None = None, scopelen: int = 0):
197 """*address*, a ``str``, is the client address information.
198
199 *srclen*, an ``int``, the source prefix length, which is the
200 leftmost number of bits of the address to be used for the
201 lookup. The default is 24 for IPv4 and 56 for IPv6.
202
203 *scopelen*, an ``int``, the scope prefix length. This value
204 must be 0 in queries, and should be set in responses.
205 """
206
207 super().__init__(OptionType.ECS)
208 af = dns.inet.af_for_address(address)
209
210 if af == socket.AF_INET6:
211 self.family = 2
212 if srclen is None:
213 srclen = 56
214 address = dns.rdata.Rdata._as_ipv6_address(address)
215 srclen = dns.rdata.Rdata._as_int(srclen, 0, 128)
216 scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 128)
217 elif af == socket.AF_INET:
218 self.family = 1
219 if srclen is None:
220 srclen = 24
221 address = dns.rdata.Rdata._as_ipv4_address(address)
222 srclen = dns.rdata.Rdata._as_int(srclen, 0, 32)
223 scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 32)
224 else: # pragma: no cover (this will never happen)
225 raise ValueError("Bad address family")
226
227 assert srclen is not None
228 self.address = address
229 self.srclen = srclen
230 self.scopelen = scopelen
231
232 addrdata = dns.inet.inet_pton(af, address)
233 nbytes = int(math.ceil(srclen / 8.0))
234
235 # Truncate to srclen and pad to the end of the last octet needed
236 # See RFC section 6
237 self.addrdata = addrdata[:nbytes]
238 nbits = srclen % 8
239 if nbits != 0:
240 last = struct.pack("B", ord(self.addrdata[-1:]) & (0xFF << (8 - nbits)))
241 self.addrdata = self.addrdata[:-1] + last
242
243 def to_text(self) -> str:
244 return f"ECS {self.address}/{self.srclen} scope/{self.scopelen}"
245
246 @staticmethod
247 def from_text(text: str) -> Option:
248 """Convert a string into a `dns.edns.ECSOption`
249
250 *text*, a `str`, the text form of the option.
251
252 Returns a `dns.edns.ECSOption`.
253
254 Examples:
255
256 >>> import dns.edns
257 >>>
258 >>> # basic example
259 >>> dns.edns.ECSOption.from_text('1.2.3.4/24')
260 >>>
261 >>> # also understands scope
262 >>> dns.edns.ECSOption.from_text('1.2.3.4/24/32')
263 >>>
264 >>> # IPv6
265 >>> dns.edns.ECSOption.from_text('2001:4b98::1/64/64')
266 >>>
267 >>> # it understands results from `dns.edns.ECSOption.to_text()`
268 >>> dns.edns.ECSOption.from_text('ECS 1.2.3.4/24/32')
269 """
270 optional_prefix = "ECS"
271 tokens = text.split()
272 ecs_text = None
273 if len(tokens) == 1:
274 ecs_text = tokens[0]
275 elif len(tokens) == 2:
276 if tokens[0] != optional_prefix:
277 raise ValueError(f'could not parse ECS from "{text}"')
278 ecs_text = tokens[1]
279 else:
280 raise ValueError(f'could not parse ECS from "{text}"')
281 n_slashes = ecs_text.count("/")
282 if n_slashes == 1:
283 address, tsrclen = ecs_text.split("/")
284 tscope = "0"
285 elif n_slashes == 2:
286 address, tsrclen, tscope = ecs_text.split("/")
287 else:
288 raise ValueError(f'could not parse ECS from "{text}"')
289 try:
290 scope = int(tscope)
291 except ValueError:
292 raise ValueError("invalid scope " + f'"{tscope}": scope must be an integer')
293 try:
294 srclen = int(tsrclen)
295 except ValueError:
296 raise ValueError(
297 "invalid srclen " + f'"{tsrclen}": srclen must be an integer'
298 )
299 return ECSOption(address, srclen, scope)
300
301 def to_wire(self, file: Any | None = None) -> bytes | None:
302 value = (
303 struct.pack("!HBB", self.family, self.srclen, self.scopelen) + self.addrdata
304 )
305 if file:
306 file.write(value)
307 return None
308 else:
309 return value
310
311 @classmethod
312 def from_wire_parser(
313 cls, otype: OptionType | str, parser: "dns.wire.Parser"
314 ) -> Option:
315 family, src, scope = parser.get_struct("!HBB")
316 addrlen = int(math.ceil(src / 8.0))
317 prefix = parser.get_bytes(addrlen)
318 if family == 1:
319 pad = 4 - addrlen
320 addr = dns.ipv4.inet_ntoa(prefix + b"\x00" * pad)
321 elif family == 2:
322 pad = 16 - addrlen
323 addr = dns.ipv6.inet_ntoa(prefix + b"\x00" * pad)
324 else:
325 raise ValueError("unsupported family")
326
327 return cls(addr, src, scope)
328
329
330 class EDECode(dns.enum.IntEnum):
331 """Extended DNS Error (EDE) codes"""
332
333 OTHER = 0
334 UNSUPPORTED_DNSKEY_ALGORITHM = 1
335 UNSUPPORTED_DS_DIGEST_TYPE = 2
336 STALE_ANSWER = 3
337 FORGED_ANSWER = 4
338 DNSSEC_INDETERMINATE = 5
339 DNSSEC_BOGUS = 6
340 SIGNATURE_EXPIRED = 7
341 SIGNATURE_NOT_YET_VALID = 8
342 DNSKEY_MISSING = 9
343 RRSIGS_MISSING = 10
344 NO_ZONE_KEY_BIT_SET = 11
345 NSEC_MISSING = 12
346 CACHED_ERROR = 13
347 NOT_READY = 14
348 BLOCKED = 15
349 CENSORED = 16
350 FILTERED = 17
351 PROHIBITED = 18
352 STALE_NXDOMAIN_ANSWER = 19
353 NOT_AUTHORITATIVE = 20
354 NOT_SUPPORTED = 21
355 NO_REACHABLE_AUTHORITY = 22
356 NETWORK_ERROR = 23
357 INVALID_DATA = 24
358
359 @classmethod
360 def _maximum(cls):
361 return 65535
362
363
364 class EDEOption(Option): # lgtm[py/missing-equals]
365 """Extended DNS Error (EDE, RFC8914)"""
366
367 _preserve_case = {"DNSKEY", "DS", "DNSSEC", "RRSIGs", "NSEC", "NXDOMAIN"}
368
369 def __init__(self, code: EDECode | str, text: str | None = None):
370 """*code*, a ``dns.edns.EDECode`` or ``str``, the info code of the
371 extended error.
372
373 *text*, a ``str`` or ``None``, specifying additional information about
374 the error.
375 """
376
377 super().__init__(OptionType.EDE)
378
379 self.code = EDECode.make(code)
380 if text is not None and not isinstance(text, str):
381 raise ValueError("text must be string or None")
382 self.text = text
383
384 def to_text(self) -> str:
385 output = f"EDE {self.code}"
386 if self.code in EDECode:
387 desc = EDECode.to_text(self.code)
388 desc = " ".join(
389 word if word in self._preserve_case else word.title()
390 for word in desc.split("_")
391 )
392 output += f" ({desc})"
393 if self.text is not None:
394 output += f": {self.text}"
395 return output
396
397 def to_wire(self, file: Any | None = None) -> bytes | None:
398 value = struct.pack("!H", self.code)
399 if self.text is not None:
400 value += self.text.encode("utf8")
401
402 if file:
403 file.write(value)
404 return None
405 else:
406 return value
407
408 @classmethod
409 def from_wire_parser(
410 cls, otype: OptionType | str, parser: "dns.wire.Parser"
411 ) -> Option:
412 code = EDECode.make(parser.get_uint16())
413 text = parser.get_remaining()
414
415 if text:
416 if text[-1] == 0: # text MAY be null-terminated
417 text = text[:-1]
418 btext = text.decode("utf8")
419 else:
420 btext = None
421
422 return cls(code, btext)
423
424
425 class NSIDOption(Option):
426 def __init__(self, nsid: bytes):
427 super().__init__(OptionType.NSID)
428 self.nsid = nsid
429
430 def to_wire(self, file: Any = None) -> bytes | None:
431 if file:
432 file.write(self.nsid)
433 return None
434 else:
435 return self.nsid
436
437 def to_text(self) -> str:
438 if all(c >= 0x20 and c <= 0x7E for c in self.nsid):
439 # All ASCII printable, so it's probably a string.
440 value = self.nsid.decode()
441 else:
442 value = binascii.hexlify(self.nsid).decode()
443 return f"NSID {value}"
444
445 @classmethod
446 def from_wire_parser(
447 cls, otype: OptionType | str, parser: dns.wire.Parser
448 ) -> Option:
449 return cls(parser.get_remaining())
450
451
452 class CookieOption(Option):
453 def __init__(self, client: bytes, server: bytes):
454 super().__init__(OptionType.COOKIE)
455 self.client = client
456 self.server = server
457 if len(client) != 8:
458 raise ValueError("client cookie must be 8 bytes")
459 if len(server) != 0 and (len(server) < 8 or len(server) > 32):
460 raise ValueError("server cookie must be empty or between 8 and 32 bytes")
461
462 def to_wire(self, file: Any = None) -> bytes | None:
463 if file:
464 file.write(self.client)
465 if len(self.server) > 0:
466 file.write(self.server)
467 return None
468 else:
469 return self.client + self.server
470
471 def to_text(self) -> str:
472 client = binascii.hexlify(self.client).decode()
473 if len(self.server) > 0:
474 server = binascii.hexlify(self.server).decode()
475 else:
476 server = ""
477 return f"COOKIE {client}{server}"
478
479 @classmethod
480 def from_wire_parser(
481 cls, otype: OptionType | str, parser: dns.wire.Parser
482 ) -> Option:
483 return cls(parser.get_bytes(8), parser.get_remaining())
484
485
486 class ReportChannelOption(Option):
487 # RFC 9567
488 def __init__(self, agent_domain: dns.name.Name):
489 super().__init__(OptionType.REPORTCHANNEL)
490 self.agent_domain = agent_domain
491
492 def to_wire(self, file: Any = None) -> bytes | None:
493 return self.agent_domain.to_wire(file)
494
495 def to_text(self) -> str:
496 return "REPORTCHANNEL " + self.agent_domain.to_text()
497
498 @classmethod
499 def from_wire_parser(
500 cls, otype: OptionType | str, parser: dns.wire.Parser
501 ) -> Option:
502 return cls(parser.get_name())
503
504
505 _type_to_class: Dict[OptionType, Any] = {
506 OptionType.ECS: ECSOption,
507 OptionType.EDE: EDEOption,
508 OptionType.NSID: NSIDOption,
509 OptionType.COOKIE: CookieOption,
510 OptionType.REPORTCHANNEL: ReportChannelOption,
511 }
512
513
514 def get_option_class(otype: OptionType) -> Any:
515 """Return the class for the specified option type.
516
517 The GenericOption class is used if a more specific class is not
518 known.
519 """
520
521 cls = _type_to_class.get(otype)
522 if cls is None:
523 cls = GenericOption
524 return cls
525
526
527 def option_from_wire_parser(
528 otype: OptionType | str, parser: "dns.wire.Parser"
529 ) -> Option:
530 """Build an EDNS option object from wire format.
531
532 *otype*, an ``int``, is the option type.
533
534 *parser*, a ``dns.wire.Parser``, the parser, which should be
535 restricted to the option length.
536
537 Returns an instance of a subclass of ``dns.edns.Option``.
538 """
539 otype = OptionType.make(otype)
540 cls = get_option_class(otype)
541 return cls.from_wire_parser(otype, parser)
542
543
544 def option_from_wire(
545 otype: OptionType | str, wire: bytes, current: int, olen: int
546 ) -> Option:
547 """Build an EDNS option object from wire format.
548
549 *otype*, an ``int``, is the option type.
550
551 *wire*, a ``bytes``, is the wire-format message.
552
553 *current*, an ``int``, is the offset in *wire* of the beginning
554 of the rdata.
555
556 *olen*, an ``int``, is the length of the wire-format option data
557
558 Returns an instance of a subclass of ``dns.edns.Option``.
559 """
560 parser = dns.wire.Parser(wire, current)
561 with parser.restrict_to(olen):
562 return option_from_wire_parser(otype, parser)
563
564
565 def register_type(implementation: Any, otype: OptionType) -> None:
566 """Register the implementation of an option type.
567
568 *implementation*, a ``class``, is a subclass of ``dns.edns.Option``.
569
570 *otype*, an ``int``, is the option type.
571 """
572
573 _type_to_class[otype] = implementation
574
575
576 ### BEGIN generated OptionType constants
577
578 NSID = OptionType.NSID
579 DAU = OptionType.DAU
580 DHU = OptionType.DHU
581 N3U = OptionType.N3U
582 ECS = OptionType.ECS
583 EXPIRE = OptionType.EXPIRE
584 COOKIE = OptionType.COOKIE
585 KEEPALIVE = OptionType.KEEPALIVE
586 PADDING = OptionType.PADDING
587 CHAIN = OptionType.CHAIN
588 EDE = OptionType.EDE
589 REPORTCHANNEL = OptionType.REPORTCHANNEL
590
591 ### END generated OptionType constants