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