|
| 1 | +"""Unauthenticated certificate retrieval and its anti-amplification rule.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Sequence |
| 6 | + |
| 7 | +from constants import ( |
| 8 | + CERTIFICATE_RECORD_TTL, |
| 9 | + DNS_CLASS_IN, |
| 10 | + DNS_HEADER_SIZE, |
| 11 | + DNS_TYPE_OPT, |
| 12 | + DNS_TYPE_TXT, |
| 13 | + EDNS_PADDING_OPTION_CODE, |
| 14 | + EDNS_UDP_PAYLOAD_SIZE, |
| 15 | +) |
| 16 | +from errors import AmplificationError |
| 17 | + |
| 18 | + |
| 19 | +def _dns_name(name: str) -> bytes: |
| 20 | + """Encode a domain name as a sequence of length-prefixed labels.""" |
| 21 | + |
| 22 | + wire = b"" |
| 23 | + for label in name.rstrip(".").split("."): |
| 24 | + encoded = label.encode("ascii") |
| 25 | + if not 1 <= len(encoded) <= 63: |
| 26 | + raise ValueError("each DNS label must be 1 to 63 bytes") |
| 27 | + wire += bytes([len(encoded)]) + encoded |
| 28 | + return wire + b"\x00" |
| 29 | + |
| 30 | + |
| 31 | +def _edns_padding(padding_len: int) -> bytes: |
| 32 | + """Build an EDNS(0) OPT record carrying a padding option (RFC 7830).""" |
| 33 | + |
| 34 | + option = ( |
| 35 | + EDNS_PADDING_OPTION_CODE.to_bytes(2, "big") |
| 36 | + + padding_len.to_bytes(2, "big") |
| 37 | + + b"\x00" * padding_len |
| 38 | + ) |
| 39 | + return ( |
| 40 | + b"\x00" # root owner name |
| 41 | + + DNS_TYPE_OPT.to_bytes(2, "big") |
| 42 | + + EDNS_UDP_PAYLOAD_SIZE.to_bytes(2, "big") |
| 43 | + + b"\x00\x00\x00\x00" # extended rcode, version, flags |
| 44 | + + len(option).to_bytes(2, "big") |
| 45 | + + option |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +def _question_end(packet: bytes) -> int: |
| 50 | + """Return the offset just past the single question of a DNS message.""" |
| 51 | + |
| 52 | + if len(packet) < DNS_HEADER_SIZE: |
| 53 | + raise ValueError("DNS message is shorter than its header") |
| 54 | + if packet[4:6] != b"\x00\x01": |
| 55 | + raise ValueError("a certificate query carries exactly one question") |
| 56 | + offset = DNS_HEADER_SIZE |
| 57 | + while True: |
| 58 | + if offset >= len(packet): |
| 59 | + raise ValueError("DNS question name is truncated") |
| 60 | + label_len = packet[offset] |
| 61 | + if label_len & 0xC0: |
| 62 | + raise ValueError("unexpected compression pointer in question name") |
| 63 | + offset += 1 + label_len |
| 64 | + if label_len == 0: |
| 65 | + break |
| 66 | + if offset + 4 > len(packet): |
| 67 | + raise ValueError("DNS question is missing its type and class") |
| 68 | + return offset + 4 |
| 69 | + |
| 70 | + |
| 71 | +def _txt_rdata(certificate: bytes) -> bytes: |
| 72 | + """Split a certificate into TXT character-strings of at most 255 bytes.""" |
| 73 | + |
| 74 | + chunks = [certificate[i : i + 255] for i in range(0, len(certificate), 255)] |
| 75 | + return b"".join(bytes([len(chunk)]) + chunk for chunk in chunks) |
| 76 | + |
| 77 | + |
| 78 | +def _txt_answer(certificate: bytes, ttl: int) -> bytes: |
| 79 | + """Encode one certificate as a TXT answer record.""" |
| 80 | + |
| 81 | + rdata = _txt_rdata(certificate) |
| 82 | + return ( |
| 83 | + b"\xc0\x0c" # owner name: compression pointer to the question |
| 84 | + + DNS_TYPE_TXT.to_bytes(2, "big") |
| 85 | + + DNS_CLASS_IN.to_bytes(2, "big") |
| 86 | + + ttl.to_bytes(4, "big") |
| 87 | + + len(rdata).to_bytes(2, "big") |
| 88 | + + rdata |
| 89 | + ) |
| 90 | + |
| 91 | + |
| 92 | +def certificate_query( |
| 93 | + provider_name: str, |
| 94 | + query_id: bytes = b"\x00\x00", |
| 95 | + padded_length: int = 0, |
| 96 | +) -> bytes: |
| 97 | + """Build an unencrypted TXT certificate query, optionally EDNS(0)-padded. |
| 98 | +
|
| 99 | + A client that wants the larger PQ certificates over UDP pads the query to at |
| 100 | + least the expected response size, so the response stays within the request and |
| 101 | + passes the anti-amplification check at the resolver and at any relay. |
| 102 | + """ |
| 103 | + |
| 104 | + question = ( |
| 105 | + _dns_name(provider_name) |
| 106 | + + DNS_TYPE_TXT.to_bytes(2, "big") |
| 107 | + + DNS_CLASS_IN.to_bytes(2, "big") |
| 108 | + ) |
| 109 | + additional = b"" |
| 110 | + arcount = b"\x00\x00" |
| 111 | + if padded_length > 0: |
| 112 | + opt_overhead = 15 # OPT record header (11) and padding option header (4) |
| 113 | + padding = max(0, padded_length - DNS_HEADER_SIZE - len(question) - opt_overhead) |
| 114 | + additional = _edns_padding(padding) |
| 115 | + arcount = b"\x00\x01" |
| 116 | + header = ( |
| 117 | + query_id |
| 118 | + + b"\x01\x00" # standard query, recursion desired |
| 119 | + + b"\x00\x01" # qdcount |
| 120 | + + b"\x00\x00" # ancount |
| 121 | + + b"\x00\x00" # nscount |
| 122 | + + arcount |
| 123 | + ) |
| 124 | + return header + question + additional |
| 125 | + |
| 126 | + |
| 127 | +def build_certificate_response( |
| 128 | + request: bytes, |
| 129 | + certificates: Sequence[bytes], |
| 130 | + truncated: bool = False, |
| 131 | + ttl: int = CERTIFICATE_RECORD_TTL, |
| 132 | +) -> bytes: |
| 133 | + """Assemble a TXT certificate response that echoes the request's question. |
| 134 | +
|
| 135 | + Each certificate becomes one TXT answer record. The request's OPT record and |
| 136 | + padding are not echoed, exactly as a resolver answers a plain TXT query. |
| 137 | + """ |
| 138 | + |
| 139 | + question = request[DNS_HEADER_SIZE : _question_end(request)] |
| 140 | + answers = b"".join(_txt_answer(certificate, ttl) for certificate in certificates) |
| 141 | + flags = 0x8400 # response, authoritative |
| 142 | + flags |= request[2] & 0x01 # preserve recursion-desired |
| 143 | + flags |= 0x0080 # recursion available |
| 144 | + if truncated: |
| 145 | + flags |= 0x0200 # TC: the full answer did not fit |
| 146 | + header = ( |
| 147 | + request[0:2] |
| 148 | + + flags.to_bytes(2, "big") |
| 149 | + + b"\x00\x01" # qdcount |
| 150 | + + len(certificates).to_bytes(2, "big") # ancount |
| 151 | + + b"\x00\x00" # nscount |
| 152 | + + b"\x00\x00" # arcount |
| 153 | + ) |
| 154 | + return header + question + answers |
| 155 | + |
| 156 | + |
| 157 | +def serve_certificates( |
| 158 | + request: bytes, |
| 159 | + classical_certificates: Sequence[bytes], |
| 160 | + pq_certificates: Sequence[bytes], |
| 161 | + over_udp: bool, |
| 162 | +) -> bytes: |
| 163 | + """Answer a certificate query under the anti-amplification rule. |
| 164 | +
|
| 165 | + The small classical certificates are always returned. The large PQ |
| 166 | + certificates are added only when the complete response still fits within the |
| 167 | + request that triggered it, because over UDP a response MUST NOT be larger than |
| 168 | + its request, or a spoofed query would be amplified. When the PQ certificates do |
| 169 | + not fit, the response carries only the classical certificates with the TC bit |
| 170 | + set and a PQ-capable client retries over TCP. Over TCP the handshake validates |
| 171 | + the source, so the PQ certificates are always included. |
| 172 | + """ |
| 173 | + |
| 174 | + full = build_certificate_response( |
| 175 | + request, [*classical_certificates, *pq_certificates] |
| 176 | + ) |
| 177 | + if not over_udp or not pq_certificates or len(full) <= len(request): |
| 178 | + return full |
| 179 | + return build_certificate_response(request, classical_certificates, truncated=True) |
| 180 | + |
| 181 | + |
| 182 | +def relay_certificate_response( |
| 183 | + forwarded_query: bytes, upstream_response: bytes |
| 184 | +) -> bytes: |
| 185 | + """Forward a certificate response only if it respects anti-amplification. |
| 186 | +
|
| 187 | + An Anonymized DNSCrypt relay forwards the certificate query upstream over UDP |
| 188 | + and must never return more bytes to the client than the client sent, so a |
| 189 | + response larger than the forwarded query is rejected. |
| 190 | + """ |
| 191 | + |
| 192 | + if len(upstream_response) > len(forwarded_query): |
| 193 | + raise AmplificationError("certificate response is larger than the query") |
| 194 | + return upstream_response |
0 commit comments