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