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