Debian Codegraph @

src/resolve/resolved-dns-transaction.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-event.h"
4 #include "sd-messages.h"
5
6 #include "af-list.h"
7 #include "alloc-util.h"
8 #include "dns-answer.h"
9 #include "dns-domain.h"
10 #include "dns-packet.h"
11 #include "dns-question.h"
12 #include "dns-rr.h"
13 #include "errno-list.h"
14 #include "errno-util.h"
15 #include "fd-util.h"
16 #include "glyph-util.h"
17 #include "log.h"
18 #include "random-util.h"
19 #include "resolved-dns-cache.h"
20 #include "resolved-dns-query.h"
21 #include "resolved-dns-scope.h"
22 #include "resolved-dns-server.h"
23 #include "resolved-dns-stream.h"
24 #include "resolved-dns-transaction.h"
25 #include "resolved-dnstls.h"
26 #include "resolved-link.h"
27 #include "resolved-llmnr.h"
28 #include "resolved-manager.h"
29 #include "resolved-socket-graveyard.h"
30 #include "resolved-timeouts.h"
31 #include "set.h"
32 #include "string-table.h"
33 #include "string-util.h"
34
35 #define TRANSACTIONS_MAX 4096
36
37 static void dns_transaction_reset_answer(DnsTransaction *t) {
38 assert(t);
39
40 t->received = dns_packet_unref(t->received);
41 t->answer = dns_answer_unref(t->answer);
42 t->answer_rcode = 0;
43 t->answer_ede_rcode = _DNS_EDE_RCODE_INVALID;
44 t->answer_ede_msg = mfree(t->answer_ede_msg);
45 t->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
46 t->answer_source = _DNS_TRANSACTION_SOURCE_INVALID;
47 t->answer_query_flags = 0;
48 t->answer_nsec_ttl = UINT32_MAX;
49 t->answer_errno = 0;
50 }
51
52 static void dns_transaction_flush_dnssec_transactions(DnsTransaction *t) {
53 DnsTransaction *z;
54
55 assert(t);
56
57 while ((z = set_steal_first(t->dnssec_transactions))) {
58 set_remove(z->notify_transactions, t);
59 set_remove(z->notify_transactions_done, t);
60 dns_transaction_gc(z);
61 }
62 }
63
64 static void dns_transaction_close_connection(
65 DnsTransaction *t,
66 bool use_graveyard) { /* Set use_graveyard = false when you know the connection is already
67 * dead, for example because you got a connection error back from the
68 * kernel. In that case there's no point in keeping the fd around,
69 * hence don't. */
70 int r;
71
72 assert(t);
73
74 if (t->stream) {
75 /* Let's detach the stream from our transaction, in case something else keeps a reference to it. */
76 LIST_REMOVE(transactions_by_stream, t->stream->transactions, t);
77
78 /* Remove packet in case it's still in the queue */
79 dns_packet_unref(ordered_set_remove(t->stream->write_queue, t->sent));
80
81 t->stream = dns_stream_unref(t->stream);
82 }
83
84 t->dns_udp_event_source = sd_event_source_disable_unref(t->dns_udp_event_source);
85
86 /* If we have a UDP socket where we sent a packet, but never received one, then add it to the socket
87 * graveyard, instead of closing it right away. That way it will stick around for a moment longer,
88 * and the reply we might still get from the server will be eaten up instead of resulting in an ICMP
89 * port unreachable error message. */
90
91 /* Skip the graveyard stuff when we're shutting down, since that requires running event loop.
92 * Note that this is also called from dns_transaction_free(). In that case, scope may be NULL. */
93 if (!t->scope ||
94 !t->scope->manager ||
95 !t->scope->manager->event ||
96 sd_event_get_state(t->scope->manager->event) == SD_EVENT_FINISHED)
97 use_graveyard = false;
98
99 if (use_graveyard && t->dns_udp_fd >= 0 && t->sent && !t->received) {
100 r = manager_add_socket_to_graveyard(t->scope->manager, t->dns_udp_fd);
101 if (r < 0)
102 log_debug_errno(r, "Failed to add UDP socket to graveyard, closing immediately: %m");
103 else
104 TAKE_FD(t->dns_udp_fd);
105 }
106
107 t->dns_udp_fd = safe_close(t->dns_udp_fd);
108 }
109
110 static void dns_transaction_stop_timeout(DnsTransaction *t) {
111 assert(t);
112
113 t->timeout_event_source = sd_event_source_disable_unref(t->timeout_event_source);
114 }
115
116 DnsTransaction* dns_transaction_free(DnsTransaction *t) {
117 DnsQueryCandidate *c;
118 DnsZoneItem *i;
119 DnsTransaction *z;
120
121 if (!t)
122 return NULL;
123
124 log_debug("Freeing transaction %" PRIu16 ".", t->id);
125
126 dns_transaction_close_connection(t, true);
127 dns_transaction_stop_timeout(t);
128
129 dns_packet_unref(t->sent);
130 dns_transaction_reset_answer(t);
131
132 dns_server_unref(t->server);
133
134 if (t->scope) {
135 if (t->key) {
136 DnsTransaction *first;
137
138 first = hashmap_get(t->scope->transactions_by_key, t->key);
139 LIST_REMOVE(transactions_by_key, first, t);
140 if (first)
141 hashmap_replace(t->scope->transactions_by_key, first->key, first);
142 else
143 hashmap_remove(t->scope->transactions_by_key, t->key);
144 }
145
146 LIST_REMOVE(transactions_by_scope, t->scope->transactions, t);
147
148 if (t->id != 0)
149 hashmap_remove(t->scope->manager->dns_transactions, UINT_TO_PTR(t->id));
150 }
151
152 while ((c = set_steal_first(t->notify_query_candidates)))
153 set_remove(c->transactions, t);
154 set_free(t->notify_query_candidates);
155
156 while ((c = set_steal_first(t->notify_query_candidates_done)))
157 set_remove(c->transactions, t);
158 set_free(t->notify_query_candidates_done);
159
160 while ((i = set_steal_first(t->notify_zone_items)))
161 i->probe_transaction = NULL;
162 set_free(t->notify_zone_items);
163
164 while ((i = set_steal_first(t->notify_zone_items_done)))
165 i->probe_transaction = NULL;
166 set_free(t->notify_zone_items_done);
167
168 while ((z = set_steal_first(t->notify_transactions)))
169 set_remove(z->dnssec_transactions, t);
170 set_free(t->notify_transactions);
171
172 while ((z = set_steal_first(t->notify_transactions_done)))
173 set_remove(z->dnssec_transactions, t);
174 set_free(t->notify_transactions_done);
175
176 dns_transaction_flush_dnssec_transactions(t);
177 set_free(t->dnssec_transactions);
178
179 dns_answer_unref(t->validated_keys);
180 dns_resource_key_unref(t->key);
181 dns_packet_unref(t->bypass);
182
183 return mfree(t);
184 }
185
186 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsTransaction*, dns_transaction_free);
187
188 DnsTransaction* dns_transaction_gc(DnsTransaction *t) {
189 assert(t);
190
191 /* Returns !NULL if we can't gc yet. */
192
193 if (t->block_gc > 0)
194 return t;
195
196 if (t->wait_for_answer && IN_SET(t->state, DNS_TRANSACTION_PENDING, DNS_TRANSACTION_VALIDATING))
197 return t;
198
199 if (set_isempty(t->notify_query_candidates) &&
200 set_isempty(t->notify_query_candidates_done) &&
201 set_isempty(t->notify_zone_items) &&
202 set_isempty(t->notify_zone_items_done) &&
203 set_isempty(t->notify_transactions) &&
204 set_isempty(t->notify_transactions_done))
205 return dns_transaction_free(t);
206
207 return t;
208 }
209
210 static uint16_t pick_new_id(Manager *m) {
211 uint16_t new_id;
212
213 /* Find a fresh, unused transaction id. Note that this loop is bounded because there's a limit on the
214 * number of transactions, and it's much lower than the space of IDs. */
215
216 assert_cc(TRANSACTIONS_MAX < 0xFFFF);
217
218 do
219 random_bytes(&new_id, sizeof(new_id));
220 while (new_id == 0 ||
221 hashmap_get(m->dns_transactions, UINT_TO_PTR(new_id)));
222
223 return new_id;
224 }
225
226 static int key_ok(
227 DnsScope *scope,
228 DnsResourceKey *key) {
229
230 /* Don't allow looking up invalid or pseudo RRs */
231 if (!dns_type_is_valid_query(key->type))
232 return -EINVAL;
233 if (dns_type_is_obsolete(key->type))
234 return -EOPNOTSUPP;
235
236 /* We only support the IN class */
237 if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
238 return -EOPNOTSUPP;
239
240 /* Don't allows DNSSEC RRs to be looked up via LLMNR/mDNS. They don't really make sense
241 * there, and it speeds up our queries if we refuse this early */
242 if (scope->protocol != DNS_PROTOCOL_DNS &&
243 dns_type_is_dnssec(key->type))
244 return -EOPNOTSUPP;
245
246 return 0;
247 }
248
249 int dns_transaction_new(
250 DnsTransaction **ret,
251 DnsScope *s,
252 DnsResourceKey *key,
253 DnsPacket *bypass,
254 uint64_t query_flags) {
255
256 _cleanup_(dns_transaction_freep) DnsTransaction *t = NULL;
257 int r;
258
259 assert(ret);
260 assert(s);
261
262 if (key) {
263 assert(!bypass);
264
265 r = key_ok(s, key);
266 if (r < 0)
267 return r;
268 } else {
269 DnsResourceKey *qk;
270 assert(bypass);
271
272 r = dns_packet_validate_query(bypass);
273 if (r < 0)
274 return r;
275
276 DNS_QUESTION_FOREACH(qk, bypass->question) {
277 r = key_ok(s, qk);
278 if (r < 0)
279 return r;
280 }
281 }
282
283 if (hashmap_size(s->manager->dns_transactions) >= TRANSACTIONS_MAX)
284 return -EBUSY;
285
286 r = hashmap_ensure_allocated(&s->manager->dns_transactions, NULL);
287 if (r < 0)
288 return r;
289
290 if (key) {
291 r = hashmap_ensure_allocated(&s->transactions_by_key, &dns_resource_key_hash_ops);
292 if (r < 0)
293 return r;
294 }
295
296 t = new(DnsTransaction, 1);
297 if (!t)
298 return -ENOMEM;
299
300 *t = (DnsTransaction) {
301 .dns_udp_fd = -EBADF,
302 .answer_source = _DNS_TRANSACTION_SOURCE_INVALID,
303 .answer_dnssec_result = _DNSSEC_RESULT_INVALID,
304 .answer_ede_rcode = _DNS_EDE_RCODE_INVALID,
305 .answer_nsec_ttl = UINT32_MAX,
306 .key = dns_resource_key_ref(key),
307 .query_flags = query_flags,
308 .bypass = dns_packet_ref(bypass),
309 .current_feature_level = _DNS_SERVER_FEATURE_LEVEL_INVALID,
310 .clamp_feature_level_servfail = _DNS_SERVER_FEATURE_LEVEL_INVALID,
311 .id = pick_new_id(s->manager),
312 };
313
314 r = hashmap_put(s->manager->dns_transactions, UINT_TO_PTR(t->id), t);
315 if (r < 0) {
316 t->id = 0;
317 return r;
318 }
319
320 if (t->key) {
321 DnsTransaction *first;
322
323 first = hashmap_get(s->transactions_by_key, t->key);
324 LIST_PREPEND(transactions_by_key, first, t);
325
326 r = hashmap_replace(s->transactions_by_key, first->key, first);
327 if (r < 0) {
328 LIST_REMOVE(transactions_by_key, first, t);
329 return r;
330 }
331 }
332
333 LIST_PREPEND(transactions_by_scope, s->transactions, t);
334 t->scope = s;
335
336 s->manager->n_transactions_total++;
337
338 if (ret)
339 *ret = t;
340
341 TAKE_PTR(t);
342 return 0;
343 }
344
345 static void dns_transaction_shuffle_id(DnsTransaction *t) {
346 uint16_t new_id;
347 assert(t);
348
349 /* Pick a new ID for this transaction. */
350
351 new_id = pick_new_id(t->scope->manager);
352 assert_se(hashmap_remove_and_put(t->scope->manager->dns_transactions, UINT_TO_PTR(t->id), UINT_TO_PTR(new_id), t) >= 0);
353
354 log_debug("Transaction %" PRIu16 " is now %" PRIu16 ".", t->id, new_id);
355 t->id = new_id;
356
357 /* Make sure we generate a new packet with the new ID */
358 t->sent = dns_packet_unref(t->sent);
359 }
360
361 static void dns_transaction_tentative(DnsTransaction *t, DnsPacket *p) {
362 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
363 DnsZoneItem *z;
364
365 assert(t);
366 assert(p);
367 assert(t->scope->protocol == DNS_PROTOCOL_LLMNR);
368
369 if (manager_packet_from_local_address(t->scope->manager, p) != 0)
370 return;
371
372 log_debug("Transaction %" PRIu16 " for <%s> on scope %s on %s/%s got tentative packet from %s.",
373 t->id,
374 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str),
375 dns_protocol_to_string(t->scope->protocol),
376 t->scope->link ? t->scope->link->ifname : "*",
377 af_to_name_short(t->scope->family),
378 IN_ADDR_TO_STRING(p->family, &p->sender));
379
380 /* RFC 4795, Section 4.1 says that the peer with the
381 * lexicographically smaller IP address loses */
382 if (memcmp(&p->sender, &p->destination, FAMILY_ADDRESS_SIZE(p->family)) >= 0) {
383 log_debug("Peer has lexicographically larger IP address and thus lost in the conflict.");
384 return;
385 }
386
387 log_debug("We have the lexicographically larger IP address and thus lost in the conflict.");
388
389 t->block_gc++;
390
391 while ((z = set_first(t->notify_zone_items))) {
392 /* First, make sure the zone item drops the reference
393 * to us */
394 dns_zone_item_probe_stop(z);
395
396 /* Secondly, report this as conflict, so that we might
397 * look for a different hostname */
398 dns_zone_item_conflict(z);
399 }
400 t->block_gc--;
401
402 dns_transaction_gc(t);
403 }
404
405 void dns_transaction_complete(DnsTransaction *t, DnsTransactionState state) {
406 DnsQueryCandidate *c;
407 DnsZoneItem *z;
408 DnsTransaction *d;
409 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
410
411 assert(t);
412 assert(!DNS_TRANSACTION_IS_LIVE(state));
413
414 if (state == DNS_TRANSACTION_DNSSEC_FAILED) {
415 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str);
416
417 log_struct(LOG_NOTICE,
418 LOG_MESSAGE_ID(SD_MESSAGE_DNSSEC_FAILURE_STR),
419 LOG_MESSAGE("DNSSEC validation failed for question %s: %s",
420 key_str, dnssec_result_to_string(t->answer_dnssec_result)),
421 LOG_ITEM("DNS_TRANSACTION=%" PRIu16, t->id),
422 LOG_ITEM("DNS_QUESTION=%s", key_str),
423 LOG_ITEM("DNSSEC_RESULT=%s", dnssec_result_to_string(t->answer_dnssec_result)),
424 LOG_ITEM("DNS_SERVER=%s", strna(dns_server_string_full(t->server))),
425 LOG_ITEM("DNS_SERVER_FEATURE_LEVEL=%s", dns_server_feature_level_to_string(t->server->possible_feature_level)));
426 }
427
428 /* Note that this call might invalidate the query. Callers
429 * should hence not attempt to access the query or transaction
430 * after calling this function. */
431
432 log_debug("%s transaction %" PRIu16 " for <%s> on scope %s on %s/%s now complete with <%s> from %s (%s; %s).",
433 t->bypass ? "Bypass" : "Regular",
434 t->id,
435 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str),
436 dns_protocol_to_string(t->scope->protocol),
437 t->scope->link ? t->scope->link->ifname : "*",
438 af_to_name_short(t->scope->family),
439 state == DNS_TRANSACTION_ERRNO ? ERRNO_NAME(t->answer_errno) : dns_transaction_state_to_string(state),
440 t->answer_source < 0 ? "none" : dns_transaction_source_to_string(t->answer_source),
441 FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) ? "not validated" :
442 (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED) ? "authenticated" : "unsigned"),
443 FLAGS_SET(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL) ? "confidential" : "non-confidential");
444
445 t->state = state;
446
447 dns_transaction_close_connection(t, true);
448 dns_transaction_stop_timeout(t);
449
450 /* Notify all queries that are interested, but make sure the
451 * transaction isn't freed while we are still looking at it */
452 t->block_gc++;
453
454 SET_FOREACH_MOVE(c, t->notify_query_candidates_done, t->notify_query_candidates)
455 dns_query_candidate_notify(c);
456 SWAP_TWO(t->notify_query_candidates, t->notify_query_candidates_done);
457
458 SET_FOREACH_MOVE(z, t->notify_zone_items_done, t->notify_zone_items)
459 dns_zone_item_notify(z);
460 SWAP_TWO(t->notify_zone_items, t->notify_zone_items_done);
461 if (t->probing && t->state == DNS_TRANSACTION_ATTEMPTS_MAX_REACHED)
462 (void) dns_scope_announce(t->scope, false);
463
464 SET_FOREACH_MOVE(d, t->notify_transactions_done, t->notify_transactions)
465 dns_transaction_notify(d, t);
466 SWAP_TWO(t->notify_transactions, t->notify_transactions_done);
467
468 t->block_gc--;
469 dns_transaction_gc(t);
470 }
471
472 static void dns_transaction_complete_errno(DnsTransaction *t, int error) {
473 assert(t);
474 assert(error != 0);
475
476 t->answer_errno = ABS(error);
477 dns_transaction_complete(t, DNS_TRANSACTION_ERRNO);
478 }
479
480 static int dns_transaction_pick_server(DnsTransaction *t) {
481 DnsServer *server;
482
483 assert(t);
484 assert(t->scope->protocol == DNS_PROTOCOL_DNS);
485
486 /* Pick a DNS server and a feature level for it. */
487
488 server = dns_scope_get_dns_server(t->scope);
489 if (!server)
490 return -ESRCH;
491
492 /* If we changed the server invalidate the feature level clamping, as the new server might have completely
493 * different properties. */
494 if (server != t->server)
495 t->clamp_feature_level_servfail = _DNS_SERVER_FEATURE_LEVEL_INVALID;
496
497 t->current_feature_level = dns_server_possible_feature_level(server);
498
499 /* Clamp the feature level if that is requested. */
500 if (t->clamp_feature_level_servfail != _DNS_SERVER_FEATURE_LEVEL_INVALID &&
501 t->current_feature_level > t->clamp_feature_level_servfail)
502 t->current_feature_level = t->clamp_feature_level_servfail;
503
504 log_debug("Using feature level %s for transaction %u.", dns_server_feature_level_to_string(t->current_feature_level), t->id);
505
506 if (server == t->server)
507 return 0;
508
509 dns_server_unref(t->server);
510 t->server = dns_server_ref(server);
511
512 t->n_picked_servers++;
513
514 log_debug("Using DNS server %s for transaction %u.", strna(dns_server_string_full(t->server)), t->id);
515
516 return 1;
517 }
518
519 static void dns_transaction_retry(DnsTransaction *t, bool next_server) {
520 int r;
521
522 assert(t);
523
524 /* Retries the transaction as it is, possibly on a different server */
525
526 if (next_server && t->scope->protocol == DNS_PROTOCOL_DNS)
527 log_debug("Retrying transaction %" PRIu16 ", after switching servers.", t->id);
528 else
529 log_debug("Retrying transaction %" PRIu16 ".", t->id);
530
531 /* Before we try again, switch to a new server. */
532 if (next_server)
533 dns_scope_next_dns_server(t->scope, t->server);
534
535 r = dns_transaction_go(t);
536 if (r < 0)
537 dns_transaction_complete_errno(t, r);
538 }
539
540 static bool dns_transaction_limited_retry(DnsTransaction *t) {
541 assert(t);
542
543 /* If we haven't tried all different servers yet, let's try again with a different server */
544
545 if (t->n_picked_servers >= dns_scope_get_n_dns_servers(t->scope))
546 return false;
547
548 dns_transaction_retry(t, /* next_server= */ true);
549 return true;
550 }
551
552 static int dns_transaction_maybe_restart(DnsTransaction *t) {
553 int r;
554
555 assert(t);
556
557 /* Restarts the transaction, under a new ID if the feature level of the server changed since we first
558 * tried, without changing DNS server. Returns > 0 if the transaction was restarted, 0 if not. */
559
560 if (!t->server)
561 return 0;
562
563 if (t->current_feature_level <= dns_server_possible_feature_level(t->server))
564 return 0;
565
566 /* The server's current feature level is lower than when we sent the original query. We learnt something from
567 the response or possibly an auxiliary DNSSEC response that we didn't know before. We take that as reason to
568 restart the whole transaction. This is a good idea to deal with servers that respond rubbish if we include
569 OPT RR or DO bit. One of these cases is documented here, for example:
570 https://open.nlnetlabs.nl/pipermail/dnssec-trigger/2014-November/000376.html */
571
572 log_debug("Server feature level is now lower than when we began our transaction. Restarting with new ID.");
573 dns_transaction_shuffle_id(t);
574
575 r = dns_transaction_go(t);
576 if (r < 0)
577 return r;
578
579 return 1;
580 }
581
582 static void on_transaction_stream_error(DnsTransaction *t, int error) {
583 assert(t);
584
585 dns_transaction_close_connection(t, true);
586
587 if (ERRNO_IS_DISCONNECT(error)) {
588 if (t->scope->protocol == DNS_PROTOCOL_LLMNR) {
589 /* If the LLMNR/TCP connection failed, the host doesn't support LLMNR, and we cannot answer the
590 * question on this scope. */
591 dns_transaction_complete(t, DNS_TRANSACTION_NOT_FOUND);
592 return;
593 }
594
595 dns_transaction_retry(t, true);
596 return;
597 }
598 if (error != 0)
599 dns_transaction_complete_errno(t, error);
600 }
601
602 static int dns_transaction_on_stream_packet(DnsTransaction *t, DnsStream *s, DnsPacket *p) {
603 bool encrypted;
604
605 assert(t);
606 assert(s);
607 assert(p);
608
609 encrypted = s->encrypted;
610
611 dns_transaction_close_connection(t, true);
612
613 if (dns_packet_validate_reply(p) <= 0) {
614 log_debug("Invalid TCP reply packet.");
615 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
616 return 0;
617 }
618
619 dns_scope_check_conflicts(t->scope, p);
620
621 t->block_gc++;
622 dns_transaction_process_reply(t, p, encrypted);
623 t->block_gc--;
624
625 /* If the response wasn't useful, then complete the transition
626 * now. After all, we are the worst feature set now with TCP
627 * sockets, and there's really no point in retrying. */
628 if (t->state == DNS_TRANSACTION_PENDING)
629 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
630 else
631 dns_transaction_gc(t);
632
633 return 0;
634 }
635
636 static int on_stream_complete(DnsStream *s, int error) {
637 assert(s);
638
639 if (ERRNO_IS_DISCONNECT(error) && s->protocol != DNS_PROTOCOL_LLMNR) {
640 log_debug_errno(error, "Connection failure for DNS TCP stream: %m");
641
642 if (error != ECONNRESET && s->transactions) {
643 DnsTransaction *t;
644
645 t = s->transactions;
646 dns_server_packet_lost(t->server, IPPROTO_TCP, t->current_feature_level);
647 }
648 }
649
650 if (error != 0) {
651 /* First, detach the stream from the server. Otherwise, transactions attached to this stream
652 * may be restarted by on_transaction_stream_error() below with this stream. */
653 dns_stream_detach(s);
654
655 /* Do not use LIST_FOREACH() here, as
656 * on_transaction_stream_error()
657 * -> dns_transaction_complete_errno()
658 * -> dns_transaction_free()
659 * may free multiple transactions in the list. */
660 DnsTransaction *t;
661 while ((t = s->transactions))
662 on_transaction_stream_error(t, error);
663 }
664
665 return 0;
666 }
667
668 static int on_stream_packet(DnsStream *s, DnsPacket *p) {
669 DnsTransaction *t;
670
671 assert(s);
672 assert(s->manager);
673 assert(p);
674
675 t = hashmap_get(s->manager->dns_transactions, UINT_TO_PTR(DNS_PACKET_ID(p)));
676 if (t && t->stream == s) /* Validate that the stream we got this on actually is the stream the
677 * transaction was using. */
678 return dns_transaction_on_stream_packet(t, s, p);
679
680 /* Ignore incorrect transaction id as an old transaction can have been canceled. */
681 log_debug("Received unexpected TCP reply packet with id %" PRIu16 ", ignoring.", DNS_PACKET_ID(p));
682 return 0;
683 }
684
685 static uint16_t dns_transaction_port(DnsTransaction *t) {
686 assert(t);
687
688 if (t->server->port > 0)
689 return t->server->port;
690
691 return DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) ? 853 : 53;
692 }
693
694 static int dns_transaction_emit_tcp(DnsTransaction *t) {
695 usec_t stream_timeout_usec = DNS_STREAM_DEFAULT_TIMEOUT_USEC;
696 _cleanup_(dns_stream_unrefp) DnsStream *s = NULL;
697 _cleanup_close_ int fd = -EBADF;
698 union sockaddr_union sa;
699 DnsStreamType type;
700 int r;
701
702 assert(t);
703 assert(t->sent);
704
705 dns_transaction_close_connection(t, true);
706
707 switch (t->scope->protocol) {
708
709 case DNS_PROTOCOL_DNS:
710 r = dns_transaction_pick_server(t);
711 if (r < 0)
712 return r;
713
714 if (manager_server_is_stub(t->scope->manager, t->server))
715 return -ELOOP;
716
717 if (!t->bypass) {
718 if (!dns_server_dnssec_supported(t->server) && dns_type_is_dnssec(dns_transaction_key(t)->type))
719 return -EOPNOTSUPP;
720
721 r = dns_server_adjust_opt(t->server, t->sent, t->current_feature_level);
722 if (r < 0)
723 return r;
724 }
725
726 if (t->server->stream && (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) == t->server->stream->encrypted))
727 s = dns_stream_ref(t->server->stream);
728 else
729 fd = dns_scope_socket_tcp(t->scope, AF_UNSPEC, NULL, t->server, dns_transaction_port(t), &sa);
730
731 /* Lower timeout in DNS-over-TLS opportunistic mode. In environments where DoT is blocked
732 * without ICMP response overly long delays when contacting DoT servers are nasty, in
733 * particular if multiple DNS servers are defined which we try in turn and all are
734 * blocked. Hence, substantially lower the timeout in that case. */
735 if (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) &&
736 dns_server_get_dns_over_tls_mode(t->server) == DNS_OVER_TLS_OPPORTUNISTIC)
737 stream_timeout_usec = DNS_STREAM_OPPORTUNISTIC_TLS_TIMEOUT_USEC;
738
739 type = DNS_STREAM_LOOKUP;
740 break;
741
742 case DNS_PROTOCOL_LLMNR:
743 /* When we already received a reply to this (but it was truncated), send to its sender address */
744 if (t->received)
745 fd = dns_scope_socket_tcp(t->scope, t->received->family, &t->received->sender, NULL, t->received->sender_port, &sa);
746 else {
747 union in_addr_union address;
748 int family = AF_UNSPEC;
749
750 /* Otherwise, try to talk to the owner of a
751 * the IP address, in case this is a reverse
752 * PTR lookup */
753
754 r = dns_name_address(dns_resource_key_name(dns_transaction_key(t)), &family, &address);
755 if (r < 0)
756 return r;
757 if (r == 0)
758 return -EINVAL;
759 if (family != t->scope->family)
760 return -ESRCH;
761
762 fd = dns_scope_socket_tcp(t->scope, family, &address, NULL, LLMNR_PORT, &sa);
763 }
764
765 type = DNS_STREAM_LLMNR_SEND;
766 break;
767
768 default:
769 return -EAFNOSUPPORT;
770 }
771
772 if (!s) {
773 if (fd < 0)
774 return fd;
775
776 r = dns_stream_new(t->scope->manager, &s, type, t->scope->protocol, fd, &sa,
777 on_stream_packet, on_stream_complete, stream_timeout_usec);
778 if (r < 0)
779 return r;
780
781 fd = -EBADF;
782
783 #if ENABLE_DNS_OVER_TLS
784 if (t->scope->protocol == DNS_PROTOCOL_DNS &&
785 DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level)) {
786
787 assert(t->server);
788 r = dnstls_stream_connect_tls(s, t->server);
789 if (r < 0)
790 return r;
791 }
792 #endif
793
794 if (t->server) {
795 dns_server_unref_stream(t->server);
796 s->server = dns_server_ref(t->server);
797 t->server->stream = dns_stream_ref(s);
798 }
799
800 /* The interface index is difficult to determine if we are
801 * connecting to the local host, hence fill this in right away
802 * instead of determining it from the socket */
803 s->ifindex = dns_scope_ifindex(t->scope);
804 }
805
806 t->stream = TAKE_PTR(s);
807 LIST_PREPEND(transactions_by_stream, t->stream->transactions, t);
808
809 r = dns_stream_write_packet(t->stream, t->sent);
810 if (r < 0) {
811 dns_transaction_close_connection(t, /* use_graveyard= */ false);
812 return r;
813 }
814
815 dns_transaction_reset_answer(t);
816
817 t->tried_stream = true;
818
819 return 0;
820 }
821
822 static void dns_transaction_cache_answer(DnsTransaction *t) {
823 assert(t);
824
825 /* For mDNS we cache whenever we get the packet, rather than
826 * in each transaction. */
827 if (!IN_SET(t->scope->protocol, DNS_PROTOCOL_DNS, DNS_PROTOCOL_LLMNR))
828 return;
829
830 /* Caching disabled? */
831 if (t->scope->manager->enable_cache == DNS_CACHE_MODE_NO)
832 return;
833
834 /* If validation is turned off for this transaction, but DNSSEC is on, then let's not cache this */
835 if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) && t->scope->dnssec_mode != DNSSEC_NO)
836 return;
837
838 /* Packet from localhost? */
839 if (!t->scope->manager->cache_from_localhost &&
840 in_addr_is_localhost(t->received->family, &t->received->sender) != 0)
841 return;
842
843 dns_cache_put(&t->scope->cache,
844 t->scope->manager->enable_cache,
845 t->scope->protocol,
846 dns_transaction_key(t),
847 t->answer_rcode,
848 t->answer,
849 /* If neither DO nor EDE is set, the full packet isn't useful to cache */
850 dns_packet_do(t->received) || t->answer_ede_rcode > 0 || t->answer_ede_msg ? t->received : NULL,
851 t->answer_query_flags,
852 t->answer_dnssec_result,
853 t->answer_nsec_ttl,
854 t->received->family,
855 &t->received->sender,
856 t->scope->manager->stale_retention_usec);
857 }
858
859 static bool dns_transaction_dnssec_is_live(DnsTransaction *t) {
860 DnsTransaction *dt;
861
862 assert(t);
863
864 SET_FOREACH(dt, t->dnssec_transactions)
865 if (DNS_TRANSACTION_IS_LIVE(dt->state))
866 return true;
867
868 return false;
869 }
870
871 static int dns_transaction_dnssec_ready(DnsTransaction *t) {
872 DnsTransaction *dt;
873 int r;
874
875 assert(t);
876
877 /* Checks whether the auxiliary DNSSEC transactions of our transaction have completed, or are still
878 * ongoing. Returns 0, if we aren't ready for the DNSSEC validation, positive if we are. */
879
880 SET_FOREACH(dt, t->dnssec_transactions) {
881
882 switch (dt->state) {
883
884 case DNS_TRANSACTION_NULL:
885 case DNS_TRANSACTION_PENDING:
886 case DNS_TRANSACTION_VALIDATING:
887 /* Still ongoing */
888 return 0;
889
890 case DNS_TRANSACTION_RCODE_FAILURE:
891 if (!IN_SET(dt->answer_rcode, DNS_RCODE_NXDOMAIN, DNS_RCODE_SERVFAIL)) {
892 log_debug("Auxiliary DNSSEC RR query failed with rcode=%s.", FORMAT_DNS_RCODE(dt->answer_rcode));
893 goto fail;
894 }
895
896 /* Fall-through: NXDOMAIN/SERVFAIL is good enough for us. This is because some DNS servers
897 * erroneously return NXDOMAIN/SERVFAIL for empty non-terminals (Akamai...) or missing DS
898 * records (Facebook), and we need to handle that nicely, when asking for parent SOA or similar
899 * RRs to make unsigned proofs. */
900
901 case DNS_TRANSACTION_SUCCESS:
902 /* All good. */
903 break;
904
905 case DNS_TRANSACTION_DNSSEC_FAILED:
906 /* We handle DNSSEC failures different from other errors, as we care about the DNSSEC
907 * validation result */
908
909 log_debug("Auxiliary DNSSEC RR query failed validation: %s%s%s%s%s%s",
910 dnssec_result_to_string(dt->answer_dnssec_result),
911 dt->answer_ede_rcode >= 0 ? " (" : "",
912 dt->answer_ede_rcode >= 0 ? FORMAT_DNS_EDE_RCODE(dt->answer_ede_rcode) : "",
913 (dt->answer_ede_rcode >= 0 && !isempty(dt->answer_ede_msg)) ? ": " : "",
914 dt->answer_ede_rcode >= 0 ? strempty(dt->answer_ede_msg) : "",
915 dt->answer_ede_rcode >= 0 ? ")" : "");
916
917 /* Copy error code over */
918 t->answer_dnssec_result = dt->answer_dnssec_result;
919 t->answer_ede_rcode = dt->answer_ede_rcode;
920 r = free_and_strdup(&t->answer_ede_msg, dt->answer_ede_msg);
921 if (r < 0)
922 log_oom_debug();
923
924 /* The answer would normally be replaced by the validated subset, but at this point
925 * we aren't going to bother validating the rest, so just drop it. */
926 t->answer = dns_answer_unref(t->answer);
927
928 dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
929 return 0;
930
931 default:
932 log_debug("Auxiliary DNSSEC RR query failed with %s", dns_transaction_state_to_string(dt->state));
933 goto fail;
934 }
935 }
936
937 /* All is ready, we can go and validate */
938 return 1;
939
940 fail:
941 /* Some auxiliary DNSSEC transaction failed for some reason. Maybe we learned something about the
942 * server due to this failure, and the feature level is now different? Let's see and restart the
943 * transaction if so. If not, let's propagate the auxiliary failure.
944 *
945 * This is particularly relevant if an auxiliary request figured out that DNSSEC doesn't work, and we
946 * are in permissive DNSSEC mode, and thus should restart things without DNSSEC magic. */
947 r = dns_transaction_maybe_restart(t);
948 if (r < 0)
949 return r;
950 if (r > 0)
951 return 0; /* don't validate just yet, we restarted things */
952
953 t->answer_dnssec_result = DNSSEC_FAILED_AUXILIARY;
954 dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
955 return 0;
956 }
957
958 static void dns_transaction_process_dnssec(DnsTransaction *t) {
959 int r;
960
961 assert(t);
962
963 /* Are there ongoing DNSSEC transactions? If so, let's wait for them. */
964 r = dns_transaction_dnssec_ready(t);
965 if (r < 0)
966 goto fail;
967 if (r == 0) /* We aren't ready yet (or one of our auxiliary transactions failed, and we shouldn't validate now */
968 return;
969
970 /* See if we learnt things from the additional DNSSEC transactions, that we didn't know before, and better
971 * restart the lookup immediately. */
972 r = dns_transaction_maybe_restart(t);
973 if (r < 0)
974 goto fail;
975 if (r > 0) /* Transaction got restarted... */
976 return;
977
978 /* All our auxiliary DNSSEC transactions are complete now. Try
979 * to validate our RRset now. */
980 r = dns_transaction_validate_dnssec(t);
981 if (r == -EBADMSG) {
982 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
983 return;
984 }
985 if (r < 0)
986 goto fail;
987
988 if (t->answer_dnssec_result == DNSSEC_INCOMPATIBLE_SERVER &&
989 t->scope->dnssec_mode == DNSSEC_YES) {
990
991 /* We are not in automatic downgrade mode, and the server is bad. Let's try a different server, maybe
992 * that works. */
993
994 if (dns_transaction_limited_retry(t))
995 return;
996
997 /* OK, let's give up, apparently all servers we tried didn't work. */
998 dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
999 return;
1000 }
1001
1002 if (!IN_SET(t->answer_dnssec_result,
1003 _DNSSEC_RESULT_INVALID, /* No DNSSEC validation enabled */
1004 DNSSEC_VALIDATED, /* Answer is signed and validated successfully */
1005 DNSSEC_UNSIGNED, /* Answer is right-fully unsigned */
1006 DNSSEC_INCOMPATIBLE_SERVER)) { /* Server does not do DNSSEC (Yay, we are downgrade attack vulnerable!) */
1007 dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
1008 return;
1009 }
1010
1011 if (t->answer_dnssec_result == DNSSEC_INCOMPATIBLE_SERVER)
1012 dns_server_warn_downgrade(t->server);
1013
1014 dns_transaction_cache_answer(t);
1015
1016 if (t->answer_rcode == DNS_RCODE_SUCCESS)
1017 dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
1018 else
1019 dns_transaction_complete(t, DNS_TRANSACTION_RCODE_FAILURE);
1020
1021 return;
1022
1023 fail:
1024 dns_transaction_complete_errno(t, r);
1025 }
1026
1027 static int dns_transaction_has_positive_answer(DnsTransaction *t, DnsAnswerFlags *flags) {
1028 int r;
1029
1030 assert(t);
1031
1032 /* Checks whether the answer is positive, i.e. either a direct
1033 * answer to the question, or a CNAME/DNAME for it */
1034
1035 r = dns_answer_match_key(t->answer, dns_transaction_key(t), flags);
1036 if (r != 0)
1037 return r;
1038
1039 r = dns_answer_find_cname_or_dname(t->answer, dns_transaction_key(t), NULL, flags);
1040 if (r != 0)
1041 return r;
1042
1043 return false;
1044 }
1045
1046 static int dns_transaction_fix_rcode(DnsTransaction *t) {
1047 int r;
1048
1049 assert(t);
1050
1051 /* Fix up the RCODE to SUCCESS if we get at least one matching RR in a response. Note that this contradicts the
1052 * DNS RFCs a bit. Specifically, RFC 6604 Section 3 clarifies that the RCODE shall say something about a
1053 * CNAME/DNAME chain element coming after the last chain element contained in the message, and not the first
1054 * one included. However, it also indicates that not all DNS servers implement this correctly. Moreover, when
1055 * using DNSSEC we usually only can prove the first element of a CNAME/DNAME chain anyway, hence let's settle
1056 * on always processing the RCODE as referring to the immediate look-up we do, i.e. the first element of a
1057 * CNAME/DNAME chain. This way, we uniformly handle CNAME/DNAME chains, regardless if the DNS server
1058 * incorrectly implements RCODE, whether DNSSEC is in use, or whether the DNS server only supplied us with an
1059 * incomplete CNAME/DNAME chain.
1060 *
1061 * Or in other words: if we get at least one positive reply in a message we patch NXDOMAIN to become SUCCESS,
1062 * and then rely on the CNAME chasing logic to figure out that there's actually a CNAME error with a new
1063 * lookup. */
1064
1065 if (t->answer_rcode != DNS_RCODE_NXDOMAIN)
1066 return 0;
1067
1068 r = dns_transaction_has_positive_answer(t, NULL);
1069 if (r <= 0)
1070 return r;
1071
1072 t->answer_rcode = DNS_RCODE_SUCCESS;
1073 return 0;
1074 }
1075
1076 void dns_transaction_process_reply(DnsTransaction *t, DnsPacket *p, bool encrypted) {
1077 bool retry_with_tcp = false;
1078 int r;
1079
1080 assert(t);
1081 assert(p);
1082 assert(t->scope);
1083 assert(t->scope->manager);
1084
1085 if (t->state != DNS_TRANSACTION_PENDING)
1086 return;
1087
1088 /* Increment the total failure counter only when it is the first attempt at querying and the upstream
1089 * server returns a failure response code. This ensures a more accurate count of the number of queries
1090 * that received a failure response code, as it doesn't consider retries. */
1091
1092 if (t->n_attempts == 1 && !IN_SET(dns_packet_rcode(p), DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
1093 t->scope->manager->n_failure_responses_total++;
1094
1095 /* Note that this call might invalidate the query. Callers
1096 * should hence not attempt to access the query or transaction
1097 * after calling this function. */
1098
1099 log_debug("Processing incoming packet of size %zu on transaction %" PRIu16" (rcode=%s).",
1100 p->size,
1101 t->id, FORMAT_DNS_RCODE(dns_packet_rcode(p)));
1102
1103 switch (t->scope->protocol) {
1104
1105 case DNS_PROTOCOL_LLMNR:
1106 /* For LLMNR we will not accept any packets from other interfaces */
1107
1108 if (p->ifindex != dns_scope_ifindex(t->scope))
1109 return;
1110
1111 if (p->family != t->scope->family)
1112 return;
1113
1114 /* Tentative packets are not full responses but still
1115 * useful for identifying uniqueness conflicts during
1116 * probing. */
1117 if (DNS_PACKET_LLMNR_T(p)) {
1118 dns_transaction_tentative(t, p);
1119 return;
1120 }
1121
1122 break;
1123
1124 case DNS_PROTOCOL_MDNS:
1125 /* For mDNS we will not accept any packets from other interfaces */
1126
1127 if (p->ifindex != dns_scope_ifindex(t->scope))
1128 return;
1129
1130 if (p->family != t->scope->family)
1131 return;
1132
1133 break;
1134
1135 case DNS_PROTOCOL_DNS:
1136 /* Note that we do not need to verify the
1137 * addresses/port numbers of incoming traffic, as we
1138 * invoked connect() on our UDP socket in which case
1139 * the kernel already does the needed verification for
1140 * us. */
1141 break;
1142
1143 default:
1144 assert_not_reached();
1145 }
1146
1147 if (t->received != p)
1148 DNS_PACKET_REPLACE(t->received, dns_packet_ref(p));
1149
1150 t->answer_source = DNS_TRANSACTION_NETWORK;
1151
1152 if (p->ipproto == IPPROTO_TCP) {
1153 if (DNS_PACKET_TC(p)) {
1154 /* Truncated via TCP? Somebody must be fucking with us */
1155 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
1156 return;
1157 }
1158
1159 if (DNS_PACKET_ID(p) != t->id) {
1160 /* Not the reply to our query? Somebody must be fucking with us */
1161 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
1162 return;
1163 }
1164 }
1165
1166 if (DNS_PACKET_TC(p)) {
1167
1168 /* Truncated packets for mDNS are not allowed. Give up immediately. */
1169 if (t->scope->protocol == DNS_PROTOCOL_MDNS) {
1170 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
1171 return;
1172 }
1173
1174 /* Response was truncated, let's try again with good old TCP */
1175 log_debug("Reply truncated, retrying via TCP.");
1176 retry_with_tcp = true;
1177
1178 } else if (t->scope->protocol == DNS_PROTOCOL_DNS &&
1179 DNS_PACKET_IS_FRAGMENTED(p)) {
1180
1181 /* Report the fragment size, so that we downgrade from LARGE to regular EDNS0 if needed */
1182 if (t->server)
1183 dns_server_packet_udp_fragmented(t->server, dns_packet_size_unfragmented(p));
1184
1185 if (t->current_feature_level > DNS_SERVER_FEATURE_LEVEL_UDP) {
1186 /* Packet was fragmented. Let's retry with TCP to avoid fragmentation attack
1187 * issues. (We don't do that on the lowest feature level however, since crappy DNS
1188 * servers often do not implement TCP, hence falling back to TCP on fragmentation is
1189 * counter-productive there.) */
1190
1191 log_debug("Reply fragmented, retrying via TCP. (Largest fragment size: %zu; Datagram size: %zu)",
1192 p->fragsize, p->size);
1193 retry_with_tcp = true;
1194 }
1195 }
1196
1197 if (retry_with_tcp) {
1198 r = dns_transaction_emit_tcp(t);
1199 if (r == -ESRCH) {
1200 /* No servers found? Damn! */
1201 dns_transaction_complete(t, DNS_TRANSACTION_NO_SERVERS);
1202 return;
1203 }
1204 if (r == -EOPNOTSUPP) {
1205 /* Tried to ask for DNSSEC RRs, on a server that doesn't do DNSSEC */
1206 dns_transaction_complete(t, DNS_TRANSACTION_RR_TYPE_UNSUPPORTED);
1207 return;
1208 }
1209 if (r < 0) {
1210 /* On LLMNR, if we cannot connect to the host,
1211 * we immediately give up */
1212 if (t->scope->protocol != DNS_PROTOCOL_DNS)
1213 goto fail;
1214
1215 /* On DNS, couldn't send? Try immediately again, with a new server */
1216 if (dns_transaction_limited_retry(t))
1217 return;
1218
1219 /* No new server to try, give up */
1220 dns_transaction_complete(t, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED);
1221 }
1222
1223 return;
1224 }
1225
1226 /* After the superficial checks, actually parse the message. */
1227 r = dns_packet_extract(p);
1228 if (r < 0) {
1229 if (t->server) {
1230 dns_server_packet_invalid(t->server, t->current_feature_level);
1231
1232 r = dns_transaction_maybe_restart(t);
1233 if (r < 0)
1234 goto fail;
1235 if (r > 0) /* Transaction got restarted... */
1236 return;
1237 }
1238
1239 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
1240 return;
1241 }
1242
1243 switch (t->scope->protocol) {
1244
1245 case DNS_PROTOCOL_DNS: {
1246 assert(t->server);
1247
1248 (void) dns_packet_ede_rcode(p, &t->answer_ede_rcode, &t->answer_ede_msg);
1249
1250 if (!t->bypass &&
1251 IN_SET(dns_packet_rcode(p), DNS_RCODE_FORMERR, DNS_RCODE_SERVFAIL, DNS_RCODE_NOTIMP)) {
1252 /* If the server has replied with detailed error data, using a degraded feature set
1253 * will likely not help anyone. Examine the detailed error to determine the best
1254 * course of action. */
1255 if (t->answer_ede_rcode >= 0 && dns_packet_rcode(p) == DNS_RCODE_SERVFAIL) {
1256 /* These codes are related to DNSSEC configuration errors. If accurate,
1257 * this is the domain operator's problem, and retrying won't help. */
1258 if (dns_ede_rcode_is_dnssec(t->answer_ede_rcode)) {
1259 log_debug("Server returned error: %s (%s%s%s). Lookup failed.",
1260 FORMAT_DNS_RCODE(dns_packet_rcode(p)),
1261 FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
1262 isempty(t->answer_ede_msg) ? "" : ": ",
1263 strempty(t->answer_ede_msg));
1264
1265 t->answer_dnssec_result = DNSSEC_UPSTREAM_FAILURE;
1266 dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
1267 return;
1268 }
1269
1270 /* These codes probably indicate a transient error. Let's try again. */
1271 if (t->answer_ede_rcode == DNS_EDE_RCODE_NOT_READY) {
1272 log_debug("Server returned error: %s (%s%s%s), retrying transaction.",
1273 FORMAT_DNS_RCODE(dns_packet_rcode(p)),
1274 FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
1275 isempty(t->answer_ede_msg) ? "" : ": ",
1276 strempty(t->answer_ede_msg));
1277 dns_transaction_retry(t, false);
1278 return;
1279 }
1280
1281 /* OK, the query failed, but we still shouldn't degrade the feature set for
1282 * this server. */
1283 log_debug("Server returned error: %s (%s%s%s)",
1284 FORMAT_DNS_RCODE(dns_packet_rcode(p)),
1285 FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
1286 isempty(t->answer_ede_msg) ? "" : ": ",
1287 strempty(t->answer_ede_msg));
1288 break;
1289 }
1290
1291 /* Request failed, immediately try again with reduced features */
1292
1293 if (t->current_feature_level <= DNS_SERVER_FEATURE_LEVEL_UDP) {
1294
1295 /* This was already at UDP feature level? If so, it doesn't make sense to downgrade
1296 * this transaction anymore, but let's see if it might make sense to send the request
1297 * to a different DNS server instead. If not let's process the response, and accept the
1298 * rcode. Note that we don't retry on TCP, since that's a suitable way to mitigate
1299 * packet loss, but is not going to give us better rcodes should we actually have
1300 * managed to get them already at UDP level. */
1301
1302 if (dns_transaction_limited_retry(t))
1303 return;
1304
1305 /* Give up, accept the rcode */
1306 log_debug("Server returned error: %s", FORMAT_DNS_RCODE(dns_packet_rcode(p)));
1307 break;
1308 }
1309
1310 /* SERVFAIL can happen for many reasons and may be transient.
1311 * To avoid unnecessary downgrades retry once with the initial level.
1312 * Check for clamp_feature_level_servfail having an invalid value as a sign that this is the
1313 * first attempt to downgrade. If so, clamp to the current value so that the transaction
1314 * is retried without actually downgrading. If the next try also fails we will downgrade by
1315 * hitting the else branch below. */
1316 if (dns_packet_rcode(p) == DNS_RCODE_SERVFAIL &&
1317 t->clamp_feature_level_servfail < 0) {
1318 t->clamp_feature_level_servfail = t->current_feature_level;
1319 log_debug("Server returned error %s, retrying transaction.",
1320 FORMAT_DNS_RCODE(dns_packet_rcode(p)));
1321 } else {
1322 /* Reduce this feature level by one and try again. */
1323 switch (t->current_feature_level) {
1324 case DNS_SERVER_FEATURE_LEVEL_TLS_DO:
1325 t->clamp_feature_level_servfail = DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN;
1326 break;
1327 case DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN + 1:
1328 /* Skip plain TLS when TLS is not supported */
1329 t->clamp_feature_level_servfail = DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN - 1;
1330 break;
1331 default:
1332 t->clamp_feature_level_servfail = t->current_feature_level - 1;
1333 }
1334
1335 log_debug("Server returned error %s, retrying transaction with reduced feature level %s.",
1336 FORMAT_DNS_RCODE(dns_packet_rcode(p)),
1337 dns_server_feature_level_to_string(t->clamp_feature_level_servfail));
1338 }
1339
1340 dns_transaction_retry(t, false /* use the same server */);
1341 return;
1342 }
1343
1344 if (dns_packet_rcode(p) == DNS_RCODE_REFUSED) {
1345 /* This server refused our request? If so, try again, use a different server */
1346 if (t->answer_ede_rcode >= 0)
1347 log_debug("Server returned REFUSED (%s), switching servers, and retrying.",
1348 FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode));
1349 else
1350 log_debug("Server returned REFUSED, switching servers, and retrying.");
1351
1352 if (dns_transaction_limited_retry(t))
1353 return;
1354
1355 break;
1356 }
1357
1358 if (DNS_PACKET_TC(p))
1359 dns_server_packet_truncated(t->server, t->current_feature_level);
1360
1361 break;
1362 }
1363
1364 case DNS_PROTOCOL_LLMNR:
1365 case DNS_PROTOCOL_MDNS:
1366 dns_scope_packet_received(t->scope, p->timestamp - t->start_usec);
1367 break;
1368
1369 default:
1370 assert_not_reached();
1371 }
1372
1373 if (t->server) {
1374 /* Report that we successfully received a valid packet with a good rcode after we initially got a bad
1375 * rcode and subsequently downgraded the protocol */
1376
1377 if (IN_SET(dns_packet_rcode(p), DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN) &&
1378 t->clamp_feature_level_servfail != _DNS_SERVER_FEATURE_LEVEL_INVALID)
1379 dns_server_packet_rcode_downgrade(t->server, t->clamp_feature_level_servfail);
1380
1381 /* Report that the OPT RR was missing */
1382 if (!p->opt)
1383 dns_server_packet_bad_opt(t->server, t->current_feature_level);
1384
1385 /* Report that the server didn't copy our query DO bit from request to response */
1386 if (dns_packet_do(t->sent) && !dns_packet_do(t->received))
1387 dns_server_packet_do_off(t->server, t->current_feature_level);
1388
1389 /* Report that we successfully received a packet. We keep track of the largest packet
1390 * size/fragment size we got. Which is useful for announcing the EDNS(0) packet size we can
1391 * receive to our server. */
1392 dns_server_packet_received(t->server, p->ipproto, t->current_feature_level, dns_packet_size_unfragmented(p));
1393 }
1394
1395 /* See if we know things we didn't know before that indicate we better restart the lookup immediately. */
1396 r = dns_transaction_maybe_restart(t);
1397 if (r < 0)
1398 goto fail;
1399 if (r > 0) /* Transaction got restarted... */
1400 return;
1401
1402 /* When dealing with protocols other than mDNS only consider responses with equivalent query section
1403 * to the request. For mDNS this check doesn't make sense, because the section 6 of RFC6762 states
1404 * that "Multicast DNS responses MUST NOT contain any questions in the Question Section". */
1405 if (t->scope->protocol != DNS_PROTOCOL_MDNS) {
1406 r = dns_packet_is_reply_for(p, dns_transaction_key(t));
1407 if (r < 0)
1408 goto fail;
1409 if (r == 0) {
1410 dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
1411 return;
1412 }
1413 }
1414
1415 /* Install the answer as answer to the transaction. We ref the answer twice here: the main `answer`
1416 * field is later replaced by the DNSSEC validated subset. The 'answer_auxiliary' field carries the
1417 * original complete record set, including RRSIG and friends. We use this when passing data to
1418 * clients that ask for DNSSEC metadata. */
1419 DNS_ANSWER_REPLACE(t->answer, dns_answer_ref(p->answer));
1420 t->answer_rcode = dns_packet_rcode(p);
1421 t->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
1422 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
1423 SET_FLAG(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, encrypted);
1424
1425 r = dns_transaction_fix_rcode(t);
1426 if (r < 0)
1427 goto fail;
1428
1429 /* Block GC while starting requests for additional DNSSEC RRs */
1430 t->block_gc++;
1431 r = dns_transaction_request_dnssec_keys(t);
1432 t->block_gc--;
1433
1434 /* Maybe the transaction is ready for GC'ing now? If so, free it and return. */
1435 if (!dns_transaction_gc(t))
1436 return;
1437
1438 /* Requesting additional keys might have resulted in this transaction to fail, since the auxiliary
1439 * request failed for some reason. If so, we are not in pending state anymore, and we should exit
1440 * quickly. */
1441 if (t->state != DNS_TRANSACTION_PENDING)
1442 return;
1443 if (r < 0)
1444 goto fail;
1445 if (r > 0) {
1446 /* There are DNSSEC transactions pending now. Update the state accordingly. */
1447 t->state = DNS_TRANSACTION_VALIDATING;
1448 dns_transaction_close_connection(t, true);
1449 dns_transaction_stop_timeout(t);
1450 return;
1451 }
1452
1453 dns_transaction_process_dnssec(t);
1454 return;
1455
1456 fail:
1457 dns_transaction_complete_errno(t, r);
1458 }
1459
1460 static int on_dns_packet(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1461 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1462 DnsTransaction *t = ASSERT_PTR(userdata);
1463 int r;
1464
1465 assert(t->scope);
1466
1467 r = manager_recv(t->scope->manager, fd, DNS_PROTOCOL_DNS, &p);
1468 if (r < 0) {
1469 if (ERRNO_IS_DISCONNECT(r)) {
1470 usec_t usec;
1471
1472 /* UDP connection failures get reported via ICMP and then are possibly delivered to us on the
1473 * next recvmsg(). Treat this like a lost packet. */
1474
1475 log_debug_errno(r, "Connection failure for DNS UDP packet: %m");
1476 assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &usec) >= 0);
1477 dns_server_packet_lost(t->server, IPPROTO_UDP, t->current_feature_level);
1478
1479 dns_transaction_close_connection(t, /* use_graveyard= */ false);
1480
1481 if (dns_transaction_limited_retry(t)) /* Try a different server */
1482 return 0;
1483 }
1484 dns_transaction_complete_errno(t, r);
1485 return 0;
1486 }
1487 if (r == 0)
1488 /* Spurious wakeup without any data */
1489 return 0;
1490
1491 r = dns_packet_validate_reply(p);
1492 if (r < 0) {
1493 log_debug_errno(r, "Received invalid DNS packet as response, ignoring: %m");
1494 return 0;
1495 }
1496 if (r == 0) {
1497 log_debug("Received inappropriate DNS packet as response, ignoring.");
1498 return 0;
1499 }
1500
1501 if (DNS_PACKET_ID(p) != t->id) {
1502 log_debug("Received packet with incorrect transaction ID, ignoring.");
1503 return 0;
1504 }
1505
1506 dns_transaction_process_reply(t, p, false);
1507 return 0;
1508 }
1509
1510 static int dns_transaction_emit_udp(DnsTransaction *t) {
1511 int r;
1512
1513 assert(t);
1514
1515 if (t->scope->protocol == DNS_PROTOCOL_DNS) {
1516
1517 r = dns_transaction_pick_server(t);
1518 if (r < 0)
1519 return r;
1520
1521 if (manager_server_is_stub(t->scope->manager, t->server))
1522 return -ELOOP;
1523
1524 if (t->current_feature_level < DNS_SERVER_FEATURE_LEVEL_UDP || DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level))
1525 return -EAGAIN; /* Sorry, can't do UDP, try TCP! */
1526
1527 if (!t->bypass && !dns_server_dnssec_supported(t->server) && dns_type_is_dnssec(dns_transaction_key(t)->type))
1528 return -EOPNOTSUPP;
1529
1530 if (r > 0 || t->dns_udp_fd < 0) { /* Server changed, or no connection yet. */
1531 int fd;
1532
1533 dns_transaction_close_connection(t, true);
1534
1535 /* Before we allocate a new UDP socket, let's process the graveyard a bit to free some fds */
1536 manager_socket_graveyard_process(t->scope->manager);
1537
1538 fd = dns_scope_socket_udp(t->scope, t->server);
1539 if (fd < 0)
1540 return fd;
1541
1542 r = sd_event_add_io(t->scope->manager->event, &t->dns_udp_event_source, fd, EPOLLIN, on_dns_packet, t);
1543 if (r < 0) {
1544 safe_close(fd);
1545 return r;
1546 }
1547
1548 (void) sd_event_source_set_description(t->dns_udp_event_source, "dns-transaction-udp");
1549 t->dns_udp_fd = fd;
1550 }
1551
1552 if (!t->bypass) {
1553 r = dns_server_adjust_opt(t->server, t->sent, t->current_feature_level);
1554 if (r < 0)
1555 return r;
1556 }
1557 } else
1558 dns_transaction_close_connection(t, true);
1559
1560 r = dns_scope_emit_udp(t->scope, t->dns_udp_fd, t->server ? t->server->family : AF_UNSPEC, t->sent);
1561 if (r < 0)
1562 return r;
1563
1564 dns_transaction_reset_answer(t);
1565
1566 return 0;
1567 }
1568
1569 static int on_transaction_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1570 DnsTransaction *t = ASSERT_PTR(userdata);
1571
1572 assert(s);
1573
1574 t->seen_timeout = true;
1575
1576 if (t->initial_jitter_scheduled && !t->initial_jitter_elapsed) {
1577 log_debug("Initial jitter phase for transaction %" PRIu16 " elapsed.", t->id);
1578 t->initial_jitter_elapsed = true;
1579 } else {
1580 /* Timeout reached? Increase the timeout for the server used */
1581 switch (t->scope->protocol) {
1582
1583 case DNS_PROTOCOL_DNS:
1584 assert(t->server);
1585 dns_server_packet_lost(t->server, t->stream ? IPPROTO_TCP : IPPROTO_UDP, t->current_feature_level);
1586 break;
1587
1588 case DNS_PROTOCOL_LLMNR:
1589 case DNS_PROTOCOL_MDNS:
1590 dns_scope_packet_lost(t->scope, usec - t->start_usec);
1591 break;
1592
1593 default:
1594 assert_not_reached();
1595 }
1596
1597 log_debug("Timeout reached on transaction %" PRIu16 ".", t->id);
1598 }
1599
1600 dns_transaction_retry(t, /* next_server= */ true); /* try a different server, but given this means
1601 * packet loss, let's do so even if we already
1602 * tried a bunch */
1603 return 0;
1604 }
1605
1606 static int dns_transaction_setup_timeout(
1607 DnsTransaction *t,
1608 usec_t timeout_usec /* relative */,
1609 usec_t next_usec /* CLOCK_BOOTTIME */) {
1610
1611 int r;
1612
1613 assert(t);
1614
1615 dns_transaction_stop_timeout(t);
1616
1617 r = sd_event_add_time_relative(
1618 t->scope->manager->event,
1619 &t->timeout_event_source,
1620 CLOCK_BOOTTIME,
1621 timeout_usec, 0,
1622 on_transaction_timeout, t);
1623 if (r < 0)
1624 return r;
1625
1626 (void) sd_event_source_set_description(t->timeout_event_source, "dns-transaction-timeout");
1627
1628 t->next_attempt_after = next_usec;
1629 t->state = DNS_TRANSACTION_PENDING;
1630 return 0;
1631 }
1632
1633 static usec_t transaction_get_resend_timeout(DnsTransaction *t) {
1634 assert(t);
1635 assert(t->scope);
1636
1637 switch (t->scope->protocol) {
1638
1639 case DNS_PROTOCOL_DNS:
1640
1641 if (t->stream)
1642 return TRANSACTION_TCP_TIMEOUT_USEC;
1643
1644 return TRANSACTION_UDP_TIMEOUT_USEC;
1645
1646 case DNS_PROTOCOL_MDNS:
1647 if (t->probing)
1648 return MDNS_PROBING_INTERVAL_USEC;
1649
1650 /* See RFC 6762 Section 5.1 suggests that timeout should be a few seconds. */
1651 assert(t->n_attempts > 0);
1652 return (1 << (t->n_attempts - 1)) * USEC_PER_SEC;
1653
1654 case DNS_PROTOCOL_LLMNR:
1655 return t->scope->resend_timeout;
1656
1657 default:
1658 assert_not_reached();
1659 }
1660 }
1661
1662 static void dns_transaction_randomize_answer(DnsTransaction *t) {
1663 int r;
1664
1665 assert(t);
1666
1667 /* Randomizes the order of the answer array. This is done for all cached responses, so that we return
1668 * a different order each time. We do this only for DNS traffic, in order to do some minimal, crappy
1669 * load balancing. We don't do this for LLMNR or mDNS, since the order (preferring link-local
1670 * addresses, and such like) might have meaning there, and load balancing is pointless. */
1671
1672 if (t->scope->protocol != DNS_PROTOCOL_DNS)
1673 return;
1674
1675 /* No point in randomizing, if there's just one RR */
1676 if (dns_answer_size(t->answer) <= 1)
1677 return;
1678
1679 r = dns_answer_reserve_or_clone(&t->answer, 0);
1680 if (r < 0) /* If this fails, just don't randomize, this is non-essential stuff after all */
1681 return (void) log_debug_errno(r, "Failed to clone answer record, not randomizing RR order of answer: %m");
1682
1683 dns_answer_randomize(t->answer);
1684 }
1685
1686 static int dns_transaction_prepare(DnsTransaction *t, usec_t ts) {
1687 int r;
1688
1689 assert(t);
1690
1691 /* Returns 0 if dns_transaction_complete() has been called. In that case the transaction and query
1692 * candidate objects may have been invalidated and must not be accessed. Returns 1 if the transaction
1693 * has been prepared. */
1694
1695 dns_transaction_stop_timeout(t);
1696
1697 if (t->n_attempts == 1 && t->seen_timeout)
1698 t->scope->manager->n_timeouts_total++;
1699
1700 if (!dns_scope_network_good(t->scope)) {
1701 dns_transaction_complete(t, DNS_TRANSACTION_NETWORK_DOWN);
1702 return 0;
1703 }
1704
1705 if (t->n_attempts >= dns_transaction_attempts_max(t->scope->protocol, t->query_flags)) {
1706 DnsTransactionState result;
1707
1708 if (t->scope->protocol == DNS_PROTOCOL_LLMNR)
1709 /* If we didn't find anything on LLMNR, it's not an error, but a failure to resolve
1710 * the name. */
1711 result = DNS_TRANSACTION_NOT_FOUND;
1712 else
1713 result = DNS_TRANSACTION_ATTEMPTS_MAX_REACHED;
1714
1715 dns_transaction_complete(t, result);
1716 return 0;
1717 }
1718
1719 if (t->scope->protocol == DNS_PROTOCOL_LLMNR && t->tried_stream) {
1720 /* If we already tried via a stream, then we don't
1721 * retry on LLMNR. See RFC 4795, Section 2.7. */
1722 dns_transaction_complete(t, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED);
1723 return 0;
1724 }
1725
1726 t->n_attempts++;
1727 t->start_usec = ts;
1728
1729 dns_transaction_reset_answer(t);
1730 dns_transaction_flush_dnssec_transactions(t);
1731
1732 /* Check the trust anchor. Do so only on classic DNS, since DNSSEC does not apply otherwise. */
1733 if (t->scope->protocol == DNS_PROTOCOL_DNS &&
1734 !FLAGS_SET(t->query_flags, SD_RESOLVED_NO_TRUST_ANCHOR)) {
1735 r = dns_trust_anchor_lookup_positive(&t->scope->manager->trust_anchor, dns_transaction_key(t), &t->answer);
1736 if (r < 0)
1737 return r;
1738 if (r > 0) {
1739 t->answer_rcode = DNS_RCODE_SUCCESS;
1740 t->answer_source = DNS_TRANSACTION_TRUST_ANCHOR;
1741 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL, true);
1742 dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
1743 return 0;
1744 }
1745
1746 if (dns_name_is_root(dns_resource_key_name(dns_transaction_key(t))) &&
1747 dns_transaction_key(t)->type == DNS_TYPE_DS) {
1748
1749 /* Hmm, this is a request for the root DS? A DS RR doesn't exist in the root zone,
1750 * and if our trust anchor didn't know it either, this means we cannot do any DNSSEC
1751 * logic anymore. */
1752
1753 if (t->scope->dnssec_mode == DNSSEC_ALLOW_DOWNGRADE) {
1754 /* We are in downgrade mode. In this case, synthesize an unsigned empty
1755 * response, so that the any lookup depending on this one can continue
1756 * assuming there was no DS, and hence the root zone was unsigned. */
1757
1758 t->answer_rcode = DNS_RCODE_SUCCESS;
1759 t->answer_source = DNS_TRANSACTION_TRUST_ANCHOR;
1760 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
1761 SET_FLAG(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, true);
1762 dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
1763 } else
1764 /* If we are not in downgrade mode, then fail the lookup, because we cannot
1765 * reasonably answer it. There might be DS RRs, but we don't know them, and
1766 * the DNS server won't tell them to us (and even if it would, we couldn't
1767 * validate and trust them. */
1768 dns_transaction_complete(t, DNS_TRANSACTION_NO_TRUST_ANCHOR);
1769
1770 return 0;
1771 }
1772 }
1773
1774 /* Check the zone. */
1775 if (!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_ZONE)) {
1776 r = dns_zone_lookup(&t->scope->zone, dns_transaction_key(t), dns_scope_ifindex(t->scope), &t->answer, NULL, NULL);
1777 if (r < 0)
1778 return r;
1779 if (r > 0) {
1780 t->answer_rcode = DNS_RCODE_SUCCESS;
1781 t->answer_source = DNS_TRANSACTION_ZONE;
1782 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL, true);
1783 dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
1784 return 0;
1785 }
1786 }
1787
1788 /* Check the cache. */
1789 if (!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_CACHE)) {
1790
1791 /* Before trying the cache, let's make sure we figured out a server to use. Should this cause
1792 * a change of server this might flush the cache. */
1793 (void) dns_scope_get_dns_server(t->scope);
1794
1795 /* Let's then prune all outdated entries */
1796 dns_cache_prune(&t->scope->cache);
1797
1798 /* For the initial attempt or when no stale data is requested, disable serve stale
1799 * and answer the question from the cache (honors ttl property).
1800 * On the second attempt, if StaleRetentionSec is greater than zero,
1801 * try to answer the question using stale date (honors until property) */
1802 uint64_t query_flags = t->query_flags;
1803 if (t->n_attempts == 1 || t->scope->manager->stale_retention_usec == 0)
1804 query_flags |= SD_RESOLVED_NO_STALE;
1805
1806 r = dns_cache_lookup(
1807 &t->scope->cache,
1808 dns_transaction_key(t),
1809 query_flags,
1810 &t->answer_rcode,
1811 &t->answer,
1812 &t->received,
1813 &t->answer_query_flags,
1814 &t->answer_dnssec_result);
1815 if (r < 0)
1816 return r;
1817 if (r > 0) {
1818 dns_transaction_randomize_answer(t);
1819
1820 if (t->bypass && t->scope->protocol == DNS_PROTOCOL_DNS && !t->received)
1821 /* When bypass mode is on, do not use cached data unless it came with a full
1822 * packet. */
1823 dns_transaction_reset_answer(t);
1824 else {
1825 if (t->n_attempts > 1 && !FLAGS_SET(query_flags, SD_RESOLVED_NO_STALE)) {
1826
1827 if (t->answer_rcode == DNS_RCODE_SUCCESS) {
1828 if (t->seen_timeout)
1829 t->scope->manager->n_timeouts_served_stale_total++;
1830 else
1831 t->scope->manager->n_failure_responses_served_stale_total++;
1832 }
1833
1834 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1835 log_debug("Serve Stale response rcode=%s for %s",
1836 FORMAT_DNS_RCODE(t->answer_rcode),
1837 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str));
1838 }
1839
1840 t->answer_source = DNS_TRANSACTION_CACHE;
1841 if (t->answer_rcode == DNS_RCODE_SUCCESS)
1842 dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
1843 else {
1844 if (t->received)
1845 (void) dns_packet_ede_rcode(t->received, &t->answer_ede_rcode, &t->answer_ede_msg);
1846
1847 dns_transaction_complete(t, DNS_TRANSACTION_RCODE_FAILURE);
1848 }
1849 return 0;
1850 }
1851 }
1852 }
1853
1854 if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_NETWORK)) {
1855 dns_transaction_complete(t, DNS_TRANSACTION_NO_SOURCE);
1856 return 0;
1857 }
1858
1859 return 1;
1860 }
1861
1862 static int dns_packet_append_zone(DnsPacket *p, DnsTransaction *t, DnsResourceKey *k, unsigned *nscount) {
1863 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
1864 bool tentative;
1865 int r;
1866
1867 assert(p);
1868 assert(t);
1869 assert(k);
1870
1871 if (k->type != DNS_TYPE_ANY)
1872 return 0;
1873
1874 r = dns_zone_lookup(&t->scope->zone, k, t->scope->link->ifindex, &answer, NULL, &tentative);
1875 if (r < 0)
1876 return r;
1877
1878 return dns_packet_append_answer(p, answer, nscount);
1879 }
1880
1881 static int mdns_make_dummy_packet(DnsTransaction *t, DnsPacket **ret_packet, Set **ret_keys) {
1882 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1883 _cleanup_set_free_ Set *keys = NULL;
1884 bool add_known_answers = false;
1885 unsigned qdcount;
1886 usec_t ts;
1887 int r;
1888
1889 assert(t);
1890 assert(t->scope);
1891 assert(t->scope->protocol == DNS_PROTOCOL_MDNS);
1892 assert(ret_packet);
1893 assert(ret_keys);
1894
1895 r = dns_packet_new_query(&p, t->scope->protocol, 0, false);
1896 if (r < 0)
1897 return r;
1898
1899 r = dns_packet_append_key(p, dns_transaction_key(t), 0, NULL);
1900 if (r < 0)
1901 return r;
1902
1903 qdcount = 1;
1904
1905 if (dns_key_is_shared(dns_transaction_key(t)))
1906 add_known_answers = true;
1907
1908 r = dns_packet_append_zone(p, t, dns_transaction_key(t), NULL);
1909 if (r < 0)
1910 return r;
1911
1912 /* Save appended keys */
1913 r = set_ensure_put(&keys, &dns_resource_key_hash_ops, dns_transaction_key(t));
1914 if (r < 0)
1915 return r;
1916
1917 assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &ts) >= 0);
1918
1919 LIST_FOREACH(transactions_by_scope, other, t->scope->transactions) {
1920
1921 /* Skip ourselves */
1922 if (other == t)
1923 continue;
1924
1925 if (other->state != DNS_TRANSACTION_PENDING)
1926 continue;
1927
1928 if (other->next_attempt_after > ts)
1929 continue;
1930
1931 if (!set_contains(keys, dns_transaction_key(other))) {
1932 size_t saved_packet_size;
1933
1934 r = dns_packet_append_key(p, dns_transaction_key(other), 0, &saved_packet_size);
1935 /* If we can't stuff more questions into the packet, just give up.
1936 * One of the 'other' transactions will fire later and take care of the rest. */
1937 if (r == -EMSGSIZE)
1938 break;
1939 if (r < 0)
1940 return r;
1941
1942 r = dns_packet_append_zone(p, t, dns_transaction_key(other), NULL);
1943 if (r == -EMSGSIZE) {
1944 dns_packet_truncate(p, saved_packet_size);
1945 break;
1946 }
1947 if (r < 0)
1948 return r;
1949
1950 r = set_ensure_put(&keys, &dns_resource_key_hash_ops, dns_transaction_key(other));
1951 if (r < 0)
1952 return r;
1953 }
1954
1955 r = dns_transaction_prepare(other, ts);
1956 if (r < 0)
1957 return r;
1958 if (r == 0)
1959 /* In this case, not only this transaction, but multiple transactions may be
1960 * freed. Hence, we need to restart the loop. */
1961 return -EAGAIN;
1962
1963 usec_t timeout = transaction_get_resend_timeout(other);
1964 r = dns_transaction_setup_timeout(other, timeout, usec_add(ts, timeout));
1965 if (r < 0)
1966 return r;
1967
1968 if (dns_key_is_shared(dns_transaction_key(other)))
1969 add_known_answers = true;
1970
1971 qdcount++;
1972 if (qdcount >= UINT16_MAX)
1973 break;
1974 }
1975
1976 DNS_PACKET_HEADER(p)->qdcount = htobe16(qdcount);
1977
1978 /* Append known answers section if we're asking for any shared record */
1979 if (add_known_answers) {
1980 r = dns_cache_export_shared_to_packet(&t->scope->cache, p, ts, 0);
1981 if (r < 0)
1982 return r;
1983 }
1984
1985 *ret_packet = TAKE_PTR(p);
1986 *ret_keys = TAKE_PTR(keys);
1987 return add_known_answers;
1988 }
1989
1990 static int dns_transaction_make_packet_mdns(DnsTransaction *t) {
1991 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL, *dummy = NULL;
1992 _cleanup_set_free_ Set *keys = NULL;
1993 bool add_known_answers;
1994 DnsResourceKey *k;
1995 unsigned c;
1996 int r;
1997
1998 assert(t);
1999 assert(t->scope->protocol == DNS_PROTOCOL_MDNS);
2000
2001 /* Discard any previously prepared packet, so we can start over and coalesce again */
2002 t->sent = dns_packet_unref(t->sent);
2003
2004 /* First, create a dummy packet to calculate the number of known answers to be appended in the first packet. */
2005 for (;;) {
2006 r = mdns_make_dummy_packet(t, &dummy, &keys);
2007 if (r == -EAGAIN)
2008 continue;
2009 if (r < 0)
2010 return r;
2011
2012 add_known_answers = r;
2013 break;
2014 }
2015
2016 /* Then, create actual packet. */
2017 r = dns_packet_new_query(&p, t->scope->protocol, 0, false);
2018 if (r < 0)
2019 return r;
2020
2021 /* Questions */
2022 c = 0;
2023 SET_FOREACH(k, keys) {
2024 r = dns_packet_append_key(p, k, 0, NULL);
2025 if (r < 0)
2026 return r;
2027 c++;
2028 }
2029 DNS_PACKET_HEADER(p)->qdcount = htobe16(c);
2030
2031 /* Known answers */
2032 if (add_known_answers) {
2033 usec_t ts;
2034
2035 assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &ts) >= 0);
2036
2037 r = dns_cache_export_shared_to_packet(&t->scope->cache, p, ts, be16toh(DNS_PACKET_HEADER(dummy)->ancount));
2038 if (r < 0)
2039 return r;
2040 }
2041
2042 /* Authorities */
2043 c = 0;
2044 SET_FOREACH(k, keys) {
2045 r = dns_packet_append_zone(p, t, k, &c);
2046 if (r < 0)
2047 return r;
2048 }
2049 DNS_PACKET_HEADER(p)->nscount = htobe16(c);
2050
2051 t->sent = TAKE_PTR(p);
2052 return 0;
2053 }
2054
2055 static int dns_transaction_make_packet(DnsTransaction *t) {
2056 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
2057 int r;
2058
2059 assert(t);
2060
2061 if (t->scope->protocol == DNS_PROTOCOL_MDNS)
2062 return dns_transaction_make_packet_mdns(t);
2063
2064 if (t->sent)
2065 return 0;
2066
2067 if (t->bypass && t->bypass->protocol == t->scope->protocol) {
2068 /* If bypass logic is enabled and the protocol if the original packet and our scope match,
2069 * take the original packet, copy it, and patch in our new ID */
2070 r = dns_packet_dup(&p, t->bypass);
2071 if (r < 0)
2072 return r;
2073 } else {
2074 r = dns_packet_new_query(
2075 &p, t->scope->protocol,
2076 /* min_alloc_dsize= */ 0,
2077 /* dnssec_checking_disabled= */ !FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) &&
2078 t->scope->dnssec_mode != DNSSEC_NO);
2079 if (r < 0)
2080 return r;
2081
2082 r = dns_packet_append_key(p, dns_transaction_key(t), 0, NULL);
2083 if (r < 0)
2084 return r;
2085
2086 DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
2087 }
2088
2089 DNS_PACKET_HEADER(p)->id = t->id;
2090
2091 t->sent = TAKE_PTR(p);
2092 return 0;
2093 }
2094
2095 int dns_transaction_go(DnsTransaction *t) {
2096 usec_t ts;
2097 int r;
2098 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
2099
2100 assert(t);
2101
2102 /* Returns > 0 if the transaction is now pending, returns 0 if could be processed immediately and has
2103 * finished now. In the latter case, the transaction and query candidate objects must not be accessed.
2104 */
2105
2106 assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &ts) >= 0);
2107
2108 r = dns_transaction_prepare(t, ts);
2109 if (r <= 0)
2110 return r;
2111
2112 log_debug("Firing %s transaction %" PRIu16 " for <%s> scope %s on %s/%s (validate=%s).",
2113 t->bypass ? "bypass" : "regular",
2114 t->id,
2115 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str),
2116 dns_protocol_to_string(t->scope->protocol),
2117 t->scope->link ? t->scope->link->ifname : "*",
2118 af_to_name_short(t->scope->family),
2119 yes_no(!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE)));
2120
2121 if (!t->initial_jitter_scheduled &&
2122 IN_SET(t->scope->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS)) {
2123 usec_t jitter;
2124
2125 /* RFC 4795 Section 2.7 suggests all LLMNR queries should be delayed by a random time from 0 to
2126 * JITTER_INTERVAL.
2127 * RFC 6762 Section 8.1 suggests initial probe queries should be delayed by a random time from
2128 * 0 to 250ms. */
2129
2130 t->initial_jitter_scheduled = true;
2131 t->n_attempts = 0;
2132
2133 switch (t->scope->protocol) {
2134
2135 case DNS_PROTOCOL_LLMNR:
2136 jitter = random_u64_range(LLMNR_JITTER_INTERVAL_USEC);
2137 break;
2138
2139 case DNS_PROTOCOL_MDNS:
2140 if (t->probing)
2141 jitter = random_u64_range(MDNS_PROBING_INTERVAL_USEC);
2142 else
2143 jitter = 0;
2144 break;
2145 default:
2146 assert_not_reached();
2147 }
2148
2149 r = dns_transaction_setup_timeout(t, jitter, ts);
2150 if (r < 0)
2151 return r;
2152
2153 log_debug("Delaying %s transaction %" PRIu16 " for " USEC_FMT "us.",
2154 dns_protocol_to_string(t->scope->protocol),
2155 t->id,
2156 jitter);
2157 return 1;
2158 }
2159
2160 /* Otherwise, we need to ask the network */
2161 r = dns_transaction_make_packet(t);
2162 if (r < 0)
2163 return r;
2164
2165 if (t->scope->protocol == DNS_PROTOCOL_LLMNR &&
2166 (dns_name_endswith(dns_resource_key_name(dns_transaction_key(t)), "in-addr.arpa") > 0 ||
2167 dns_name_endswith(dns_resource_key_name(dns_transaction_key(t)), "ip6.arpa") > 0)) {
2168
2169 /* RFC 4795, Section 2.4. says reverse lookups shall
2170 * always be made via TCP on LLMNR */
2171 r = dns_transaction_emit_tcp(t);
2172 } else {
2173 /* Try via UDP, and if that fails due to large size or lack of
2174 * support try via TCP */
2175 r = dns_transaction_emit_udp(t);
2176 if (r == -EMSGSIZE)
2177 log_debug("Sending query via TCP since it is too large.");
2178 else if (r == -EAGAIN)
2179 log_debug("Sending query via TCP since UDP isn't supported or DNS-over-TLS is selected.");
2180 else if (r == -EPERM)
2181 log_debug("Sending query via TCP since UDP is blocked.");
2182 if (IN_SET(r, -EMSGSIZE, -EAGAIN, -EPERM))
2183 r = dns_transaction_emit_tcp(t);
2184 }
2185 if (r == -ELOOP) {
2186 if (t->scope->protocol != DNS_PROTOCOL_DNS)
2187 return r;
2188
2189 /* One of our own stub listeners */
2190 log_debug_errno(r, "Detected that specified DNS server is our own extra listener, switching DNS servers.");
2191
2192 dns_scope_next_dns_server(t->scope, t->server);
2193
2194 if (dns_scope_get_dns_server(t->scope) == t->server) {
2195 log_debug_errno(r, "Still pointing to extra listener after switching DNS servers, refusing operation.");
2196 dns_transaction_complete(t, DNS_TRANSACTION_STUB_LOOP);
2197 return 0;
2198 }
2199
2200 return dns_transaction_go(t);
2201 }
2202 if (r == -ESRCH) {
2203 /* No servers to send this to? */
2204 dns_transaction_complete(t, DNS_TRANSACTION_NO_SERVERS);
2205 return 0;
2206 }
2207 if (r == -EOPNOTSUPP) {
2208 /* Tried to ask for DNSSEC RRs, on a server that doesn't do DNSSEC */
2209 dns_transaction_complete(t, DNS_TRANSACTION_RR_TYPE_UNSUPPORTED);
2210 return 0;
2211 }
2212 if (t->scope->protocol == DNS_PROTOCOL_LLMNR && ERRNO_IS_NEG_DISCONNECT(r)) {
2213 /* On LLMNR, if we cannot connect to a host via TCP when doing reverse lookups. This means we cannot
2214 * answer this request with this protocol. */
2215 dns_transaction_complete(t, DNS_TRANSACTION_NOT_FOUND);
2216 return 0;
2217 }
2218 if (r < 0) {
2219 if (t->scope->protocol != DNS_PROTOCOL_DNS)
2220 return r;
2221
2222 /* Couldn't send? Try immediately again, with a new server */
2223 dns_scope_next_dns_server(t->scope, t->server);
2224
2225 return dns_transaction_go(t);
2226 }
2227
2228 usec_t timeout = transaction_get_resend_timeout(t);
2229 r = dns_transaction_setup_timeout(t, timeout, usec_add(ts, timeout));
2230 if (r < 0)
2231 return r;
2232
2233 return 1;
2234 }
2235
2236 static int dns_transaction_find_cyclic(DnsTransaction *t, DnsTransaction *aux) {
2237 DnsTransaction *n;
2238 int r;
2239
2240 assert(t);
2241 assert(aux);
2242
2243 /* Try to find cyclic dependencies between transaction objects */
2244
2245 if (t == aux)
2246 return 1;
2247
2248 SET_FOREACH(n, aux->dnssec_transactions) {
2249 r = dns_transaction_find_cyclic(t, n);
2250 if (r != 0)
2251 return r;
2252 }
2253
2254 return 0;
2255 }
2256
2257 static int dns_transaction_add_dnssec_transaction(DnsTransaction *t, DnsResourceKey *key, DnsTransaction **ret) {
2258 _cleanup_(dns_transaction_gcp) DnsTransaction *aux = NULL;
2259 int r;
2260
2261 assert(t);
2262 assert(ret);
2263 assert(key);
2264
2265 aux = dns_scope_find_transaction(t->scope, key, t->query_flags);
2266 if (!aux) {
2267 r = dns_transaction_new(&aux, t->scope, key, NULL, t->query_flags);
2268 if (r < 0)
2269 return r;
2270 } else {
2271 if (set_contains(t->dnssec_transactions, aux)) {
2272 *ret = aux;
2273 return 0;
2274 }
2275
2276 r = dns_transaction_find_cyclic(t, aux);
2277 if (r < 0)
2278 return r;
2279 if (r > 0) {
2280 char s[DNS_RESOURCE_KEY_STRING_MAX], saux[DNS_RESOURCE_KEY_STRING_MAX];
2281
2282 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
2283 "Potential cyclic dependency, refusing to add transaction %" PRIu16 " (%s) as dependency for %" PRIu16 " (%s).",
2284 aux->id,
2285 dns_resource_key_to_string(dns_transaction_key(t), s, sizeof s),
2286 t->id,
2287 dns_resource_key_to_string(dns_transaction_key(aux), saux, sizeof saux));
2288 }
2289 }
2290
2291 r = set_ensure_allocated(&aux->notify_transactions_done, NULL);
2292 if (r < 0)
2293 return r;
2294
2295 r = set_ensure_put(&t->dnssec_transactions, NULL, aux);
2296 if (r < 0)
2297 return r;
2298
2299 r = set_ensure_put(&aux->notify_transactions, NULL, t);
2300 if (r < 0) {
2301 (void) set_remove(t->dnssec_transactions, aux);
2302 return r;
2303 }
2304
2305 *ret = TAKE_PTR(aux);
2306 return 1;
2307 }
2308
2309 static int dns_transaction_request_dnssec_rr_full(DnsTransaction *t, DnsResourceKey *key, DnsTransaction **ret) {
2310 _cleanup_(dns_answer_unrefp) DnsAnswer *a = NULL;
2311 DnsTransaction *aux;
2312 int r;
2313
2314 assert(t);
2315 assert(key);
2316
2317 /* Try to get the data from the trust anchor */
2318 r = dns_trust_anchor_lookup_positive(&t->scope->manager->trust_anchor, key, &a);
2319 if (r < 0)
2320 return r;
2321 if (r > 0) {
2322 r = dns_answer_extend(&t->validated_keys, a);
2323 if (r < 0)
2324 return r;
2325
2326 if (ret)
2327 *ret = NULL;
2328 return 0;
2329 }
2330
2331 /* This didn't work, ask for it via the network/cache then. */
2332 r = dns_transaction_add_dnssec_transaction(t, key, &aux);
2333 if (r == -ELOOP) { /* This would result in a cyclic dependency */
2334 if (ret)
2335 *ret = NULL;
2336 return 0;
2337 }
2338 if (r < 0)
2339 return r;
2340
2341 if (aux->state == DNS_TRANSACTION_NULL) {
2342 r = dns_transaction_go(aux);
2343 if (r < 0)
2344 return r;
2345 }
2346 if (ret)
2347 *ret = aux;
2348
2349 return 1;
2350 }
2351
2352 static int dns_transaction_request_dnssec_rr(DnsTransaction *t, DnsResourceKey *key) {
2353 assert(t);
2354 assert(key);
2355 return dns_transaction_request_dnssec_rr_full(t, key, NULL);
2356 }
2357
2358 static int dns_transaction_negative_trust_anchor_lookup(DnsTransaction *t, const char *name) {
2359 int r;
2360
2361 assert(t);
2362
2363 /* Check whether the specified name is in the NTA
2364 * database, either in the global one, or the link-local
2365 * one. */
2366
2367 r = dns_trust_anchor_lookup_negative(&t->scope->manager->trust_anchor, name);
2368 if (r != 0)
2369 return r;
2370
2371 if (!t->scope->link)
2372 return 0;
2373
2374 return link_negative_trust_anchor_lookup(t->scope->link, name);
2375 }
2376
2377 static int dns_transaction_has_negative_answer(DnsTransaction *t) {
2378 int r;
2379
2380 assert(t);
2381
2382 /* Checks whether the answer is negative, and lacks NSEC/NSEC3
2383 * RRs to prove it */
2384
2385 r = dns_transaction_has_positive_answer(t, NULL);
2386 if (r < 0)
2387 return r;
2388 if (r > 0)
2389 return false;
2390
2391 /* Is this key explicitly listed as a negative trust anchor?
2392 * If so, it's nothing we need to care about */
2393 r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(dns_transaction_key(t)));
2394 if (r < 0)
2395 return r;
2396 return !r;
2397 }
2398
2399 static int dns_transaction_is_primary_response(DnsTransaction *t, DnsResourceRecord *rr) {
2400 int r;
2401
2402 assert(t);
2403 assert(rr);
2404
2405 /* Check if the specified RR is the "primary" response,
2406 * i.e. either matches the question precisely or is a
2407 * CNAME/DNAME for it. */
2408
2409 r = dns_resource_key_match_rr(dns_transaction_key(t), rr, NULL);
2410 if (r != 0)
2411 return r;
2412
2413 return dns_resource_key_match_cname_or_dname(dns_transaction_key(t), rr->key, NULL);
2414 }
2415
2416 static bool dns_transaction_dnssec_supported(DnsTransaction *t) {
2417 assert(t);
2418
2419 /* Checks whether our transaction's DNS server is assumed to be compatible with DNSSEC. Returns false as soon
2420 * as we changed our mind about a server, and now believe it is incompatible with DNSSEC. */
2421
2422 if (t->scope->protocol != DNS_PROTOCOL_DNS)
2423 return false;
2424
2425 /* If we have picked no server, then we are working from the cache or some other source, and DNSSEC might well
2426 * be supported, hence return true. */
2427 if (!t->server)
2428 return true;
2429
2430 /* Note that we do not check the feature level actually used for the transaction but instead the feature level
2431 * the server is known to support currently, as the transaction feature level might be lower than what the
2432 * server actually supports, since we might have downgraded this transaction's feature level because we got a
2433 * SERVFAIL earlier and wanted to check whether downgrading fixes it. */
2434
2435 return dns_server_dnssec_supported(t->server);
2436 }
2437
2438 static bool dns_transaction_dnssec_supported_full(DnsTransaction *t) {
2439 DnsTransaction *dt;
2440
2441 assert(t);
2442
2443 /* Checks whether our transaction our any of the auxiliary transactions couldn't do DNSSEC. */
2444
2445 if (!dns_transaction_dnssec_supported(t))
2446 return false;
2447
2448 SET_FOREACH(dt, t->dnssec_transactions)
2449 if (!dns_transaction_dnssec_supported(dt))
2450 return false;
2451
2452 return true;
2453 }
2454
2455 int dns_transaction_request_dnssec_keys(DnsTransaction *t) {
2456 DnsResourceRecord *rr;
2457
2458 /* Have we already requested a record that would be sufficient to validate an insecure delegation? */
2459 bool chased_insecure = false;
2460 int r;
2461
2462 assert(t);
2463
2464 /*
2465 * Retrieve all auxiliary RRs for the answer we got, so that
2466 * we can verify signatures or prove that RRs are rightfully
2467 * unsigned. Specifically:
2468 *
2469 * - For RRSIG we get the matching DNSKEY
2470 * - For DNSKEY we get the matching DS
2471 * - For unsigned SOA/NS we get the matching DS
2472 * - For unsigned CNAME/DNAME/DS we get the parent DS RR
2473 * - For other unsigned RRs we get the matching DS RR
2474 * - For SOA/NS queries with no matching response RR, and no NSEC/NSEC3, the DS RR
2475 * - For DS queries with no matching response RRs, and no NSEC/NSEC3, the parent's DS RR
2476 * - For other queries with no matching response RRs, and no NSEC/NSEC3, the DS RR
2477 */
2478
2479 if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) || t->scope->dnssec_mode == DNSSEC_NO)
2480 return 0;
2481 if (t->answer_source != DNS_TRANSACTION_NETWORK)
2482 return 0; /* We only need to validate stuff from the network */
2483 if (!dns_transaction_dnssec_supported(t))
2484 return 0; /* If we can't do DNSSEC anyway there's no point in getting the auxiliary RRs */
2485
2486 DNS_ANSWER_FOREACH(rr, t->answer) {
2487
2488 if (dns_type_is_pseudo(rr->key->type))
2489 continue;
2490
2491 /* If this RR is in the negative trust anchor, we don't need to validate it. */
2492 r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(rr->key));
2493 if (r < 0)
2494 return r;
2495 if (r > 0)
2496 continue;
2497
2498 switch (rr->key->type) {
2499
2500 case DNS_TYPE_RRSIG: {
2501 /* For each RRSIG we request the matching DNSKEY */
2502 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *dnskey = NULL;
2503 DnsTransaction *aux;
2504
2505 /* If this RRSIG is about a DNSKEY RR and the
2506 * signer is the same as the owner, then we
2507 * already have the DNSKEY, and we don't have
2508 * to look for more. */
2509 if (rr->rrsig.type_covered == DNS_TYPE_DNSKEY) {
2510 r = dns_name_equal(rr->rrsig.signer, dns_resource_key_name(rr->key));
2511 if (r < 0)
2512 return r;
2513 if (r > 0)
2514 continue;
2515 }
2516
2517 /* If the signer is not a parent of our
2518 * original query, then this is about an
2519 * auxiliary RRset, but not anything we asked
2520 * for. In this case we aren't interested,
2521 * because we don't want to request additional
2522 * RRs for stuff we didn't really ask for, and
2523 * also to avoid request loops, where
2524 * additional RRs from one transaction result
2525 * in another transaction whose additional RRs
2526 * point back to the original transaction, and
2527 * we deadlock. */
2528 r = dns_name_endswith(dns_resource_key_name(dns_transaction_key(t)), rr->rrsig.signer);
2529 if (r < 0)
2530 return r;
2531 if (r == 0)
2532 continue;
2533
2534 dnskey = dns_resource_key_new(rr->key->class, DNS_TYPE_DNSKEY, rr->rrsig.signer);
2535 if (!dnskey)
2536 return -ENOMEM;
2537
2538 log_debug("Requesting DNSKEY to validate transaction %" PRIu16" (%s, RRSIG with key tag: %" PRIu16 ").",
2539 t->id, dns_resource_key_name(rr->key), rr->rrsig.key_tag);
2540 r = dns_transaction_request_dnssec_rr_full(t, dnskey, &aux);
2541 if (r < 0)
2542 return r;
2543
2544 /* If we are requesting a DNSKEY, we can anticipate that we will want the matching DS
2545 * in the near future. Let's request it in advance so we don't have to wait in the
2546 * common case. */
2547 if (aux) {
2548 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds =
2549 dns_resource_key_new(rr->key->class, DNS_TYPE_DS, dns_resource_key_name(dnskey));
2550 if (!ds)
2551 return -ENOMEM;
2552 r = dns_transaction_request_dnssec_rr(t, ds);
2553 if (r < 0)
2554 return r;
2555 }
2556 break;
2557 }
2558
2559 case DNS_TYPE_DNSKEY: {
2560 /* For each DNSKEY we request the matching DS */
2561 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds = NULL;
2562
2563 /* If the DNSKEY we are looking at is not for
2564 * zone we are interested in, nor any of its
2565 * parents, we aren't interested, and don't
2566 * request it. After all, we don't want to end
2567 * up in request loops, and want to keep
2568 * additional traffic down. */
2569
2570 r = dns_name_endswith(dns_resource_key_name(dns_transaction_key(t)), dns_resource_key_name(rr->key));
2571 if (r < 0)
2572 return r;
2573 if (r == 0)
2574 continue;
2575
2576 ds = dns_resource_key_new(rr->key->class, DNS_TYPE_DS, dns_resource_key_name(rr->key));
2577 if (!ds)
2578 return -ENOMEM;
2579
2580 log_debug("Requesting DS to validate transaction %" PRIu16" (%s, DNSKEY with key tag: %" PRIu16 ").",
2581 t->id, dns_resource_key_name(rr->key), dnssec_keytag(rr, false));
2582 r = dns_transaction_request_dnssec_rr(t, ds);
2583 if (r < 0)
2584 return r;
2585
2586 break;
2587 }
2588
2589 case DNS_TYPE_SOA:
2590 case DNS_TYPE_NS: {
2591 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds = NULL;
2592
2593 /* For an unsigned SOA or NS, try to acquire
2594 * the matching DS RR, as we are at a zone cut
2595 * then, and whether a DS exists tells us
2596 * whether the zone is signed. Do so only if
2597 * this RR matches our original question,
2598 * however. */
2599
2600 r = dns_resource_key_match_rr(dns_transaction_key(t), rr, NULL);
2601 if (r < 0)
2602 return r;
2603 if (r == 0) {
2604 /* Hmm, so this SOA RR doesn't match our original question. In this case, maybe this is
2605 * a negative reply, and we need the SOA RR's TTL in order to cache a negative entry?
2606 * If so, we need to validate it, too. */
2607
2608 r = dns_answer_match_key(t->answer, dns_transaction_key(t), NULL);
2609 if (r < 0)
2610 return r;
2611 if (r > 0) /* positive reply, we won't need the SOA and hence don't need to validate
2612 * it. */
2613 continue;
2614
2615 /* Only bother with this if the SOA/NS RR we are looking at is actually a parent of
2616 * what we are looking for, otherwise there's no value in it for us. */
2617 r = dns_name_endswith(dns_resource_key_name(dns_transaction_key(t)), dns_resource_key_name(rr->key));
2618 if (r < 0)
2619 return r;
2620 if (r == 0)
2621 continue;
2622
2623 /* If we were looking for the DS RR, don't request it again. */
2624 r = dns_name_equal(dns_resource_key_name(dns_transaction_key(t)), dns_resource_key_name(rr->key));
2625 if (r < 0)
2626 return r;
2627 if (r > 0 && dns_transaction_key(t)->type == DNS_TYPE_DS)
2628 continue;
2629 }
2630
2631 r = dnssec_has_rrsig(t->answer, rr->key);
2632 if (r < 0)
2633 return r;
2634 if (r > 0)
2635 continue;
2636
2637 chased_insecure = true;
2638 ds = dns_resource_key_new(rr->key->class, DNS_TYPE_DS, dns_resource_key_name(rr->key));
2639 if (!ds)
2640 return -ENOMEM;
2641
2642 log_debug("Requesting DS to validate transaction %" PRIu16 " (%s, unsigned SOA/NS RRset).",
2643 t->id, dns_resource_key_name(rr->key));
2644 r = dns_transaction_request_dnssec_rr(t, ds);
2645 if (r < 0)
2646 return r;
2647
2648 break;
2649 }
2650
2651 case DNS_TYPE_DS:
2652 case DNS_TYPE_CNAME:
2653 case DNS_TYPE_DNAME: {
2654 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds = NULL;
2655 const char *name;
2656
2657 /* CNAMEs and DNAMEs cannot be located at a
2658 * zone apex, hence ask for the parent DS for
2659 * unsigned CNAME/DNAME RRs, maybe that's the
2660 * apex. But do all that only if this is
2661 * actually a response to our original
2662 * question.
2663 *
2664 * Similar for DS RRs, which are signed when
2665 * the parent SOA is signed. */
2666
2667 r = dns_transaction_is_primary_response(t, rr);
2668 if (r < 0)
2669 return r;
2670 if (r == 0)
2671 continue;
2672
2673 r = dnssec_has_rrsig(t->answer, rr->key);
2674 if (r < 0)
2675 return r;
2676 if (r > 0)
2677 continue;
2678
2679 r = dns_answer_has_dname_for_cname(t->answer, rr);
2680 if (r < 0)
2681 return r;
2682 if (r > 0)
2683 continue;
2684
2685 name = dns_resource_key_name(rr->key);
2686 r = dns_name_parent(&name);
2687 if (r < 0)
2688 return r;
2689 if (r == 0)
2690 continue;
2691
2692 ds = dns_resource_key_new(rr->key->class, DNS_TYPE_DS, name);
2693 if (!ds)
2694 return -ENOMEM;
2695
2696 log_debug("Requesting parent DS to validate transaction %" PRIu16 " (%s, unsigned CNAME/DNAME/DS RRset).",
2697 t->id, dns_resource_key_name(rr->key));
2698 r = dns_transaction_request_dnssec_rr(t, ds);
2699 if (r < 0)
2700 return r;
2701
2702 if (t->scope->dnssec_mode == DNSSEC_ALLOW_DOWNGRADE && dns_name_is_root(name)) {
2703 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *soa = NULL;
2704 /* We made it all the way to the root zone. If we are in allow-downgrade
2705 * mode, we need to make at least one request that we can be certain should
2706 * have been signed, to test for servers that are not dnssec aware. */
2707 soa = dns_resource_key_new(rr->key->class, DNS_TYPE_SOA, name);
2708 if (!soa)
2709 return -ENOMEM;
2710
2711 log_debug("Requesting root zone SOA to probe dnssec support.");
2712 r = dns_transaction_request_dnssec_rr(t, soa);
2713 if (r < 0)
2714 return r;
2715 }
2716
2717 break;
2718 }
2719
2720 default: {
2721 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds = NULL;
2722
2723 /* For other unsigned RRsets (including
2724 * NSEC/NSEC3!), look for proof the zone is
2725 * unsigned, by requesting the DS RR of the
2726 * zone. However, do so only if they are
2727 * directly relevant to our original
2728 * question. */
2729
2730 r = dns_transaction_is_primary_response(t, rr);
2731 if (r < 0)
2732 return r;
2733 if (r == 0)
2734 continue;
2735
2736 r = dnssec_has_rrsig(t->answer, rr->key);
2737 if (r < 0)
2738 return r;
2739 if (r > 0)
2740 continue;
2741
2742 ds = dns_resource_key_new(rr->key->class, DNS_TYPE_DS, dns_resource_key_name(rr->key));
2743 if (!ds)
2744 return -ENOMEM;
2745
2746 log_debug("Requesting DS to validate transaction %" PRIu16 " (%s, unsigned non-SOA/NS RRset <%s>).",
2747 t->id, dns_resource_key_name(rr->key), dns_resource_record_to_string(rr));
2748 r = dns_transaction_request_dnssec_rr(t, ds);
2749 if (r < 0)
2750 return r;
2751 break;
2752 }}
2753 }
2754
2755 /* Above, we requested everything necessary to validate what
2756 * we got. Now, let's request what we need to validate what we
2757 * didn't get... */
2758
2759 r = dns_transaction_has_negative_answer(t);
2760 if (r < 0)
2761 return r;
2762 if (r > 0) {
2763 const char *name = dns_resource_key_name(dns_transaction_key(t));
2764 bool was_signed = dns_answer_contains_nsec_or_nsec3(t->answer);
2765
2766 /* If the response is empty, seek the DS for this name, just in case we're at a zone cut
2767 * already, unless we just requested the DS, in which case we have to ask the parent to make
2768 * progress.
2769 *
2770 * If this was an SOA or NS request, we could also skip to the parent, but in real world
2771 * setups there are too many broken DNS servers (Hello, incapdns.net!) where non-terminal
2772 * zones return NXDOMAIN even though they have further children. */
2773
2774 if (chased_insecure || was_signed)
2775 /* In this case we already requested what we need above. */
2776 name = NULL;
2777 else if (dns_transaction_key(t)->type == DNS_TYPE_DS)
2778 /* If the DS response is empty, we'll walk up the dns labels requesting DS until we
2779 * find a referral to the SOA or hit it anyway and get a positive DS response. */
2780 if (dns_name_parent(&name) <= 0)
2781 name = NULL;
2782
2783 if (name) {
2784 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *ds = NULL;
2785
2786 log_debug("Requesting DS (%s %s) to validate transaction %" PRIu16 " (%s empty response).",
2787 glyph(GLYPH_ARROW_RIGHT), name, t->id,
2788 dns_resource_key_name(dns_transaction_key(t)));
2789
2790 ds = dns_resource_key_new(dns_transaction_key(t)->class, DNS_TYPE_DS, name);
2791 if (!ds)
2792 return -ENOMEM;
2793
2794 r = dns_transaction_request_dnssec_rr(t, ds);
2795 if (r < 0)
2796 return r;
2797 }
2798 }
2799
2800 return dns_transaction_dnssec_is_live(t);
2801 }
2802
2803 DnsResourceKey* dns_transaction_key(DnsTransaction *t) {
2804 assert(t);
2805
2806 /* Return the lookup key of this transaction. Either takes the lookup key from the bypass packet if
2807 * we are a bypass transaction. Or take the configured key for regular transactions. */
2808
2809 if (t->key)
2810 return t->key;
2811
2812 assert(t->bypass);
2813
2814 return dns_question_first_key(t->bypass->question);
2815 }
2816
2817 void dns_transaction_notify(DnsTransaction *t, DnsTransaction *source) {
2818 assert(t);
2819 assert(source);
2820
2821 /* Invoked whenever any of our auxiliary DNSSEC transactions completed its work. If the state is still PENDING,
2822 we are still in the loop that adds further DNSSEC transactions, hence don't check if we are ready yet. If
2823 the state is VALIDATING however, we should check if we are complete now. */
2824
2825 if (t->state == DNS_TRANSACTION_VALIDATING)
2826 dns_transaction_process_dnssec(t);
2827 }
2828
2829 static int dns_transaction_validate_dnskey_by_ds(DnsTransaction *t) {
2830 DnsAnswerItem *item;
2831 int r;
2832
2833 assert(t);
2834
2835 /* Add all DNSKEY RRs from the answer that are validated by DS
2836 * RRs from the list of validated keys to the list of
2837 * validated keys. */
2838
2839 DNS_ANSWER_FOREACH_ITEM(item, t->answer) {
2840
2841 r = dnssec_verify_dnskey_by_ds_search(item->rr, t->validated_keys);
2842 if (r < 0 && r != -EOPNOTSUPP)
2843 return r;
2844 if (r == 0)
2845 continue;
2846
2847 /* If so, the DNSKEY is validated too, but only mark it authenticated if the DS verification
2848 * succeeded with a known algorithm. */
2849 if (r == -EOPNOTSUPP)
2850 r = dns_answer_add_extend(&t->validated_keys, item->rr, item->ifindex, item->flags, NULL);
2851 else
2852 r = dns_answer_add_extend(&t->validated_keys, item->rr, item->ifindex, item->flags|DNS_ANSWER_AUTHENTICATED, item->rrsig);
2853
2854 if (r < 0)
2855 return r;
2856 }
2857
2858 return 0;
2859 }
2860
2861 static int dns_transaction_requires_rrsig(DnsTransaction *t, DnsResourceRecord *rr) {
2862 int r;
2863
2864 assert(t);
2865 assert(rr);
2866
2867 /* Checks if the RR we are looking for must be signed with an
2868 * RRSIG. This is used for positive responses. */
2869
2870 if (t->scope->dnssec_mode == DNSSEC_NO)
2871 return false;
2872
2873 if (dns_type_is_pseudo(rr->key->type))
2874 return -EINVAL;
2875
2876 r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(rr->key));
2877 if (r < 0)
2878 return r;
2879 if (r > 0)
2880 return false;
2881
2882 switch (rr->key->type) {
2883
2884 case DNS_TYPE_RRSIG:
2885 /* RRSIGs are the signatures themselves, they need no signing. */
2886 return false;
2887
2888 case DNS_TYPE_SOA:
2889 case DNS_TYPE_NS: {
2890 DnsTransaction *dt;
2891
2892 /* For SOA or NS RRs we look for a matching DS transaction */
2893 SET_FOREACH(dt, t->dnssec_transactions) {
2894
2895 if (dns_transaction_key(dt)->class != rr->key->class)
2896 continue;
2897 if (dns_transaction_key(dt)->type != DNS_TYPE_DS)
2898 continue;
2899
2900 r = dns_name_endswith(dns_resource_key_name(rr->key), dns_resource_key_name(dns_transaction_key(dt)));
2901 if (r < 0)
2902 return r;
2903 if (r == 0)
2904 continue;
2905
2906 /* We found a DS transactions for the SOA/NS
2907 * RRs we are looking at. If it discovered signed DS
2908 * RRs, then we need to be signed, too. */
2909
2910 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
2911 return false;
2912
2913 return dns_answer_match_key(dt->answer, dns_transaction_key(dt), NULL);
2914 }
2915
2916 /* We found nothing that proves this is safe to leave
2917 * this unauthenticated, hence ask inist on
2918 * authentication. */
2919 return true;
2920 }
2921
2922 case DNS_TYPE_DS:
2923 case DNS_TYPE_CNAME:
2924 case DNS_TYPE_DNAME: {
2925 const char *parent = NULL;
2926 DnsTransaction *dt;
2927
2928 /*
2929 * CNAME/DNAME RRs cannot be located at a zone apex, hence look directly for the parent DS.
2930 *
2931 * DS RRs are signed if the parent is signed, hence also look at the parent DS
2932 */
2933
2934 SET_FOREACH(dt, t->dnssec_transactions) {
2935
2936 if (dns_transaction_key(dt)->class != rr->key->class)
2937 continue;
2938 if (dns_transaction_key(dt)->type != DNS_TYPE_DS)
2939 continue;
2940
2941 if (!parent) {
2942 parent = dns_resource_key_name(rr->key);
2943 r = dns_name_parent(&parent);
2944 if (r < 0)
2945 return r;
2946 if (r == 0) {
2947 if (rr->key->type == DNS_TYPE_DS)
2948 return true;
2949
2950 /* A CNAME/DNAME without a parent? That's sooo weird. */
2951 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2952 "Transaction %" PRIu16 " claims CNAME/DNAME at root. Refusing.", t->id);
2953 }
2954 }
2955
2956 r = dns_name_endswith(parent, dns_resource_key_name(dns_transaction_key(dt)));
2957 if (r < 0)
2958 return r;
2959 if (r == 0)
2960 continue;
2961
2962 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
2963 return false;
2964
2965 /* We expect this to be signed when the DS record exists, and don't expect it to be
2966 * signed when the DS record is proven not to exist. */
2967 return dns_answer_match_key(dt->answer, dns_transaction_key(dt), NULL);
2968 }
2969
2970 return true;
2971 }
2972
2973 default: {
2974 DnsTransaction *dt;
2975
2976 /* Any other kind of RR (including DNSKEY/NSEC/NSEC3). Let's see if our DS lookup was authenticated */
2977
2978 SET_FOREACH(dt, t->dnssec_transactions) {
2979 if (dns_transaction_key(dt)->class != rr->key->class)
2980 continue;
2981 if (dns_transaction_key(dt)->type != DNS_TYPE_DS)
2982 continue;
2983
2984 r = dns_name_endswith(dns_resource_key_name(rr->key), dns_resource_key_name(dns_transaction_key(dt)));
2985 if (r < 0)
2986 return r;
2987 if (r == 0)
2988 continue;
2989
2990 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
2991 return false;
2992
2993 /* We expect this to be signed when the DS record exists, and don't expect it to be
2994 * signed when the DS record is proven not to exist. */
2995 return dns_answer_match_key(dt->answer, dns_transaction_key(dt), NULL);
2996 }
2997
2998 return true;
2999 }}
3000 }
3001
3002 static int dns_transaction_in_private_tld(DnsTransaction *t, const DnsResourceKey *key) {
3003 DnsTransaction *dt;
3004 const char *tld;
3005 int r;
3006
3007 /* If DNSSEC downgrade mode is on, checks whether the
3008 * specified RR is one level below a TLD we have proven not to
3009 * exist. In such a case we assume that this is a private
3010 * domain, and permit it.
3011 *
3012 * This detects cases like the Fritz!Box router networks. Each
3013 * Fritz!Box router serves a private "fritz.box" zone, in the
3014 * non-existing TLD "box". Requests for the "fritz.box" domain
3015 * are served by the router itself, while requests for the
3016 * "box" domain will result in NXDOMAIN.
3017 *
3018 * Note that this logic is unable to detect cases where a
3019 * router serves a private DNS zone directly under
3020 * non-existing TLD. In such a case we cannot detect whether
3021 * the TLD is supposed to exist or not, as all requests we
3022 * make for it will be answered by the router's zone, and not
3023 * by the root zone. */
3024
3025 assert(t);
3026
3027 if (t->scope->dnssec_mode != DNSSEC_ALLOW_DOWNGRADE)
3028 return false; /* In strict DNSSEC mode what doesn't exist, doesn't exist */
3029
3030 tld = dns_resource_key_name(key);
3031 r = dns_name_parent(&tld);
3032 if (r < 0)
3033 return r;
3034 if (r == 0)
3035 return false; /* Already the root domain */
3036
3037 if (!dns_name_is_single_label(tld))
3038 return false;
3039
3040 SET_FOREACH(dt, t->dnssec_transactions) {
3041
3042 if (dns_transaction_key(dt)->class != key->class)
3043 continue;
3044
3045 r = dns_name_equal(dns_resource_key_name(dns_transaction_key(dt)), tld);
3046 if (r < 0)
3047 return r;
3048 if (r == 0)
3049 continue;
3050
3051 /* We found an auxiliary lookup we did for the TLD. If
3052 * that returned with NXDOMAIN, we know the TLD didn't
3053 * exist, and hence this might be a private zone. */
3054
3055 return dt->answer_rcode == DNS_RCODE_NXDOMAIN;
3056 }
3057
3058 return false;
3059 }
3060
3061 static int dns_transaction_requires_nsec(DnsTransaction *t) {
3062 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
3063 DnsTransaction *dt;
3064 const char *name;
3065 int r;
3066
3067 assert(t);
3068
3069 /* Checks if we need to insist on NSEC/NSEC3 RRs for proving
3070 * this negative reply */
3071
3072 if (t->scope->dnssec_mode == DNSSEC_NO)
3073 return false;
3074
3075 if (dns_type_is_pseudo(dns_transaction_key(t)->type))
3076 return -EINVAL;
3077
3078 r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(dns_transaction_key(t)));
3079 if (r < 0)
3080 return r;
3081 if (r > 0)
3082 return false;
3083
3084 r = dns_transaction_in_private_tld(t, dns_transaction_key(t));
3085 if (r < 0)
3086 return r;
3087 if (r > 0) {
3088 /* The lookup is from a TLD that is proven not to
3089 * exist, and we are in downgrade mode, hence ignore
3090 * that fact that we didn't get any NSEC RRs. */
3091
3092 log_info("Detected a negative query %s in a private DNS zone, permitting unsigned response.",
3093 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str));
3094 return false;
3095 }
3096
3097 name = dns_resource_key_name(dns_transaction_key(t));
3098
3099 /* For all other RRs we check the DS on the same level to see
3100 * if it's signed. */
3101
3102 SET_FOREACH(dt, t->dnssec_transactions) {
3103 if (dns_transaction_key(dt)->class != dns_transaction_key(t)->class)
3104 continue;
3105 if (dns_transaction_key(dt)->type != DNS_TYPE_DS)
3106 continue;
3107
3108 r = dns_name_endswith(name, dns_resource_key_name(dns_transaction_key(dt)));
3109 if (r < 0)
3110 return r;
3111 if (r == 0)
3112 continue;
3113
3114 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
3115 return false;
3116
3117 /* We expect this to be signed when the DS record exists, and don't expect it to be signed
3118 * when the DS record is proven not to exist. */
3119 return dns_answer_match_key(dt->answer, dns_transaction_key(dt), NULL);
3120 }
3121
3122 /* If in doubt, require NSEC/NSEC3 */
3123 return true;
3124 }
3125
3126 static int dns_transaction_dnskey_authenticated(DnsTransaction *t, DnsResourceRecord *rr) {
3127 DnsResourceRecord *rrsig;
3128 bool found = false;
3129 int r;
3130
3131 /* Checks whether any of the DNSKEYs used for the RRSIGs for
3132 * the specified RRset is authenticated (i.e. has a matching
3133 * DS RR). */
3134
3135 r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(rr->key));
3136 if (r < 0)
3137 return r;
3138 if (r > 0)
3139 return false;
3140
3141 DNS_ANSWER_FOREACH(rrsig, t->answer) {
3142 DnsTransaction *dt;
3143
3144 r = dnssec_key_match_rrsig(rr->key, rrsig);
3145 if (r < 0)
3146 return r;
3147 if (r == 0)
3148 continue;
3149
3150 SET_FOREACH(dt, t->dnssec_transactions) {
3151
3152 if (dns_transaction_key(dt)->class != rr->key->class)
3153 continue;
3154
3155 if (dns_transaction_key(dt)->type == DNS_TYPE_DNSKEY) {
3156
3157 r = dns_name_equal(dns_resource_key_name(dns_transaction_key(dt)), rrsig->rrsig.signer);
3158 if (r < 0)
3159 return r;
3160 if (r == 0)
3161 continue;
3162
3163 /* OK, we found an auxiliary DNSKEY lookup. If that lookup is authenticated,
3164 * report this. */
3165
3166 if (FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
3167 return true;
3168
3169 found = true;
3170
3171 } else if (dns_transaction_key(dt)->type == DNS_TYPE_DS) {
3172
3173 r = dns_name_equal(dns_resource_key_name(dns_transaction_key(dt)), rrsig->rrsig.signer);
3174 if (r < 0)
3175 return r;
3176 if (r == 0)
3177 continue;
3178
3179 /* OK, we found an auxiliary DS lookup. If that lookup is authenticated and
3180 * non-zero, we won! */
3181
3182 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
3183 return false;
3184
3185 return dns_answer_match_key(dt->answer, dns_transaction_key(dt), NULL);
3186 }
3187 }
3188 }
3189
3190 return found ? false : -ENXIO;
3191 }
3192
3193 static int dns_transaction_known_signed(DnsTransaction *t, DnsResourceRecord *rr) {
3194 assert(t);
3195 assert(rr);
3196
3197 /* We know that the root domain is signed, hence if it appears
3198 * not to be signed, there's a problem with the DNS server */
3199
3200 return rr->key->class == DNS_CLASS_IN &&
3201 dns_name_is_root(dns_resource_key_name(rr->key));
3202 }
3203
3204 static int dns_transaction_check_revoked_trust_anchors(DnsTransaction *t) {
3205 DnsResourceRecord *rr;
3206 int r;
3207
3208 assert(t);
3209
3210 /* Maybe warn the user that we encountered a revoked DNSKEY
3211 * for a key from our trust anchor. Note that we don't care
3212 * whether the DNSKEY can be authenticated or not. It's
3213 * sufficient if it is self-signed. */
3214
3215 DNS_ANSWER_FOREACH(rr, t->answer) {
3216 r = dns_trust_anchor_check_revoked(&t->scope->manager->trust_anchor, rr, t->answer);
3217 if (r < 0)
3218 return r;
3219 }
3220
3221 return 0;
3222 }
3223
3224 static int dns_transaction_invalidate_revoked_keys(DnsTransaction *t) {
3225 bool changed;
3226 int r;
3227
3228 assert(t);
3229
3230 /* Removes all DNSKEY/DS objects from t->validated_keys that
3231 * our trust anchors database considers revoked. */
3232
3233 do {
3234 DnsResourceRecord *rr;
3235
3236 changed = false;
3237
3238 DNS_ANSWER_FOREACH(rr, t->validated_keys) {
3239 r = dns_trust_anchor_is_revoked(&t->scope->manager->trust_anchor, rr);
3240 if (r < 0)
3241 return r;
3242 if (r > 0) {
3243 r = dns_answer_remove_by_rr(&t->validated_keys, rr);
3244 if (r < 0)
3245 return r;
3246
3247 assert(r > 0);
3248 changed = true;
3249 break;
3250 }
3251 }
3252 } while (changed);
3253
3254 return 0;
3255 }
3256
3257 static int dns_transaction_copy_validated(DnsTransaction *t) {
3258 DnsTransaction *dt;
3259 int r;
3260
3261 assert(t);
3262
3263 /* Copy all validated RRs from the auxiliary DNSSEC transactions into our set of validated RRs */
3264
3265 SET_FOREACH(dt, t->dnssec_transactions) {
3266
3267 if (DNS_TRANSACTION_IS_LIVE(dt->state))
3268 continue;
3269
3270 /* Some of the validated keys may not be authenticated, but are still useful to report
3271 * insecure answers when the domain is signed only by unsupported algorithms. */
3272 r = dns_answer_extend(&t->validated_keys, dt->validated_keys);
3273 if (r < 0)
3274 return r;
3275
3276 if (!FLAGS_SET(dt->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
3277 continue;
3278
3279 r = dns_answer_extend(&t->validated_keys, dt->answer);
3280 if (r < 0)
3281 return r;
3282 }
3283
3284 return 0;
3285 }
3286
3287 typedef enum {
3288 DNSSEC_PHASE_DNSKEY, /* Phase #1, only validate DNSKEYs */
3289 DNSSEC_PHASE_NSEC, /* Phase #2, only validate NSEC+NSEC3 */
3290 DNSSEC_PHASE_ALL, /* Phase #3, validate everything else */
3291 } Phase;
3292
3293 static int dnssec_validate_records(
3294 DnsTransaction *t,
3295 Phase phase,
3296 bool *have_nsec,
3297 unsigned *nvalidations,
3298 DnsAnswer **validated) {
3299
3300 DnsResourceRecord *rr;
3301 int r;
3302
3303 assert(have_nsec);
3304 assert(nvalidations);
3305 assert(validated);
3306
3307 /* Returns negative on error, 0 if validation failed, 1 to restart validation, 2 when finished. */
3308
3309 DNS_ANSWER_FOREACH(rr, t->answer) {
3310 _unused_ _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr_ref = dns_resource_record_ref(rr);
3311 DnsResourceRecord *rrsig = NULL;
3312 DnssecResult result;
3313
3314 switch (rr->key->type) {
3315 case DNS_TYPE_RRSIG:
3316 continue;
3317
3318 case DNS_TYPE_DNSKEY:
3319 /* We validate DNSKEYs only in the DNSKEY and ALL phases */
3320 if (phase == DNSSEC_PHASE_NSEC)
3321 continue;
3322 break;
3323
3324 case DNS_TYPE_NSEC:
3325 case DNS_TYPE_NSEC3:
3326 *have_nsec = true;
3327
3328 /* We validate NSEC/NSEC3 only in the NSEC and ALL phases */
3329 if (phase == DNSSEC_PHASE_DNSKEY)
3330 continue;
3331 break;
3332
3333 default:
3334 /* We validate all other RRs only in the ALL phases */
3335 if (phase != DNSSEC_PHASE_ALL)
3336 continue;
3337 }
3338
3339 r = dnssec_verify_rrset_search(
3340 t->answer,
3341 rr->key,
3342 t->validated_keys,
3343 USEC_INFINITY,
3344 &result,
3345 &rrsig);
3346 if (r < 0)
3347 return r;
3348 *nvalidations += r;
3349
3350 log_debug("Looking at %s: %s", strna(dns_resource_record_to_string(rr)), dnssec_result_to_string(result));
3351
3352 if (result == DNSSEC_VALIDATED) {
3353 assert(rrsig);
3354
3355 if (rr->key->type == DNS_TYPE_DNSKEY) {
3356 /* If we just validated a DNSKEY RRset, then let's add these keys to
3357 * the set of validated keys for this transaction. */
3358
3359 r = dns_answer_copy_by_key(&t->validated_keys, t->answer, rr->key, DNS_ANSWER_AUTHENTICATED, rrsig);
3360 if (r < 0)
3361 return r;
3362
3363 /* Some of the DNSKEYs we just added might already have been revoked,
3364 * remove them again in that case. */
3365 r = dns_transaction_invalidate_revoked_keys(t);
3366 if (r < 0)
3367 return r;
3368 }
3369
3370 /* Add the validated RRset to the new list of validated RRsets, and remove it from
3371 * the unvalidated RRsets. We mark the RRset as authenticated and cacheable. */
3372 r = dns_answer_move_by_key(validated, &t->answer, rr->key, DNS_ANSWER_AUTHENTICATED|DNS_ANSWER_CACHEABLE, rrsig);
3373 if (r < 0)
3374 return r;
3375
3376 manager_dnssec_verdict(t->scope->manager, DNSSEC_SECURE, rr->key);
3377
3378 /* Exit the loop, we dropped something from the answer, start from the beginning */
3379 return 1;
3380 }
3381
3382 /* If we haven't read all DNSKEYs yet a negative result of the validation is irrelevant, as
3383 * there might be more DNSKEYs coming. Similar, if we haven't read all NSEC/NSEC3 RRs yet,
3384 * we cannot do positive wildcard proofs yet, as those require the NSEC/NSEC3 RRs. */
3385 if (phase != DNSSEC_PHASE_ALL)
3386 continue;
3387
3388 if (result == DNSSEC_VALIDATED_WILDCARD) {
3389 bool authenticated = false;
3390 const char *source;
3391
3392 assert(rrsig);
3393
3394 /* This RRset validated, but as a wildcard. This means we need
3395 * to prove via NSEC/NSEC3 that no matching non-wildcard RR exists. */
3396
3397 /* First step, determine the source of synthesis */
3398 r = dns_resource_record_source(rrsig, &source);
3399 if (r < 0)
3400 return r;
3401
3402 r = dnssec_test_positive_wildcard(*validated,
3403 dns_resource_key_name(rr->key),
3404 source,
3405 rrsig->rrsig.signer,
3406 &authenticated);
3407
3408 /* Unless the NSEC proof showed that the key really doesn't exist something is off. */
3409 if (r == 0)
3410 result = DNSSEC_INVALID;
3411 else {
3412 r = dns_answer_move_by_key(
3413 validated,
3414 &t->answer,
3415 rr->key,
3416 authenticated ? (DNS_ANSWER_AUTHENTICATED|DNS_ANSWER_CACHEABLE) : 0,
3417 rrsig);
3418 if (r < 0)
3419 return r;
3420
3421 manager_dnssec_verdict(t->scope->manager, authenticated ? DNSSEC_SECURE : DNSSEC_INSECURE, rr->key);
3422
3423 /* Exit the loop, we dropped something from the answer, start from the beginning */
3424 return 1;
3425 }
3426 }
3427
3428 if (result == DNSSEC_NO_SIGNATURE) {
3429 r = dns_transaction_requires_rrsig(t, rr);
3430 if (r < 0)
3431 return r;
3432 if (r == 0) {
3433 /* Data does not require signing. In that case, just copy it over,
3434 * but remember that this is by no means authenticated. */
3435 r = dns_answer_move_by_key(
3436 validated,
3437 &t->answer,
3438 rr->key,
3439 0,
3440 NULL);
3441 if (r < 0)
3442 return r;
3443
3444 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, rr->key);
3445 return 1;
3446 }
3447
3448 r = dns_transaction_known_signed(t, rr);
3449 if (r < 0)
3450 return r;
3451 if (r > 0) {
3452 /* This is an RR we know has to be signed. If it isn't this means
3453 * the server is not attaching RRSIGs, hence complain. */
3454
3455 dns_server_packet_rrsig_missing(t->server, t->current_feature_level);
3456
3457 if (t->scope->dnssec_mode == DNSSEC_ALLOW_DOWNGRADE) {
3458
3459 /* Downgrading is OK? If so, just consider the information unsigned */
3460
3461 r = dns_answer_move_by_key(validated, &t->answer, rr->key, 0, NULL);
3462 if (r < 0)
3463 return r;
3464
3465 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, rr->key);
3466 return 1;
3467 }
3468
3469 /* Otherwise, fail */
3470 t->answer_dnssec_result = DNSSEC_INCOMPATIBLE_SERVER;
3471 return 0;
3472 }
3473
3474 r = dns_transaction_in_private_tld(t, rr->key);
3475 if (r < 0)
3476 return r;
3477 if (r > 0) {
3478 char s[DNS_RESOURCE_KEY_STRING_MAX];
3479
3480 /* The data is from a TLD that is proven not to exist, and we are in downgrade
3481 * mode, hence ignore the fact that this was not signed. */
3482
3483 log_info("Detected RRset %s is in a private DNS zone, permitting unsigned RRs.",
3484 dns_resource_key_to_string(rr->key, s, sizeof s));
3485
3486 r = dns_answer_move_by_key(validated, &t->answer, rr->key, 0, NULL);
3487 if (r < 0)
3488 return r;
3489
3490 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, rr->key);
3491 return 1;
3492 }
3493 }
3494
3495 /* https://datatracker.ietf.org/doc/html/rfc6840#section-5.2 */
3496 if (result == DNSSEC_UNSUPPORTED_ALGORITHM) {
3497 if (rr->key->type == DNS_TYPE_DNSKEY) {
3498 /* This is a DNSKEY we cannot authenticate, but it might still be the best
3499 * offer from the resolver. Add it to the validated keys in case it's the
3500 * best we can find, but do not mark it as authenticated.
3501 */
3502
3503 r = dns_answer_copy_by_key(&t->validated_keys, t->answer, rr->key, 0, NULL);
3504 if (r < 0)
3505 return r;
3506
3507 /* Some of the DNSKEYs we just added might already have been revoked,
3508 * remove them again in that case. */
3509 r = dns_transaction_invalidate_revoked_keys(t);
3510 if (r < 0)
3511 return r;
3512 }
3513
3514 r = dns_answer_move_by_key(validated, &t->answer, rr->key, 0, NULL);
3515 if (r < 0)
3516 return r;
3517
3518 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, rr->key);
3519 return 1;
3520 }
3521
3522 if (IN_SET(result,
3523 DNSSEC_MISSING_KEY,
3524 DNSSEC_SIGNATURE_EXPIRED)) {
3525
3526 r = dns_transaction_dnskey_authenticated(t, rr);
3527 if (r < 0 && r != -ENXIO)
3528 return r;
3529 if (r == 0) {
3530 /* The DNSKEY transaction was not authenticated, this means there's
3531 * no DS for this, which means it's OK if no keys are found for this signature. */
3532
3533 r = dns_answer_move_by_key(validated, &t->answer, rr->key, 0, NULL);
3534 if (r < 0)
3535 return r;
3536
3537 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, rr->key);
3538 return 1;
3539 }
3540 }
3541
3542 r = dns_transaction_is_primary_response(t, rr);
3543 if (r < 0)
3544 return r;
3545 if (r > 0) {
3546 /* Look for a matching DNAME for this CNAME */
3547 r = dns_answer_has_dname_for_cname(t->answer, rr);
3548 if (r < 0)
3549 return r;
3550 if (r == 0) {
3551 /* Also look among the stuff we already validated */
3552 r = dns_answer_has_dname_for_cname(*validated, rr);
3553 if (r < 0)
3554 return r;
3555 }
3556
3557 if (r == 0) {
3558 if (IN_SET(result,
3559 DNSSEC_INVALID,
3560 DNSSEC_SIGNATURE_EXPIRED,
3561 DNSSEC_NO_SIGNATURE))
3562 manager_dnssec_verdict(t->scope->manager, DNSSEC_BOGUS, rr->key);
3563 else /* DNSSEC_MISSING_KEY, DNSSEC_UNSUPPORTED_ALGORITHM,
3564 or DNSSEC_TOO_MANY_VALIDATIONS */
3565 manager_dnssec_verdict(t->scope->manager, DNSSEC_INDETERMINATE, rr->key);
3566
3567 /* This is a primary response to our question, and it failed validation.
3568 * That's fatal. */
3569 t->answer_dnssec_result = result;
3570 return 0;
3571 }
3572
3573 /* This is a primary response, but we do have a DNAME RR
3574 * in the RR that can replay this CNAME, hence rely on
3575 * that, and we can remove the CNAME in favour of it. */
3576 }
3577
3578 /* This is just some auxiliary data. Just remove the RRset and continue. */
3579 r = dns_answer_remove_by_key(&t->answer, rr->key);
3580 if (r < 0)
3581 return r;
3582
3583 /* We dropped something from the answer, start from the beginning. */
3584 return 1;
3585 }
3586
3587 return 2; /* Finito. */
3588 }
3589
3590 int dns_transaction_validate_dnssec(DnsTransaction *t) {
3591 _cleanup_(dns_answer_unrefp) DnsAnswer *validated = NULL;
3592 Phase phase;
3593 DnsAnswerFlags flags;
3594 int r;
3595 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
3596
3597 assert(t);
3598
3599 /* We have now collected all DS and DNSKEY RRs in t->validated_keys, let's see which RRs we can now
3600 * authenticate with that. */
3601
3602 if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) || t->scope->dnssec_mode == DNSSEC_NO)
3603 return 0;
3604
3605 /* Already validated */
3606 if (t->answer_dnssec_result != _DNSSEC_RESULT_INVALID)
3607 return 0;
3608
3609 /* Our own stuff needs no validation */
3610 if (IN_SET(t->answer_source, DNS_TRANSACTION_ZONE, DNS_TRANSACTION_TRUST_ANCHOR)) {
3611 t->answer_dnssec_result = DNSSEC_VALIDATED;
3612 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, true);
3613 return 0;
3614 }
3615
3616 /* Cached stuff is not affected by validation. */
3617 if (t->answer_source != DNS_TRANSACTION_NETWORK)
3618 return 0;
3619
3620 if (!dns_transaction_dnssec_supported_full(t)) {
3621 /* The server does not support DNSSEC, or doesn't augment responses with RRSIGs. */
3622 t->answer_dnssec_result = DNSSEC_INCOMPATIBLE_SERVER;
3623 log_debug("Not validating response for %" PRIu16 ", used server feature level does not support DNSSEC.", t->id);
3624 return 0;
3625 }
3626
3627 log_debug("Validating response from transaction %" PRIu16 " (%s).",
3628 t->id,
3629 dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str));
3630
3631 /* First, see if this response contains any revoked trust anchors we care about. */
3632 r = dns_transaction_check_revoked_trust_anchors(t);
3633 if (r < 0)
3634 return r;
3635
3636 /* Second, copy all RRs we acquired successfully from auxiliary RRs over. */
3637 r = dns_transaction_copy_validated(t);
3638 if (r < 0)
3639 return r;
3640
3641 /* Third, see if there are DNSKEYs we already know a validated DS for. */
3642 r = dns_transaction_validate_dnskey_by_ds(t);
3643 if (r < 0)
3644 return r;
3645
3646 /* Fourth, remove all DNSKEY and DS RRs again that our trust anchor says are revoked. After all we
3647 * might have marked some keys revoked above, but they might still be lingering in our validated_keys
3648 * list. */
3649 r = dns_transaction_invalidate_revoked_keys(t);
3650 if (r < 0)
3651 return r;
3652
3653 phase = DNSSEC_PHASE_DNSKEY;
3654 for (unsigned nvalidations = 0;;) {
3655 bool have_nsec = false;
3656
3657 r = dnssec_validate_records(t, phase, &have_nsec, &nvalidations, &validated);
3658 if (r <= 0) {
3659 DNS_ANSWER_REPLACE(t->answer, TAKE_PTR(validated));
3660 return r;
3661 }
3662
3663 if (nvalidations > DNSSEC_VALIDATION_MAX) {
3664 /* This reply requires an onerous number of signature validations to verify. Let's
3665 * not waste our time trying, as this shouldn't happen for well-behaved domains
3666 * anyway. */
3667 t->answer_dnssec_result = DNSSEC_TOO_MANY_VALIDATIONS;
3668 DNS_ANSWER_REPLACE(t->answer, TAKE_PTR(validated));
3669 return 0;
3670 }
3671
3672 /* Try again as long as we managed to achieve something */
3673 if (r == 1)
3674 continue;
3675
3676 if (phase == DNSSEC_PHASE_DNSKEY && have_nsec) {
3677 /* OK, we processed all DNSKEYs, and there are NSEC/NSEC3 RRs, look at those now. */
3678 phase = DNSSEC_PHASE_NSEC;
3679 continue;
3680 }
3681
3682 if (phase != DNSSEC_PHASE_ALL) {
3683 /* OK, we processed all DNSKEYs and NSEC/NSEC3 RRs, look at all the rest now.
3684 * Note that in this third phase we start to remove RRs we couldn't validate. */
3685 phase = DNSSEC_PHASE_ALL;
3686 continue;
3687 }
3688
3689 /* We're done */
3690 break;
3691 }
3692
3693 DNS_ANSWER_REPLACE(t->answer, TAKE_PTR(validated));
3694
3695 /* At this point the answer only contains validated
3696 * RRsets. Now, let's see if it actually answers the question
3697 * we asked. If so, great! If it doesn't, then see if
3698 * NSEC/NSEC3 can prove this. */
3699 r = dns_transaction_has_positive_answer(t, &flags);
3700 if (r > 0) {
3701 /* Yes, it answers the question! */
3702
3703 if (flags & DNS_ANSWER_AUTHENTICATED) {
3704 /* The answer is fully authenticated, yay. */
3705 t->answer_dnssec_result = DNSSEC_VALIDATED;
3706 t->answer_rcode = DNS_RCODE_SUCCESS;
3707 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, true);
3708 } else {
3709 /* The answer is not fully authenticated. */
3710 t->answer_dnssec_result = DNSSEC_UNSIGNED;
3711 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
3712 }
3713
3714 } else if (r == 0) {
3715 DnssecNsecResult nr;
3716 bool authenticated = false;
3717
3718 /* Bummer! Let's check NSEC/NSEC3 */
3719 r = dnssec_nsec_test(t->answer, dns_transaction_key(t), &nr, &authenticated, &t->answer_nsec_ttl);
3720 if (r < 0)
3721 return r;
3722
3723 switch (nr) {
3724
3725 case DNSSEC_NSEC_NXDOMAIN:
3726 /* NSEC proves the domain doesn't exist. Very good. */
3727 log_debug("Proved NXDOMAIN via NSEC/NSEC3 for transaction %u (%s)", t->id, key_str);
3728 t->answer_dnssec_result = DNSSEC_VALIDATED;
3729 t->answer_rcode = DNS_RCODE_NXDOMAIN;
3730 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, authenticated);
3731
3732 manager_dnssec_verdict(t->scope->manager, authenticated ? DNSSEC_SECURE : DNSSEC_INSECURE, dns_transaction_key(t));
3733 break;
3734
3735 case DNSSEC_NSEC_NODATA:
3736 /* NSEC proves that there's no data here, very good. */
3737 log_debug("Proved NODATA via NSEC/NSEC3 for transaction %u (%s)", t->id, key_str);
3738 t->answer_dnssec_result = DNSSEC_VALIDATED;
3739 t->answer_rcode = DNS_RCODE_SUCCESS;
3740 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, authenticated);
3741
3742 manager_dnssec_verdict(t->scope->manager, authenticated ? DNSSEC_SECURE : DNSSEC_INSECURE, dns_transaction_key(t));
3743 break;
3744
3745 case DNSSEC_NSEC_OPTOUT:
3746 /* NSEC3 says the data might not be signed */
3747 log_debug("Data is NSEC3 opt-out via NSEC/NSEC3 for transaction %u (%s)", t->id, key_str);
3748 t->answer_dnssec_result = DNSSEC_UNSIGNED;
3749 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
3750
3751 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, dns_transaction_key(t));
3752 break;
3753
3754 case DNSSEC_NSEC_NO_RR:
3755 /* No NSEC data? Bummer! */
3756
3757 r = dns_transaction_requires_nsec(t);
3758 if (r < 0)
3759 return r;
3760 if (r > 0) {
3761 t->answer_dnssec_result = DNSSEC_NO_SIGNATURE;
3762 manager_dnssec_verdict(t->scope->manager, DNSSEC_BOGUS, dns_transaction_key(t));
3763 } else {
3764 t->answer_dnssec_result = DNSSEC_UNSIGNED;
3765 SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
3766 manager_dnssec_verdict(t->scope->manager, DNSSEC_INSECURE, dns_transaction_key(t));
3767 }
3768
3769 break;
3770
3771 case DNSSEC_NSEC_UNSUPPORTED_ALGORITHM:
3772 /* We don't know the NSEC3 algorithm used? */
3773 t->answer_dnssec_result = DNSSEC_UNSUPPORTED_ALGORITHM;
3774 manager_dnssec_verdict(t->scope->manager, DNSSEC_INDETERMINATE, dns_transaction_key(t));
3775 break;
3776
3777 case DNSSEC_NSEC_FOUND:
3778 case DNSSEC_NSEC_CNAME:
3779 /* NSEC says it needs to be there, but we couldn't find it? Bummer! */
3780 t->answer_dnssec_result = DNSSEC_NSEC_MISMATCH;
3781 manager_dnssec_verdict(t->scope->manager, DNSSEC_BOGUS, dns_transaction_key(t));
3782 break;
3783
3784 default:
3785 assert_not_reached();
3786 }
3787 }
3788
3789 return 1;
3790 }
3791
3792 static const char* const dns_transaction_state_table[_DNS_TRANSACTION_STATE_MAX] = {
3793 [DNS_TRANSACTION_NULL] = "null",
3794 [DNS_TRANSACTION_PENDING] = "pending",
3795 [DNS_TRANSACTION_VALIDATING] = "validating",
3796 [DNS_TRANSACTION_RCODE_FAILURE] = "rcode-failure",
3797 [DNS_TRANSACTION_SUCCESS] = "success",
3798 [DNS_TRANSACTION_NO_SERVERS] = "no-servers",
3799 [DNS_TRANSACTION_TIMEOUT] = "timeout",
3800 [DNS_TRANSACTION_ATTEMPTS_MAX_REACHED] = "attempts-max-reached",
3801 [DNS_TRANSACTION_INVALID_REPLY] = "invalid-reply",
3802 [DNS_TRANSACTION_ERRNO] = "errno",
3803 [DNS_TRANSACTION_ABORTED] = "aborted",
3804 [DNS_TRANSACTION_DNSSEC_FAILED] = "dnssec-failed",
3805 [DNS_TRANSACTION_NO_TRUST_ANCHOR] = "no-trust-anchor",
3806 [DNS_TRANSACTION_RR_TYPE_UNSUPPORTED] = "rr-type-unsupported",
3807 [DNS_TRANSACTION_NETWORK_DOWN] = "network-down",
3808 [DNS_TRANSACTION_NOT_FOUND] = "not-found",
3809 [DNS_TRANSACTION_NO_SOURCE] = "no-source",
3810 [DNS_TRANSACTION_STUB_LOOP] = "stub-loop",
3811 };
3812 DEFINE_STRING_TABLE_LOOKUP(dns_transaction_state, DnsTransactionState);
3813
3814 static const char* const dns_transaction_source_table[_DNS_TRANSACTION_SOURCE_MAX] = {
3815 [DNS_TRANSACTION_NETWORK] = "network",
3816 [DNS_TRANSACTION_CACHE] = "cache",
3817 [DNS_TRANSACTION_ZONE] = "zone",
3818 [DNS_TRANSACTION_TRUST_ANCHOR] = "trust-anchor",
3819 };
3820 DEFINE_STRING_TABLE_LOOKUP(dns_transaction_source, DnsTransactionSource);