1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include "sd-messages.h"
6 #include "alloc-util.h"
7 #include "dns-domain.h"
8 #include "errno-list.h"
9 #include "errno-util.h"
11 #include "random-util.h"
12 #include "resolved-dns-cache.h"
13 #include "resolved-dns-transaction.h"
14 #include "resolved-dnstls.h"
15 #include "resolved-llmnr.h"
16 #include "string-table.h"
18 #define TRANSACTIONS_MAX 4096
19 #define TRANSACTION_TCP_TIMEOUT_USEC (10U*USEC_PER_SEC)
21 /* After how much time to repeat classic DNS requests */
22 #define DNS_TIMEOUT_USEC (SD_RESOLVED_QUERY_TIMEOUT_USEC / DNS_TRANSACTION_ATTEMPTS_MAX)
24 static void dns_transaction_reset_answer(DnsTransaction
*t
) {
27 t
->received
= dns_packet_unref(t
->received
);
28 t
->answer
= dns_answer_unref(t
->answer
);
30 t
->answer_dnssec_result
= _DNSSEC_RESULT_INVALID
;
31 t
->answer_source
= _DNS_TRANSACTION_SOURCE_INVALID
;
32 t
->answer_query_flags
= 0;
33 t
->answer_nsec_ttl
= UINT32_MAX
;
37 static void dns_transaction_flush_dnssec_transactions(DnsTransaction
*t
) {
42 while ((z
= set_steal_first(t
->dnssec_transactions
))) {
43 set_remove(z
->notify_transactions
, t
);
44 set_remove(z
->notify_transactions_done
, t
);
45 dns_transaction_gc(z
);
49 static void dns_transaction_close_connection(
51 bool use_graveyard
) { /* Set use_graveyard = false when you know the connection is already
52 * dead, for example because you got a connection error back from the
53 * kernel. In that case there's no point in keeping the fd around,
60 /* Let's detach the stream from our transaction, in case something else keeps a reference to it. */
61 LIST_REMOVE(transactions_by_stream
, t
->stream
->transactions
, t
);
63 /* Remove packet in case it's still in the queue */
64 dns_packet_unref(ordered_set_remove(t
->stream
->write_queue
, t
->sent
));
66 t
->stream
= dns_stream_unref(t
->stream
);
69 t
->dns_udp_event_source
= sd_event_source_disable_unref(t
->dns_udp_event_source
);
71 /* If we have an UDP socket where we sent a packet, but never received one, then add it to the socket
72 * graveyard, instead of closing it right away. That way it will stick around for a moment longer,
73 * and the reply we might still get from the server will be eaten up instead of resulting in an ICMP
74 * port unreachable error message. */
76 if (use_graveyard
&& t
->dns_udp_fd
>= 0 && t
->sent
&& !t
->received
) {
77 r
= manager_add_socket_to_graveyard(t
->scope
->manager
, t
->dns_udp_fd
);
79 log_debug_errno(r
, "Failed to add UDP socket to graveyard, closing immediately: %m");
81 TAKE_FD(t
->dns_udp_fd
);
84 t
->dns_udp_fd
= safe_close(t
->dns_udp_fd
);
87 static void dns_transaction_stop_timeout(DnsTransaction
*t
) {
90 t
->timeout_event_source
= sd_event_source_disable_unref(t
->timeout_event_source
);
93 DnsTransaction
* dns_transaction_free(DnsTransaction
*t
) {
101 log_debug("Freeing transaction %" PRIu16
".", t
->id
);
103 dns_transaction_close_connection(t
, true);
104 dns_transaction_stop_timeout(t
);
106 dns_packet_unref(t
->sent
);
107 dns_transaction_reset_answer(t
);
109 dns_server_unref(t
->server
);
113 DnsTransaction
*first
;
115 first
= hashmap_get(t
->scope
->transactions_by_key
, t
->key
);
116 LIST_REMOVE(transactions_by_key
, first
, t
);
118 hashmap_replace(t
->scope
->transactions_by_key
, first
->key
, first
);
120 hashmap_remove(t
->scope
->transactions_by_key
, t
->key
);
123 LIST_REMOVE(transactions_by_scope
, t
->scope
->transactions
, t
);
126 hashmap_remove(t
->scope
->manager
->dns_transactions
, UINT_TO_PTR(t
->id
));
129 while ((c
= set_steal_first(t
->notify_query_candidates
)))
130 set_remove(c
->transactions
, t
);
131 set_free(t
->notify_query_candidates
);
133 while ((c
= set_steal_first(t
->notify_query_candidates_done
)))
134 set_remove(c
->transactions
, t
);
135 set_free(t
->notify_query_candidates_done
);
137 while ((i
= set_steal_first(t
->notify_zone_items
)))
138 i
->probe_transaction
= NULL
;
139 set_free(t
->notify_zone_items
);
141 while ((i
= set_steal_first(t
->notify_zone_items_done
)))
142 i
->probe_transaction
= NULL
;
143 set_free(t
->notify_zone_items_done
);
145 while ((z
= set_steal_first(t
->notify_transactions
)))
146 set_remove(z
->dnssec_transactions
, t
);
147 set_free(t
->notify_transactions
);
149 while ((z
= set_steal_first(t
->notify_transactions_done
)))
150 set_remove(z
->dnssec_transactions
, t
);
151 set_free(t
->notify_transactions_done
);
153 dns_transaction_flush_dnssec_transactions(t
);
154 set_free(t
->dnssec_transactions
);
156 dns_answer_unref(t
->validated_keys
);
157 dns_resource_key_unref(t
->key
);
158 dns_packet_unref(t
->bypass
);
163 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsTransaction
*, dns_transaction_free
);
165 DnsTransaction
* dns_transaction_gc(DnsTransaction
*t
) {
168 /* Returns !NULL if we can't gc yet. */
173 if (set_isempty(t
->notify_query_candidates
) &&
174 set_isempty(t
->notify_query_candidates_done
) &&
175 set_isempty(t
->notify_zone_items
) &&
176 set_isempty(t
->notify_zone_items_done
) &&
177 set_isempty(t
->notify_transactions
) &&
178 set_isempty(t
->notify_transactions_done
))
179 return dns_transaction_free(t
);
184 static uint16_t pick_new_id(Manager
*m
) {
187 /* Find a fresh, unused transaction id. Note that this loop is bounded because there's a limit on the
188 * number of transactions, and it's much lower than the space of IDs. */
190 assert_cc(TRANSACTIONS_MAX
< 0xFFFF);
193 random_bytes(&new_id
, sizeof(new_id
));
194 while (new_id
== 0 ||
195 hashmap_get(m
->dns_transactions
, UINT_TO_PTR(new_id
)));
202 DnsResourceKey
*key
) {
204 /* Don't allow looking up invalid or pseudo RRs */
205 if (!dns_type_is_valid_query(key
->type
))
207 if (dns_type_is_obsolete(key
->type
))
210 /* We only support the IN class */
211 if (!IN_SET(key
->class, DNS_CLASS_IN
, DNS_CLASS_ANY
))
214 /* Don't allows DNSSEC RRs to be looked up via LLMNR/mDNS. They don't really make sense
215 * there, and it speeds up our queries if we refuse this early */
216 if (scope
->protocol
!= DNS_PROTOCOL_DNS
&&
217 dns_type_is_dnssec(key
->type
))
223 int dns_transaction_new(
224 DnsTransaction
**ret
,
228 uint64_t query_flags
) {
230 _cleanup_(dns_transaction_freep
) DnsTransaction
*t
= NULL
;
246 r
= dns_packet_validate_query(bypass
);
250 DNS_QUESTION_FOREACH(qk
, bypass
->question
) {
257 if (hashmap_size(s
->manager
->dns_transactions
) >= TRANSACTIONS_MAX
)
260 r
= hashmap_ensure_allocated(&s
->manager
->dns_transactions
, NULL
);
265 r
= hashmap_ensure_allocated(&s
->transactions_by_key
, &dns_resource_key_hash_ops
);
270 t
= new(DnsTransaction
, 1);
274 *t
= (DnsTransaction
) {
276 .answer_source
= _DNS_TRANSACTION_SOURCE_INVALID
,
277 .answer_dnssec_result
= _DNSSEC_RESULT_INVALID
,
278 .answer_nsec_ttl
= UINT32_MAX
,
279 .key
= dns_resource_key_ref(key
),
280 .query_flags
= query_flags
,
281 .bypass
= dns_packet_ref(bypass
),
282 .current_feature_level
= _DNS_SERVER_FEATURE_LEVEL_INVALID
,
283 .clamp_feature_level_servfail
= _DNS_SERVER_FEATURE_LEVEL_INVALID
,
284 .clamp_feature_level_nxdomain
= _DNS_SERVER_FEATURE_LEVEL_INVALID
,
285 .id
= pick_new_id(s
->manager
),
288 r
= hashmap_put(s
->manager
->dns_transactions
, UINT_TO_PTR(t
->id
), t
);
295 DnsTransaction
*first
;
297 first
= hashmap_get(s
->transactions_by_key
, t
->key
);
298 LIST_PREPEND(transactions_by_key
, first
, t
);
300 r
= hashmap_replace(s
->transactions_by_key
, first
->key
, first
);
302 LIST_REMOVE(transactions_by_key
, first
, t
);
307 LIST_PREPEND(transactions_by_scope
, s
->transactions
, t
);
310 s
->manager
->n_transactions_total
++;
319 static void dns_transaction_shuffle_id(DnsTransaction
*t
) {
323 /* Pick a new ID for this transaction. */
325 new_id
= pick_new_id(t
->scope
->manager
);
326 assert_se(hashmap_remove_and_put(t
->scope
->manager
->dns_transactions
, UINT_TO_PTR(t
->id
), UINT_TO_PTR(new_id
), t
) >= 0);
328 log_debug("Transaction %" PRIu16
" is now %" PRIu16
".", t
->id
, new_id
);
331 /* Make sure we generate a new packet with the new ID */
332 t
->sent
= dns_packet_unref(t
->sent
);
335 static void dns_transaction_tentative(DnsTransaction
*t
, DnsPacket
*p
) {
336 _cleanup_free_
char *pretty
= NULL
;
337 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
342 assert(t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
);
344 if (manager_packet_from_local_address(t
->scope
->manager
, p
) != 0)
347 (void) in_addr_to_string(p
->family
, &p
->sender
, &pretty
);
349 log_debug("Transaction %" PRIu16
" for <%s> on scope %s on %s/%s got tentative packet from %s.",
351 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
),
352 dns_protocol_to_string(t
->scope
->protocol
),
353 t
->scope
->link
? t
->scope
->link
->ifname
: "*",
354 af_to_name_short(t
->scope
->family
),
357 /* RFC 4795, Section 4.1 says that the peer with the
358 * lexicographically smaller IP address loses */
359 if (memcmp(&p
->sender
, &p
->destination
, FAMILY_ADDRESS_SIZE(p
->family
)) >= 0) {
360 log_debug("Peer has lexicographically larger IP address and thus lost in the conflict.");
364 log_debug("We have the lexicographically larger IP address and thus lost in the conflict.");
368 while ((z
= set_first(t
->notify_zone_items
))) {
369 /* First, make sure the zone item drops the reference
371 dns_zone_item_probe_stop(z
);
373 /* Secondly, report this as conflict, so that we might
374 * look for a different hostname */
375 dns_zone_item_conflict(z
);
379 dns_transaction_gc(t
);
382 void dns_transaction_complete(DnsTransaction
*t
, DnsTransactionState state
) {
383 DnsQueryCandidate
*c
;
387 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
390 assert(!DNS_TRANSACTION_IS_LIVE(state
));
392 if (state
== DNS_TRANSACTION_DNSSEC_FAILED
) {
393 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
);
395 log_struct(LOG_NOTICE
,
396 "MESSAGE_ID=" SD_MESSAGE_DNSSEC_FAILURE_STR
,
397 LOG_MESSAGE("DNSSEC validation failed for question %s: %s",
398 key_str
, dnssec_result_to_string(t
->answer_dnssec_result
)),
399 "DNS_TRANSACTION=%" PRIu16
, t
->id
,
400 "DNS_QUESTION=%s", key_str
,
401 "DNSSEC_RESULT=%s", dnssec_result_to_string(t
->answer_dnssec_result
),
402 "DNS_SERVER=%s", strna(dns_server_string_full(t
->server
)),
403 "DNS_SERVER_FEATURE_LEVEL=%s", dns_server_feature_level_to_string(t
->server
->possible_feature_level
));
406 /* Note that this call might invalidate the query. Callers
407 * should hence not attempt to access the query or transaction
408 * after calling this function. */
410 if (state
== DNS_TRANSACTION_ERRNO
)
411 st
= errno_to_name(t
->answer_errno
);
413 st
= dns_transaction_state_to_string(state
);
415 log_debug("%s transaction %" PRIu16
" for <%s> on scope %s on %s/%s now complete with <%s> from %s (%s; %s).",
416 t
->bypass
? "Bypass" : "Regular",
418 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
),
419 dns_protocol_to_string(t
->scope
->protocol
),
420 t
->scope
->link
? t
->scope
->link
->ifname
: "*",
421 af_to_name_short(t
->scope
->family
),
423 t
->answer_source
< 0 ? "none" : dns_transaction_source_to_string(t
->answer_source
),
424 FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
) ? "not validated" :
425 (FLAGS_SET(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
) ? "authenticated" : "unsigned"),
426 FLAGS_SET(t
->answer_query_flags
, SD_RESOLVED_CONFIDENTIAL
) ? "confidential" : "non-confidential");
430 dns_transaction_close_connection(t
, true);
431 dns_transaction_stop_timeout(t
);
433 /* Notify all queries that are interested, but make sure the
434 * transaction isn't freed while we are still looking at it */
437 SET_FOREACH_MOVE(c
, t
->notify_query_candidates_done
, t
->notify_query_candidates
)
438 dns_query_candidate_notify(c
);
439 SWAP_TWO(t
->notify_query_candidates
, t
->notify_query_candidates_done
);
441 SET_FOREACH_MOVE(z
, t
->notify_zone_items_done
, t
->notify_zone_items
)
442 dns_zone_item_notify(z
);
443 SWAP_TWO(t
->notify_zone_items
, t
->notify_zone_items_done
);
444 if (t
->probing
&& t
->state
== DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
)
445 (void) dns_scope_announce(t
->scope
, false);
447 SET_FOREACH_MOVE(d
, t
->notify_transactions_done
, t
->notify_transactions
)
448 dns_transaction_notify(d
, t
);
449 SWAP_TWO(t
->notify_transactions
, t
->notify_transactions_done
);
452 dns_transaction_gc(t
);
455 static void dns_transaction_complete_errno(DnsTransaction
*t
, int error
) {
459 t
->answer_errno
= abs(error
);
460 dns_transaction_complete(t
, DNS_TRANSACTION_ERRNO
);
463 static int dns_transaction_pick_server(DnsTransaction
*t
) {
467 assert(t
->scope
->protocol
== DNS_PROTOCOL_DNS
);
469 /* Pick a DNS server and a feature level for it. */
471 server
= dns_scope_get_dns_server(t
->scope
);
475 /* If we changed the server invalidate the feature level clamping, as the new server might have completely
476 * different properties. */
477 if (server
!= t
->server
) {
478 t
->clamp_feature_level_servfail
= _DNS_SERVER_FEATURE_LEVEL_INVALID
;
479 t
->clamp_feature_level_nxdomain
= _DNS_SERVER_FEATURE_LEVEL_INVALID
;
482 t
->current_feature_level
= dns_server_possible_feature_level(server
);
484 /* Clamp the feature level if that is requested. */
485 if (t
->clamp_feature_level_servfail
!= _DNS_SERVER_FEATURE_LEVEL_INVALID
&&
486 t
->current_feature_level
> t
->clamp_feature_level_servfail
)
487 t
->current_feature_level
= t
->clamp_feature_level_servfail
;
488 if (t
->clamp_feature_level_nxdomain
!= _DNS_SERVER_FEATURE_LEVEL_INVALID
&&
489 t
->current_feature_level
> t
->clamp_feature_level_nxdomain
)
490 t
->current_feature_level
= t
->clamp_feature_level_nxdomain
;
492 log_debug("Using feature level %s for transaction %u.", dns_server_feature_level_to_string(t
->current_feature_level
), t
->id
);
494 if (server
== t
->server
)
497 dns_server_unref(t
->server
);
498 t
->server
= dns_server_ref(server
);
500 t
->n_picked_servers
++;
502 log_debug("Using DNS server %s for transaction %u.", strna(dns_server_string_full(t
->server
)), t
->id
);
507 static void dns_transaction_retry(DnsTransaction
*t
, bool next_server
) {
512 /* Retries the transaction as it is, possibly on a different server */
514 if (next_server
&& t
->scope
->protocol
== DNS_PROTOCOL_DNS
)
515 log_debug("Retrying transaction %" PRIu16
", after switching servers.", t
->id
);
517 log_debug("Retrying transaction %" PRIu16
".", t
->id
);
519 /* Before we try again, switch to a new server. */
521 dns_scope_next_dns_server(t
->scope
, t
->server
);
523 r
= dns_transaction_go(t
);
525 dns_transaction_complete_errno(t
, r
);
528 static bool dns_transaction_limited_retry(DnsTransaction
*t
) {
531 /* If we haven't tried all different servers yet, let's try again with a different server */
533 if (t
->n_picked_servers
>= dns_scope_get_n_dns_servers(t
->scope
))
536 dns_transaction_retry(t
, /* next_server= */ true);
540 static int dns_transaction_maybe_restart(DnsTransaction
*t
) {
545 /* Restarts the transaction, under a new ID if the feature level of the server changed since we first
546 * tried, without changing DNS server. Returns > 0 if the transaction was restarted, 0 if not. */
551 if (t
->current_feature_level
<= dns_server_possible_feature_level(t
->server
))
554 /* The server's current feature level is lower than when we sent the original query. We learnt something from
555 the response or possibly an auxiliary DNSSEC response that we didn't know before. We take that as reason to
556 restart the whole transaction. This is a good idea to deal with servers that respond rubbish if we include
557 OPT RR or DO bit. One of these cases is documented here, for example:
558 https://open.nlnetlabs.nl/pipermail/dnssec-trigger/2014-November/000376.html */
560 log_debug("Server feature level is now lower than when we began our transaction. Restarting with new ID.");
561 dns_transaction_shuffle_id(t
);
563 r
= dns_transaction_go(t
);
570 static void on_transaction_stream_error(DnsTransaction
*t
, int error
) {
573 dns_transaction_close_connection(t
, true);
575 if (ERRNO_IS_DISCONNECT(error
)) {
576 if (t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
) {
577 /* If the LLMNR/TCP connection failed, the host doesn't support LLMNR, and we cannot answer the
578 * question on this scope. */
579 dns_transaction_complete(t
, DNS_TRANSACTION_NOT_FOUND
);
583 dns_transaction_retry(t
, true);
587 dns_transaction_complete_errno(t
, error
);
590 static int dns_transaction_on_stream_packet(DnsTransaction
*t
, DnsStream
*s
, DnsPacket
*p
) {
597 encrypted
= s
->encrypted
;
599 dns_transaction_close_connection(t
, true);
601 if (dns_packet_validate_reply(p
) <= 0) {
602 log_debug("Invalid TCP reply packet.");
603 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
607 dns_scope_check_conflicts(t
->scope
, p
);
610 dns_transaction_process_reply(t
, p
, encrypted
);
613 /* If the response wasn't useful, then complete the transition
614 * now. After all, we are the worst feature set now with TCP
615 * sockets, and there's really no point in retrying. */
616 if (t
->state
== DNS_TRANSACTION_PENDING
)
617 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
619 dns_transaction_gc(t
);
624 static int on_stream_complete(DnsStream
*s
, int error
) {
627 if (ERRNO_IS_DISCONNECT(error
) && s
->protocol
!= DNS_PROTOCOL_LLMNR
) {
628 log_debug_errno(error
, "Connection failure for DNS TCP stream: %m");
630 if (s
->transactions
) {
634 dns_server_packet_lost(t
->server
, IPPROTO_TCP
, t
->current_feature_level
);
639 LIST_FOREACH(transactions_by_stream
, t
, s
->transactions
)
640 on_transaction_stream_error(t
, error
);
645 static int on_stream_packet(DnsStream
*s
, DnsPacket
*p
) {
652 t
= hashmap_get(s
->manager
->dns_transactions
, UINT_TO_PTR(DNS_PACKET_ID(p
)));
653 if (t
&& t
->stream
== s
) /* Validate that the stream we got this on actually is the stream the
654 * transaction was using. */
655 return dns_transaction_on_stream_packet(t
, s
, p
);
657 /* Ignore incorrect transaction id as an old transaction can have been canceled. */
658 log_debug("Received unexpected TCP reply packet with id %" PRIu16
", ignoring.", DNS_PACKET_ID(p
));
662 static uint16_t dns_transaction_port(DnsTransaction
*t
) {
665 if (t
->server
->port
> 0)
666 return t
->server
->port
;
668 return DNS_SERVER_FEATURE_LEVEL_IS_TLS(t
->current_feature_level
) ? 853 : 53;
671 static int dns_transaction_emit_tcp(DnsTransaction
*t
) {
672 usec_t stream_timeout_usec
= DNS_STREAM_DEFAULT_TIMEOUT_USEC
;
673 _cleanup_(dns_stream_unrefp
) DnsStream
*s
= NULL
;
674 _cleanup_close_
int fd
= -1;
675 union sockaddr_union sa
;
682 dns_transaction_close_connection(t
, true);
684 switch (t
->scope
->protocol
) {
686 case DNS_PROTOCOL_DNS
:
687 r
= dns_transaction_pick_server(t
);
691 if (manager_server_is_stub(t
->scope
->manager
, t
->server
))
695 if (!dns_server_dnssec_supported(t
->server
) && dns_type_is_dnssec(dns_transaction_key(t
)->type
))
698 r
= dns_server_adjust_opt(t
->server
, t
->sent
, t
->current_feature_level
);
703 if (t
->server
->stream
&& (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t
->current_feature_level
) == t
->server
->stream
->encrypted
))
704 s
= dns_stream_ref(t
->server
->stream
);
706 fd
= dns_scope_socket_tcp(t
->scope
, AF_UNSPEC
, NULL
, t
->server
, dns_transaction_port(t
), &sa
);
708 /* Lower timeout in DNS-over-TLS opportunistic mode. In environments where DoT is blocked
709 * without ICMP response overly long delays when contacting DoT servers are nasty, in
710 * particular if multiple DNS servers are defined which we try in turn and all are
711 * blocked. Hence, substantially lower the timeout in that case. */
712 if (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t
->current_feature_level
) &&
713 dns_server_get_dns_over_tls_mode(t
->server
) == DNS_OVER_TLS_OPPORTUNISTIC
)
714 stream_timeout_usec
= DNS_STREAM_OPPORTUNISTIC_TLS_TIMEOUT_USEC
;
716 type
= DNS_STREAM_LOOKUP
;
719 case DNS_PROTOCOL_LLMNR
:
720 /* When we already received a reply to this (but it was truncated), send to its sender address */
722 fd
= dns_scope_socket_tcp(t
->scope
, t
->received
->family
, &t
->received
->sender
, NULL
, t
->received
->sender_port
, &sa
);
724 union in_addr_union address
;
725 int family
= AF_UNSPEC
;
727 /* Otherwise, try to talk to the owner of a
728 * the IP address, in case this is a reverse
731 r
= dns_name_address(dns_resource_key_name(dns_transaction_key(t
)), &family
, &address
);
736 if (family
!= t
->scope
->family
)
739 fd
= dns_scope_socket_tcp(t
->scope
, family
, &address
, NULL
, LLMNR_PORT
, &sa
);
742 type
= DNS_STREAM_LLMNR_SEND
;
746 return -EAFNOSUPPORT
;
753 r
= dns_stream_new(t
->scope
->manager
, &s
, type
, t
->scope
->protocol
, fd
, &sa
,
754 on_stream_packet
, on_stream_complete
, stream_timeout_usec
);
760 #if ENABLE_DNS_OVER_TLS
761 if (t
->scope
->protocol
== DNS_PROTOCOL_DNS
&&
762 DNS_SERVER_FEATURE_LEVEL_IS_TLS(t
->current_feature_level
)) {
765 r
= dnstls_stream_connect_tls(s
, t
->server
);
772 dns_server_unref_stream(t
->server
);
773 s
->server
= dns_server_ref(t
->server
);
774 t
->server
->stream
= dns_stream_ref(s
);
777 /* The interface index is difficult to determine if we are
778 * connecting to the local host, hence fill this in right away
779 * instead of determining it from the socket */
780 s
->ifindex
= dns_scope_ifindex(t
->scope
);
783 t
->stream
= TAKE_PTR(s
);
784 LIST_PREPEND(transactions_by_stream
, t
->stream
->transactions
, t
);
786 r
= dns_stream_write_packet(t
->stream
, t
->sent
);
788 dns_transaction_close_connection(t
, /* use_graveyard= */ false);
792 dns_transaction_reset_answer(t
);
794 t
->tried_stream
= true;
799 static void dns_transaction_cache_answer(DnsTransaction
*t
) {
802 /* For mDNS we cache whenever we get the packet, rather than
803 * in each transaction. */
804 if (!IN_SET(t
->scope
->protocol
, DNS_PROTOCOL_DNS
, DNS_PROTOCOL_LLMNR
))
807 /* Caching disabled? */
808 if (t
->scope
->manager
->enable_cache
== DNS_CACHE_MODE_NO
)
811 /* If validation is turned off for this transaction, but DNSSEC is on, then let's not cache this */
812 if (FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
) && t
->scope
->dnssec_mode
!= DNSSEC_NO
)
815 /* Packet from localhost? */
816 if (!t
->scope
->manager
->cache_from_localhost
&&
817 in_addr_is_localhost(t
->received
->family
, &t
->received
->sender
) != 0)
820 dns_cache_put(&t
->scope
->cache
,
821 t
->scope
->manager
->enable_cache
,
822 dns_transaction_key(t
),
825 DNS_PACKET_CD(t
->received
) ? t
->received
: NULL
, /* only cache full packets with CD on,
826 * since our usecase for caching them
827 * is "bypass" mode which is only
828 * enabled for CD packets. */
829 t
->answer_query_flags
,
830 t
->answer_dnssec_result
,
833 &t
->received
->sender
);
836 static bool dns_transaction_dnssec_is_live(DnsTransaction
*t
) {
841 SET_FOREACH(dt
, t
->dnssec_transactions
)
842 if (DNS_TRANSACTION_IS_LIVE(dt
->state
))
848 static int dns_transaction_dnssec_ready(DnsTransaction
*t
) {
854 /* Checks whether the auxiliary DNSSEC transactions of our transaction have completed, or are still
855 * ongoing. Returns 0, if we aren't ready for the DNSSEC validation, positive if we are. */
857 SET_FOREACH(dt
, t
->dnssec_transactions
) {
861 case DNS_TRANSACTION_NULL
:
862 case DNS_TRANSACTION_PENDING
:
863 case DNS_TRANSACTION_VALIDATING
:
867 case DNS_TRANSACTION_RCODE_FAILURE
:
868 if (!IN_SET(dt
->answer_rcode
, DNS_RCODE_NXDOMAIN
, DNS_RCODE_SERVFAIL
)) {
869 log_debug("Auxiliary DNSSEC RR query failed with rcode=%s.", dns_rcode_to_string(dt
->answer_rcode
));
873 /* Fall-through: NXDOMAIN/SERVFAIL is good enough for us. This is because some DNS servers
874 * erroneously return NXDOMAIN/SERVFAIL for empty non-terminals (Akamai...) or missing DS
875 * records (Facebook), and we need to handle that nicely, when asking for parent SOA or similar
876 * RRs to make unsigned proofs. */
878 case DNS_TRANSACTION_SUCCESS
:
882 case DNS_TRANSACTION_DNSSEC_FAILED
:
883 /* We handle DNSSEC failures different from other errors, as we care about the DNSSEC
884 * validation result */
886 log_debug("Auxiliary DNSSEC RR query failed validation: %s", dnssec_result_to_string(dt
->answer_dnssec_result
));
887 t
->answer_dnssec_result
= dt
->answer_dnssec_result
; /* Copy error code over */
888 dns_transaction_complete(t
, DNS_TRANSACTION_DNSSEC_FAILED
);
892 log_debug("Auxiliary DNSSEC RR query failed with %s", dns_transaction_state_to_string(dt
->state
));
897 /* All is ready, we can go and validate */
901 /* Some auxiliary DNSSEC transaction failed for some reason. Maybe we learned something about the
902 * server due to this failure, and the feature level is now different? Let's see and restart the
903 * transaction if so. If not, let's propagate the auxiliary failure.
905 * This is particularly relevant if an auxiliary request figured out that DNSSEC doesn't work, and we
906 * are in permissive DNSSEC mode, and thus should restart things without DNSSEC magic. */
907 r
= dns_transaction_maybe_restart(t
);
911 return 0; /* don't validate just yet, we restarted things */
913 t
->answer_dnssec_result
= DNSSEC_FAILED_AUXILIARY
;
914 dns_transaction_complete(t
, DNS_TRANSACTION_DNSSEC_FAILED
);
918 static void dns_transaction_process_dnssec(DnsTransaction
*t
) {
923 /* Are there ongoing DNSSEC transactions? If so, let's wait for them. */
924 r
= dns_transaction_dnssec_ready(t
);
927 if (r
== 0) /* We aren't ready yet (or one of our auxiliary transactions failed, and we shouldn't validate now */
930 /* See if we learnt things from the additional DNSSEC transactions, that we didn't know before, and better
931 * restart the lookup immediately. */
932 r
= dns_transaction_maybe_restart(t
);
935 if (r
> 0) /* Transaction got restarted... */
938 /* All our auxiliary DNSSEC transactions are complete now. Try
939 * to validate our RRset now. */
940 r
= dns_transaction_validate_dnssec(t
);
942 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
948 if (t
->answer_dnssec_result
== DNSSEC_INCOMPATIBLE_SERVER
&&
949 t
->scope
->dnssec_mode
== DNSSEC_YES
) {
951 /* We are not in automatic downgrade mode, and the server is bad. Let's try a different server, maybe
954 if (dns_transaction_limited_retry(t
))
957 /* OK, let's give up, apparently all servers we tried didn't work. */
958 dns_transaction_complete(t
, DNS_TRANSACTION_DNSSEC_FAILED
);
962 if (!IN_SET(t
->answer_dnssec_result
,
963 _DNSSEC_RESULT_INVALID
, /* No DNSSEC validation enabled */
964 DNSSEC_VALIDATED
, /* Answer is signed and validated successfully */
965 DNSSEC_UNSIGNED
, /* Answer is right-fully unsigned */
966 DNSSEC_INCOMPATIBLE_SERVER
)) { /* Server does not do DNSSEC (Yay, we are downgrade attack vulnerable!) */
967 dns_transaction_complete(t
, DNS_TRANSACTION_DNSSEC_FAILED
);
971 if (t
->answer_dnssec_result
== DNSSEC_INCOMPATIBLE_SERVER
)
972 dns_server_warn_downgrade(t
->server
);
974 dns_transaction_cache_answer(t
);
976 if (t
->answer_rcode
== DNS_RCODE_SUCCESS
)
977 dns_transaction_complete(t
, DNS_TRANSACTION_SUCCESS
);
979 dns_transaction_complete(t
, DNS_TRANSACTION_RCODE_FAILURE
);
984 dns_transaction_complete_errno(t
, r
);
987 static int dns_transaction_has_positive_answer(DnsTransaction
*t
, DnsAnswerFlags
*flags
) {
992 /* Checks whether the answer is positive, i.e. either a direct
993 * answer to the question, or a CNAME/DNAME for it */
995 r
= dns_answer_match_key(t
->answer
, dns_transaction_key(t
), flags
);
999 r
= dns_answer_find_cname_or_dname(t
->answer
, dns_transaction_key(t
), NULL
, flags
);
1006 static int dns_transaction_fix_rcode(DnsTransaction
*t
) {
1011 /* Fix up the RCODE to SUCCESS if we get at least one matching RR in a response. Note that this contradicts the
1012 * DNS RFCs a bit. Specifically, RFC 6604 Section 3 clarifies that the RCODE shall say something about a
1013 * CNAME/DNAME chain element coming after the last chain element contained in the message, and not the first
1014 * one included. However, it also indicates that not all DNS servers implement this correctly. Moreover, when
1015 * using DNSSEC we usually only can prove the first element of a CNAME/DNAME chain anyway, hence let's settle
1016 * on always processing the RCODE as referring to the immediate look-up we do, i.e. the first element of a
1017 * CNAME/DNAME chain. This way, we uniformly handle CNAME/DNAME chains, regardless if the DNS server
1018 * incorrectly implements RCODE, whether DNSSEC is in use, or whether the DNS server only supplied us with an
1019 * incomplete CNAME/DNAME chain.
1021 * Or in other words: if we get at least one positive reply in a message we patch NXDOMAIN to become SUCCESS,
1022 * and then rely on the CNAME chasing logic to figure out that there's actually a CNAME error with a new
1025 if (t
->answer_rcode
!= DNS_RCODE_NXDOMAIN
)
1028 r
= dns_transaction_has_positive_answer(t
, NULL
);
1032 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
1036 void dns_transaction_process_reply(DnsTransaction
*t
, DnsPacket
*p
, bool encrypted
) {
1037 bool retry_with_tcp
= false;
1043 assert(t
->scope
->manager
);
1045 if (t
->state
!= DNS_TRANSACTION_PENDING
)
1048 /* Note that this call might invalidate the query. Callers
1049 * should hence not attempt to access the query or transaction
1050 * after calling this function. */
1052 log_debug("Processing incoming packet of size %zu on transaction %" PRIu16
" (rcode=%s).",
1054 t
->id
, dns_rcode_to_string(DNS_PACKET_RCODE(p
)));
1056 switch (t
->scope
->protocol
) {
1058 case DNS_PROTOCOL_LLMNR
:
1059 /* For LLMNR we will not accept any packets from other interfaces */
1061 if (p
->ifindex
!= dns_scope_ifindex(t
->scope
))
1064 if (p
->family
!= t
->scope
->family
)
1067 /* Tentative packets are not full responses but still
1068 * useful for identifying uniqueness conflicts during
1070 if (DNS_PACKET_LLMNR_T(p
)) {
1071 dns_transaction_tentative(t
, p
);
1077 case DNS_PROTOCOL_MDNS
:
1078 /* For mDNS we will not accept any packets from other interfaces */
1080 if (p
->ifindex
!= dns_scope_ifindex(t
->scope
))
1083 if (p
->family
!= t
->scope
->family
)
1088 case DNS_PROTOCOL_DNS
:
1089 /* Note that we do not need to verify the
1090 * addresses/port numbers of incoming traffic, as we
1091 * invoked connect() on our UDP socket in which case
1092 * the kernel already does the needed verification for
1097 assert_not_reached();
1100 if (t
->received
!= p
) {
1101 dns_packet_unref(t
->received
);
1102 t
->received
= dns_packet_ref(p
);
1105 t
->answer_source
= DNS_TRANSACTION_NETWORK
;
1107 if (p
->ipproto
== IPPROTO_TCP
) {
1108 if (DNS_PACKET_TC(p
)) {
1109 /* Truncated via TCP? Somebody must be fucking with us */
1110 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
1114 if (DNS_PACKET_ID(p
) != t
->id
) {
1115 /* Not the reply to our query? Somebody must be fucking with us */
1116 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
1121 switch (t
->scope
->protocol
) {
1123 case DNS_PROTOCOL_DNS
:
1127 IN_SET(DNS_PACKET_RCODE(p
), DNS_RCODE_FORMERR
, DNS_RCODE_SERVFAIL
, DNS_RCODE_NOTIMP
)) {
1129 /* Request failed, immediately try again with reduced features */
1131 if (t
->current_feature_level
<= DNS_SERVER_FEATURE_LEVEL_UDP
) {
1133 /* This was already at UDP feature level? If so, it doesn't make sense to downgrade
1134 * this transaction anymore, but let's see if it might make sense to send the request
1135 * to a different DNS server instead. If not let's process the response, and accept the
1136 * rcode. Note that we don't retry on TCP, since that's a suitable way to mitigate
1137 * packet loss, but is not going to give us better rcodes should we actually have
1138 * managed to get them already at UDP level. */
1140 if (dns_transaction_limited_retry(t
))
1143 /* Give up, accept the rcode */
1144 log_debug("Server returned error: %s", dns_rcode_to_string(DNS_PACKET_RCODE(p
)));
1148 /* SERVFAIL can happen for many reasons and may be transient.
1149 * To avoid unnecessary downgrades retry once with the initial level.
1150 * Check for clamp_feature_level_servfail having an invalid value as a sign that this is the
1151 * first attempt to downgrade. If so, clamp to the current value so that the transaction
1152 * is retried without actually downgrading. If the next try also fails we will downgrade by
1153 * hitting the else branch below. */
1154 if (DNS_PACKET_RCODE(p
) == DNS_RCODE_SERVFAIL
&&
1155 t
->clamp_feature_level_servfail
< 0) {
1156 t
->clamp_feature_level_servfail
= t
->current_feature_level
;
1157 log_debug("Server returned error %s, retrying transaction.",
1158 dns_rcode_to_string(DNS_PACKET_RCODE(p
)));
1160 /* Reduce this feature level by one and try again. */
1161 switch (t
->current_feature_level
) {
1162 case DNS_SERVER_FEATURE_LEVEL_TLS_DO
:
1163 t
->clamp_feature_level_servfail
= DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN
;
1165 case DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN
+ 1:
1166 /* Skip plain TLS when TLS is not supported */
1167 t
->clamp_feature_level_servfail
= DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN
- 1;
1170 t
->clamp_feature_level_servfail
= t
->current_feature_level
- 1;
1173 log_debug("Server returned error %s, retrying transaction with reduced feature level %s.",
1174 dns_rcode_to_string(DNS_PACKET_RCODE(p
)),
1175 dns_server_feature_level_to_string(t
->clamp_feature_level_servfail
));
1178 dns_transaction_retry(t
, false /* use the same server */);
1182 if (DNS_PACKET_RCODE(p
) == DNS_RCODE_REFUSED
) {
1183 /* This server refused our request? If so, try again, use a different server */
1184 log_debug("Server returned REFUSED, switching servers, and retrying.");
1186 if (dns_transaction_limited_retry(t
))
1192 if (DNS_PACKET_TC(p
))
1193 dns_server_packet_truncated(t
->server
, t
->current_feature_level
);
1197 case DNS_PROTOCOL_LLMNR
:
1198 case DNS_PROTOCOL_MDNS
:
1199 dns_scope_packet_received(t
->scope
, p
->timestamp
- t
->start_usec
);
1203 assert_not_reached();
1206 if (DNS_PACKET_TC(p
)) {
1208 /* Truncated packets for mDNS are not allowed. Give up immediately. */
1209 if (t
->scope
->protocol
== DNS_PROTOCOL_MDNS
) {
1210 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
1214 /* Response was truncated, let's try again with good old TCP */
1215 log_debug("Reply truncated, retrying via TCP.");
1216 retry_with_tcp
= true;
1218 } else if (t
->scope
->protocol
== DNS_PROTOCOL_DNS
&&
1219 DNS_PACKET_IS_FRAGMENTED(p
)) {
1221 /* Report the fragment size, so that we downgrade from LARGE to regular EDNS0 if needed */
1223 dns_server_packet_udp_fragmented(t
->server
, dns_packet_size_unfragmented(p
));
1225 if (t
->current_feature_level
> DNS_SERVER_FEATURE_LEVEL_UDP
) {
1226 /* Packet was fragmented. Let's retry with TCP to avoid fragmentation attack
1227 * issues. (We don't do that on the lowest feature level however, since crappy DNS
1228 * servers often do not implement TCP, hence falling back to TCP on fragmentation is
1229 * counter-productive there.) */
1231 log_debug("Reply fragmented, retrying via TCP. (Largest fragment size: %zu; Datagram size: %zu)",
1232 p
->fragsize
, p
->size
);
1233 retry_with_tcp
= true;
1237 if (retry_with_tcp
) {
1238 r
= dns_transaction_emit_tcp(t
);
1240 /* No servers found? Damn! */
1241 dns_transaction_complete(t
, DNS_TRANSACTION_NO_SERVERS
);
1244 if (r
== -EOPNOTSUPP
) {
1245 /* Tried to ask for DNSSEC RRs, on a server that doesn't do DNSSEC */
1246 dns_transaction_complete(t
, DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
);
1250 /* On LLMNR, if we cannot connect to the host,
1251 * we immediately give up */
1252 if (t
->scope
->protocol
!= DNS_PROTOCOL_DNS
)
1255 /* On DNS, couldn't send? Try immediately again, with a new server */
1256 if (dns_transaction_limited_retry(t
))
1259 /* No new server to try, give up */
1260 dns_transaction_complete(t
, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
);
1266 /* After the superficial checks, actually parse the message. */
1267 r
= dns_packet_extract(p
);
1270 dns_server_packet_invalid(t
->server
, t
->current_feature_level
);
1272 r
= dns_transaction_maybe_restart(t
);
1275 if (r
> 0) /* Transaction got restarted... */
1279 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
1283 if (t
->scope
->protocol
== DNS_PROTOCOL_DNS
&&
1285 DNS_PACKET_RCODE(p
) == DNS_RCODE_NXDOMAIN
&&
1286 p
->opt
&& !DNS_PACKET_DO(p
) &&
1287 DNS_SERVER_FEATURE_LEVEL_IS_EDNS0(t
->current_feature_level
) &&
1288 DNS_SERVER_FEATURE_LEVEL_IS_UDP(t
->current_feature_level
) &&
1289 t
->scope
->dnssec_mode
!= DNSSEC_YES
) {
1291 /* Some captive portals are special in that the Aruba/Datavalet hardware will miss
1292 * replacing the packets with the local server IP to point to the authenticated side
1293 * of the network if EDNS0 is enabled. Instead they return NXDOMAIN, with DO bit set
1294 * to zero... nothing to see here, yet respond with the captive portal IP, when using
1295 * the more simple UDP level.
1297 * Common portal names that fail like so are:
1298 * secure.datavalet.io
1299 * securelogin.arubanetworks.com
1300 * securelogin.networks.mycompany.com
1302 * Thus retry NXDOMAIN RCODES with a lower feature level.
1304 * Do not lower the server's tracked feature level, as the captive portal should not
1305 * be lying for the wider internet (e.g. _other_ queries were observed fine with
1306 * EDNS0 on these networks, post auth), i.e. let's just lower the level transaction's
1309 * This is reported as https://github.com/dns-violations/dns-violations/blob/master/2018/DVE-2018-0001.md
1312 t
->clamp_feature_level_nxdomain
= DNS_SERVER_FEATURE_LEVEL_UDP
;
1314 log_debug("Server returned error %s in EDNS0 mode, retrying transaction with reduced feature level %s (DVE-2018-0001 mitigation)",
1315 dns_rcode_to_string(DNS_PACKET_RCODE(p
)),
1316 dns_server_feature_level_to_string(t
->clamp_feature_level_nxdomain
));
1318 dns_transaction_retry(t
, false /* use the same server */);
1323 /* Report that we successfully received a valid packet with a good rcode after we initially got a bad
1324 * rcode and subsequently downgraded the protocol */
1326 if (IN_SET(DNS_PACKET_RCODE(p
), DNS_RCODE_SUCCESS
, DNS_RCODE_NXDOMAIN
) &&
1327 t
->clamp_feature_level_servfail
!= _DNS_SERVER_FEATURE_LEVEL_INVALID
)
1328 dns_server_packet_rcode_downgrade(t
->server
, t
->clamp_feature_level_servfail
);
1330 /* Report that the OPT RR was missing */
1332 dns_server_packet_bad_opt(t
->server
, t
->current_feature_level
);
1334 /* Report that the server didn't copy our query DO bit from request to response */
1335 if (DNS_PACKET_DO(t
->sent
) && !DNS_PACKET_DO(t
->received
))
1336 dns_server_packet_do_off(t
->server
, t
->current_feature_level
);
1338 /* Report that we successfully received a packet. We keep track of the largest packet
1339 * size/fragment size we got. Which is useful for announcing the EDNS(0) packet size we can
1340 * receive to our server. */
1341 dns_server_packet_received(t
->server
, p
->ipproto
, t
->current_feature_level
, dns_packet_size_unfragmented(p
));
1344 /* See if we know things we didn't know before that indicate we better restart the lookup immediately. */
1345 r
= dns_transaction_maybe_restart(t
);
1348 if (r
> 0) /* Transaction got restarted... */
1351 /* When dealing with protocols other than mDNS only consider responses with equivalent query section
1352 * to the request. For mDNS this check doesn't make sense, because the section 6 of RFC6762 states
1353 * that "Multicast DNS responses MUST NOT contain any questions in the Question Section". */
1354 if (t
->scope
->protocol
!= DNS_PROTOCOL_MDNS
) {
1355 r
= dns_packet_is_reply_for(p
, dns_transaction_key(t
));
1359 dns_transaction_complete(t
, DNS_TRANSACTION_INVALID_REPLY
);
1364 /* Install the answer as answer to the transaction. We ref the answer twice here: the main `answer`
1365 * field is later replaced by the DNSSEC validated subset. The 'answer_auxiliary' field carries the
1366 * original complete record set, including RRSIG and friends. We use this when passing data to
1367 * clients that ask for DNSSEC metadata. */
1368 dns_answer_unref(t
->answer
);
1369 t
->answer
= dns_answer_ref(p
->answer
);
1370 t
->answer_rcode
= DNS_PACKET_RCODE(p
);
1371 t
->answer_dnssec_result
= _DNSSEC_RESULT_INVALID
;
1372 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, false);
1373 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_CONFIDENTIAL
, encrypted
);
1375 r
= dns_transaction_fix_rcode(t
);
1379 /* Block GC while starting requests for additional DNSSEC RRs */
1381 r
= dns_transaction_request_dnssec_keys(t
);
1384 /* Maybe the transaction is ready for GC'ing now? If so, free it and return. */
1385 if (!dns_transaction_gc(t
))
1388 /* Requesting additional keys might have resulted in this transaction to fail, since the auxiliary
1389 * request failed for some reason. If so, we are not in pending state anymore, and we should exit
1391 if (t
->state
!= DNS_TRANSACTION_PENDING
)
1396 /* There are DNSSEC transactions pending now. Update the state accordingly. */
1397 t
->state
= DNS_TRANSACTION_VALIDATING
;
1398 dns_transaction_close_connection(t
, true);
1399 dns_transaction_stop_timeout(t
);
1403 dns_transaction_process_dnssec(t
);
1407 dns_transaction_complete_errno(t
, r
);
1410 static int on_dns_packet(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1411 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1412 DnsTransaction
*t
= userdata
;
1418 r
= manager_recv(t
->scope
->manager
, fd
, DNS_PROTOCOL_DNS
, &p
);
1419 if (ERRNO_IS_DISCONNECT(r
)) {
1422 /* UDP connection failures get reported via ICMP and then are possibly delivered to us on the
1423 * next recvmsg(). Treat this like a lost packet. */
1425 log_debug_errno(r
, "Connection failure for DNS UDP packet: %m");
1426 assert_se(sd_event_now(t
->scope
->manager
->event
, CLOCK_BOOTTIME
, &usec
) >= 0);
1427 dns_server_packet_lost(t
->server
, IPPROTO_UDP
, t
->current_feature_level
);
1429 dns_transaction_close_connection(t
, /* use_graveyard = */ false);
1431 if (dns_transaction_limited_retry(t
)) /* Try a different server */
1434 dns_transaction_complete_errno(t
, r
);
1438 dns_transaction_complete_errno(t
, r
);
1442 /* Spurious wakeup without any data */
1445 r
= dns_packet_validate_reply(p
);
1447 log_debug_errno(r
, "Received invalid DNS packet as response, ignoring: %m");
1451 log_debug("Received inappropriate DNS packet as response, ignoring.");
1455 if (DNS_PACKET_ID(p
) != t
->id
) {
1456 log_debug("Received packet with incorrect transaction ID, ignoring.");
1460 dns_transaction_process_reply(t
, p
, false);
1464 static int dns_transaction_emit_udp(DnsTransaction
*t
) {
1469 if (t
->scope
->protocol
== DNS_PROTOCOL_DNS
) {
1471 r
= dns_transaction_pick_server(t
);
1475 if (manager_server_is_stub(t
->scope
->manager
, t
->server
))
1478 if (t
->current_feature_level
< DNS_SERVER_FEATURE_LEVEL_UDP
|| DNS_SERVER_FEATURE_LEVEL_IS_TLS(t
->current_feature_level
))
1479 return -EAGAIN
; /* Sorry, can't do UDP, try TCP! */
1481 if (!t
->bypass
&& !dns_server_dnssec_supported(t
->server
) && dns_type_is_dnssec(dns_transaction_key(t
)->type
))
1484 if (r
> 0 || t
->dns_udp_fd
< 0) { /* Server changed, or no connection yet. */
1487 dns_transaction_close_connection(t
, true);
1489 /* Before we allocate a new UDP socket, let's process the graveyard a bit to free some fds */
1490 manager_socket_graveyard_process(t
->scope
->manager
);
1492 fd
= dns_scope_socket_udp(t
->scope
, t
->server
);
1496 r
= sd_event_add_io(t
->scope
->manager
->event
, &t
->dns_udp_event_source
, fd
, EPOLLIN
, on_dns_packet
, t
);
1502 (void) sd_event_source_set_description(t
->dns_udp_event_source
, "dns-transaction-udp");
1507 r
= dns_server_adjust_opt(t
->server
, t
->sent
, t
->current_feature_level
);
1512 dns_transaction_close_connection(t
, true);
1514 r
= dns_scope_emit_udp(t
->scope
, t
->dns_udp_fd
, t
->server
? t
->server
->family
: AF_UNSPEC
, t
->sent
);
1518 dns_transaction_reset_answer(t
);
1523 static int on_transaction_timeout(sd_event_source
*s
, usec_t usec
, void *userdata
) {
1524 DnsTransaction
*t
= userdata
;
1529 if (t
->initial_jitter_scheduled
&& !t
->initial_jitter_elapsed
) {
1530 log_debug("Initial jitter phase for transaction %" PRIu16
" elapsed.", t
->id
);
1531 t
->initial_jitter_elapsed
= true;
1533 /* Timeout reached? Increase the timeout for the server used */
1534 switch (t
->scope
->protocol
) {
1536 case DNS_PROTOCOL_DNS
:
1538 dns_server_packet_lost(t
->server
, t
->stream
? IPPROTO_TCP
: IPPROTO_UDP
, t
->current_feature_level
);
1541 case DNS_PROTOCOL_LLMNR
:
1542 case DNS_PROTOCOL_MDNS
:
1543 dns_scope_packet_lost(t
->scope
, usec
- t
->start_usec
);
1547 assert_not_reached();
1550 log_debug("Timeout reached on transaction %" PRIu16
".", t
->id
);
1553 dns_transaction_retry(t
, /* next_server= */ true); /* try a different server, but given this means
1554 * packet loss, let's do so even if we already
1559 static usec_t
transaction_get_resend_timeout(DnsTransaction
*t
) {
1563 switch (t
->scope
->protocol
) {
1565 case DNS_PROTOCOL_DNS
:
1567 /* When we do TCP, grant a much longer timeout, as in this case there's no need for us to quickly
1568 * resend, as the kernel does that anyway for us, and we really don't want to interrupt it in that
1571 return TRANSACTION_TCP_TIMEOUT_USEC
;
1573 return DNS_TIMEOUT_USEC
;
1575 case DNS_PROTOCOL_MDNS
:
1576 assert(t
->n_attempts
> 0);
1578 return MDNS_PROBING_INTERVAL_USEC
;
1580 return (1 << (t
->n_attempts
- 1)) * USEC_PER_SEC
;
1582 case DNS_PROTOCOL_LLMNR
:
1583 return t
->scope
->resend_timeout
;
1586 assert_not_reached();
1590 static void dns_transaction_randomize_answer(DnsTransaction
*t
) {
1595 /* Randomizes the order of the answer array. This is done for all cached responses, so that we return
1596 * a different order each time. We do this only for DNS traffic, in order to do some minimal, crappy
1597 * load balancing. We don't do this for LLMNR or mDNS, since the order (preferring link-local
1598 * addresses, and such like) might have meaning there, and load balancing is pointless. */
1600 if (t
->scope
->protocol
!= DNS_PROTOCOL_DNS
)
1603 /* No point in randomizing, if there's just one RR */
1604 if (dns_answer_size(t
->answer
) <= 1)
1607 r
= dns_answer_reserve_or_clone(&t
->answer
, 0);
1608 if (r
< 0) /* If this fails, just don't randomize, this is non-essential stuff after all */
1609 return (void) log_debug_errno(r
, "Failed to clone answer record, not randomizing RR order of answer: %m");
1611 dns_answer_randomize(t
->answer
);
1614 static int dns_transaction_prepare(DnsTransaction
*t
, usec_t ts
) {
1619 /* Returns 0 if dns_transaction_complete() has been called. In that case the transaction and query
1620 * candidate objects may have been invalidated and must not be accessed. Returns 1 if the transaction
1621 * has been prepared. */
1623 dns_transaction_stop_timeout(t
);
1625 if (!dns_scope_network_good(t
->scope
)) {
1626 dns_transaction_complete(t
, DNS_TRANSACTION_NETWORK_DOWN
);
1630 if (t
->n_attempts
>= TRANSACTION_ATTEMPTS_MAX(t
->scope
->protocol
)) {
1631 DnsTransactionState result
;
1633 if (t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
)
1634 /* If we didn't find anything on LLMNR, it's not an error, but a failure to resolve
1636 result
= DNS_TRANSACTION_NOT_FOUND
;
1638 result
= DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
;
1640 dns_transaction_complete(t
, result
);
1644 if (t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
&& t
->tried_stream
) {
1645 /* If we already tried via a stream, then we don't
1646 * retry on LLMNR. See RFC 4795, Section 2.7. */
1647 dns_transaction_complete(t
, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
);
1654 dns_transaction_reset_answer(t
);
1655 dns_transaction_flush_dnssec_transactions(t
);
1657 /* Check the trust anchor. Do so only on classic DNS, since DNSSEC does not apply otherwise. */
1658 if (t
->scope
->protocol
== DNS_PROTOCOL_DNS
&&
1659 !FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_TRUST_ANCHOR
)) {
1660 r
= dns_trust_anchor_lookup_positive(&t
->scope
->manager
->trust_anchor
, dns_transaction_key(t
), &t
->answer
);
1664 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
1665 t
->answer_source
= DNS_TRANSACTION_TRUST_ANCHOR
;
1666 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
|SD_RESOLVED_CONFIDENTIAL
, true);
1667 dns_transaction_complete(t
, DNS_TRANSACTION_SUCCESS
);
1671 if (dns_name_is_root(dns_resource_key_name(dns_transaction_key(t
))) &&
1672 dns_transaction_key(t
)->type
== DNS_TYPE_DS
) {
1674 /* Hmm, this is a request for the root DS? A DS RR doesn't exist in the root zone,
1675 * and if our trust anchor didn't know it either, this means we cannot do any DNSSEC
1678 if (t
->scope
->dnssec_mode
== DNSSEC_ALLOW_DOWNGRADE
) {
1679 /* We are in downgrade mode. In this case, synthesize an unsigned empty
1680 * response, so that the any lookup depending on this one can continue
1681 * assuming there was no DS, and hence the root zone was unsigned. */
1683 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
1684 t
->answer_source
= DNS_TRANSACTION_TRUST_ANCHOR
;
1685 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, false);
1686 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_CONFIDENTIAL
, true);
1687 dns_transaction_complete(t
, DNS_TRANSACTION_SUCCESS
);
1689 /* If we are not in downgrade mode, then fail the lookup, because we cannot
1690 * reasonably answer it. There might be DS RRs, but we don't know them, and
1691 * the DNS server won't tell them to us (and even if it would, we couldn't
1692 * validate and trust them. */
1693 dns_transaction_complete(t
, DNS_TRANSACTION_NO_TRUST_ANCHOR
);
1699 /* Check the zone. */
1700 if (!FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_ZONE
)) {
1701 r
= dns_zone_lookup(&t
->scope
->zone
, dns_transaction_key(t
), dns_scope_ifindex(t
->scope
), &t
->answer
, NULL
, NULL
);
1705 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
1706 t
->answer_source
= DNS_TRANSACTION_ZONE
;
1707 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
|SD_RESOLVED_CONFIDENTIAL
, true);
1708 dns_transaction_complete(t
, DNS_TRANSACTION_SUCCESS
);
1713 /* Check the cache. */
1714 if (!FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_CACHE
)) {
1716 /* Before trying the cache, let's make sure we figured out a server to use. Should this cause
1717 * a change of server this might flush the cache. */
1718 (void) dns_scope_get_dns_server(t
->scope
);
1720 /* Let's then prune all outdated entries */
1721 dns_cache_prune(&t
->scope
->cache
);
1723 r
= dns_cache_lookup(
1725 dns_transaction_key(t
),
1730 &t
->answer_query_flags
,
1731 &t
->answer_dnssec_result
);
1735 dns_transaction_randomize_answer(t
);
1737 if (t
->bypass
&& t
->scope
->protocol
== DNS_PROTOCOL_DNS
&& !t
->received
)
1738 /* When bypass mode is on, do not use cached data unless it came with a full
1740 dns_transaction_reset_answer(t
);
1742 t
->answer_source
= DNS_TRANSACTION_CACHE
;
1743 if (t
->answer_rcode
== DNS_RCODE_SUCCESS
)
1744 dns_transaction_complete(t
, DNS_TRANSACTION_SUCCESS
);
1746 dns_transaction_complete(t
, DNS_TRANSACTION_RCODE_FAILURE
);
1752 if (FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_NETWORK
)) {
1753 dns_transaction_complete(t
, DNS_TRANSACTION_NO_SOURCE
);
1760 static int dns_transaction_make_packet_mdns(DnsTransaction
*t
) {
1761 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1762 bool add_known_answers
= false;
1763 DnsResourceKey
*tkey
;
1764 _cleanup_set_free_ Set
*keys
= NULL
;
1766 unsigned nscount
= 0;
1771 assert(t
->scope
->protocol
== DNS_PROTOCOL_MDNS
);
1773 /* Discard any previously prepared packet, so we can start over and coalesce again */
1774 t
->sent
= dns_packet_unref(t
->sent
);
1776 r
= dns_packet_new_query(&p
, t
->scope
->protocol
, 0, false);
1780 r
= dns_packet_append_key(p
, dns_transaction_key(t
), 0, NULL
);
1786 if (dns_key_is_shared(dns_transaction_key(t
)))
1787 add_known_answers
= true;
1789 if (dns_transaction_key(t
)->type
== DNS_TYPE_ANY
) {
1790 r
= set_ensure_put(&keys
, &dns_resource_key_hash_ops
, dns_transaction_key(t
));
1796 * For mDNS, we want to coalesce as many open queries in pending transactions into one single
1797 * query packet on the wire as possible. To achieve that, we iterate through all pending transactions
1798 * in our current scope, and see whether their timing constraints allow them to be sent.
1801 assert_se(sd_event_now(t
->scope
->manager
->event
, CLOCK_BOOTTIME
, &ts
) >= 0);
1803 LIST_FOREACH(transactions_by_scope
, other
, t
->scope
->transactions
) {
1805 /* Skip ourselves */
1809 if (other
->state
!= DNS_TRANSACTION_PENDING
)
1812 if (other
->next_attempt_after
> ts
)
1815 if (qdcount
>= UINT16_MAX
)
1818 r
= dns_packet_append_key(p
, dns_transaction_key(other
), 0, NULL
);
1821 * If we can't stuff more questions into the packet, just give up.
1822 * One of the 'other' transactions will fire later and take care of the rest.
1830 r
= dns_transaction_prepare(other
, ts
);
1834 ts
+= transaction_get_resend_timeout(other
);
1836 r
= sd_event_add_time(
1837 other
->scope
->manager
->event
,
1838 &other
->timeout_event_source
,
1841 on_transaction_timeout
, other
);
1845 (void) sd_event_source_set_description(other
->timeout_event_source
, "dns-transaction-timeout");
1847 other
->state
= DNS_TRANSACTION_PENDING
;
1848 other
->next_attempt_after
= ts
;
1852 if (dns_key_is_shared(dns_transaction_key(other
)))
1853 add_known_answers
= true;
1855 if (dns_transaction_key(other
)->type
== DNS_TYPE_ANY
) {
1856 r
= set_ensure_put(&keys
, &dns_resource_key_hash_ops
, dns_transaction_key(other
));
1862 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(qdcount
);
1864 /* Append known answer section if we're asking for any shared record */
1865 if (add_known_answers
) {
1866 r
= dns_cache_export_shared_to_packet(&t
->scope
->cache
, p
);
1871 SET_FOREACH(tkey
, keys
) {
1872 _cleanup_(dns_answer_unrefp
) DnsAnswer
*answer
= NULL
;
1875 r
= dns_zone_lookup(&t
->scope
->zone
, tkey
, t
->scope
->link
->ifindex
, &answer
, NULL
, &tentative
);
1879 r
= dns_packet_append_answer(p
, answer
, &nscount
);
1883 DNS_PACKET_HEADER(p
)->nscount
= htobe16(nscount
);
1885 t
->sent
= TAKE_PTR(p
);
1890 static int dns_transaction_make_packet(DnsTransaction
*t
) {
1891 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1896 if (t
->scope
->protocol
== DNS_PROTOCOL_MDNS
)
1897 return dns_transaction_make_packet_mdns(t
);
1902 if (t
->bypass
&& t
->bypass
->protocol
== t
->scope
->protocol
) {
1903 /* If bypass logic is enabled and the protocol if the original packet and our scope match,
1904 * take the original packet, copy it, and patch in our new ID */
1905 r
= dns_packet_dup(&p
, t
->bypass
);
1909 r
= dns_packet_new_query(
1910 &p
, t
->scope
->protocol
,
1911 /* min_alloc_dsize = */ 0,
1912 /* dnssec_cd = */ !FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
) &&
1913 t
->scope
->dnssec_mode
!= DNSSEC_NO
);
1917 r
= dns_packet_append_key(p
, dns_transaction_key(t
), 0, NULL
);
1921 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(1);
1924 DNS_PACKET_HEADER(p
)->id
= t
->id
;
1926 t
->sent
= TAKE_PTR(p
);
1930 int dns_transaction_go(DnsTransaction
*t
) {
1933 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
1937 /* Returns > 0 if the transaction is now pending, returns 0 if could be processed immediately and has
1938 * finished now. In the latter case, the transaction and query candidate objects must not be accessed.
1941 assert_se(sd_event_now(t
->scope
->manager
->event
, CLOCK_BOOTTIME
, &ts
) >= 0);
1943 r
= dns_transaction_prepare(t
, ts
);
1947 log_debug("Firing %s transaction %" PRIu16
" for <%s> scope %s on %s/%s (validate=%s).",
1948 t
->bypass
? "bypass" : "regular",
1950 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
),
1951 dns_protocol_to_string(t
->scope
->protocol
),
1952 t
->scope
->link
? t
->scope
->link
->ifname
: "*",
1953 af_to_name_short(t
->scope
->family
),
1954 yes_no(!FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
)));
1956 if (!t
->initial_jitter_scheduled
&&
1957 IN_SET(t
->scope
->protocol
, DNS_PROTOCOL_LLMNR
, DNS_PROTOCOL_MDNS
)) {
1958 usec_t jitter
, accuracy
;
1960 /* RFC 4795 Section 2.7 suggests all queries should be delayed by a random time from 0 to
1961 * JITTER_INTERVAL. */
1963 t
->initial_jitter_scheduled
= true;
1965 switch (t
->scope
->protocol
) {
1967 case DNS_PROTOCOL_LLMNR
:
1968 jitter
= random_u64_range(LLMNR_JITTER_INTERVAL_USEC
);
1969 accuracy
= LLMNR_JITTER_INTERVAL_USEC
;
1972 case DNS_PROTOCOL_MDNS
:
1973 jitter
= usec_add(random_u64_range(MDNS_JITTER_RANGE_USEC
), MDNS_JITTER_MIN_USEC
);
1974 accuracy
= MDNS_JITTER_RANGE_USEC
;
1977 assert_not_reached();
1980 assert(!t
->timeout_event_source
);
1982 r
= sd_event_add_time_relative(
1983 t
->scope
->manager
->event
,
1984 &t
->timeout_event_source
,
1987 on_transaction_timeout
, t
);
1991 (void) sd_event_source_set_description(t
->timeout_event_source
, "dns-transaction-timeout");
1994 t
->next_attempt_after
= ts
;
1995 t
->state
= DNS_TRANSACTION_PENDING
;
1997 log_debug("Delaying %s transaction %" PRIu16
" for " USEC_FMT
"us.",
1998 dns_protocol_to_string(t
->scope
->protocol
),
2004 /* Otherwise, we need to ask the network */
2005 r
= dns_transaction_make_packet(t
);
2009 if (t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
&&
2010 (dns_name_endswith(dns_resource_key_name(dns_transaction_key(t
)), "in-addr.arpa") > 0 ||
2011 dns_name_endswith(dns_resource_key_name(dns_transaction_key(t
)), "ip6.arpa") > 0)) {
2013 /* RFC 4795, Section 2.4. says reverse lookups shall
2014 * always be made via TCP on LLMNR */
2015 r
= dns_transaction_emit_tcp(t
);
2017 /* Try via UDP, and if that fails due to large size or lack of
2018 * support try via TCP */
2019 r
= dns_transaction_emit_udp(t
);
2021 log_debug("Sending query via TCP since it is too large.");
2022 else if (r
== -EAGAIN
)
2023 log_debug("Sending query via TCP since UDP isn't supported or DNS-over-TLS is selected.");
2024 if (IN_SET(r
, -EMSGSIZE
, -EAGAIN
))
2025 r
= dns_transaction_emit_tcp(t
);
2028 if (t
->scope
->protocol
!= DNS_PROTOCOL_DNS
)
2031 /* One of our own stub listeners */
2032 log_debug_errno(r
, "Detected that specified DNS server is our own extra listener, switching DNS servers.");
2034 dns_scope_next_dns_server(t
->scope
, t
->server
);
2036 if (dns_scope_get_dns_server(t
->scope
) == t
->server
) {
2037 log_debug_errno(r
, "Still pointing to extra listener after switching DNS servers, refusing operation.");
2038 dns_transaction_complete(t
, DNS_TRANSACTION_STUB_LOOP
);
2042 return dns_transaction_go(t
);
2045 /* No servers to send this to? */
2046 dns_transaction_complete(t
, DNS_TRANSACTION_NO_SERVERS
);
2049 if (r
== -EOPNOTSUPP
) {
2050 /* Tried to ask for DNSSEC RRs, on a server that doesn't do DNSSEC */
2051 dns_transaction_complete(t
, DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
);
2054 if (t
->scope
->protocol
== DNS_PROTOCOL_LLMNR
&& ERRNO_IS_DISCONNECT(r
)) {
2055 /* On LLMNR, if we cannot connect to a host via TCP when doing reverse lookups. This means we cannot
2056 * answer this request with this protocol. */
2057 dns_transaction_complete(t
, DNS_TRANSACTION_NOT_FOUND
);
2061 if (t
->scope
->protocol
!= DNS_PROTOCOL_DNS
)
2064 /* Couldn't send? Try immediately again, with a new server */
2065 dns_scope_next_dns_server(t
->scope
, t
->server
);
2067 return dns_transaction_go(t
);
2070 ts
+= transaction_get_resend_timeout(t
);
2072 r
= sd_event_add_time(
2073 t
->scope
->manager
->event
,
2074 &t
->timeout_event_source
,
2077 on_transaction_timeout
, t
);
2081 (void) sd_event_source_set_description(t
->timeout_event_source
, "dns-transaction-timeout");
2083 t
->state
= DNS_TRANSACTION_PENDING
;
2084 t
->next_attempt_after
= ts
;
2089 static int dns_transaction_find_cyclic(DnsTransaction
*t
, DnsTransaction
*aux
) {
2096 /* Try to find cyclic dependencies between transaction objects */
2101 SET_FOREACH(n
, aux
->dnssec_transactions
) {
2102 r
= dns_transaction_find_cyclic(t
, n
);
2110 static int dns_transaction_add_dnssec_transaction(DnsTransaction
*t
, DnsResourceKey
*key
, DnsTransaction
**ret
) {
2111 _cleanup_(dns_transaction_gcp
) DnsTransaction
*aux
= NULL
;
2118 aux
= dns_scope_find_transaction(t
->scope
, key
, t
->query_flags
);
2120 r
= dns_transaction_new(&aux
, t
->scope
, key
, NULL
, t
->query_flags
);
2124 if (set_contains(t
->dnssec_transactions
, aux
)) {
2129 r
= dns_transaction_find_cyclic(t
, aux
);
2133 char s
[DNS_RESOURCE_KEY_STRING_MAX
], saux
[DNS_RESOURCE_KEY_STRING_MAX
];
2135 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
2136 "Potential cyclic dependency, refusing to add transaction %" PRIu16
" (%s) as dependency for %" PRIu16
" (%s).",
2138 dns_resource_key_to_string(dns_transaction_key(t
), s
, sizeof s
),
2140 dns_resource_key_to_string(dns_transaction_key(aux
), saux
, sizeof saux
));
2144 r
= set_ensure_allocated(&aux
->notify_transactions_done
, NULL
);
2148 r
= set_ensure_put(&t
->dnssec_transactions
, NULL
, aux
);
2152 r
= set_ensure_put(&aux
->notify_transactions
, NULL
, t
);
2154 (void) set_remove(t
->dnssec_transactions
, aux
);
2158 *ret
= TAKE_PTR(aux
);
2162 static int dns_transaction_request_dnssec_rr(DnsTransaction
*t
, DnsResourceKey
*key
) {
2163 _cleanup_(dns_answer_unrefp
) DnsAnswer
*a
= NULL
;
2164 DnsTransaction
*aux
;
2170 /* Try to get the data from the trust anchor */
2171 r
= dns_trust_anchor_lookup_positive(&t
->scope
->manager
->trust_anchor
, key
, &a
);
2175 r
= dns_answer_extend(&t
->validated_keys
, a
);
2182 /* This didn't work, ask for it via the network/cache then. */
2183 r
= dns_transaction_add_dnssec_transaction(t
, key
, &aux
);
2184 if (r
== -ELOOP
) /* This would result in a cyclic dependency */
2189 if (aux
->state
== DNS_TRANSACTION_NULL
) {
2190 r
= dns_transaction_go(aux
);
2198 static int dns_transaction_negative_trust_anchor_lookup(DnsTransaction
*t
, const char *name
) {
2203 /* Check whether the specified name is in the NTA
2204 * database, either in the global one, or the link-local
2207 r
= dns_trust_anchor_lookup_negative(&t
->scope
->manager
->trust_anchor
, name
);
2211 if (!t
->scope
->link
)
2214 return link_negative_trust_anchor_lookup(t
->scope
->link
, name
);
2217 static int dns_transaction_has_unsigned_negative_answer(DnsTransaction
*t
) {
2222 /* Checks whether the answer is negative, and lacks NSEC/NSEC3
2223 * RRs to prove it */
2225 r
= dns_transaction_has_positive_answer(t
, NULL
);
2231 /* Is this key explicitly listed as a negative trust anchor?
2232 * If so, it's nothing we need to care about */
2233 r
= dns_transaction_negative_trust_anchor_lookup(t
, dns_resource_key_name(dns_transaction_key(t
)));
2239 /* The answer does not contain any RRs that match to the
2240 * question. If so, let's see if there are any NSEC/NSEC3 RRs
2241 * included. If not, the answer is unsigned. */
2243 return !dns_answer_contains_nsec_or_nsec3(t
->answer
);
2246 static int dns_transaction_is_primary_response(DnsTransaction
*t
, DnsResourceRecord
*rr
) {
2252 /* Check if the specified RR is the "primary" response,
2253 * i.e. either matches the question precisely or is a
2254 * CNAME/DNAME for it. */
2256 r
= dns_resource_key_match_rr(dns_transaction_key(t
), rr
, NULL
);
2260 return dns_resource_key_match_cname_or_dname(dns_transaction_key(t
), rr
->key
, NULL
);
2263 static bool dns_transaction_dnssec_supported(DnsTransaction
*t
) {
2266 /* Checks whether our transaction's DNS server is assumed to be compatible with DNSSEC. Returns false as soon
2267 * as we changed our mind about a server, and now believe it is incompatible with DNSSEC. */
2269 if (t
->scope
->protocol
!= DNS_PROTOCOL_DNS
)
2272 /* If we have picked no server, then we are working from the cache or some other source, and DNSSEC might well
2273 * be supported, hence return true. */
2277 /* Note that we do not check the feature level actually used for the transaction but instead the feature level
2278 * the server is known to support currently, as the transaction feature level might be lower than what the
2279 * server actually supports, since we might have downgraded this transaction's feature level because we got a
2280 * SERVFAIL earlier and wanted to check whether downgrading fixes it. */
2282 return dns_server_dnssec_supported(t
->server
);
2285 static bool dns_transaction_dnssec_supported_full(DnsTransaction
*t
) {
2290 /* Checks whether our transaction our any of the auxiliary transactions couldn't do DNSSEC. */
2292 if (!dns_transaction_dnssec_supported(t
))
2295 SET_FOREACH(dt
, t
->dnssec_transactions
)
2296 if (!dns_transaction_dnssec_supported(dt
))
2302 int dns_transaction_request_dnssec_keys(DnsTransaction
*t
) {
2303 DnsResourceRecord
*rr
;
2310 * Retrieve all auxiliary RRs for the answer we got, so that
2311 * we can verify signatures or prove that RRs are rightfully
2312 * unsigned. Specifically:
2314 * - For RRSIG we get the matching DNSKEY
2315 * - For DNSKEY we get the matching DS
2316 * - For unsigned SOA/NS we get the matching DS
2317 * - For unsigned CNAME/DNAME/DS we get the parent SOA RR
2318 * - For other unsigned RRs we get the matching SOA RR
2319 * - For SOA/NS queries with no matching response RR, and no NSEC/NSEC3, the DS RR
2320 * - For DS queries with no matching response RRs, and no NSEC/NSEC3, the parent's SOA RR
2321 * - For other queries with no matching response RRs, and no NSEC/NSEC3, the SOA RR
2324 if (FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
) || t
->scope
->dnssec_mode
== DNSSEC_NO
)
2326 if (t
->answer_source
!= DNS_TRANSACTION_NETWORK
)
2327 return 0; /* We only need to validate stuff from the network */
2328 if (!dns_transaction_dnssec_supported(t
))
2329 return 0; /* If we can't do DNSSEC anyway there's no point in getting the auxiliary RRs */
2331 DNS_ANSWER_FOREACH(rr
, t
->answer
) {
2333 if (dns_type_is_pseudo(rr
->key
->type
))
2336 /* If this RR is in the negative trust anchor, we don't need to validate it. */
2337 r
= dns_transaction_negative_trust_anchor_lookup(t
, dns_resource_key_name(rr
->key
));
2343 switch (rr
->key
->type
) {
2345 case DNS_TYPE_RRSIG
: {
2346 /* For each RRSIG we request the matching DNSKEY */
2347 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*dnskey
= NULL
;
2349 /* If this RRSIG is about a DNSKEY RR and the
2350 * signer is the same as the owner, then we
2351 * already have the DNSKEY, and we don't have
2352 * to look for more. */
2353 if (rr
->rrsig
.type_covered
== DNS_TYPE_DNSKEY
) {
2354 r
= dns_name_equal(rr
->rrsig
.signer
, dns_resource_key_name(rr
->key
));
2361 /* If the signer is not a parent of our
2362 * original query, then this is about an
2363 * auxiliary RRset, but not anything we asked
2364 * for. In this case we aren't interested,
2365 * because we don't want to request additional
2366 * RRs for stuff we didn't really ask for, and
2367 * also to avoid request loops, where
2368 * additional RRs from one transaction result
2369 * in another transaction whose additional RRs
2370 * point back to the original transaction, and
2372 r
= dns_name_endswith(dns_resource_key_name(dns_transaction_key(t
)), rr
->rrsig
.signer
);
2378 dnskey
= dns_resource_key_new(rr
->key
->class, DNS_TYPE_DNSKEY
, rr
->rrsig
.signer
);
2382 log_debug("Requesting DNSKEY to validate transaction %" PRIu16
" (%s, RRSIG with key tag: %" PRIu16
").",
2383 t
->id
, dns_resource_key_name(rr
->key
), rr
->rrsig
.key_tag
);
2384 r
= dns_transaction_request_dnssec_rr(t
, dnskey
);
2390 case DNS_TYPE_DNSKEY
: {
2391 /* For each DNSKEY we request the matching DS */
2392 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*ds
= NULL
;
2394 /* If the DNSKEY we are looking at is not for
2395 * zone we are interested in, nor any of its
2396 * parents, we aren't interested, and don't
2397 * request it. After all, we don't want to end
2398 * up in request loops, and want to keep
2399 * additional traffic down. */
2401 r
= dns_name_endswith(dns_resource_key_name(dns_transaction_key(t
)), dns_resource_key_name(rr
->key
));
2407 ds
= dns_resource_key_new(rr
->key
->class, DNS_TYPE_DS
, dns_resource_key_name(rr
->key
));
2411 log_debug("Requesting DS to validate transaction %" PRIu16
" (%s, DNSKEY with key tag: %" PRIu16
").",
2412 t
->id
, dns_resource_key_name(rr
->key
), dnssec_keytag(rr
, false));
2413 r
= dns_transaction_request_dnssec_rr(t
, ds
);
2422 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*ds
= NULL
;
2424 /* For an unsigned SOA or NS, try to acquire
2425 * the matching DS RR, as we are at a zone cut
2426 * then, and whether a DS exists tells us
2427 * whether the zone is signed. Do so only if
2428 * this RR matches our original question,
2431 r
= dns_resource_key_match_rr(dns_transaction_key(t
), rr
, NULL
);
2435 /* Hmm, so this SOA RR doesn't match our original question. In this case, maybe this is
2436 * a negative reply, and we need the SOA RR's TTL in order to cache a negative entry?
2437 * If so, we need to validate it, too. */
2439 r
= dns_answer_match_key(t
->answer
, dns_transaction_key(t
), NULL
);
2442 if (r
> 0) /* positive reply, we won't need the SOA and hence don't need to validate
2446 /* Only bother with this if the SOA/NS RR we are looking at is actually a parent of
2447 * what we are looking for, otherwise there's no value in it for us. */
2448 r
= dns_name_endswith(dns_resource_key_name(dns_transaction_key(t
)), dns_resource_key_name(rr
->key
));
2455 r
= dnssec_has_rrsig(t
->answer
, rr
->key
);
2461 ds
= dns_resource_key_new(rr
->key
->class, DNS_TYPE_DS
, dns_resource_key_name(rr
->key
));
2465 log_debug("Requesting DS to validate transaction %" PRIu16
" (%s, unsigned SOA/NS RRset).",
2466 t
->id
, dns_resource_key_name(rr
->key
));
2467 r
= dns_transaction_request_dnssec_rr(t
, ds
);
2475 case DNS_TYPE_CNAME
:
2476 case DNS_TYPE_DNAME
: {
2477 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*soa
= NULL
;
2480 /* CNAMEs and DNAMEs cannot be located at a
2481 * zone apex, hence ask for the parent SOA for
2482 * unsigned CNAME/DNAME RRs, maybe that's the
2483 * apex. But do all that only if this is
2484 * actually a response to our original
2487 * Similar for DS RRs, which are signed when
2488 * the parent SOA is signed. */
2490 r
= dns_transaction_is_primary_response(t
, rr
);
2496 r
= dnssec_has_rrsig(t
->answer
, rr
->key
);
2502 r
= dns_answer_has_dname_for_cname(t
->answer
, rr
);
2508 name
= dns_resource_key_name(rr
->key
);
2509 r
= dns_name_parent(&name
);
2515 soa
= dns_resource_key_new(rr
->key
->class, DNS_TYPE_SOA
, name
);
2519 log_debug("Requesting parent SOA to validate transaction %" PRIu16
" (%s, unsigned CNAME/DNAME/DS RRset).",
2520 t
->id
, dns_resource_key_name(rr
->key
));
2521 r
= dns_transaction_request_dnssec_rr(t
, soa
);
2529 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*soa
= NULL
;
2531 /* For other unsigned RRsets (including
2532 * NSEC/NSEC3!), look for proof the zone is
2533 * unsigned, by requesting the SOA RR of the
2534 * zone. However, do so only if they are
2535 * directly relevant to our original
2538 r
= dns_transaction_is_primary_response(t
, rr
);
2544 r
= dnssec_has_rrsig(t
->answer
, rr
->key
);
2550 soa
= dns_resource_key_new(rr
->key
->class, DNS_TYPE_SOA
, dns_resource_key_name(rr
->key
));
2554 log_debug("Requesting SOA to validate transaction %" PRIu16
" (%s, unsigned non-SOA/NS RRset <%s>).",
2555 t
->id
, dns_resource_key_name(rr
->key
), dns_resource_record_to_string(rr
));
2556 r
= dns_transaction_request_dnssec_rr(t
, soa
);
2563 /* Above, we requested everything necessary to validate what
2564 * we got. Now, let's request what we need to validate what we
2567 r
= dns_transaction_has_unsigned_negative_answer(t
);
2574 name
= dns_resource_key_name(dns_transaction_key(t
));
2576 /* If this was a SOA or NS request, then check if there's a DS RR for the same domain. Note that this
2577 * could also be used as indication that we are not at a zone apex, but in real world setups there are
2578 * too many broken DNS servers (Hello, incapdns.net!) where non-terminal zones return NXDOMAIN even
2579 * though they have further children. If this was a DS request, then it's signed when the parent zone
2580 * is signed, hence ask the parent SOA in that case. If this was any other RR then ask for the SOA RR,
2581 * to see if that is signed. */
2583 if (dns_transaction_key(t
)->type
== DNS_TYPE_DS
) {
2584 r
= dns_name_parent(&name
);
2586 type
= DNS_TYPE_SOA
;
2587 log_debug("Requesting parent SOA (→ %s) to validate transaction %" PRIu16
" (%s, unsigned empty DS response).",
2588 name
, t
->id
, dns_resource_key_name(dns_transaction_key(t
)));
2592 } else if (IN_SET(dns_transaction_key(t
)->type
, DNS_TYPE_SOA
, DNS_TYPE_NS
)) {
2595 log_debug("Requesting DS (→ %s) to validate transaction %" PRIu16
" (%s, unsigned empty SOA/NS response).",
2599 type
= DNS_TYPE_SOA
;
2600 log_debug("Requesting SOA (→ %s) to validate transaction %" PRIu16
" (%s, unsigned empty non-SOA/NS/DS response).",
2605 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*soa
= NULL
;
2607 soa
= dns_resource_key_new(dns_transaction_key(t
)->class, type
, name
);
2611 r
= dns_transaction_request_dnssec_rr(t
, soa
);
2617 return dns_transaction_dnssec_is_live(t
);
2620 void dns_transaction_notify(DnsTransaction
*t
, DnsTransaction
*source
) {
2624 /* Invoked whenever any of our auxiliary DNSSEC transactions completed its work. If the state is still PENDING,
2625 we are still in the loop that adds further DNSSEC transactions, hence don't check if we are ready yet. If
2626 the state is VALIDATING however, we should check if we are complete now. */
2628 if (t
->state
== DNS_TRANSACTION_VALIDATING
)
2629 dns_transaction_process_dnssec(t
);
2632 static int dns_transaction_validate_dnskey_by_ds(DnsTransaction
*t
) {
2633 DnsAnswerItem
*item
;
2638 /* Add all DNSKEY RRs from the answer that are validated by DS
2639 * RRs from the list of validated keys to the list of
2640 * validated keys. */
2642 DNS_ANSWER_FOREACH_ITEM(item
, t
->answer
) {
2644 r
= dnssec_verify_dnskey_by_ds_search(item
->rr
, t
->validated_keys
);
2650 /* If so, the DNSKEY is validated too. */
2651 r
= dns_answer_add_extend(&t
->validated_keys
, item
->rr
, item
->ifindex
, item
->flags
|DNS_ANSWER_AUTHENTICATED
, item
->rrsig
);
2659 static int dns_transaction_requires_rrsig(DnsTransaction
*t
, DnsResourceRecord
*rr
) {
2665 /* Checks if the RR we are looking for must be signed with an
2666 * RRSIG. This is used for positive responses. */
2668 if (t
->scope
->dnssec_mode
== DNSSEC_NO
)
2671 if (dns_type_is_pseudo(rr
->key
->type
))
2674 r
= dns_transaction_negative_trust_anchor_lookup(t
, dns_resource_key_name(rr
->key
));
2680 switch (rr
->key
->type
) {
2682 case DNS_TYPE_RRSIG
:
2683 /* RRSIGs are the signatures themselves, they need no signing. */
2690 /* For SOA or NS RRs we look for a matching DS transaction */
2692 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2694 if (dns_transaction_key(dt
)->class != rr
->key
->class)
2696 if (dns_transaction_key(dt
)->type
!= DNS_TYPE_DS
)
2699 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), dns_resource_key_name(rr
->key
));
2705 /* We found a DS transactions for the SOA/NS
2706 * RRs we are looking at. If it discovered signed DS
2707 * RRs, then we need to be signed, too. */
2709 if (!FLAGS_SET(dt
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
))
2712 return dns_answer_match_key(dt
->answer
, dns_transaction_key(dt
), NULL
);
2715 /* We found nothing that proves this is safe to leave
2716 * this unauthenticated, hence ask inist on
2717 * authentication. */
2722 case DNS_TYPE_CNAME
:
2723 case DNS_TYPE_DNAME
: {
2724 const char *parent
= NULL
;
2728 * CNAME/DNAME RRs cannot be located at a zone apex, hence look directly for the parent SOA.
2730 * DS RRs are signed if the parent is signed, hence also look at the parent SOA
2733 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2735 if (dns_transaction_key(dt
)->class != rr
->key
->class)
2737 if (dns_transaction_key(dt
)->type
!= DNS_TYPE_SOA
)
2741 parent
= dns_resource_key_name(rr
->key
);
2742 r
= dns_name_parent(&parent
);
2746 if (rr
->key
->type
== DNS_TYPE_DS
)
2749 /* A CNAME/DNAME without a parent? That's sooo weird. */
2750 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG
),
2751 "Transaction %" PRIu16
" claims CNAME/DNAME at root. Refusing.", t
->id
);
2755 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), parent
);
2761 return FLAGS_SET(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
);
2770 /* Any other kind of RR (including DNSKEY/NSEC/NSEC3). Let's see if our SOA lookup was authenticated */
2772 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2774 if (dns_transaction_key(dt
)->class != rr
->key
->class)
2776 if (dns_transaction_key(dt
)->type
!= DNS_TYPE_SOA
)
2779 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), dns_resource_key_name(rr
->key
));
2785 /* We found the transaction that was supposed to find the SOA RR for us. It was
2786 * successful, but found no RR for us. This means we are not at a zone cut. In this
2787 * case, we require authentication if the SOA lookup was authenticated too. */
2788 return FLAGS_SET(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
);
2795 static int dns_transaction_in_private_tld(DnsTransaction
*t
, const DnsResourceKey
*key
) {
2800 /* If DNSSEC downgrade mode is on, checks whether the
2801 * specified RR is one level below a TLD we have proven not to
2802 * exist. In such a case we assume that this is a private
2803 * domain, and permit it.
2805 * This detects cases like the Fritz!Box router networks. Each
2806 * Fritz!Box router serves a private "fritz.box" zone, in the
2807 * non-existing TLD "box". Requests for the "fritz.box" domain
2808 * are served by the router itself, while requests for the
2809 * "box" domain will result in NXDOMAIN.
2811 * Note that this logic is unable to detect cases where a
2812 * router serves a private DNS zone directly under
2813 * non-existing TLD. In such a case we cannot detect whether
2814 * the TLD is supposed to exist or not, as all requests we
2815 * make for it will be answered by the router's zone, and not
2816 * by the root zone. */
2820 if (t
->scope
->dnssec_mode
!= DNSSEC_ALLOW_DOWNGRADE
)
2821 return false; /* In strict DNSSEC mode what doesn't exist, doesn't exist */
2823 tld
= dns_resource_key_name(key
);
2824 r
= dns_name_parent(&tld
);
2828 return false; /* Already the root domain */
2830 if (!dns_name_is_single_label(tld
))
2833 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2835 if (dns_transaction_key(dt
)->class != key
->class)
2838 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), tld
);
2844 /* We found an auxiliary lookup we did for the TLD. If
2845 * that returned with NXDOMAIN, we know the TLD didn't
2846 * exist, and hence this might be a private zone. */
2848 return dt
->answer_rcode
== DNS_RCODE_NXDOMAIN
;
2854 static int dns_transaction_requires_nsec(DnsTransaction
*t
) {
2855 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
2863 /* Checks if we need to insist on NSEC/NSEC3 RRs for proving
2864 * this negative reply */
2866 if (t
->scope
->dnssec_mode
== DNSSEC_NO
)
2869 if (dns_type_is_pseudo(dns_transaction_key(t
)->type
))
2872 r
= dns_transaction_negative_trust_anchor_lookup(t
, dns_resource_key_name(dns_transaction_key(t
)));
2878 r
= dns_transaction_in_private_tld(t
, dns_transaction_key(t
));
2882 /* The lookup is from a TLD that is proven not to
2883 * exist, and we are in downgrade mode, hence ignore
2884 * that fact that we didn't get any NSEC RRs. */
2886 log_info("Detected a negative query %s in a private DNS zone, permitting unsigned response.",
2887 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
));
2891 name
= dns_resource_key_name(dns_transaction_key(t
));
2893 if (dns_transaction_key(t
)->type
== DNS_TYPE_DS
) {
2895 /* We got a negative reply for this DS lookup? DS RRs are signed when their parent zone is signed,
2896 * hence check the parent SOA in this case. */
2898 r
= dns_name_parent(&name
);
2904 type
= DNS_TYPE_SOA
;
2906 } else if (IN_SET(dns_transaction_key(t
)->type
, DNS_TYPE_SOA
, DNS_TYPE_NS
))
2907 /* We got a negative reply for this SOA/NS lookup? If so, check if there's a DS RR for this */
2910 /* For all other negative replies, check for the SOA lookup */
2911 type
= DNS_TYPE_SOA
;
2913 /* For all other RRs we check the SOA on the same level to see
2914 * if it's signed. */
2916 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2918 if (dns_transaction_key(dt
)->class != dns_transaction_key(t
)->class)
2920 if (dns_transaction_key(dt
)->type
!= type
)
2923 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), name
);
2929 return FLAGS_SET(dt
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
);
2932 /* If in doubt, require NSEC/NSEC3 */
2936 static int dns_transaction_dnskey_authenticated(DnsTransaction
*t
, DnsResourceRecord
*rr
) {
2937 DnsResourceRecord
*rrsig
;
2941 /* Checks whether any of the DNSKEYs used for the RRSIGs for
2942 * the specified RRset is authenticated (i.e. has a matching
2945 r
= dns_transaction_negative_trust_anchor_lookup(t
, dns_resource_key_name(rr
->key
));
2951 DNS_ANSWER_FOREACH(rrsig
, t
->answer
) {
2954 r
= dnssec_key_match_rrsig(rr
->key
, rrsig
);
2960 SET_FOREACH(dt
, t
->dnssec_transactions
) {
2962 if (dns_transaction_key(dt
)->class != rr
->key
->class)
2965 if (dns_transaction_key(dt
)->type
== DNS_TYPE_DNSKEY
) {
2967 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), rrsig
->rrsig
.signer
);
2973 /* OK, we found an auxiliary DNSKEY lookup. If that lookup is authenticated,
2976 if (FLAGS_SET(dt
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
))
2981 } else if (dns_transaction_key(dt
)->type
== DNS_TYPE_DS
) {
2983 r
= dns_name_equal(dns_resource_key_name(dns_transaction_key(dt
)), rrsig
->rrsig
.signer
);
2989 /* OK, we found an auxiliary DS lookup. If that lookup is authenticated and
2990 * non-zero, we won! */
2992 if (!FLAGS_SET(dt
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
))
2995 return dns_answer_match_key(dt
->answer
, dns_transaction_key(dt
), NULL
);
3000 return found
? false : -ENXIO
;
3003 static int dns_transaction_known_signed(DnsTransaction
*t
, DnsResourceRecord
*rr
) {
3007 /* We know that the root domain is signed, hence if it appears
3008 * not to be signed, there's a problem with the DNS server */
3010 return rr
->key
->class == DNS_CLASS_IN
&&
3011 dns_name_is_root(dns_resource_key_name(rr
->key
));
3014 static int dns_transaction_check_revoked_trust_anchors(DnsTransaction
*t
) {
3015 DnsResourceRecord
*rr
;
3020 /* Maybe warn the user that we encountered a revoked DNSKEY
3021 * for a key from our trust anchor. Note that we don't care
3022 * whether the DNSKEY can be authenticated or not. It's
3023 * sufficient if it is self-signed. */
3025 DNS_ANSWER_FOREACH(rr
, t
->answer
) {
3026 r
= dns_trust_anchor_check_revoked(&t
->scope
->manager
->trust_anchor
, rr
, t
->answer
);
3034 static int dns_transaction_invalidate_revoked_keys(DnsTransaction
*t
) {
3040 /* Removes all DNSKEY/DS objects from t->validated_keys that
3041 * our trust anchors database considers revoked. */
3044 DnsResourceRecord
*rr
;
3048 DNS_ANSWER_FOREACH(rr
, t
->validated_keys
) {
3049 r
= dns_trust_anchor_is_revoked(&t
->scope
->manager
->trust_anchor
, rr
);
3053 r
= dns_answer_remove_by_rr(&t
->validated_keys
, rr
);
3067 static int dns_transaction_copy_validated(DnsTransaction
*t
) {
3073 /* Copy all validated RRs from the auxiliary DNSSEC transactions into our set of validated RRs */
3075 SET_FOREACH(dt
, t
->dnssec_transactions
) {
3077 if (DNS_TRANSACTION_IS_LIVE(dt
->state
))
3080 if (!FLAGS_SET(dt
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
))
3083 r
= dns_answer_extend(&t
->validated_keys
, dt
->answer
);
3092 DNSSEC_PHASE_DNSKEY
, /* Phase #1, only validate DNSKEYs */
3093 DNSSEC_PHASE_NSEC
, /* Phase #2, only validate NSEC+NSEC3 */
3094 DNSSEC_PHASE_ALL
, /* Phase #3, validate everything else */
3097 static int dnssec_validate_records(
3101 DnsAnswer
**validated
) {
3103 DnsResourceRecord
*rr
;
3106 /* Returns negative on error, 0 if validation failed, 1 to restart validation, 2 when finished. */
3108 DNS_ANSWER_FOREACH(rr
, t
->answer
) {
3109 DnsResourceRecord
*rrsig
= NULL
;
3110 DnssecResult result
;
3112 switch (rr
->key
->type
) {
3113 case DNS_TYPE_RRSIG
:
3116 case DNS_TYPE_DNSKEY
:
3117 /* We validate DNSKEYs only in the DNSKEY and ALL phases */
3118 if (phase
== DNSSEC_PHASE_NSEC
)
3123 case DNS_TYPE_NSEC3
:
3126 /* We validate NSEC/NSEC3 only in the NSEC and ALL phases */
3127 if (phase
== DNSSEC_PHASE_DNSKEY
)
3132 /* We validate all other RRs only in the ALL phases */
3133 if (phase
!= DNSSEC_PHASE_ALL
)
3137 r
= dnssec_verify_rrset_search(
3147 log_debug("Looking at %s: %s", strna(dns_resource_record_to_string(rr
)), dnssec_result_to_string(result
));
3149 if (result
== DNSSEC_VALIDATED
) {
3152 if (rr
->key
->type
== DNS_TYPE_DNSKEY
) {
3153 /* If we just validated a DNSKEY RRset, then let's add these keys to
3154 * the set of validated keys for this transaction. */
3156 r
= dns_answer_copy_by_key(&t
->validated_keys
, t
->answer
, rr
->key
, DNS_ANSWER_AUTHENTICATED
, rrsig
);
3160 /* Some of the DNSKEYs we just added might already have been revoked,
3161 * remove them again in that case. */
3162 r
= dns_transaction_invalidate_revoked_keys(t
);
3167 /* Add the validated RRset to the new list of validated RRsets, and remove it from
3168 * the unvalidated RRsets. We mark the RRset as authenticated and cacheable. */
3169 r
= dns_answer_move_by_key(validated
, &t
->answer
, rr
->key
, DNS_ANSWER_AUTHENTICATED
|DNS_ANSWER_CACHEABLE
, rrsig
);
3173 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_SECURE
, rr
->key
);
3175 /* Exit the loop, we dropped something from the answer, start from the beginning */
3179 /* If we haven't read all DNSKEYs yet a negative result of the validation is irrelevant, as
3180 * there might be more DNSKEYs coming. Similar, if we haven't read all NSEC/NSEC3 RRs yet,
3181 * we cannot do positive wildcard proofs yet, as those require the NSEC/NSEC3 RRs. */
3182 if (phase
!= DNSSEC_PHASE_ALL
)
3185 if (result
== DNSSEC_VALIDATED_WILDCARD
) {
3186 bool authenticated
= false;
3191 /* This RRset validated, but as a wildcard. This means we need
3192 * to prove via NSEC/NSEC3 that no matching non-wildcard RR exists. */
3194 /* First step, determine the source of synthesis */
3195 r
= dns_resource_record_source(rrsig
, &source
);
3199 r
= dnssec_test_positive_wildcard(*validated
,
3200 dns_resource_key_name(rr
->key
),
3202 rrsig
->rrsig
.signer
,
3205 /* Unless the NSEC proof showed that the key really doesn't exist something is off. */
3207 result
= DNSSEC_INVALID
;
3209 r
= dns_answer_move_by_key(
3213 authenticated
? (DNS_ANSWER_AUTHENTICATED
|DNS_ANSWER_CACHEABLE
) : 0,
3218 manager_dnssec_verdict(t
->scope
->manager
, authenticated
? DNSSEC_SECURE
: DNSSEC_INSECURE
, rr
->key
);
3220 /* Exit the loop, we dropped something from the answer, start from the beginning */
3225 if (result
== DNSSEC_NO_SIGNATURE
) {
3226 r
= dns_transaction_requires_rrsig(t
, rr
);
3230 /* Data does not require signing. In that case, just copy it over,
3231 * but remember that this is by no means authenticated. */
3232 r
= dns_answer_move_by_key(
3241 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, rr
->key
);
3245 r
= dns_transaction_known_signed(t
, rr
);
3249 /* This is an RR we know has to be signed. If it isn't this means
3250 * the server is not attaching RRSIGs, hence complain. */
3252 dns_server_packet_rrsig_missing(t
->server
, t
->current_feature_level
);
3254 if (t
->scope
->dnssec_mode
== DNSSEC_ALLOW_DOWNGRADE
) {
3256 /* Downgrading is OK? If so, just consider the information unsigned */
3258 r
= dns_answer_move_by_key(validated
, &t
->answer
, rr
->key
, 0, NULL
);
3262 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, rr
->key
);
3266 /* Otherwise, fail */
3267 t
->answer_dnssec_result
= DNSSEC_INCOMPATIBLE_SERVER
;
3271 r
= dns_transaction_in_private_tld(t
, rr
->key
);
3275 char s
[DNS_RESOURCE_KEY_STRING_MAX
];
3277 /* The data is from a TLD that is proven not to exist, and we are in downgrade
3278 * mode, hence ignore the fact that this was not signed. */
3280 log_info("Detected RRset %s is in a private DNS zone, permitting unsigned RRs.",
3281 dns_resource_key_to_string(rr
->key
, s
, sizeof s
));
3283 r
= dns_answer_move_by_key(validated
, &t
->answer
, rr
->key
, 0, NULL
);
3287 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, rr
->key
);
3294 DNSSEC_SIGNATURE_EXPIRED
,
3295 DNSSEC_UNSUPPORTED_ALGORITHM
)) {
3297 r
= dns_transaction_dnskey_authenticated(t
, rr
);
3298 if (r
< 0 && r
!= -ENXIO
)
3301 /* The DNSKEY transaction was not authenticated, this means there's
3302 * no DS for this, which means it's OK if no keys are found for this signature. */
3304 r
= dns_answer_move_by_key(validated
, &t
->answer
, rr
->key
, 0, NULL
);
3308 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, rr
->key
);
3313 r
= dns_transaction_is_primary_response(t
, rr
);
3317 /* Look for a matching DNAME for this CNAME */
3318 r
= dns_answer_has_dname_for_cname(t
->answer
, rr
);
3322 /* Also look among the stuff we already validated */
3323 r
= dns_answer_has_dname_for_cname(*validated
, rr
);
3331 DNSSEC_SIGNATURE_EXPIRED
,
3332 DNSSEC_NO_SIGNATURE
))
3333 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_BOGUS
, rr
->key
);
3334 else /* DNSSEC_MISSING_KEY or DNSSEC_UNSUPPORTED_ALGORITHM */
3335 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INDETERMINATE
, rr
->key
);
3337 /* This is a primary response to our question, and it failed validation.
3339 t
->answer_dnssec_result
= result
;
3343 /* This is a primary response, but we do have a DNAME RR
3344 * in the RR that can replay this CNAME, hence rely on
3345 * that, and we can remove the CNAME in favour of it. */
3348 /* This is just some auxiliary data. Just remove the RRset and continue. */
3349 r
= dns_answer_remove_by_key(&t
->answer
, rr
->key
);
3353 /* We dropped something from the answer, start from the beginning. */
3357 return 2; /* Finito. */
3360 int dns_transaction_validate_dnssec(DnsTransaction
*t
) {
3361 _cleanup_(dns_answer_unrefp
) DnsAnswer
*validated
= NULL
;
3363 DnsAnswerFlags flags
;
3365 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
3369 /* We have now collected all DS and DNSKEY RRs in t->validated_keys, let's see which RRs we can now
3370 * authenticate with that. */
3372 if (FLAGS_SET(t
->query_flags
, SD_RESOLVED_NO_VALIDATE
) || t
->scope
->dnssec_mode
== DNSSEC_NO
)
3375 /* Already validated */
3376 if (t
->answer_dnssec_result
!= _DNSSEC_RESULT_INVALID
)
3379 /* Our own stuff needs no validation */
3380 if (IN_SET(t
->answer_source
, DNS_TRANSACTION_ZONE
, DNS_TRANSACTION_TRUST_ANCHOR
)) {
3381 t
->answer_dnssec_result
= DNSSEC_VALIDATED
;
3382 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, true);
3386 /* Cached stuff is not affected by validation. */
3387 if (t
->answer_source
!= DNS_TRANSACTION_NETWORK
)
3390 if (!dns_transaction_dnssec_supported_full(t
)) {
3391 /* The server does not support DNSSEC, or doesn't augment responses with RRSIGs. */
3392 t
->answer_dnssec_result
= DNSSEC_INCOMPATIBLE_SERVER
;
3393 log_debug("Not validating response for %" PRIu16
", used server feature level does not support DNSSEC.", t
->id
);
3397 log_debug("Validating response from transaction %" PRIu16
" (%s).",
3399 dns_resource_key_to_string(dns_transaction_key(t
), key_str
, sizeof key_str
));
3401 /* First, see if this response contains any revoked trust
3402 * anchors we care about */
3403 r
= dns_transaction_check_revoked_trust_anchors(t
);
3407 /* Third, copy all RRs we acquired successfully from auxiliary RRs over. */
3408 r
= dns_transaction_copy_validated(t
);
3412 /* Second, see if there are DNSKEYs we already know a
3413 * validated DS for. */
3414 r
= dns_transaction_validate_dnskey_by_ds(t
);
3418 /* Fourth, remove all DNSKEY and DS RRs again that our trust
3419 * anchor says are revoked. After all we might have marked
3420 * some keys revoked above, but they might still be lingering
3421 * in our validated_keys list. */
3422 r
= dns_transaction_invalidate_revoked_keys(t
);
3426 phase
= DNSSEC_PHASE_DNSKEY
;
3428 bool have_nsec
= false;
3430 r
= dnssec_validate_records(t
, phase
, &have_nsec
, &validated
);
3434 /* Try again as long as we managed to achieve something */
3438 if (phase
== DNSSEC_PHASE_DNSKEY
&& have_nsec
) {
3439 /* OK, we processed all DNSKEYs, and there are NSEC/NSEC3 RRs, look at those now. */
3440 phase
= DNSSEC_PHASE_NSEC
;
3444 if (phase
!= DNSSEC_PHASE_ALL
) {
3445 /* OK, we processed all DNSKEYs and NSEC/NSEC3 RRs, look at all the rest now.
3446 * Note that in this third phase we start to remove RRs we couldn't validate. */
3447 phase
= DNSSEC_PHASE_ALL
;
3455 dns_answer_unref(t
->answer
);
3456 t
->answer
= TAKE_PTR(validated
);
3458 /* At this point the answer only contains validated
3459 * RRsets. Now, let's see if it actually answers the question
3460 * we asked. If so, great! If it doesn't, then see if
3461 * NSEC/NSEC3 can prove this. */
3462 r
= dns_transaction_has_positive_answer(t
, &flags
);
3464 /* Yes, it answers the question! */
3466 if (flags
& DNS_ANSWER_AUTHENTICATED
) {
3467 /* The answer is fully authenticated, yay. */
3468 t
->answer_dnssec_result
= DNSSEC_VALIDATED
;
3469 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
3470 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, true);
3472 /* The answer is not fully authenticated. */
3473 t
->answer_dnssec_result
= DNSSEC_UNSIGNED
;
3474 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, false);
3477 } else if (r
== 0) {
3478 DnssecNsecResult nr
;
3479 bool authenticated
= false;
3481 /* Bummer! Let's check NSEC/NSEC3 */
3482 r
= dnssec_nsec_test(t
->answer
, dns_transaction_key(t
), &nr
, &authenticated
, &t
->answer_nsec_ttl
);
3488 case DNSSEC_NSEC_NXDOMAIN
:
3489 /* NSEC proves the domain doesn't exist. Very good. */
3490 log_debug("Proved NXDOMAIN via NSEC/NSEC3 for transaction %u (%s)", t
->id
, key_str
);
3491 t
->answer_dnssec_result
= DNSSEC_VALIDATED
;
3492 t
->answer_rcode
= DNS_RCODE_NXDOMAIN
;
3493 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, authenticated
);
3495 manager_dnssec_verdict(t
->scope
->manager
, authenticated
? DNSSEC_SECURE
: DNSSEC_INSECURE
, dns_transaction_key(t
));
3498 case DNSSEC_NSEC_NODATA
:
3499 /* NSEC proves that there's no data here, very good. */
3500 log_debug("Proved NODATA via NSEC/NSEC3 for transaction %u (%s)", t
->id
, key_str
);
3501 t
->answer_dnssec_result
= DNSSEC_VALIDATED
;
3502 t
->answer_rcode
= DNS_RCODE_SUCCESS
;
3503 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, authenticated
);
3505 manager_dnssec_verdict(t
->scope
->manager
, authenticated
? DNSSEC_SECURE
: DNSSEC_INSECURE
, dns_transaction_key(t
));
3508 case DNSSEC_NSEC_OPTOUT
:
3509 /* NSEC3 says the data might not be signed */
3510 log_debug("Data is NSEC3 opt-out via NSEC/NSEC3 for transaction %u (%s)", t
->id
, key_str
);
3511 t
->answer_dnssec_result
= DNSSEC_UNSIGNED
;
3512 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, false);
3514 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, dns_transaction_key(t
));
3517 case DNSSEC_NSEC_NO_RR
:
3518 /* No NSEC data? Bummer! */
3520 r
= dns_transaction_requires_nsec(t
);
3524 t
->answer_dnssec_result
= DNSSEC_NO_SIGNATURE
;
3525 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_BOGUS
, dns_transaction_key(t
));
3527 t
->answer_dnssec_result
= DNSSEC_UNSIGNED
;
3528 SET_FLAG(t
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
, false);
3529 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INSECURE
, dns_transaction_key(t
));
3534 case DNSSEC_NSEC_UNSUPPORTED_ALGORITHM
:
3535 /* We don't know the NSEC3 algorithm used? */
3536 t
->answer_dnssec_result
= DNSSEC_UNSUPPORTED_ALGORITHM
;
3537 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_INDETERMINATE
, dns_transaction_key(t
));
3540 case DNSSEC_NSEC_FOUND
:
3541 case DNSSEC_NSEC_CNAME
:
3542 /* NSEC says it needs to be there, but we couldn't find it? Bummer! */
3543 t
->answer_dnssec_result
= DNSSEC_NSEC_MISMATCH
;
3544 manager_dnssec_verdict(t
->scope
->manager
, DNSSEC_BOGUS
, dns_transaction_key(t
));
3548 assert_not_reached();
3555 static const char* const dns_transaction_state_table
[_DNS_TRANSACTION_STATE_MAX
] = {
3556 [DNS_TRANSACTION_NULL
] = "null",
3557 [DNS_TRANSACTION_PENDING
] = "pending",
3558 [DNS_TRANSACTION_VALIDATING
] = "validating",
3559 [DNS_TRANSACTION_RCODE_FAILURE
] = "rcode-failure",
3560 [DNS_TRANSACTION_SUCCESS
] = "success",
3561 [DNS_TRANSACTION_NO_SERVERS
] = "no-servers",
3562 [DNS_TRANSACTION_TIMEOUT
] = "timeout",
3563 [DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
] = "attempts-max-reached",
3564 [DNS_TRANSACTION_INVALID_REPLY
] = "invalid-reply",
3565 [DNS_TRANSACTION_ERRNO
] = "errno",
3566 [DNS_TRANSACTION_ABORTED
] = "aborted",
3567 [DNS_TRANSACTION_DNSSEC_FAILED
] = "dnssec-failed",
3568 [DNS_TRANSACTION_NO_TRUST_ANCHOR
] = "no-trust-anchor",
3569 [DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
] = "rr-type-unsupported",
3570 [DNS_TRANSACTION_NETWORK_DOWN
] = "network-down",
3571 [DNS_TRANSACTION_NOT_FOUND
] = "not-found",
3572 [DNS_TRANSACTION_NO_SOURCE
] = "no-source",
3573 [DNS_TRANSACTION_STUB_LOOP
] = "stub-loop",
3575 DEFINE_STRING_TABLE_LOOKUP(dns_transaction_state
, DnsTransactionState
);
3577 static const char* const dns_transaction_source_table
[_DNS_TRANSACTION_SOURCE_MAX
] = {
3578 [DNS_TRANSACTION_NETWORK
] = "network",
3579 [DNS_TRANSACTION_CACHE
] = "cache",
3580 [DNS_TRANSACTION_ZONE
] = "zone",
3581 [DNS_TRANSACTION_TRUST_ANCHOR
] = "trust-anchor",
3583 DEFINE_STRING_TABLE_LOOKUP(dns_transaction_source
, DnsTransactionSource
);