1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #if HAVE_GCRYPT
4 #  include <gcrypt.h>
5 #endif
6 
7 #include "alloc-util.h"
8 #include "dns-domain.h"
9 #include "memory-util.h"
10 #include "resolved-dns-packet.h"
11 #include "set.h"
12 #include "string-table.h"
13 #include "strv.h"
14 #include "unaligned.h"
15 #include "utf8.h"
16 #include "util.h"
17 
18 #define EDNS0_OPT_DO (1<<15)
19 
20 assert_cc(DNS_PACKET_SIZE_START > DNS_PACKET_HEADER_SIZE);
21 
22 typedef struct DnsPacketRewinder {
23         DnsPacket *packet;
24         size_t saved_rindex;
25 } DnsPacketRewinder;
26 
rewind_dns_packet(DnsPacketRewinder * rewinder)27 static void rewind_dns_packet(DnsPacketRewinder *rewinder) {
28         if (rewinder->packet)
29                 dns_packet_rewind(rewinder->packet, rewinder->saved_rindex);
30 }
31 
32 #define REWINDER_INIT(p) {                              \
33                 .packet = (p),                          \
34                 .saved_rindex = (p)->rindex,            \
35         }
36 #define CANCEL_REWINDER(rewinder) do { (rewinder).packet = NULL; } while (0)
37 
dns_packet_new(DnsPacket ** ret,DnsProtocol protocol,size_t min_alloc_dsize,size_t max_size)38 int dns_packet_new(
39                 DnsPacket **ret,
40                 DnsProtocol protocol,
41                 size_t min_alloc_dsize,
42                 size_t max_size) {
43 
44         DnsPacket *p;
45         size_t a;
46 
47         assert(ret);
48         assert(max_size >= DNS_PACKET_HEADER_SIZE);
49 
50         if (max_size > DNS_PACKET_SIZE_MAX)
51                 max_size = DNS_PACKET_SIZE_MAX;
52 
53         /* The caller may not check what is going to be truly allocated, so do not allow to
54          * allocate a DNS packet bigger than DNS_PACKET_SIZE_MAX.
55          */
56         if (min_alloc_dsize > DNS_PACKET_SIZE_MAX)
57                 return log_error_errno(SYNTHETIC_ERRNO(EFBIG),
58                                        "Requested packet data size too big: %zu",
59                                        min_alloc_dsize);
60 
61         /* When dns_packet_new() is called with min_alloc_dsize == 0, allocate more than the
62          * absolute minimum (which is the dns packet header size), to avoid
63          * resizing immediately again after appending the first data to the packet.
64          */
65         if (min_alloc_dsize < DNS_PACKET_HEADER_SIZE)
66                 a = DNS_PACKET_SIZE_START;
67         else
68                 a = min_alloc_dsize;
69 
70         /* round up to next page size */
71         a = PAGE_ALIGN(ALIGN(sizeof(DnsPacket)) + a) - ALIGN(sizeof(DnsPacket));
72 
73         /* make sure we never allocate more than useful */
74         if (a > max_size)
75                 a = max_size;
76 
77         p = malloc0(ALIGN(sizeof(DnsPacket)) + a);
78         if (!p)
79                 return -ENOMEM;
80 
81         *p = (DnsPacket) {
82                 .n_ref = 1,
83                 .protocol = protocol,
84                 .size = DNS_PACKET_HEADER_SIZE,
85                 .rindex = DNS_PACKET_HEADER_SIZE,
86                 .allocated = a,
87                 .max_size = max_size,
88                 .opt_start = SIZE_MAX,
89                 .opt_size = SIZE_MAX,
90         };
91 
92         *ret = p;
93 
94         return 0;
95 }
96 
dns_packet_set_flags(DnsPacket * p,bool dnssec_checking_disabled,bool truncated)97 void dns_packet_set_flags(DnsPacket *p, bool dnssec_checking_disabled, bool truncated) {
98 
99         DnsPacketHeader *h;
100 
101         assert(p);
102 
103         h = DNS_PACKET_HEADER(p);
104 
105         switch (p->protocol) {
106         case DNS_PROTOCOL_LLMNR:
107                 assert(!truncated);
108 
109                 h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
110                                                          0 /* opcode */,
111                                                          0 /* c */,
112                                                          0 /* tc */,
113                                                          0 /* t */,
114                                                          0 /* ra */,
115                                                          0 /* ad */,
116                                                          0 /* cd */,
117                                                          0 /* rcode */));
118                 break;
119 
120         case DNS_PROTOCOL_MDNS:
121                 h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0         /* qr */,
122                                                          0         /* opcode */,
123                                                          0         /* aa */,
124                                                          truncated /* tc */,
125                                                          0         /* rd (ask for recursion) */,
126                                                          0         /* ra */,
127                                                          0         /* ad */,
128                                                          0         /* cd */,
129                                                          0         /* rcode */));
130                 break;
131 
132         default:
133                 assert(!truncated);
134 
135                 h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
136                                                          0 /* opcode */,
137                                                          0 /* aa */,
138                                                          0 /* tc */,
139                                                          1 /* rd (ask for recursion) */,
140                                                          0 /* ra */,
141                                                          0 /* ad */,
142                                                          dnssec_checking_disabled /* cd */,
143                                                          0 /* rcode */));
144         }
145 }
146 
dns_packet_new_query(DnsPacket ** ret,DnsProtocol protocol,size_t min_alloc_dsize,bool dnssec_checking_disabled)147 int dns_packet_new_query(DnsPacket **ret, DnsProtocol protocol, size_t min_alloc_dsize, bool dnssec_checking_disabled) {
148         DnsPacket *p;
149         int r;
150 
151         assert(ret);
152 
153         r = dns_packet_new(&p, protocol, min_alloc_dsize, DNS_PACKET_SIZE_MAX);
154         if (r < 0)
155                 return r;
156 
157         /* Always set the TC bit to 0 initially.
158          * If there are multiple packets later, we'll update the bit shortly before sending.
159          */
160         dns_packet_set_flags(p, dnssec_checking_disabled, false);
161 
162         *ret = p;
163         return 0;
164 }
165 
dns_packet_dup(DnsPacket ** ret,DnsPacket * p)166 int dns_packet_dup(DnsPacket **ret, DnsPacket *p) {
167         DnsPacket *c;
168         int r;
169 
170         assert(ret);
171         assert(p);
172 
173         r = dns_packet_validate(p);
174         if (r < 0)
175                 return r;
176 
177         c = malloc(ALIGN(sizeof(DnsPacket)) + p->size);
178         if (!c)
179                 return -ENOMEM;
180 
181         *c = (DnsPacket) {
182                 .n_ref = 1,
183                 .protocol = p->protocol,
184                 .size = p->size,
185                 .rindex = DNS_PACKET_HEADER_SIZE,
186                 .allocated = p->size,
187                 .max_size = p->max_size,
188                 .opt_start = SIZE_MAX,
189                 .opt_size = SIZE_MAX,
190         };
191 
192         memcpy(DNS_PACKET_DATA(c), DNS_PACKET_DATA(p), p->size);
193 
194         *ret = c;
195         return 0;
196 }
197 
dns_packet_ref(DnsPacket * p)198 DnsPacket *dns_packet_ref(DnsPacket *p) {
199 
200         if (!p)
201                 return NULL;
202 
203         assert(!p->on_stack);
204 
205         assert(p->n_ref > 0);
206         p->n_ref++;
207         return p;
208 }
209 
dns_packet_free(DnsPacket * p)210 static void dns_packet_free(DnsPacket *p) {
211         char *s;
212 
213         assert(p);
214 
215         dns_question_unref(p->question);
216         dns_answer_unref(p->answer);
217         dns_resource_record_unref(p->opt);
218 
219         while ((s = hashmap_steal_first_key(p->names)))
220                 free(s);
221         hashmap_free(p->names);
222 
223         free(p->_data);
224 
225         if (!p->on_stack)
226                 free(p);
227 }
228 
dns_packet_unref(DnsPacket * p)229 DnsPacket *dns_packet_unref(DnsPacket *p) {
230         if (!p)
231                 return NULL;
232 
233         assert(p->n_ref > 0);
234 
235         dns_packet_unref(p->more);
236 
237         if (p->n_ref == 1)
238                 dns_packet_free(p);
239         else
240                 p->n_ref--;
241 
242         return NULL;
243 }
244 
dns_packet_validate(DnsPacket * p)245 int dns_packet_validate(DnsPacket *p) {
246         assert(p);
247 
248         if (p->size < DNS_PACKET_HEADER_SIZE)
249                 return -EBADMSG;
250 
251         if (p->size > DNS_PACKET_SIZE_MAX)
252                 return -EBADMSG;
253 
254         return 1;
255 }
256 
dns_packet_validate_reply(DnsPacket * p)257 int dns_packet_validate_reply(DnsPacket *p) {
258         int r;
259 
260         assert(p);
261 
262         r = dns_packet_validate(p);
263         if (r < 0)
264                 return r;
265 
266         if (DNS_PACKET_QR(p) != 1)
267                 return 0;
268 
269         if (DNS_PACKET_OPCODE(p) != 0)
270                 return -EBADMSG;
271 
272         switch (p->protocol) {
273 
274         case DNS_PROTOCOL_LLMNR:
275                 /* RFC 4795, Section 2.1.1. says to discard all replies with QDCOUNT != 1 */
276                 if (DNS_PACKET_QDCOUNT(p) != 1)
277                         return -EBADMSG;
278 
279                 break;
280 
281         case DNS_PROTOCOL_MDNS:
282                 /* RFC 6762, Section 18 */
283                 if (DNS_PACKET_RCODE(p) != 0)
284                         return -EBADMSG;
285 
286                 break;
287 
288         default:
289                 break;
290         }
291 
292         return 1;
293 }
294 
dns_packet_validate_query(DnsPacket * p)295 int dns_packet_validate_query(DnsPacket *p) {
296         int r;
297 
298         assert(p);
299 
300         r = dns_packet_validate(p);
301         if (r < 0)
302                 return r;
303 
304         if (DNS_PACKET_QR(p) != 0)
305                 return 0;
306 
307         if (DNS_PACKET_OPCODE(p) != 0)
308                 return -EBADMSG;
309 
310         if (DNS_PACKET_TC(p))
311                 return -EBADMSG;
312 
313         switch (p->protocol) {
314 
315         case DNS_PROTOCOL_LLMNR:
316         case DNS_PROTOCOL_DNS:
317                 /* RFC 4795, Section 2.1.1. says to discard all queries with QDCOUNT != 1 */
318                 if (DNS_PACKET_QDCOUNT(p) != 1)
319                         return -EBADMSG;
320 
321                 /* RFC 4795, Section 2.1.1. says to discard all queries with ANCOUNT != 0 */
322                 if (DNS_PACKET_ANCOUNT(p) > 0)
323                         return -EBADMSG;
324 
325                 /* RFC 4795, Section 2.1.1. says to discard all queries with NSCOUNT != 0 */
326                 if (DNS_PACKET_NSCOUNT(p) > 0)
327                         return -EBADMSG;
328 
329                 break;
330 
331         case DNS_PROTOCOL_MDNS:
332                 /* RFC 6762, Section 18 specifies that messages with non-zero RCODE
333                  * must be silently ignored, and that we must ignore the values of
334                  * AA, RD, RA, AD, and CD bits. */
335                 if (DNS_PACKET_RCODE(p) != 0)
336                         return -EBADMSG;
337 
338                 break;
339 
340         default:
341                 break;
342         }
343 
344         return 1;
345 }
346 
dns_packet_extend(DnsPacket * p,size_t add,void ** ret,size_t * start)347 static int dns_packet_extend(DnsPacket *p, size_t add, void **ret, size_t *start) {
348         assert(p);
349 
350         if (p->size + add > p->allocated) {
351                 size_t a, ms;
352 
353                 a = PAGE_ALIGN((p->size + add) * 2);
354 
355                 ms = dns_packet_size_max(p);
356                 if (a > ms)
357                         a = ms;
358 
359                 if (p->size + add > a)
360                         return -EMSGSIZE;
361 
362                 if (p->_data) {
363                         void *d;
364 
365                         d = realloc(p->_data, a);
366                         if (!d)
367                                 return -ENOMEM;
368 
369                         p->_data = d;
370                 } else {
371                         p->_data = malloc(a);
372                         if (!p->_data)
373                                 return -ENOMEM;
374 
375                         memcpy(p->_data, (uint8_t*) p + ALIGN(sizeof(DnsPacket)), p->size);
376                         memzero((uint8_t*) p->_data + p->size, a - p->size);
377                 }
378 
379                 p->allocated = a;
380         }
381 
382         if (start)
383                 *start = p->size;
384 
385         if (ret)
386                 *ret = (uint8_t*) DNS_PACKET_DATA(p) + p->size;
387 
388         p->size += add;
389         return 0;
390 }
391 
dns_packet_truncate(DnsPacket * p,size_t sz)392 void dns_packet_truncate(DnsPacket *p, size_t sz) {
393         char *s;
394         void *n;
395 
396         assert(p);
397 
398         if (p->size <= sz)
399                 return;
400 
401         HASHMAP_FOREACH_KEY(n, s, p->names) {
402 
403                 if (PTR_TO_SIZE(n) < sz)
404                         continue;
405 
406                 hashmap_remove(p->names, s);
407                 free(s);
408         }
409 
410         p->size = sz;
411 }
412 
dns_packet_append_blob(DnsPacket * p,const void * d,size_t l,size_t * start)413 int dns_packet_append_blob(DnsPacket *p, const void *d, size_t l, size_t *start) {
414         void *q;
415         int r;
416 
417         assert(p);
418 
419         r = dns_packet_extend(p, l, &q, start);
420         if (r < 0)
421                 return r;
422 
423         memcpy_safe(q, d, l);
424         return 0;
425 }
426 
dns_packet_append_uint8(DnsPacket * p,uint8_t v,size_t * start)427 int dns_packet_append_uint8(DnsPacket *p, uint8_t v, size_t *start) {
428         void *d;
429         int r;
430 
431         assert(p);
432 
433         r = dns_packet_extend(p, sizeof(uint8_t), &d, start);
434         if (r < 0)
435                 return r;
436 
437         ((uint8_t*) d)[0] = v;
438 
439         return 0;
440 }
441 
dns_packet_append_uint16(DnsPacket * p,uint16_t v,size_t * start)442 int dns_packet_append_uint16(DnsPacket *p, uint16_t v, size_t *start) {
443         void *d;
444         int r;
445 
446         assert(p);
447 
448         r = dns_packet_extend(p, sizeof(uint16_t), &d, start);
449         if (r < 0)
450                 return r;
451 
452         unaligned_write_be16(d, v);
453 
454         return 0;
455 }
456 
dns_packet_append_uint32(DnsPacket * p,uint32_t v,size_t * start)457 int dns_packet_append_uint32(DnsPacket *p, uint32_t v, size_t *start) {
458         void *d;
459         int r;
460 
461         assert(p);
462 
463         r = dns_packet_extend(p, sizeof(uint32_t), &d, start);
464         if (r < 0)
465                 return r;
466 
467         unaligned_write_be32(d, v);
468 
469         return 0;
470 }
471 
dns_packet_append_string(DnsPacket * p,const char * s,size_t * start)472 int dns_packet_append_string(DnsPacket *p, const char *s, size_t *start) {
473         assert(p);
474         assert(s);
475 
476         return dns_packet_append_raw_string(p, s, strlen(s), start);
477 }
478 
dns_packet_append_raw_string(DnsPacket * p,const void * s,size_t size,size_t * start)479 int dns_packet_append_raw_string(DnsPacket *p, const void *s, size_t size, size_t *start) {
480         void *d;
481         int r;
482 
483         assert(p);
484         assert(s || size == 0);
485 
486         if (size > 255)
487                 return -E2BIG;
488 
489         r = dns_packet_extend(p, 1 + size, &d, start);
490         if (r < 0)
491                 return r;
492 
493         ((uint8_t*) d)[0] = (uint8_t) size;
494 
495         memcpy_safe(((uint8_t*) d) + 1, s, size);
496 
497         return 0;
498 }
499 
dns_packet_append_label(DnsPacket * p,const char * d,size_t l,bool canonical_candidate,size_t * start)500 int dns_packet_append_label(DnsPacket *p, const char *d, size_t l, bool canonical_candidate, size_t *start) {
501         uint8_t *w;
502         int r;
503 
504         /* Append a label to a packet. Optionally, does this in DNSSEC
505          * canonical form, if this label is marked as a candidate for
506          * it, and the canonical form logic is enabled for the
507          * packet */
508 
509         assert(p);
510         assert(d);
511 
512         if (l > DNS_LABEL_MAX)
513                 return -E2BIG;
514 
515         r = dns_packet_extend(p, 1 + l, (void**) &w, start);
516         if (r < 0)
517                 return r;
518 
519         *(w++) = (uint8_t) l;
520 
521         if (p->canonical_form && canonical_candidate)
522                 /* Generate in canonical form, as defined by DNSSEC
523                  * RFC 4034, Section 6.2, i.e. all lower-case. */
524                 for (size_t i = 0; i < l; i++)
525                         w[i] = (uint8_t) ascii_tolower(d[i]);
526         else
527                 /* Otherwise, just copy the string unaltered. This is
528                  * essential for DNS-SD, where the casing of labels
529                  * matters and needs to be retained. */
530                 memcpy(w, d, l);
531 
532         return 0;
533 }
534 
dns_packet_append_name(DnsPacket * p,const char * name,bool allow_compression,bool canonical_candidate,size_t * start)535 int dns_packet_append_name(
536                 DnsPacket *p,
537                 const char *name,
538                 bool allow_compression,
539                 bool canonical_candidate,
540                 size_t *start) {
541 
542         size_t saved_size;
543         int r;
544 
545         assert(p);
546         assert(name);
547 
548         if (p->refuse_compression)
549                 allow_compression = false;
550 
551         saved_size = p->size;
552 
553         while (!dns_name_is_root(name)) {
554                 const char *z = name;
555                 char label[DNS_LABEL_MAX];
556                 size_t n = 0;
557 
558                 if (allow_compression)
559                         n = PTR_TO_SIZE(hashmap_get(p->names, name));
560                 if (n > 0) {
561                         assert(n < p->size);
562 
563                         if (n < 0x4000) {
564                                 r = dns_packet_append_uint16(p, 0xC000 | n, NULL);
565                                 if (r < 0)
566                                         goto fail;
567 
568                                 goto done;
569                         }
570                 }
571 
572                 r = dns_label_unescape(&name, label, sizeof label, 0);
573                 if (r < 0)
574                         goto fail;
575 
576                 r = dns_packet_append_label(p, label, r, canonical_candidate, &n);
577                 if (r < 0)
578                         goto fail;
579 
580                 if (allow_compression) {
581                         _cleanup_free_ char *s = NULL;
582 
583                         s = strdup(z);
584                         if (!s) {
585                                 r = -ENOMEM;
586                                 goto fail;
587                         }
588 
589                         r = hashmap_ensure_put(&p->names, &dns_name_hash_ops, s, SIZE_TO_PTR(n));
590                         if (r < 0)
591                                 goto fail;
592 
593                         TAKE_PTR(s);
594                 }
595         }
596 
597         r = dns_packet_append_uint8(p, 0, NULL);
598         if (r < 0)
599                 return r;
600 
601 done:
602         if (start)
603                 *start = saved_size;
604 
605         return 0;
606 
607 fail:
608         dns_packet_truncate(p, saved_size);
609         return r;
610 }
611 
dns_packet_append_key(DnsPacket * p,const DnsResourceKey * k,const DnsAnswerFlags flags,size_t * start)612 int dns_packet_append_key(DnsPacket *p, const DnsResourceKey *k, const DnsAnswerFlags flags, size_t *start) {
613         size_t saved_size;
614         uint16_t class;
615         int r;
616 
617         assert(p);
618         assert(k);
619 
620         saved_size = p->size;
621 
622         r = dns_packet_append_name(p, dns_resource_key_name(k), true, true, NULL);
623         if (r < 0)
624                 goto fail;
625 
626         r = dns_packet_append_uint16(p, k->type, NULL);
627         if (r < 0)
628                 goto fail;
629 
630         class = flags & DNS_ANSWER_CACHE_FLUSH ? k->class | MDNS_RR_CACHE_FLUSH_OR_QU : k->class;
631         r = dns_packet_append_uint16(p, class, NULL);
632         if (r < 0)
633                 goto fail;
634 
635         if (start)
636                 *start = saved_size;
637 
638         return 0;
639 
640 fail:
641         dns_packet_truncate(p, saved_size);
642         return r;
643 }
644 
dns_packet_append_type_window(DnsPacket * p,uint8_t window,uint8_t length,const uint8_t * types,size_t * start)645 static int dns_packet_append_type_window(DnsPacket *p, uint8_t window, uint8_t length, const uint8_t *types, size_t *start) {
646         size_t saved_size;
647         int r;
648 
649         assert(p);
650         assert(types);
651         assert(length > 0);
652 
653         saved_size = p->size;
654 
655         r = dns_packet_append_uint8(p, window, NULL);
656         if (r < 0)
657                 goto fail;
658 
659         r = dns_packet_append_uint8(p, length, NULL);
660         if (r < 0)
661                 goto fail;
662 
663         r = dns_packet_append_blob(p, types, length, NULL);
664         if (r < 0)
665                 goto fail;
666 
667         if (start)
668                 *start = saved_size;
669 
670         return 0;
671 fail:
672         dns_packet_truncate(p, saved_size);
673         return r;
674 }
675 
dns_packet_append_types(DnsPacket * p,Bitmap * types,size_t * start)676 static int dns_packet_append_types(DnsPacket *p, Bitmap *types, size_t *start) {
677         uint8_t window = 0;
678         uint8_t entry = 0;
679         uint8_t bitmaps[32] = {};
680         unsigned n;
681         size_t saved_size;
682         int r;
683 
684         assert(p);
685 
686         saved_size = p->size;
687 
688         BITMAP_FOREACH(n, types) {
689                 assert(n <= 0xffff);
690 
691                 if ((n >> 8) != window && bitmaps[entry / 8] != 0) {
692                         r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
693                         if (r < 0)
694                                 goto fail;
695 
696                         zero(bitmaps);
697                 }
698 
699                 window = n >> 8;
700                 entry = n & 255;
701 
702                 bitmaps[entry / 8] |= 1 << (7 - (entry % 8));
703         }
704 
705         if (bitmaps[entry / 8] != 0) {
706                 r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
707                 if (r < 0)
708                         goto fail;
709         }
710 
711         if (start)
712                 *start = saved_size;
713 
714         return 0;
715 fail:
716         dns_packet_truncate(p, saved_size);
717         return r;
718 }
719 
720 /* Append the OPT pseudo-RR described in RFC6891 */
dns_packet_append_opt(DnsPacket * p,uint16_t max_udp_size,bool edns0_do,bool include_rfc6975,const char * nsid,int rcode,size_t * ret_start)721 int dns_packet_append_opt(
722                 DnsPacket *p,
723                 uint16_t max_udp_size,
724                 bool edns0_do,
725                 bool include_rfc6975,
726                 const char *nsid,
727                 int rcode,
728                 size_t *ret_start) {
729 
730         size_t saved_size;
731         int r;
732 
733         assert(p);
734         /* we must never advertise supported packet size smaller than the legacy max */
735         assert(max_udp_size >= DNS_PACKET_UNICAST_SIZE_MAX);
736         assert(rcode >= 0);
737         assert(rcode <= _DNS_RCODE_MAX);
738 
739         if (p->opt_start != SIZE_MAX)
740                 return -EBUSY;
741 
742         assert(p->opt_size == SIZE_MAX);
743 
744         saved_size = p->size;
745 
746         /* empty name */
747         r = dns_packet_append_uint8(p, 0, NULL);
748         if (r < 0)
749                 return r;
750 
751         /* type */
752         r = dns_packet_append_uint16(p, DNS_TYPE_OPT, NULL);
753         if (r < 0)
754                 goto fail;
755 
756         /* class: maximum udp packet that can be received */
757         r = dns_packet_append_uint16(p, max_udp_size, NULL);
758         if (r < 0)
759                 goto fail;
760 
761         /* extended RCODE and VERSION */
762         r = dns_packet_append_uint16(p, ((uint16_t) rcode & 0x0FF0) << 4, NULL);
763         if (r < 0)
764                 goto fail;
765 
766         /* flags: DNSSEC OK (DO), see RFC3225 */
767         r = dns_packet_append_uint16(p, edns0_do ? EDNS0_OPT_DO : 0, NULL);
768         if (r < 0)
769                 goto fail;
770 
771         if (edns0_do && include_rfc6975) {
772                 /* If DO is on and this is requested, also append RFC6975 Algorithm data. This is supposed to
773                  * be done on queries, not on replies, hencer callers should turn this off when finishing off
774                  * replies. */
775 
776                 static const uint8_t rfc6975[] = {
777 
778                         0, 5, /* OPTION_CODE: DAU */
779 #if PREFER_OPENSSL || (HAVE_GCRYPT && GCRYPT_VERSION_NUMBER >= 0x010600)
780                         0, 7, /* LIST_LENGTH */
781 #else
782                         0, 6, /* LIST_LENGTH */
783 #endif
784                         DNSSEC_ALGORITHM_RSASHA1,
785                         DNSSEC_ALGORITHM_RSASHA1_NSEC3_SHA1,
786                         DNSSEC_ALGORITHM_RSASHA256,
787                         DNSSEC_ALGORITHM_RSASHA512,
788                         DNSSEC_ALGORITHM_ECDSAP256SHA256,
789                         DNSSEC_ALGORITHM_ECDSAP384SHA384,
790 #if PREFER_OPENSSL || (HAVE_GCRYPT && GCRYPT_VERSION_NUMBER >= 0x010600)
791                         DNSSEC_ALGORITHM_ED25519,
792 #endif
793 
794                         0, 6, /* OPTION_CODE: DHU */
795                         0, 3, /* LIST_LENGTH */
796                         DNSSEC_DIGEST_SHA1,
797                         DNSSEC_DIGEST_SHA256,
798                         DNSSEC_DIGEST_SHA384,
799 
800                         0, 7, /* OPTION_CODE: N3U */
801                         0, 1, /* LIST_LENGTH */
802                         NSEC3_ALGORITHM_SHA1,
803                 };
804 
805                 r = dns_packet_append_uint16(p, sizeof(rfc6975), NULL); /* RDLENGTH */
806                 if (r < 0)
807                         goto fail;
808 
809                 r = dns_packet_append_blob(p, rfc6975, sizeof(rfc6975), NULL); /* the payload, as defined above */
810 
811         } else if (nsid) {
812 
813                 if (strlen(nsid) > UINT16_MAX - 4) {
814                         r = -E2BIG;
815                         goto fail;
816                 }
817 
818                 r = dns_packet_append_uint16(p, 4 + strlen(nsid), NULL); /* RDLENGTH */
819                 if (r < 0)
820                         goto fail;
821 
822                 r = dns_packet_append_uint16(p, 3, NULL); /* OPTION-CODE: NSID */
823                 if (r < 0)
824                         goto fail;
825 
826                 r = dns_packet_append_uint16(p, strlen(nsid), NULL); /* OPTION-LENGTH */
827                 if (r < 0)
828                         goto fail;
829 
830                 r = dns_packet_append_blob(p, nsid, strlen(nsid), NULL);
831         } else
832                 r = dns_packet_append_uint16(p, 0, NULL);
833         if (r < 0)
834                 goto fail;
835 
836         DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) + 1);
837 
838         p->opt_start = saved_size;
839         p->opt_size = p->size - saved_size;
840 
841         if (ret_start)
842                 *ret_start = saved_size;
843 
844         return 0;
845 
846 fail:
847         dns_packet_truncate(p, saved_size);
848         return r;
849 }
850 
dns_packet_truncate_opt(DnsPacket * p)851 int dns_packet_truncate_opt(DnsPacket *p) {
852         assert(p);
853 
854         if (p->opt_start == SIZE_MAX) {
855                 assert(p->opt_size == SIZE_MAX);
856                 return 0;
857         }
858 
859         assert(p->opt_size != SIZE_MAX);
860         assert(DNS_PACKET_ARCOUNT(p) > 0);
861 
862         if (p->opt_start + p->opt_size != p->size)
863                 return -EBUSY;
864 
865         dns_packet_truncate(p, p->opt_start);
866         DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) - 1);
867         p->opt_start = p->opt_size = SIZE_MAX;
868 
869         return 1;
870 }
871 
dns_packet_append_rr(DnsPacket * p,const DnsResourceRecord * rr,const DnsAnswerFlags flags,size_t * start,size_t * rdata_start)872 int dns_packet_append_rr(DnsPacket *p, const DnsResourceRecord *rr, const DnsAnswerFlags flags, size_t *start, size_t *rdata_start) {
873 
874         size_t saved_size, rdlength_offset, end, rdlength, rds;
875         uint32_t ttl;
876         int r;
877 
878         assert(p);
879         assert(rr);
880 
881         saved_size = p->size;
882 
883         r = dns_packet_append_key(p, rr->key, flags, NULL);
884         if (r < 0)
885                 goto fail;
886 
887         ttl = flags & DNS_ANSWER_GOODBYE ? 0 : rr->ttl;
888         r = dns_packet_append_uint32(p, ttl, NULL);
889         if (r < 0)
890                 goto fail;
891 
892         /* Initially we write 0 here */
893         r = dns_packet_append_uint16(p, 0, &rdlength_offset);
894         if (r < 0)
895                 goto fail;
896 
897         rds = p->size - saved_size;
898 
899         switch (rr->unparsable ? _DNS_TYPE_INVALID : rr->key->type) {
900 
901         case DNS_TYPE_SRV:
902                 r = dns_packet_append_uint16(p, rr->srv.priority, NULL);
903                 if (r < 0)
904                         goto fail;
905 
906                 r = dns_packet_append_uint16(p, rr->srv.weight, NULL);
907                 if (r < 0)
908                         goto fail;
909 
910                 r = dns_packet_append_uint16(p, rr->srv.port, NULL);
911                 if (r < 0)
912                         goto fail;
913 
914                 /* RFC 2782 states "Unless and until permitted by future standards
915                  * action, name compression is not to be used for this field." */
916                 r = dns_packet_append_name(p, rr->srv.name, false, true, NULL);
917                 break;
918 
919         case DNS_TYPE_PTR:
920         case DNS_TYPE_NS:
921         case DNS_TYPE_CNAME:
922         case DNS_TYPE_DNAME:
923                 r = dns_packet_append_name(p, rr->ptr.name, true, true, NULL);
924                 break;
925 
926         case DNS_TYPE_HINFO:
927                 r = dns_packet_append_string(p, rr->hinfo.cpu, NULL);
928                 if (r < 0)
929                         goto fail;
930 
931                 r = dns_packet_append_string(p, rr->hinfo.os, NULL);
932                 break;
933 
934         case DNS_TYPE_SPF: /* exactly the same as TXT */
935         case DNS_TYPE_TXT:
936 
937                 if (!rr->txt.items) {
938                         /* RFC 6763, section 6.1 suggests to generate
939                          * single empty string for an empty array. */
940 
941                         r = dns_packet_append_raw_string(p, NULL, 0, NULL);
942                         if (r < 0)
943                                 goto fail;
944                 } else
945                         LIST_FOREACH(items, i, rr->txt.items) {
946                                 r = dns_packet_append_raw_string(p, i->data, i->length, NULL);
947                                 if (r < 0)
948                                         goto fail;
949                         }
950 
951                 r = 0;
952                 break;
953 
954         case DNS_TYPE_A:
955                 r = dns_packet_append_blob(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
956                 break;
957 
958         case DNS_TYPE_AAAA:
959                 r = dns_packet_append_blob(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
960                 break;
961 
962         case DNS_TYPE_SOA:
963                 r = dns_packet_append_name(p, rr->soa.mname, true, true, NULL);
964                 if (r < 0)
965                         goto fail;
966 
967                 r = dns_packet_append_name(p, rr->soa.rname, true, true, NULL);
968                 if (r < 0)
969                         goto fail;
970 
971                 r = dns_packet_append_uint32(p, rr->soa.serial, NULL);
972                 if (r < 0)
973                         goto fail;
974 
975                 r = dns_packet_append_uint32(p, rr->soa.refresh, NULL);
976                 if (r < 0)
977                         goto fail;
978 
979                 r = dns_packet_append_uint32(p, rr->soa.retry, NULL);
980                 if (r < 0)
981                         goto fail;
982 
983                 r = dns_packet_append_uint32(p, rr->soa.expire, NULL);
984                 if (r < 0)
985                         goto fail;
986 
987                 r = dns_packet_append_uint32(p, rr->soa.minimum, NULL);
988                 break;
989 
990         case DNS_TYPE_MX:
991                 r = dns_packet_append_uint16(p, rr->mx.priority, NULL);
992                 if (r < 0)
993                         goto fail;
994 
995                 r = dns_packet_append_name(p, rr->mx.exchange, true, true, NULL);
996                 break;
997 
998         case DNS_TYPE_LOC:
999                 r = dns_packet_append_uint8(p, rr->loc.version, NULL);
1000                 if (r < 0)
1001                         goto fail;
1002 
1003                 r = dns_packet_append_uint8(p, rr->loc.size, NULL);
1004                 if (r < 0)
1005                         goto fail;
1006 
1007                 r = dns_packet_append_uint8(p, rr->loc.horiz_pre, NULL);
1008                 if (r < 0)
1009                         goto fail;
1010 
1011                 r = dns_packet_append_uint8(p, rr->loc.vert_pre, NULL);
1012                 if (r < 0)
1013                         goto fail;
1014 
1015                 r = dns_packet_append_uint32(p, rr->loc.latitude, NULL);
1016                 if (r < 0)
1017                         goto fail;
1018 
1019                 r = dns_packet_append_uint32(p, rr->loc.longitude, NULL);
1020                 if (r < 0)
1021                         goto fail;
1022 
1023                 r = dns_packet_append_uint32(p, rr->loc.altitude, NULL);
1024                 break;
1025 
1026         case DNS_TYPE_DS:
1027                 r = dns_packet_append_uint16(p, rr->ds.key_tag, NULL);
1028                 if (r < 0)
1029                         goto fail;
1030 
1031                 r = dns_packet_append_uint8(p, rr->ds.algorithm, NULL);
1032                 if (r < 0)
1033                         goto fail;
1034 
1035                 r = dns_packet_append_uint8(p, rr->ds.digest_type, NULL);
1036                 if (r < 0)
1037                         goto fail;
1038 
1039                 r = dns_packet_append_blob(p, rr->ds.digest, rr->ds.digest_size, NULL);
1040                 break;
1041 
1042         case DNS_TYPE_SSHFP:
1043                 r = dns_packet_append_uint8(p, rr->sshfp.algorithm, NULL);
1044                 if (r < 0)
1045                         goto fail;
1046 
1047                 r = dns_packet_append_uint8(p, rr->sshfp.fptype, NULL);
1048                 if (r < 0)
1049                         goto fail;
1050 
1051                 r = dns_packet_append_blob(p, rr->sshfp.fingerprint, rr->sshfp.fingerprint_size, NULL);
1052                 break;
1053 
1054         case DNS_TYPE_DNSKEY:
1055                 r = dns_packet_append_uint16(p, rr->dnskey.flags, NULL);
1056                 if (r < 0)
1057                         goto fail;
1058 
1059                 r = dns_packet_append_uint8(p, rr->dnskey.protocol, NULL);
1060                 if (r < 0)
1061                         goto fail;
1062 
1063                 r = dns_packet_append_uint8(p, rr->dnskey.algorithm, NULL);
1064                 if (r < 0)
1065                         goto fail;
1066 
1067                 r = dns_packet_append_blob(p, rr->dnskey.key, rr->dnskey.key_size, NULL);
1068                 break;
1069 
1070         case DNS_TYPE_RRSIG:
1071                 r = dns_packet_append_uint16(p, rr->rrsig.type_covered, NULL);
1072                 if (r < 0)
1073                         goto fail;
1074 
1075                 r = dns_packet_append_uint8(p, rr->rrsig.algorithm, NULL);
1076                 if (r < 0)
1077                         goto fail;
1078 
1079                 r = dns_packet_append_uint8(p, rr->rrsig.labels, NULL);
1080                 if (r < 0)
1081                         goto fail;
1082 
1083                 r = dns_packet_append_uint32(p, rr->rrsig.original_ttl, NULL);
1084                 if (r < 0)
1085                         goto fail;
1086 
1087                 r = dns_packet_append_uint32(p, rr->rrsig.expiration, NULL);
1088                 if (r < 0)
1089                         goto fail;
1090 
1091                 r = dns_packet_append_uint32(p, rr->rrsig.inception, NULL);
1092                 if (r < 0)
1093                         goto fail;
1094 
1095                 r = dns_packet_append_uint16(p, rr->rrsig.key_tag, NULL);
1096                 if (r < 0)
1097                         goto fail;
1098 
1099                 r = dns_packet_append_name(p, rr->rrsig.signer, false, true, NULL);
1100                 if (r < 0)
1101                         goto fail;
1102 
1103                 r = dns_packet_append_blob(p, rr->rrsig.signature, rr->rrsig.signature_size, NULL);
1104                 break;
1105 
1106         case DNS_TYPE_NSEC:
1107                 r = dns_packet_append_name(p, rr->nsec.next_domain_name, false, false, NULL);
1108                 if (r < 0)
1109                         goto fail;
1110 
1111                 r = dns_packet_append_types(p, rr->nsec.types, NULL);
1112                 if (r < 0)
1113                         goto fail;
1114 
1115                 break;
1116 
1117         case DNS_TYPE_NSEC3:
1118                 r = dns_packet_append_uint8(p, rr->nsec3.algorithm, NULL);
1119                 if (r < 0)
1120                         goto fail;
1121 
1122                 r = dns_packet_append_uint8(p, rr->nsec3.flags, NULL);
1123                 if (r < 0)
1124                         goto fail;
1125 
1126                 r = dns_packet_append_uint16(p, rr->nsec3.iterations, NULL);
1127                 if (r < 0)
1128                         goto fail;
1129 
1130                 r = dns_packet_append_uint8(p, rr->nsec3.salt_size, NULL);
1131                 if (r < 0)
1132                         goto fail;
1133 
1134                 r = dns_packet_append_blob(p, rr->nsec3.salt, rr->nsec3.salt_size, NULL);
1135                 if (r < 0)
1136                         goto fail;
1137 
1138                 r = dns_packet_append_uint8(p, rr->nsec3.next_hashed_name_size, NULL);
1139                 if (r < 0)
1140                         goto fail;
1141 
1142                 r = dns_packet_append_blob(p, rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size, NULL);
1143                 if (r < 0)
1144                         goto fail;
1145 
1146                 r = dns_packet_append_types(p, rr->nsec3.types, NULL);
1147                 if (r < 0)
1148                         goto fail;
1149 
1150                 break;
1151 
1152         case DNS_TYPE_TLSA:
1153                 r = dns_packet_append_uint8(p, rr->tlsa.cert_usage, NULL);
1154                 if (r < 0)
1155                         goto fail;
1156 
1157                 r = dns_packet_append_uint8(p, rr->tlsa.selector, NULL);
1158                 if (r < 0)
1159                         goto fail;
1160 
1161                 r = dns_packet_append_uint8(p, rr->tlsa.matching_type, NULL);
1162                 if (r < 0)
1163                         goto fail;
1164 
1165                 r = dns_packet_append_blob(p, rr->tlsa.data, rr->tlsa.data_size, NULL);
1166                 break;
1167 
1168         case DNS_TYPE_CAA:
1169                 r = dns_packet_append_uint8(p, rr->caa.flags, NULL);
1170                 if (r < 0)
1171                         goto fail;
1172 
1173                 r = dns_packet_append_string(p, rr->caa.tag, NULL);
1174                 if (r < 0)
1175                         goto fail;
1176 
1177                 r = dns_packet_append_blob(p, rr->caa.value, rr->caa.value_size, NULL);
1178                 break;
1179 
1180         case DNS_TYPE_OPT:
1181         case DNS_TYPE_OPENPGPKEY:
1182         case _DNS_TYPE_INVALID: /* unparsable */
1183         default:
1184 
1185                 r = dns_packet_append_blob(p, rr->generic.data, rr->generic.data_size, NULL);
1186                 break;
1187         }
1188         if (r < 0)
1189                 goto fail;
1190 
1191         /* Let's calculate the actual data size and update the field */
1192         rdlength = p->size - rdlength_offset - sizeof(uint16_t);
1193         if (rdlength > 0xFFFF) {
1194                 r = -ENOSPC;
1195                 goto fail;
1196         }
1197 
1198         end = p->size;
1199         p->size = rdlength_offset;
1200         r = dns_packet_append_uint16(p, rdlength, NULL);
1201         if (r < 0)
1202                 goto fail;
1203         p->size = end;
1204 
1205         if (start)
1206                 *start = saved_size;
1207 
1208         if (rdata_start)
1209                 *rdata_start = rds;
1210 
1211         return 0;
1212 
1213 fail:
1214         dns_packet_truncate(p, saved_size);
1215         return r;
1216 }
1217 
dns_packet_append_question(DnsPacket * p,DnsQuestion * q)1218 int dns_packet_append_question(DnsPacket *p, DnsQuestion *q) {
1219         DnsResourceKey *key;
1220         int r;
1221 
1222         assert(p);
1223 
1224         DNS_QUESTION_FOREACH(key, q) {
1225                 r = dns_packet_append_key(p, key, 0, NULL);
1226                 if (r < 0)
1227                         return r;
1228         }
1229 
1230         return 0;
1231 }
1232 
dns_packet_append_answer(DnsPacket * p,DnsAnswer * a,unsigned * completed)1233 int dns_packet_append_answer(DnsPacket *p, DnsAnswer *a, unsigned *completed) {
1234         DnsResourceRecord *rr;
1235         DnsAnswerFlags flags;
1236         int r;
1237 
1238         assert(p);
1239 
1240         DNS_ANSWER_FOREACH_FLAGS(rr, flags, a) {
1241                 r = dns_packet_append_rr(p, rr, flags, NULL, NULL);
1242                 if (r < 0)
1243                         return r;
1244 
1245                 if (completed)
1246                         (*completed)++;
1247         }
1248 
1249         return 0;
1250 }
1251 
dns_packet_read(DnsPacket * p,size_t sz,const void ** ret,size_t * start)1252 int dns_packet_read(DnsPacket *p, size_t sz, const void **ret, size_t *start) {
1253         assert(p);
1254 
1255         if (p->rindex + sz > p->size)
1256                 return -EMSGSIZE;
1257 
1258         if (ret)
1259                 *ret = (uint8_t*) DNS_PACKET_DATA(p) + p->rindex;
1260 
1261         if (start)
1262                 *start = p->rindex;
1263 
1264         p->rindex += sz;
1265         return 0;
1266 }
1267 
dns_packet_rewind(DnsPacket * p,size_t idx)1268 void dns_packet_rewind(DnsPacket *p, size_t idx) {
1269         assert(p);
1270         assert(idx <= p->size);
1271         assert(idx >= DNS_PACKET_HEADER_SIZE);
1272 
1273         p->rindex = idx;
1274 }
1275 
dns_packet_read_blob(DnsPacket * p,void * d,size_t sz,size_t * start)1276 int dns_packet_read_blob(DnsPacket *p, void *d, size_t sz, size_t *start) {
1277         const void *q;
1278         int r;
1279 
1280         assert(p);
1281         assert(d);
1282 
1283         r = dns_packet_read(p, sz, &q, start);
1284         if (r < 0)
1285                 return r;
1286 
1287         memcpy(d, q, sz);
1288         return 0;
1289 }
1290 
dns_packet_read_memdup(DnsPacket * p,size_t size,void ** ret,size_t * ret_size,size_t * ret_start)1291 static int dns_packet_read_memdup(
1292                 DnsPacket *p, size_t size,
1293                 void **ret, size_t *ret_size,
1294                 size_t *ret_start) {
1295 
1296         const void *src;
1297         size_t start;
1298         int r;
1299 
1300         assert(p);
1301         assert(ret);
1302 
1303         r = dns_packet_read(p, size, &src, &start);
1304         if (r < 0)
1305                 return r;
1306 
1307         if (size <= 0)
1308                 *ret = NULL;
1309         else {
1310                 void *copy;
1311 
1312                 copy = memdup(src, size);
1313                 if (!copy)
1314                         return -ENOMEM;
1315 
1316                 *ret = copy;
1317         }
1318 
1319         if (ret_size)
1320                 *ret_size = size;
1321         if (ret_start)
1322                 *ret_start = start;
1323 
1324         return 0;
1325 }
1326 
dns_packet_read_uint8(DnsPacket * p,uint8_t * ret,size_t * start)1327 int dns_packet_read_uint8(DnsPacket *p, uint8_t *ret, size_t *start) {
1328         const void *d;
1329         int r;
1330 
1331         assert(p);
1332 
1333         r = dns_packet_read(p, sizeof(uint8_t), &d, start);
1334         if (r < 0)
1335                 return r;
1336 
1337         *ret = ((uint8_t*) d)[0];
1338         return 0;
1339 }
1340 
dns_packet_read_uint16(DnsPacket * p,uint16_t * ret,size_t * start)1341 int dns_packet_read_uint16(DnsPacket *p, uint16_t *ret, size_t *start) {
1342         const void *d;
1343         int r;
1344 
1345         assert(p);
1346 
1347         r = dns_packet_read(p, sizeof(uint16_t), &d, start);
1348         if (r < 0)
1349                 return r;
1350 
1351         if (ret)
1352                 *ret = unaligned_read_be16(d);
1353 
1354         return 0;
1355 }
1356 
dns_packet_read_uint32(DnsPacket * p,uint32_t * ret,size_t * start)1357 int dns_packet_read_uint32(DnsPacket *p, uint32_t *ret, size_t *start) {
1358         const void *d;
1359         int r;
1360 
1361         assert(p);
1362 
1363         r = dns_packet_read(p, sizeof(uint32_t), &d, start);
1364         if (r < 0)
1365                 return r;
1366 
1367         *ret = unaligned_read_be32(d);
1368 
1369         return 0;
1370 }
1371 
dns_packet_read_string(DnsPacket * p,char ** ret,size_t * start)1372 int dns_packet_read_string(DnsPacket *p, char **ret, size_t *start) {
1373         assert(p);
1374 
1375         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1376         const void *d;
1377         char *t;
1378         uint8_t c;
1379         int r;
1380 
1381         r = dns_packet_read_uint8(p, &c, NULL);
1382         if (r < 0)
1383                 return r;
1384 
1385         r = dns_packet_read(p, c, &d, NULL);
1386         if (r < 0)
1387                 return r;
1388 
1389         if (memchr(d, 0, c))
1390                 return -EBADMSG;
1391 
1392         t = strndup(d, c);
1393         if (!t)
1394                 return -ENOMEM;
1395 
1396         if (!utf8_is_valid(t)) {
1397                 free(t);
1398                 return -EBADMSG;
1399         }
1400 
1401         *ret = t;
1402 
1403         if (start)
1404                 *start = rewinder.saved_rindex;
1405         CANCEL_REWINDER(rewinder);
1406 
1407         return 0;
1408 }
1409 
dns_packet_read_raw_string(DnsPacket * p,const void ** ret,size_t * size,size_t * start)1410 int dns_packet_read_raw_string(DnsPacket *p, const void **ret, size_t *size, size_t *start) {
1411         assert(p);
1412 
1413         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1414         uint8_t c;
1415         int r;
1416 
1417         r = dns_packet_read_uint8(p, &c, NULL);
1418         if (r < 0)
1419                 return r;
1420 
1421         r = dns_packet_read(p, c, ret, NULL);
1422         if (r < 0)
1423                 return r;
1424 
1425         if (size)
1426                 *size = c;
1427         if (start)
1428                 *start = rewinder.saved_rindex;
1429         CANCEL_REWINDER(rewinder);
1430 
1431         return 0;
1432 }
1433 
dns_packet_read_name(DnsPacket * p,char ** ret,bool allow_compression,size_t * ret_start)1434 int dns_packet_read_name(
1435                 DnsPacket *p,
1436                 char **ret,
1437                 bool allow_compression,
1438                 size_t *ret_start) {
1439 
1440         assert(p);
1441 
1442         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1443         size_t after_rindex = 0, jump_barrier = p->rindex;
1444         _cleanup_free_ char *name = NULL;
1445         bool first = true;
1446         size_t n = 0;
1447         int r;
1448 
1449         if (p->refuse_compression)
1450                 allow_compression = false;
1451 
1452         for (;;) {
1453                 uint8_t c, d;
1454 
1455                 r = dns_packet_read_uint8(p, &c, NULL);
1456                 if (r < 0)
1457                         return r;
1458 
1459                 if (c == 0)
1460                         /* End of name */
1461                         break;
1462                 else if (c <= 63) {
1463                         const char *label;
1464 
1465                         /* Literal label */
1466                         r = dns_packet_read(p, c, (const void**) &label, NULL);
1467                         if (r < 0)
1468                                 return r;
1469 
1470                         if (!GREEDY_REALLOC(name, n + !first + DNS_LABEL_ESCAPED_MAX))
1471                                 return -ENOMEM;
1472 
1473                         if (first)
1474                                 first = false;
1475                         else
1476                                 name[n++] = '.';
1477 
1478                         r = dns_label_escape(label, c, name + n, DNS_LABEL_ESCAPED_MAX);
1479                         if (r < 0)
1480                                 return r;
1481 
1482                         n += r;
1483                         continue;
1484                 } else if (allow_compression && FLAGS_SET(c, 0xc0)) {
1485                         uint16_t ptr;
1486 
1487                         /* Pointer */
1488                         r = dns_packet_read_uint8(p, &d, NULL);
1489                         if (r < 0)
1490                                 return r;
1491 
1492                         ptr = (uint16_t) (c & ~0xc0) << 8 | (uint16_t) d;
1493                         if (ptr < DNS_PACKET_HEADER_SIZE || ptr >= jump_barrier)
1494                                 return -EBADMSG;
1495 
1496                         if (after_rindex == 0)
1497                                 after_rindex = p->rindex;
1498 
1499                         /* Jumps are limited to a "prior occurrence" (RFC-1035 4.1.4) */
1500                         jump_barrier = ptr;
1501                         p->rindex = ptr;
1502                 } else
1503                         return -EBADMSG;
1504         }
1505 
1506         if (!GREEDY_REALLOC(name, n + 1))
1507                 return -ENOMEM;
1508 
1509         name[n] = 0;
1510 
1511         if (after_rindex != 0)
1512                 p->rindex= after_rindex;
1513 
1514         if (ret)
1515                 *ret = TAKE_PTR(name);
1516         if (ret_start)
1517                 *ret_start = rewinder.saved_rindex;
1518 
1519         CANCEL_REWINDER(rewinder);
1520 
1521         return 0;
1522 }
1523 
dns_packet_read_type_window(DnsPacket * p,Bitmap ** types,size_t * start)1524 static int dns_packet_read_type_window(DnsPacket *p, Bitmap **types, size_t *start) {
1525         assert(p);
1526         assert(types);
1527 
1528         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1529         uint8_t window, length;
1530         const uint8_t *bitmap;
1531         uint8_t bit = 0;
1532         bool found = false;
1533         int r;
1534 
1535         r = bitmap_ensure_allocated(types);
1536         if (r < 0)
1537                 return r;
1538 
1539         r = dns_packet_read_uint8(p, &window, NULL);
1540         if (r < 0)
1541                 return r;
1542 
1543         r = dns_packet_read_uint8(p, &length, NULL);
1544         if (r < 0)
1545                 return r;
1546 
1547         if (length == 0 || length > 32)
1548                 return -EBADMSG;
1549 
1550         r = dns_packet_read(p, length, (const void **)&bitmap, NULL);
1551         if (r < 0)
1552                 return r;
1553 
1554         for (uint8_t i = 0; i < length; i++) {
1555                 uint8_t bitmask = 1 << 7;
1556 
1557                 if (!bitmap[i]) {
1558                         found = false;
1559                         bit += 8;
1560                         continue;
1561                 }
1562 
1563                 found = true;
1564 
1565                 for (; bitmask; bit++, bitmask >>= 1)
1566                         if (bitmap[i] & bitmask) {
1567                                 uint16_t n;
1568 
1569                                 n = (uint16_t) window << 8 | (uint16_t) bit;
1570 
1571                                 /* Ignore pseudo-types. see RFC4034 section 4.1.2 */
1572                                 if (dns_type_is_pseudo(n))
1573                                         continue;
1574 
1575                                 r = bitmap_set(*types, n);
1576                                 if (r < 0)
1577                                         return r;
1578                         }
1579         }
1580 
1581         if (!found)
1582                 return -EBADMSG;
1583 
1584         if (start)
1585                 *start = rewinder.saved_rindex;
1586         CANCEL_REWINDER(rewinder);
1587 
1588         return 0;
1589 }
1590 
dns_packet_read_type_windows(DnsPacket * p,Bitmap ** types,size_t size,size_t * start)1591 static int dns_packet_read_type_windows(DnsPacket *p, Bitmap **types, size_t size, size_t *start) {
1592         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1593         int r;
1594 
1595         while (p->rindex < rewinder.saved_rindex + size) {
1596                 r = dns_packet_read_type_window(p, types, NULL);
1597                 if (r < 0)
1598                         return r;
1599 
1600                 /* don't read past end of current RR */
1601                 if (p->rindex > rewinder.saved_rindex + size)
1602                         return -EBADMSG;
1603         }
1604 
1605         if (p->rindex != rewinder.saved_rindex + size)
1606                 return -EBADMSG;
1607 
1608         if (start)
1609                 *start = rewinder.saved_rindex;
1610         CANCEL_REWINDER(rewinder);
1611 
1612         return 0;
1613 }
1614 
dns_packet_read_key(DnsPacket * p,DnsResourceKey ** ret,bool * ret_cache_flush_or_qu,size_t * ret_start)1615 int dns_packet_read_key(
1616                 DnsPacket *p,
1617                 DnsResourceKey **ret,
1618                 bool *ret_cache_flush_or_qu,
1619                 size_t *ret_start) {
1620 
1621         assert(p);
1622 
1623         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1624         _cleanup_free_ char *name = NULL;
1625         bool cache_flush_or_qu = false;
1626         uint16_t class, type;
1627         int r;
1628 
1629         r = dns_packet_read_name(p, &name, true, NULL);
1630         if (r < 0)
1631                 return r;
1632 
1633         r = dns_packet_read_uint16(p, &type, NULL);
1634         if (r < 0)
1635                 return r;
1636 
1637         r = dns_packet_read_uint16(p, &class, NULL);
1638         if (r < 0)
1639                 return r;
1640 
1641         if (p->protocol == DNS_PROTOCOL_MDNS) {
1642                 /* See RFC6762, sections 5.4 and 10.2 */
1643 
1644                 if (type != DNS_TYPE_OPT && (class & MDNS_RR_CACHE_FLUSH_OR_QU)) {
1645                         class &= ~MDNS_RR_CACHE_FLUSH_OR_QU;
1646                         cache_flush_or_qu = true;
1647                 }
1648         }
1649 
1650         if (ret) {
1651                 DnsResourceKey *key;
1652 
1653                 key = dns_resource_key_new_consume(class, type, name);
1654                 if (!key)
1655                         return -ENOMEM;
1656 
1657                 TAKE_PTR(name);
1658                 *ret = key;
1659         }
1660 
1661         if (ret_cache_flush_or_qu)
1662                 *ret_cache_flush_or_qu = cache_flush_or_qu;
1663         if (ret_start)
1664                 *ret_start = rewinder.saved_rindex;
1665 
1666         CANCEL_REWINDER(rewinder);
1667         return 0;
1668 }
1669 
loc_size_ok(uint8_t size)1670 static bool loc_size_ok(uint8_t size) {
1671         uint8_t m = size >> 4, e = size & 0xF;
1672 
1673         return m <= 9 && e <= 9 && (m > 0 || e == 0);
1674 }
1675 
dns_packet_read_rr(DnsPacket * p,DnsResourceRecord ** ret,bool * ret_cache_flush,size_t * ret_start)1676 int dns_packet_read_rr(
1677                 DnsPacket *p,
1678                 DnsResourceRecord **ret,
1679                 bool *ret_cache_flush,
1680                 size_t *ret_start) {
1681 
1682         assert(p);
1683 
1684         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
1685         _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1686         _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1687         size_t offset;
1688         uint16_t rdlength;
1689         bool cache_flush;
1690         int r;
1691 
1692         r = dns_packet_read_key(p, &key, &cache_flush, NULL);
1693         if (r < 0)
1694                 return r;
1695 
1696         if (!dns_class_is_valid_rr(key->class) || !dns_type_is_valid_rr(key->type))
1697                 return -EBADMSG;
1698 
1699         rr = dns_resource_record_new(key);
1700         if (!rr)
1701                 return -ENOMEM;
1702 
1703         r = dns_packet_read_uint32(p, &rr->ttl, NULL);
1704         if (r < 0)
1705                 return r;
1706 
1707         /* RFC 2181, Section 8, suggests to
1708          * treat a TTL with the MSB set as a zero TTL. */
1709         if (rr->ttl & UINT32_C(0x80000000))
1710                 rr->ttl = 0;
1711 
1712         r = dns_packet_read_uint16(p, &rdlength, NULL);
1713         if (r < 0)
1714                 return r;
1715 
1716         if (p->rindex + rdlength > p->size)
1717                 return -EBADMSG;
1718 
1719         offset = p->rindex;
1720 
1721         switch (rr->key->type) {
1722 
1723         case DNS_TYPE_SRV:
1724                 r = dns_packet_read_uint16(p, &rr->srv.priority, NULL);
1725                 if (r < 0)
1726                         return r;
1727                 r = dns_packet_read_uint16(p, &rr->srv.weight, NULL);
1728                 if (r < 0)
1729                         return r;
1730                 r = dns_packet_read_uint16(p, &rr->srv.port, NULL);
1731                 if (r < 0)
1732                         return r;
1733                 r = dns_packet_read_name(p, &rr->srv.name, true, NULL);
1734                 break;
1735 
1736         case DNS_TYPE_PTR:
1737         case DNS_TYPE_NS:
1738         case DNS_TYPE_CNAME:
1739         case DNS_TYPE_DNAME:
1740                 r = dns_packet_read_name(p, &rr->ptr.name, true, NULL);
1741                 break;
1742 
1743         case DNS_TYPE_HINFO:
1744                 r = dns_packet_read_string(p, &rr->hinfo.cpu, NULL);
1745                 if (r < 0)
1746                         return r;
1747 
1748                 r = dns_packet_read_string(p, &rr->hinfo.os, NULL);
1749                 break;
1750 
1751         case DNS_TYPE_SPF: /* exactly the same as TXT */
1752         case DNS_TYPE_TXT:
1753                 if (rdlength <= 0) {
1754                         r = dns_txt_item_new_empty(&rr->txt.items);
1755                         if (r < 0)
1756                                 return r;
1757                 } else {
1758                         DnsTxtItem *last = NULL;
1759 
1760                         while (p->rindex < offset + rdlength) {
1761                                 DnsTxtItem *i;
1762                                 const void *data;
1763                                 size_t sz;
1764 
1765                                 r = dns_packet_read_raw_string(p, &data, &sz, NULL);
1766                                 if (r < 0)
1767                                         return r;
1768 
1769                                 i = malloc0(offsetof(DnsTxtItem, data) + sz + 1); /* extra NUL byte at the end */
1770                                 if (!i)
1771                                         return -ENOMEM;
1772 
1773                                 memcpy(i->data, data, sz);
1774                                 i->length = sz;
1775 
1776                                 LIST_INSERT_AFTER(items, rr->txt.items, last, i);
1777                                 last = i;
1778                         }
1779                 }
1780 
1781                 r = 0;
1782                 break;
1783 
1784         case DNS_TYPE_A:
1785                 r = dns_packet_read_blob(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
1786                 break;
1787 
1788         case DNS_TYPE_AAAA:
1789                 r = dns_packet_read_blob(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
1790                 break;
1791 
1792         case DNS_TYPE_SOA:
1793                 r = dns_packet_read_name(p, &rr->soa.mname, true, NULL);
1794                 if (r < 0)
1795                         return r;
1796 
1797                 r = dns_packet_read_name(p, &rr->soa.rname, true, NULL);
1798                 if (r < 0)
1799                         return r;
1800 
1801                 r = dns_packet_read_uint32(p, &rr->soa.serial, NULL);
1802                 if (r < 0)
1803                         return r;
1804 
1805                 r = dns_packet_read_uint32(p, &rr->soa.refresh, NULL);
1806                 if (r < 0)
1807                         return r;
1808 
1809                 r = dns_packet_read_uint32(p, &rr->soa.retry, NULL);
1810                 if (r < 0)
1811                         return r;
1812 
1813                 r = dns_packet_read_uint32(p, &rr->soa.expire, NULL);
1814                 if (r < 0)
1815                         return r;
1816 
1817                 r = dns_packet_read_uint32(p, &rr->soa.minimum, NULL);
1818                 break;
1819 
1820         case DNS_TYPE_MX:
1821                 r = dns_packet_read_uint16(p, &rr->mx.priority, NULL);
1822                 if (r < 0)
1823                         return r;
1824 
1825                 r = dns_packet_read_name(p, &rr->mx.exchange, true, NULL);
1826                 break;
1827 
1828         case DNS_TYPE_LOC: {
1829                 uint8_t t;
1830                 size_t pos;
1831 
1832                 r = dns_packet_read_uint8(p, &t, &pos);
1833                 if (r < 0)
1834                         return r;
1835 
1836                 if (t == 0) {
1837                         rr->loc.version = t;
1838 
1839                         r = dns_packet_read_uint8(p, &rr->loc.size, NULL);
1840                         if (r < 0)
1841                                 return r;
1842 
1843                         if (!loc_size_ok(rr->loc.size))
1844                                 return -EBADMSG;
1845 
1846                         r = dns_packet_read_uint8(p, &rr->loc.horiz_pre, NULL);
1847                         if (r < 0)
1848                                 return r;
1849 
1850                         if (!loc_size_ok(rr->loc.horiz_pre))
1851                                 return -EBADMSG;
1852 
1853                         r = dns_packet_read_uint8(p, &rr->loc.vert_pre, NULL);
1854                         if (r < 0)
1855                                 return r;
1856 
1857                         if (!loc_size_ok(rr->loc.vert_pre))
1858                                 return -EBADMSG;
1859 
1860                         r = dns_packet_read_uint32(p, &rr->loc.latitude, NULL);
1861                         if (r < 0)
1862                                 return r;
1863 
1864                         r = dns_packet_read_uint32(p, &rr->loc.longitude, NULL);
1865                         if (r < 0)
1866                                 return r;
1867 
1868                         r = dns_packet_read_uint32(p, &rr->loc.altitude, NULL);
1869                         if (r < 0)
1870                                 return r;
1871 
1872                         break;
1873                 } else {
1874                         dns_packet_rewind(p, pos);
1875                         rr->unparsable = true;
1876                         goto unparsable;
1877                 }
1878         }
1879 
1880         case DNS_TYPE_DS:
1881                 r = dns_packet_read_uint16(p, &rr->ds.key_tag, NULL);
1882                 if (r < 0)
1883                         return r;
1884 
1885                 r = dns_packet_read_uint8(p, &rr->ds.algorithm, NULL);
1886                 if (r < 0)
1887                         return r;
1888 
1889                 r = dns_packet_read_uint8(p, &rr->ds.digest_type, NULL);
1890                 if (r < 0)
1891                         return r;
1892 
1893                 if (rdlength < 4)
1894                         return -EBADMSG;
1895 
1896                 r = dns_packet_read_memdup(p, rdlength - 4,
1897                                            &rr->ds.digest, &rr->ds.digest_size,
1898                                            NULL);
1899                 if (r < 0)
1900                         return r;
1901 
1902                 if (rr->ds.digest_size <= 0)
1903                         /* the accepted size depends on the algorithm, but for now
1904                            just ensure that the value is greater than zero */
1905                         return -EBADMSG;
1906 
1907                 break;
1908 
1909         case DNS_TYPE_SSHFP:
1910                 r = dns_packet_read_uint8(p, &rr->sshfp.algorithm, NULL);
1911                 if (r < 0)
1912                         return r;
1913 
1914                 r = dns_packet_read_uint8(p, &rr->sshfp.fptype, NULL);
1915                 if (r < 0)
1916                         return r;
1917 
1918                 if (rdlength < 2)
1919                         return -EBADMSG;
1920 
1921                 r = dns_packet_read_memdup(p, rdlength - 2,
1922                                            &rr->sshfp.fingerprint, &rr->sshfp.fingerprint_size,
1923                                            NULL);
1924 
1925                 if (rr->sshfp.fingerprint_size <= 0)
1926                         /* the accepted size depends on the algorithm, but for now
1927                            just ensure that the value is greater than zero */
1928                         return -EBADMSG;
1929 
1930                 break;
1931 
1932         case DNS_TYPE_DNSKEY:
1933                 r = dns_packet_read_uint16(p, &rr->dnskey.flags, NULL);
1934                 if (r < 0)
1935                         return r;
1936 
1937                 r = dns_packet_read_uint8(p, &rr->dnskey.protocol, NULL);
1938                 if (r < 0)
1939                         return r;
1940 
1941                 r = dns_packet_read_uint8(p, &rr->dnskey.algorithm, NULL);
1942                 if (r < 0)
1943                         return r;
1944 
1945                 if (rdlength < 4)
1946                         return -EBADMSG;
1947 
1948                 r = dns_packet_read_memdup(p, rdlength - 4,
1949                                            &rr->dnskey.key, &rr->dnskey.key_size,
1950                                            NULL);
1951 
1952                 if (rr->dnskey.key_size <= 0)
1953                         /* the accepted size depends on the algorithm, but for now
1954                            just ensure that the value is greater than zero */
1955                         return -EBADMSG;
1956 
1957                 break;
1958 
1959         case DNS_TYPE_RRSIG:
1960                 r = dns_packet_read_uint16(p, &rr->rrsig.type_covered, NULL);
1961                 if (r < 0)
1962                         return r;
1963 
1964                 r = dns_packet_read_uint8(p, &rr->rrsig.algorithm, NULL);
1965                 if (r < 0)
1966                         return r;
1967 
1968                 r = dns_packet_read_uint8(p, &rr->rrsig.labels, NULL);
1969                 if (r < 0)
1970                         return r;
1971 
1972                 r = dns_packet_read_uint32(p, &rr->rrsig.original_ttl, NULL);
1973                 if (r < 0)
1974                         return r;
1975 
1976                 r = dns_packet_read_uint32(p, &rr->rrsig.expiration, NULL);
1977                 if (r < 0)
1978                         return r;
1979 
1980                 r = dns_packet_read_uint32(p, &rr->rrsig.inception, NULL);
1981                 if (r < 0)
1982                         return r;
1983 
1984                 r = dns_packet_read_uint16(p, &rr->rrsig.key_tag, NULL);
1985                 if (r < 0)
1986                         return r;
1987 
1988                 r = dns_packet_read_name(p, &rr->rrsig.signer, false, NULL);
1989                 if (r < 0)
1990                         return r;
1991 
1992                 if (rdlength + offset < p->rindex)
1993                         return -EBADMSG;
1994 
1995                 r = dns_packet_read_memdup(p, offset + rdlength - p->rindex,
1996                                            &rr->rrsig.signature, &rr->rrsig.signature_size,
1997                                            NULL);
1998 
1999                 if (rr->rrsig.signature_size <= 0)
2000                         /* the accepted size depends on the algorithm, but for now
2001                            just ensure that the value is greater than zero */
2002                         return -EBADMSG;
2003 
2004                 break;
2005 
2006         case DNS_TYPE_NSEC: {
2007 
2008                 /*
2009                  * RFC6762, section 18.14 explicitly states mDNS should use name compression.
2010                  * This contradicts RFC3845, section 2.1.1
2011                  */
2012 
2013                 bool allow_compressed = p->protocol == DNS_PROTOCOL_MDNS;
2014 
2015                 r = dns_packet_read_name(p, &rr->nsec.next_domain_name, allow_compressed, NULL);
2016                 if (r < 0)
2017                         return r;
2018 
2019                 r = dns_packet_read_type_windows(p, &rr->nsec.types, offset + rdlength - p->rindex, NULL);
2020 
2021                 /* We accept empty NSEC bitmaps. The bit indicating the presence of the NSEC record itself
2022                  * is redundant and in e.g., RFC4956 this fact is used to define a use for NSEC records
2023                  * without the NSEC bit set. */
2024 
2025                 break;
2026         }
2027         case DNS_TYPE_NSEC3: {
2028                 uint8_t size;
2029 
2030                 r = dns_packet_read_uint8(p, &rr->nsec3.algorithm, NULL);
2031                 if (r < 0)
2032                         return r;
2033 
2034                 r = dns_packet_read_uint8(p, &rr->nsec3.flags, NULL);
2035                 if (r < 0)
2036                         return r;
2037 
2038                 r = dns_packet_read_uint16(p, &rr->nsec3.iterations, NULL);
2039                 if (r < 0)
2040                         return r;
2041 
2042                 /* this may be zero */
2043                 r = dns_packet_read_uint8(p, &size, NULL);
2044                 if (r < 0)
2045                         return r;
2046 
2047                 r = dns_packet_read_memdup(p, size, &rr->nsec3.salt, &rr->nsec3.salt_size, NULL);
2048                 if (r < 0)
2049                         return r;
2050 
2051                 r = dns_packet_read_uint8(p, &size, NULL);
2052                 if (r < 0)
2053                         return r;
2054 
2055                 if (size <= 0)
2056                         return -EBADMSG;
2057 
2058                 r = dns_packet_read_memdup(p, size,
2059                                            &rr->nsec3.next_hashed_name, &rr->nsec3.next_hashed_name_size,
2060                                            NULL);
2061                 if (r < 0)
2062                         return r;
2063 
2064                 r = dns_packet_read_type_windows(p, &rr->nsec3.types, offset + rdlength - p->rindex, NULL);
2065 
2066                 /* empty non-terminals can have NSEC3 records, so empty bitmaps are allowed */
2067 
2068                 break;
2069         }
2070 
2071         case DNS_TYPE_TLSA:
2072                 r = dns_packet_read_uint8(p, &rr->tlsa.cert_usage, NULL);
2073                 if (r < 0)
2074                         return r;
2075 
2076                 r = dns_packet_read_uint8(p, &rr->tlsa.selector, NULL);
2077                 if (r < 0)
2078                         return r;
2079 
2080                 r = dns_packet_read_uint8(p, &rr->tlsa.matching_type, NULL);
2081                 if (r < 0)
2082                         return r;
2083 
2084                 if (rdlength < 3)
2085                         return -EBADMSG;
2086 
2087                 r = dns_packet_read_memdup(p, rdlength - 3,
2088                                            &rr->tlsa.data, &rr->tlsa.data_size,
2089                                            NULL);
2090 
2091                 if (rr->tlsa.data_size <= 0)
2092                         /* the accepted size depends on the algorithm, but for now
2093                            just ensure that the value is greater than zero */
2094                         return -EBADMSG;
2095 
2096                 break;
2097 
2098         case DNS_TYPE_CAA:
2099                 r = dns_packet_read_uint8(p, &rr->caa.flags, NULL);
2100                 if (r < 0)
2101                         return r;
2102 
2103                 r = dns_packet_read_string(p, &rr->caa.tag, NULL);
2104                 if (r < 0)
2105                         return r;
2106 
2107                 if (rdlength + offset < p->rindex)
2108                         return -EBADMSG;
2109 
2110                 r = dns_packet_read_memdup(p,
2111                                            rdlength + offset - p->rindex,
2112                                            &rr->caa.value, &rr->caa.value_size, NULL);
2113 
2114                 break;
2115 
2116         case DNS_TYPE_OPT: /* we only care about the header of OPT for now. */
2117         case DNS_TYPE_OPENPGPKEY:
2118         default:
2119         unparsable:
2120                 r = dns_packet_read_memdup(p, rdlength, &rr->generic.data, &rr->generic.data_size, NULL);
2121 
2122                 break;
2123         }
2124         if (r < 0)
2125                 return r;
2126         if (p->rindex != offset + rdlength)
2127                 return -EBADMSG;
2128 
2129         if (ret)
2130                 *ret = TAKE_PTR(rr);
2131         if (ret_cache_flush)
2132                 *ret_cache_flush = cache_flush;
2133         if (ret_start)
2134                 *ret_start = rewinder.saved_rindex;
2135 
2136         CANCEL_REWINDER(rewinder);
2137         return 0;
2138 }
2139 
opt_is_good(DnsResourceRecord * rr,bool * rfc6975)2140 static bool opt_is_good(DnsResourceRecord *rr, bool *rfc6975) {
2141         const uint8_t* p;
2142         bool found_dau_dhu_n3u = false;
2143         size_t l;
2144 
2145         /* Checks whether the specified OPT RR is well-formed and whether it contains RFC6975 data (which is not OK in
2146          * a reply). */
2147 
2148         assert(rr);
2149         assert(rr->key->type == DNS_TYPE_OPT);
2150 
2151         /* Check that the version is 0 */
2152         if (((rr->ttl >> 16) & UINT32_C(0xFF)) != 0) {
2153                 *rfc6975 = false;
2154                 return true; /* if it's not version 0, it's OK, but we will ignore the OPT field contents */
2155         }
2156 
2157         p = rr->opt.data;
2158         l = rr->opt.data_size;
2159         while (l > 0) {
2160                 uint16_t option_code, option_length;
2161 
2162                 /* At least four bytes for OPTION-CODE and OPTION-LENGTH are required */
2163                 if (l < 4U)
2164                         return false;
2165 
2166                 option_code = unaligned_read_be16(p);
2167                 option_length = unaligned_read_be16(p + 2);
2168 
2169                 if (l < option_length + 4U)
2170                         return false;
2171 
2172                 /* RFC 6975 DAU, DHU or N3U fields found. */
2173                 if (IN_SET(option_code, 5, 6, 7))
2174                         found_dau_dhu_n3u = true;
2175 
2176                 p += option_length + 4U;
2177                 l -= option_length + 4U;
2178         }
2179 
2180         *rfc6975 = found_dau_dhu_n3u;
2181         return true;
2182 }
2183 
dns_packet_extract_question(DnsPacket * p,DnsQuestion ** ret_question)2184 static int dns_packet_extract_question(DnsPacket *p, DnsQuestion **ret_question) {
2185         _cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
2186         unsigned n;
2187         int r;
2188 
2189         n = DNS_PACKET_QDCOUNT(p);
2190         if (n > 0) {
2191                 question = dns_question_new(n);
2192                 if (!question)
2193                         return -ENOMEM;
2194 
2195                 _cleanup_set_free_ Set *keys = NULL; /* references to keys are kept by Question */
2196 
2197                 keys = set_new(&dns_resource_key_hash_ops);
2198                 if (!keys)
2199                         return log_oom();
2200 
2201                 r = set_reserve(keys, n * 2); /* Higher multipliers give slightly higher efficiency through
2202                                                * hash collisions, but the gains quickly drop off after 2. */
2203                 if (r < 0)
2204                         return r;
2205 
2206                 for (unsigned i = 0; i < n; i++) {
2207                         _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
2208                         bool qu;
2209 
2210                         r = dns_packet_read_key(p, &key, &qu, NULL);
2211                         if (r < 0)
2212                                 return r;
2213 
2214                         if (!dns_type_is_valid_query(key->type))
2215                                 return -EBADMSG;
2216 
2217                         r = set_put(keys, key);
2218                         if (r < 0)
2219                                 return r;
2220                         if (r == 0)
2221                                 /* Already in the Question, let's skip */
2222                                 continue;
2223 
2224                         r = dns_question_add_raw(question, key, qu ? DNS_QUESTION_WANTS_UNICAST_REPLY : 0);
2225                         if (r < 0)
2226                                 return r;
2227                 }
2228         }
2229 
2230         *ret_question = TAKE_PTR(question);
2231 
2232         return 0;
2233 }
2234 
dns_packet_extract_answer(DnsPacket * p,DnsAnswer ** ret_answer)2235 static int dns_packet_extract_answer(DnsPacket *p, DnsAnswer **ret_answer) {
2236         _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
2237         unsigned n;
2238         _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *previous = NULL;
2239         bool bad_opt = false;
2240         int r;
2241 
2242         n = DNS_PACKET_RRCOUNT(p);
2243         if (n == 0)
2244                 return 0;
2245 
2246         answer = dns_answer_new(n);
2247         if (!answer)
2248                 return -ENOMEM;
2249 
2250         for (unsigned i = 0; i < n; i++) {
2251                 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
2252                 bool cache_flush = false;
2253                 size_t start;
2254 
2255                 if (p->rindex == p->size && p->opt) {
2256                         /* If we reached the end of the packet already, but there are still more RRs
2257                          * declared, then that's a corrupt packet. Let's accept the packet anyway, since it's
2258                          * apparently a common bug in routers. Let's however suppress OPT support in this
2259                          * case, so that we force the rest of the logic into lowest DNS baseline support. Or
2260                          * to say this differently: if the DNS server doesn't even get the RR counts right,
2261                          * it's highly unlikely it gets EDNS right. */
2262                         log_debug("More resource records declared in packet than included, suppressing OPT.");
2263                         bad_opt = true;
2264                         break;
2265                 }
2266 
2267                 r = dns_packet_read_rr(p, &rr, &cache_flush, &start);
2268                 if (r < 0)
2269                         return r;
2270 
2271                 /* Try to reduce memory usage a bit */
2272                 if (previous)
2273                         dns_resource_key_reduce(&rr->key, &previous->key);
2274 
2275                 if (rr->key->type == DNS_TYPE_OPT) {
2276                         bool has_rfc6975;
2277 
2278                         if (p->opt || bad_opt) {
2279                                 /* Multiple OPT RRs? if so, let's ignore all, because there's
2280                                  * something wrong with the server, and if one is valid we wouldn't
2281                                  * know which one. */
2282                                 log_debug("Multiple OPT RRs detected, ignoring all.");
2283                                 bad_opt = true;
2284                                 continue;
2285                         }
2286 
2287                         if (!dns_name_is_root(dns_resource_key_name(rr->key))) {
2288                                 /* If the OPT RR is not owned by the root domain, then it is bad,
2289                                  * let's ignore it. */
2290                                 log_debug("OPT RR is not owned by root domain, ignoring.");
2291                                 bad_opt = true;
2292                                 continue;
2293                         }
2294 
2295                         if (i < DNS_PACKET_ANCOUNT(p) + DNS_PACKET_NSCOUNT(p)) {
2296                                 /* OPT RR is in the wrong section? Some Belkin routers do this. This
2297                                  * is a hint the EDNS implementation is borked, like the Belkin one
2298                                  * is, hence ignore it. */
2299                                 log_debug("OPT RR in wrong section, ignoring.");
2300                                 bad_opt = true;
2301                                 continue;
2302                         }
2303 
2304                         if (!opt_is_good(rr, &has_rfc6975)) {
2305                                 log_debug("Malformed OPT RR, ignoring.");
2306                                 bad_opt = true;
2307                                 continue;
2308                         }
2309 
2310                         if (DNS_PACKET_QR(p)) {
2311                                 /* Additional checks for responses */
2312 
2313                                 if (!DNS_RESOURCE_RECORD_OPT_VERSION_SUPPORTED(rr))
2314                                         /* If this is a reply and we don't know the EDNS version
2315                                          * then something is weird... */
2316                                         return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2317                                                                "EDNS version newer that our request, bad server.");
2318 
2319                                 if (has_rfc6975) {
2320                                         /* If the OPT RR contains RFC6975 algorithm data, then this
2321                                          * is indication that the server just copied the OPT it got
2322                                          * from us (which contained that data) back into the reply.
2323                                          * If so, then it doesn't properly support EDNS, as RFC6975
2324                                          * makes it very clear that the algorithm data should only
2325                                          * be contained in questions, never in replies. Crappy
2326                                          * Belkin routers copy the OPT data for example, hence let's
2327                                          * detect this so that we downgrade early. */
2328                                         log_debug("OPT RR contains RFC6975 data, ignoring.");
2329                                         bad_opt = true;
2330                                         continue;
2331                                 }
2332                         }
2333 
2334                         p->opt = dns_resource_record_ref(rr);
2335                         p->opt_start = start;
2336                         assert(p->rindex >= start);
2337                         p->opt_size = p->rindex - start;
2338                 } else {
2339                         DnsAnswerFlags flags = 0;
2340 
2341                         if (p->protocol == DNS_PROTOCOL_MDNS && !cache_flush)
2342                                 flags |= DNS_ANSWER_SHARED_OWNER;
2343 
2344                         /* According to RFC 4795, section 2.9. only the RRs from the Answer section shall be
2345                          * cached. Hence mark only those RRs as cacheable by default, but not the ones from
2346                          * the Additional or Authority sections. */
2347                         if (i < DNS_PACKET_ANCOUNT(p))
2348                                 flags |= DNS_ANSWER_CACHEABLE|DNS_ANSWER_SECTION_ANSWER;
2349                         else if (i < DNS_PACKET_ANCOUNT(p) + DNS_PACKET_NSCOUNT(p))
2350                                 flags |= DNS_ANSWER_SECTION_AUTHORITY;
2351                         else
2352                                 flags |= DNS_ANSWER_SECTION_ADDITIONAL;
2353 
2354                         r = dns_answer_add(answer, rr, p->ifindex, flags, NULL);
2355                         if (r < 0)
2356                                 return r;
2357                 }
2358 
2359                 /* Remember this RR, so that we can potentially merge its ->key object with the
2360                  * next RR. Note that we only do this if we actually decided to keep the RR around.
2361                  */
2362                 DNS_RR_REPLACE(previous, dns_resource_record_ref(rr));
2363         }
2364 
2365         if (bad_opt) {
2366                 p->opt = dns_resource_record_unref(p->opt);
2367                 p->opt_start = p->opt_size = SIZE_MAX;
2368         }
2369 
2370         *ret_answer = TAKE_PTR(answer);
2371 
2372         return 0;
2373 }
2374 
dns_packet_extract(DnsPacket * p)2375 int dns_packet_extract(DnsPacket *p) {
2376         assert(p);
2377 
2378         if (p->extracted)
2379                 return 0;
2380 
2381         _cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
2382         _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
2383         _unused_ _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
2384         int r;
2385 
2386         dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
2387 
2388         r = dns_packet_extract_question(p, &question);
2389         if (r < 0)
2390                 return r;
2391 
2392         r = dns_packet_extract_answer(p, &answer);
2393         if (r < 0)
2394                 return r;
2395 
2396         if (p->rindex < p->size)  {
2397                 log_debug("Trailing garbage in packet, suppressing OPT.");
2398                 p->opt = dns_resource_record_unref(p->opt);
2399                 p->opt_start = p->opt_size = SIZE_MAX;
2400         }
2401 
2402         p->question = TAKE_PTR(question);
2403         p->answer = TAKE_PTR(answer);
2404         p->extracted = true;
2405 
2406         /* no CANCEL, always rewind */
2407         return 0;
2408 }
2409 
dns_packet_is_reply_for(DnsPacket * p,const DnsResourceKey * key)2410 int dns_packet_is_reply_for(DnsPacket *p, const DnsResourceKey *key) {
2411         int r;
2412 
2413         assert(p);
2414         assert(key);
2415 
2416         /* Checks if the specified packet is a reply for the specified
2417          * key and the specified key is the only one in the question
2418          * section. */
2419 
2420         if (DNS_PACKET_QR(p) != 1)
2421                 return 0;
2422 
2423         /* Let's unpack the packet, if that hasn't happened yet. */
2424         r = dns_packet_extract(p);
2425         if (r < 0)
2426                 return r;
2427 
2428         if (!p->question)
2429                 return 0;
2430 
2431         if (p->question->n_keys != 1)
2432                 return 0;
2433 
2434         return dns_resource_key_equal(dns_question_first_key(p->question), key);
2435 }
2436 
dns_packet_patch_max_udp_size(DnsPacket * p,uint16_t max_udp_size)2437 int dns_packet_patch_max_udp_size(DnsPacket *p, uint16_t max_udp_size) {
2438         assert(p);
2439         assert(max_udp_size >= DNS_PACKET_UNICAST_SIZE_MAX);
2440 
2441         if (p->opt_start == SIZE_MAX) /* No OPT section, nothing to patch */
2442                 return 0;
2443 
2444         assert(p->opt_size != SIZE_MAX);
2445         assert(p->opt_size >= 5);
2446 
2447         unaligned_write_be16(DNS_PACKET_DATA(p) + p->opt_start + 3, max_udp_size);
2448         return 1;
2449 }
2450 
patch_rr(DnsPacket * p,usec_t age)2451 static int patch_rr(DnsPacket *p, usec_t age) {
2452         _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
2453         size_t ttl_index;
2454         uint32_t ttl;
2455         uint16_t type, rdlength;
2456         int r;
2457 
2458         /* Patches the RR at the current rindex, subtracts the specified time from the TTL */
2459 
2460         r = dns_packet_read_name(p, NULL, true, NULL);
2461         if (r < 0)
2462                 return r;
2463 
2464         r = dns_packet_read_uint16(p, &type, NULL);
2465         if (r < 0)
2466                 return r;
2467 
2468         r = dns_packet_read_uint16(p, NULL, NULL);
2469         if (r < 0)
2470                 return r;
2471 
2472         r = dns_packet_read_uint32(p, &ttl, &ttl_index);
2473         if (r < 0)
2474                 return r;
2475 
2476         if (type != DNS_TYPE_OPT) { /* The TTL of the OPT field is not actually a TTL, skip it */
2477                 ttl = LESS_BY(ttl * USEC_PER_SEC, age) / USEC_PER_SEC;
2478                 unaligned_write_be32(DNS_PACKET_DATA(p) + ttl_index, ttl);
2479         }
2480 
2481         r = dns_packet_read_uint16(p, &rdlength, NULL);
2482         if (r < 0)
2483                 return r;
2484 
2485         r = dns_packet_read(p, rdlength, NULL, NULL);
2486         if (r < 0)
2487                 return r;
2488 
2489         CANCEL_REWINDER(rewinder);
2490         return 0;
2491 }
2492 
dns_packet_patch_ttls(DnsPacket * p,usec_t timestamp)2493 int dns_packet_patch_ttls(DnsPacket *p, usec_t timestamp) {
2494         assert(p);
2495         assert(timestamp_is_set(timestamp));
2496 
2497         /* Adjusts all TTLs in the packet by subtracting the time difference between now and the specified timestamp */
2498 
2499         _unused_ _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
2500         unsigned n;
2501         usec_t k;
2502         int r;
2503 
2504         k = now(CLOCK_BOOTTIME);
2505         assert(k >= timestamp);
2506         k -= timestamp;
2507 
2508         dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
2509 
2510         n = DNS_PACKET_QDCOUNT(p);
2511         for (unsigned i = 0; i < n; i++) {
2512                 r = dns_packet_read_key(p, NULL, NULL, NULL);
2513                 if (r < 0)
2514                         return r;
2515         }
2516 
2517         n = DNS_PACKET_RRCOUNT(p);
2518         for (unsigned i = 0; i < n; i++) {
2519 
2520                 /* DNS servers suck, hence the RR count is in many servers off. If we reached the end
2521                  * prematurely, accept that, exit early */
2522                 if (p->rindex == p->size)
2523                         break;
2524 
2525                 r = patch_rr(p, k);
2526                 if (r < 0)
2527                         return r;
2528         }
2529 
2530         return 0;
2531 }
2532 
dns_packet_hash_func(const DnsPacket * s,struct siphash * state)2533 static void dns_packet_hash_func(const DnsPacket *s, struct siphash *state) {
2534         assert(s);
2535 
2536         siphash24_compress(&s->size, sizeof(s->size), state);
2537         siphash24_compress(DNS_PACKET_DATA((DnsPacket*) s), s->size, state);
2538 }
2539 
dns_packet_compare_func(const DnsPacket * x,const DnsPacket * y)2540 static int dns_packet_compare_func(const DnsPacket *x, const DnsPacket *y) {
2541         int r;
2542 
2543         r = CMP(x->size, y->size);
2544         if (r != 0)
2545                 return r;
2546 
2547         return memcmp(DNS_PACKET_DATA((DnsPacket*) x), DNS_PACKET_DATA((DnsPacket*) y), x->size);
2548 }
2549 
2550 DEFINE_HASH_OPS(dns_packet_hash_ops, DnsPacket, dns_packet_hash_func, dns_packet_compare_func);
2551 
dns_packet_equal(const DnsPacket * a,const DnsPacket * b)2552 bool dns_packet_equal(const DnsPacket *a, const DnsPacket *b) {
2553         return dns_packet_compare_func(a, b) == 0;
2554 }
2555 
dns_packet_has_nsid_request(DnsPacket * p)2556 int dns_packet_has_nsid_request(DnsPacket *p) {
2557         bool has_nsid = false;
2558         const uint8_t *d;
2559         size_t l;
2560 
2561         assert(p);
2562 
2563         if (!p->opt)
2564                 return false;
2565 
2566         d = p->opt->opt.data;
2567         l = p->opt->opt.data_size;
2568 
2569         while (l > 0) {
2570                 uint16_t code, length;
2571 
2572                 if (l < 4U)
2573                         return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2574                                                "EDNS0 variable part has invalid size.");
2575 
2576                 code = unaligned_read_be16(d);
2577                 length = unaligned_read_be16(d + 2);
2578 
2579                 if (l < 4U + length)
2580                         return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2581                                                "Truncated option in EDNS0 variable part.");
2582 
2583                 if (code == 3) {
2584                         if (has_nsid)
2585                                 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2586                                                        "Duplicate NSID option in EDNS0 variable part.");
2587 
2588                         if (length != 0)
2589                                 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2590                                                        "Non-empty NSID option in DNS request.");
2591 
2592                         has_nsid = true;
2593                 }
2594 
2595                 d += 4U + length;
2596                 l -= 4U + length;
2597         }
2598 
2599         return has_nsid;
2600 }
2601 
dns_packet_size_unfragmented(DnsPacket * p)2602 size_t dns_packet_size_unfragmented(DnsPacket *p) {
2603         assert(p);
2604 
2605         if (p->fragsize == 0) /* Wasn't fragmented */
2606                 return p->size;
2607 
2608         /* The fragment size (p->fragsize) covers the whole (fragmented) IP packet, while the regular packet
2609          * size (p->size) only covers the DNS part. Thus, subtract the UDP header from the largest fragment
2610          * size, in order to determine which size of DNS packet would have gone through without
2611          * fragmenting. */
2612 
2613         return LESS_BY(p->fragsize, udp_header_size(p->family));
2614 }
2615 
2616 static const char* const dns_rcode_table[_DNS_RCODE_MAX_DEFINED] = {
2617         [DNS_RCODE_SUCCESS]   = "SUCCESS",
2618         [DNS_RCODE_FORMERR]   = "FORMERR",
2619         [DNS_RCODE_SERVFAIL]  = "SERVFAIL",
2620         [DNS_RCODE_NXDOMAIN]  = "NXDOMAIN",
2621         [DNS_RCODE_NOTIMP]    = "NOTIMP",
2622         [DNS_RCODE_REFUSED]   = "REFUSED",
2623         [DNS_RCODE_YXDOMAIN]  = "YXDOMAIN",
2624         [DNS_RCODE_YXRRSET]   = "YRRSET",
2625         [DNS_RCODE_NXRRSET]   = "NXRRSET",
2626         [DNS_RCODE_NOTAUTH]   = "NOTAUTH",
2627         [DNS_RCODE_NOTZONE]   = "NOTZONE",
2628         [DNS_RCODE_BADVERS]   = "BADVERS",
2629         [DNS_RCODE_BADKEY]    = "BADKEY",
2630         [DNS_RCODE_BADTIME]   = "BADTIME",
2631         [DNS_RCODE_BADMODE]   = "BADMODE",
2632         [DNS_RCODE_BADNAME]   = "BADNAME",
2633         [DNS_RCODE_BADALG]    = "BADALG",
2634         [DNS_RCODE_BADTRUNC]  = "BADTRUNC",
2635         [DNS_RCODE_BADCOOKIE] = "BADCOOKIE",
2636 };
2637 DEFINE_STRING_TABLE_LOOKUP(dns_rcode, int);
2638 
2639 static const char* const dns_protocol_table[_DNS_PROTOCOL_MAX] = {
2640         [DNS_PROTOCOL_DNS]   = "dns",
2641         [DNS_PROTOCOL_MDNS]  = "mdns",
2642         [DNS_PROTOCOL_LLMNR] = "llmnr",
2643 };
2644 DEFINE_STRING_TABLE_LOOKUP(dns_protocol, DnsProtocol);
2645