1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <net/if_arp.h>
4 #include <netinet/tcp.h>
6 #include "errno-util.h"
8 #include "missing_network.h"
9 #include "missing_socket.h"
10 #include "resolved-dns-stub.h"
11 #include "socket-netlink.h"
12 #include "socket-util.h"
13 #include "stdio-util.h"
14 #include "string-table.h"
16 /* The MTU of the loopback device is 64K on Linux, advertise that as maximum datagram size, but subtract the Ethernet,
17 * IP and UDP header sizes */
18 #define ADVERTISE_DATAGRAM_SIZE_MAX (65536U-14U-20U-8U)
20 /* On the extra stubs, use a more conservative choice */
21 #define ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX DNS_PACKET_UNICAST_SIZE_LARGE_MAX
23 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
);
25 static void dns_stub_listener_extra_hash_func(const DnsStubListenerExtra
*a
, struct siphash
*state
) {
28 siphash24_compress(&a
->mode
, sizeof(a
->mode
), state
);
29 siphash24_compress(&a
->family
, sizeof(a
->family
), state
);
30 siphash24_compress(&a
->address
, FAMILY_ADDRESS_SIZE(a
->family
), state
);
31 siphash24_compress(&a
->port
, sizeof(a
->port
), state
);
34 static int dns_stub_listener_extra_compare_func(const DnsStubListenerExtra
*a
, const DnsStubListenerExtra
*b
) {
40 r
= CMP(a
->mode
, b
->mode
);
44 r
= CMP(a
->family
, b
->family
);
48 r
= memcmp(&a
->address
, &b
->address
, FAMILY_ADDRESS_SIZE(a
->family
));
52 return CMP(a
->port
, b
->port
);
55 DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(
56 dns_stub_listener_extra_hash_ops
,
58 dns_stub_listener_extra_hash_func
,
59 dns_stub_listener_extra_compare_func
,
60 dns_stub_listener_extra_free
);
62 int dns_stub_listener_extra_new(
64 DnsStubListenerExtra
**ret
) {
66 DnsStubListenerExtra
*l
;
68 l
= new(DnsStubListenerExtra
, 1);
72 *l
= (DnsStubListenerExtra
) {
80 DnsStubListenerExtra
*dns_stub_listener_extra_free(DnsStubListenerExtra
*p
) {
84 p
->udp_event_source
= sd_event_source_disable_unref(p
->udp_event_source
);
85 p
->tcp_event_source
= sd_event_source_disable_unref(p
->tcp_event_source
);
87 hashmap_free(p
->queries_by_packet
);
92 static void stub_packet_hash_func(const DnsPacket
*p
, struct siphash
*state
) {
95 siphash24_compress(&p
->protocol
, sizeof(p
->protocol
), state
);
96 siphash24_compress(&p
->family
, sizeof(p
->family
), state
);
97 siphash24_compress(&p
->sender
, sizeof(p
->sender
), state
);
98 siphash24_compress(&p
->ipproto
, sizeof(p
->ipproto
), state
);
99 siphash24_compress(&p
->sender_port
, sizeof(p
->sender_port
), state
);
100 siphash24_compress(DNS_PACKET_HEADER(p
), sizeof(DnsPacketHeader
), state
);
102 /* We don't bother hashing the full packet here, just the header */
105 static int stub_packet_compare_func(const DnsPacket
*x
, const DnsPacket
*y
) {
108 r
= CMP(x
->protocol
, y
->protocol
);
112 r
= CMP(x
->family
, y
->family
);
116 r
= memcmp(&x
->sender
, &y
->sender
, sizeof(x
->sender
));
120 r
= CMP(x
->ipproto
, y
->ipproto
);
124 r
= CMP(x
->sender_port
, y
->sender_port
);
128 return memcmp(DNS_PACKET_HEADER(x
), DNS_PACKET_HEADER(y
), sizeof(DnsPacketHeader
));
131 DEFINE_HASH_OPS(stub_packet_hash_ops
, DnsPacket
, stub_packet_hash_func
, stub_packet_compare_func
);
133 static int reply_add_with_rrsig(
135 DnsResourceRecord
*rr
,
137 DnsAnswerFlags flags
,
138 DnsResourceRecord
*rrsig
,
145 r
= dns_answer_add_extend(reply
, rr
, ifindex
, flags
, rrsig
);
149 if (with_rrsig
&& rrsig
) {
150 r
= dns_answer_add_extend(reply
, rrsig
, ifindex
, flags
, NULL
);
158 static int dns_stub_collect_answer_by_question(
161 DnsQuestion
*question
,
162 bool with_rrsig
) { /* Add RRSIG RR matching each RR */
169 /* Copies all RRs from 'answer' into 'reply', if they match 'question'. */
171 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
173 /* We have a question, let's see if this RR matches it */
174 r
= dns_question_matches_rr(question
, item
->rr
, NULL
);
178 /* Maybe there's a CNAME/DNAME in here? If so, that's an answer too */
179 r
= dns_question_matches_cname_or_dname(question
, item
->rr
, NULL
);
186 /* Mask the section info, we want the primary answers to always go without section
187 * info, so that it is added to the answer section when we synthesize a reply. */
189 r
= reply_add_with_rrsig(
193 item
->flags
& ~DNS_ANSWER_MASK_SECTIONS
,
203 static int dns_stub_collect_answer_by_section(
206 DnsAnswerFlags section
,
209 bool with_dnssec
) { /* Include DNSSEC RRs. RRSIG, NSEC, … */
216 /* Copies all RRs from 'answer' into 'reply', if they originate from the specified section. Also,
217 * avoid any RRs listed in 'exclude'. */
219 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
221 if (dns_answer_contains(exclude1
, item
->rr
) ||
222 dns_answer_contains(exclude2
, item
->rr
))
226 dns_type_is_dnssec(item
->rr
->key
->type
))
229 if (((item
->flags
^ section
) & DNS_ANSWER_MASK_SECTIONS
) != 0)
232 r
= reply_add_with_rrsig(
246 static int dns_stub_assign_sections(
248 DnsQuestion
*question
,
256 /* Let's assign the 'answer' RRs we collected to their respective sections in the reply datagram. We
257 * try to reproduce a section assignment similar to what the upstream DNS server responded to us. We
258 * use the DNS_ANSWER_SECTION_xyz flags to match things up, which is where the original upstream's
259 * packet section assignment is stored in the DnsAnswer object. Not all RRs in the 'answer' objects
260 * come with section information though (for example, because they were synthesized locally, and not
261 * from a DNS packet). To deal with that we extend the assignment logic a bit: anything from the
262 * 'answer' object that directly matches the original question is always put in the ANSWER section,
263 * regardless if it carries section info, or what that section info says. Then, anything from the
264 * 'answer' objects that is from the ANSWER or AUTHORITY sections, and wasn't already added to the
265 * ANSWER section is placed in the AUTHORITY section. Everything else from either object is added to
266 * the ADDITIONAL section. */
268 /* Include all RRs that directly answer the question in the answer section */
269 r
= dns_stub_collect_answer_by_question(
277 /* Include all RRs that originate from the authority sections, and aren't already listed in the
278 * answer section, in the authority section */
279 r
= dns_stub_collect_answer_by_section(
280 &q
->reply_authoritative
,
282 DNS_ANSWER_SECTION_AUTHORITY
,
283 q
->reply_answer
, NULL
,
288 /* Include all RRs that originate from the answer or additional sections in the additional section
289 * (except if already listed in the other two sections). Also add all RRs with no section marking. */
290 r
= dns_stub_collect_answer_by_section(
291 &q
->reply_additional
,
293 DNS_ANSWER_SECTION_ANSWER
,
294 q
->reply_answer
, q
->reply_authoritative
,
298 r
= dns_stub_collect_answer_by_section(
299 &q
->reply_additional
,
301 DNS_ANSWER_SECTION_ADDITIONAL
,
302 q
->reply_answer
, q
->reply_authoritative
,
306 r
= dns_stub_collect_answer_by_section(
307 &q
->reply_additional
,
310 q
->reply_answer
, q
->reply_authoritative
,
318 static int dns_stub_make_reply_packet(
322 bool *ret_truncated
) {
324 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
330 r
= dns_packet_new(&p
, DNS_PROTOCOL_DNS
, 0, max_size
);
334 r
= dns_packet_append_question(p
, q
);
345 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(dns_question_size(q
));
351 static int dns_stub_add_reply_packet_body(
354 DnsAnswer
*authoritative
,
355 DnsAnswer
*additional
,
356 bool edns0_do
, /* Client expects DNSSEC RRs? */
359 unsigned n_answer
= 0, n_authoritative
= 0, n_additional
= 0;
365 /* Add the three sections to the packet. If the answer section doesn't fit we'll signal that as
366 * truncation. If the authoritative section doesn't fit and we are in DNSSEC mode, also signal
367 * truncation. In all other cases where things don't fit don't signal truncation, as for those cases
368 * the dropped RRs should not be essential. */
370 r
= dns_packet_append_answer(p
, answer
, &n_answer
);
376 r
= dns_packet_append_answer(p
, authoritative
, &n_authoritative
);
377 if (r
== -EMSGSIZE
) {
383 r
= dns_packet_append_answer(p
, additional
, &n_additional
);
384 if (r
< 0 && r
!= -EMSGSIZE
)
396 DNS_PACKET_HEADER(p
)->ancount
= htobe16(n_answer
);
397 DNS_PACKET_HEADER(p
)->nscount
= htobe16(n_authoritative
);
398 DNS_PACKET_HEADER(p
)->arcount
= htobe16(n_additional
);
402 static const char *nsid_string(void) {
403 static char buffer
[SD_ID128_STRING_MAX
+ STRLEN(".resolved.systemd.io")] = "";
407 /* Let's generate a string that we can use as RFC5001 NSID identifier. The string shall identify us
408 * as systemd-resolved, and return a different string for each resolved instance without leaking host
409 * identity. Hence let's use a fixed suffix that identifies resolved, and a prefix generated from the
410 * machine ID but from which the machine ID cannot be determined.
412 * Clients can use this to determine whether an answer is originating locally or is proxied from
415 if (!isempty(buffer
))
418 r
= sd_id128_get_machine_app_specific(
419 SD_ID128_MAKE(ed
,d3
,12,5d
,16,b9
,41,f9
,a1
,49,5f
,ab
,15,62,ab
,27),
422 log_debug_errno(r
, "Failed to determine machine ID, ignoring: %m");
426 xsprintf(buffer
, SD_ID128_FORMAT_STR
".resolved.systemd.io", SD_ID128_FORMAT_VAL(id
));
430 static int dns_stub_finish_reply_packet(
434 bool tc
, /* set the Truncated bit? */
435 bool aa
, /* set the Authoritative Answer bit? */
436 bool rd
, /* set the Recursion Desired bit? */
437 bool add_opt
, /* add an OPT RR to this packet? */
438 bool edns0_do
, /* set the EDNS0 DNSSEC OK bit? */
439 bool ad
, /* set the DNSSEC authenticated data bit? */
440 bool cd
, /* set the DNSSEC checking disabled bit? */
441 uint16_t max_udp_size
, /* The maximum UDP datagram size to advertise to clients */
442 bool nsid
) { /* whether to add NSID */
449 r
= dns_packet_append_opt(p
, max_udp_size
, edns0_do
, /* include_rfc6975 = */ false, nsid
? nsid_string() : NULL
, rcode
, NULL
);
450 if (r
== -EMSGSIZE
) /* Hit the size limit? then indicate truncation */
455 /* If the client can't to EDNS0, don't do DO either */
458 /* If we don't do EDNS, clamp the rcode to 4 bit */
460 rcode
= DNS_RCODE_SERVFAIL
;
463 /* Don't set the CD bit unless DO is on, too */
467 /* Note that we allow the AD bit to be set even if client didn't signal DO, as per RFC 6840, section
470 DNS_PACKET_HEADER(p
)->id
= id
;
472 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
486 static int dns_stub_send(
488 DnsStubListenerExtra
*l
,
500 r
= dns_stream_write_packet(s
, reply
);
502 /* Note that it is essential here that we explicitly choose the source IP address for this packet. This
503 * is because otherwise the kernel will choose it automatically based on the routing table and will
504 * thus pick 127.0.0.1 rather than 127.0.0.53. */
506 manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
),
507 l
? p
->ifindex
: LOOPBACK_IFINDEX
, /* force loopback iface if this is the main listener stub */
508 p
->family
, &p
->sender
, p
->sender_port
, &p
->destination
,
511 return log_debug_errno(r
, "Failed to send reply packet: %m");
516 static int dns_stub_reply_with_edns0_do(DnsQuery
*q
) {
519 /* Reply with DNSSEC DO set? Only if client supports it; and we did any DNSSEC verification
520 * ourselves, or consider the data fully authenticated because we generated it locally, or the client
523 return DNS_PACKET_DO(q
->request_packet
) &&
524 (q
->answer_dnssec_result
>= 0 || /* we did proper DNSSEC validation … */
525 dns_query_fully_authenticated(q
) || /* … or we considered it authentic otherwise … */
526 DNS_PACKET_CD(q
->request_packet
)); /* … or client set CD */
529 static void dns_stub_suppress_duplicate_section_rrs(DnsQuery
*q
) {
530 /* If we follow a CNAME/DNAME chain we might end up populating our sections with redundant RRs
531 * because we built up the sections from multiple reply packets (one from each CNAME/DNAME chain
532 * element). E.g. it could be that an RR that was included in the first reply's additional section
533 * ends up being relevant as main answer in a subsequent reply in the chain. Let's clean this up, and
534 * remove everything in the "higher priority" sections from the "lower priority" sections.
536 * Note that this removal matches by RR keys instead of the full RRs. This is because RRsets should
537 * always end up in one section fully or not at all, but never be split among sections.
539 * Specifically: we remove ANSWER section RRs from the AUTHORITATIVE and ADDITIONAL sections, as well
540 * as AUTHORITATIVE section RRs from the ADDITIONAL section. */
542 dns_answer_remove_by_answer_keys(&q
->reply_authoritative
, q
->reply_answer
);
543 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_answer
);
544 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_authoritative
);
547 static int dns_stub_send_reply(
551 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
552 bool truncated
, edns0_do
;
557 edns0_do
= dns_stub_reply_with_edns0_do(q
); /* let's check if we shall reply with EDNS0 DO? */
559 r
= dns_stub_make_reply_packet(
561 DNS_PACKET_PAYLOAD_SIZE_MAX(q
->request_packet
),
562 q
->request_packet
->question
,
565 return log_debug_errno(r
, "Failed to build reply packet: %m");
567 dns_stub_suppress_duplicate_section_rrs(q
);
569 r
= dns_stub_add_reply_packet_body(
572 q
->reply_authoritative
,
577 return log_debug_errno(r
, "Failed to append reply packet body: %m");
579 r
= dns_stub_finish_reply_packet(
581 DNS_PACKET_ID(q
->request_packet
),
584 dns_query_fully_authoritative(q
),
585 DNS_PACKET_RD(q
->request_packet
),
586 !!q
->request_packet
->opt
,
588 DNS_PACKET_AD(q
->request_packet
) && dns_query_fully_authenticated(q
),
589 DNS_PACKET_CD(q
->request_packet
),
590 q
->stub_listener_extra
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
591 dns_packet_has_nsid_request(q
->request_packet
) > 0 && !q
->stub_listener_extra
);
593 return log_debug_errno(r
, "Failed to build failure packet: %m");
595 return dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
598 static int dns_stub_send_failure(
600 DnsStubListenerExtra
*l
,
604 bool authenticated
) {
606 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
613 r
= dns_stub_make_reply_packet(
615 DNS_PACKET_PAYLOAD_SIZE_MAX(p
),
619 return log_debug_errno(r
, "Failed to make failure packet: %m");
621 r
= dns_stub_finish_reply_packet(
630 DNS_PACKET_AD(p
) && authenticated
,
632 l
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
633 dns_packet_has_nsid_request(p
) > 0 && !l
);
635 return log_debug_errno(r
, "Failed to build failure packet: %m");
637 return dns_stub_send(m
, l
, s
, p
, reply
);
640 static int dns_stub_patch_bypass_reply_packet(
641 DnsPacket
**ret
, /* Where to place the patched packet */
642 DnsPacket
*original
, /* The packet to patch */
643 DnsPacket
*request
) { /* The packet the patched packet shall look like a reply to */
644 _cleanup_(dns_packet_unrefp
) DnsPacket
*c
= NULL
;
651 r
= dns_packet_dup(&c
, original
);
655 /* Extract the packet, so that we know where the OPT field is */
656 r
= dns_packet_extract(c
);
660 /* Copy over the original client request ID, so that we can make the upstream query look like our own reply. */
661 DNS_PACKET_HEADER(c
)->id
= DNS_PACKET_HEADER(request
)->id
;
663 /* Patch in our own maximum datagram size, if EDNS0 was on */
664 r
= dns_packet_patch_max_udp_size(c
, ADVERTISE_DATAGRAM_SIZE_MAX
);
668 /* Lower all TTLs by the time passed since we received the datagram. */
669 if (timestamp_is_set(original
->timestamp
)) {
670 r
= dns_packet_patch_ttls(c
, original
->timestamp
);
675 /* Our upstream connection might have supported larger DNS requests than our downstream one, hence
676 * set the TC bit if our reply is larger than what the client supports, and truncate. */
677 if (c
->size
> DNS_PACKET_PAYLOAD_SIZE_MAX(request
)) {
678 log_debug("Artificially truncating stub response, as advertised size of client is smaller than upstream one.");
679 dns_packet_truncate(c
, DNS_PACKET_PAYLOAD_SIZE_MAX(request
));
680 DNS_PACKET_HEADER(c
)->flags
= htobe16(be16toh(DNS_PACKET_HEADER(c
)->flags
) | DNS_PACKET_FLAG_TC
);
687 static void dns_stub_query_complete(DnsQuery
*q
) {
691 assert(q
->request_packet
);
693 if (q
->question_bypass
) {
694 /* This is a bypass reply. If so, let's propagate the upstream packet, if we have it and it
695 * is regular DNS. (We can't do this if the upstream packet is LLMNR or mDNS, since the
696 * packets are not 100% compatible.) */
698 if (q
->answer_full_packet
&&
699 q
->answer_full_packet
->protocol
== DNS_PROTOCOL_DNS
) {
700 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
702 r
= dns_stub_patch_bypass_reply_packet(&reply
, q
->answer_full_packet
, q
->request_packet
);
704 log_debug_errno(r
, "Failed to patch bypass reply packet: %m");
706 (void) dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
713 /* Take all data from the current reply, and merge it into the three reply sections we are building
714 * up. We do this before processing CNAME redirects, so that we gradually build up our sections, and
715 * and keep adding all RRs in the CNAME chain. */
716 r
= dns_stub_assign_sections(
718 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
719 dns_stub_reply_with_edns0_do(q
));
721 log_debug_errno(r
, "Failed to assign sections: %m");
728 case DNS_TRANSACTION_SUCCESS
: {
734 cname_result
= dns_query_process_cname_one(q
);
735 if (cname_result
== -ELOOP
) { /* CNAME loop, let's send what we already have */
736 log_debug_errno(r
, "Detected CNAME loop, returning what we already have.");
737 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
740 if (cname_result
< 0) {
741 log_debug_errno(cname_result
, "Failed to process CNAME: %m");
745 if (cname_result
== DNS_QUERY_NOMATCH
) {
746 /* This answer doesn't contain any RR that would answer our question
747 * positively, i.e. neither directly nor via CNAME. */
749 if (first
) /* We never followed a CNAME and the answer doesn't match our
750 * question at all? Then this is final, the empty answer is the
754 /* Otherwise, we already followed a CNAME once within this packet, and the
755 * packet doesn't answer our question. In that case let's restart the query,
756 * now with the redirected question. We'll */
759 log_debug_errno(r
, "Failed to restart query: %m");
764 r
= dns_stub_assign_sections(
766 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
767 dns_stub_reply_with_edns0_do(q
));
769 log_debug_errno(r
, "Failed to assign sections: %m");
774 if (cname_result
== DNS_QUERY_MATCH
) /* A match? Then we are done, let's return what we got */
777 /* We followed a CNAME. and collected the RRs that answer the redirected question
778 * successfully. Let's not try to do this again. */
779 assert(cname_result
== DNS_QUERY_CNAME
);
786 case DNS_TRANSACTION_RCODE_FAILURE
:
787 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
790 case DNS_TRANSACTION_NOT_FOUND
:
791 (void) dns_stub_send_reply(q
, DNS_RCODE_NXDOMAIN
);
794 case DNS_TRANSACTION_TIMEOUT
:
795 case DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
:
796 /* Propagate a timeout as a no packet, i.e. that the client also gets a timeout */
799 case DNS_TRANSACTION_NO_SERVERS
:
800 case DNS_TRANSACTION_INVALID_REPLY
:
801 case DNS_TRANSACTION_ERRNO
:
802 case DNS_TRANSACTION_ABORTED
:
803 case DNS_TRANSACTION_DNSSEC_FAILED
:
804 case DNS_TRANSACTION_NO_TRUST_ANCHOR
:
805 case DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
:
806 case DNS_TRANSACTION_NETWORK_DOWN
:
807 case DNS_TRANSACTION_NO_SOURCE
:
808 case DNS_TRANSACTION_STUB_LOOP
:
809 (void) dns_stub_send_reply(q
, DNS_RCODE_SERVFAIL
);
812 case DNS_TRANSACTION_NULL
:
813 case DNS_TRANSACTION_PENDING
:
814 case DNS_TRANSACTION_VALIDATING
:
816 assert_not_reached("Impossible state");
822 static int dns_stub_stream_complete(DnsStream
*s
, int error
) {
825 log_debug_errno(error
, "DNS TCP connection terminated, destroying queries: %m");
830 q
= set_first(s
->queries
);
837 /* This drops the implicit ref we keep around since it was allocated, as incoming stub connections
838 * should be kept as long as the client wants to. */
843 static void dns_stub_process_query(Manager
*m
, DnsStubListenerExtra
*l
, DnsStream
*s
, DnsPacket
*p
) {
844 _cleanup_(dns_query_freep
) DnsQuery
*q
= NULL
;
845 Hashmap
**queries_by_packet
;
851 assert(p
->protocol
== DNS_PROTOCOL_DNS
);
853 if (!l
&& /* l == NULL if this is the main stub */
854 (in_addr_is_localhost(p
->family
, &p
->sender
) <= 0 ||
855 in_addr_is_localhost(p
->family
, &p
->destination
) <= 0)) {
856 log_warning("Got packet on unexpected (i.e. non-localhost) IP range, ignoring.");
860 if (manager_packet_from_our_transaction(m
, p
)) {
861 log_debug("Got our own packet looped back, ignoring.");
865 queries_by_packet
= l
? &l
->queries_by_packet
: &m
->stub_queries_by_packet
;
866 existing
= hashmap_get(*queries_by_packet
, p
);
867 if (existing
&& dns_packet_equal(existing
->request_packet
, p
)) {
868 log_debug("Got repeat packet from client, ignoring.");
872 r
= dns_packet_extract(p
);
874 log_debug_errno(r
, "Failed to extract resources from incoming packet, ignoring packet: %m");
875 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_FORMERR
, false);
879 if (!DNS_PACKET_VERSION_SUPPORTED(p
)) {
880 log_debug("Got EDNS OPT field with unsupported version number.");
881 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_BADVERS
, false);
885 if (dns_type_is_obsolete(dns_question_first_key(p
->question
)->type
)) {
886 log_debug("Got message with obsolete key type, refusing.");
887 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
891 if (dns_type_is_zone_transer(dns_question_first_key(p
->question
)->type
)) {
892 log_debug("Got request for zone transfer, refusing.");
893 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
897 if (!DNS_PACKET_RD(p
)) {
898 /* If the "rd" bit is off (i.e. recursion was not requested), then refuse operation */
899 log_debug("Got request with recursion disabled, refusing.");
900 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
904 r
= hashmap_ensure_allocated(queries_by_packet
, &stub_packet_hash_ops
);
910 if (DNS_PACKET_DO(p
) && DNS_PACKET_CD(p
)) {
911 log_debug("Got request with DNSSEC checking disabled, enabling bypass logic.");
913 r
= dns_query_new(m
, &q
, NULL
, NULL
, p
, 0,
914 SD_RESOLVED_PROTOCOLS_ALL
|
915 SD_RESOLVED_NO_CNAME
|
916 SD_RESOLVED_NO_SEARCH
|
917 SD_RESOLVED_NO_VALIDATE
|
918 SD_RESOLVED_REQUIRE_PRIMARY
|
919 SD_RESOLVED_CLAMP_TTL
);
921 r
= dns_query_new(m
, &q
, p
->question
, p
->question
, NULL
, 0,
922 SD_RESOLVED_PROTOCOLS_ALL
|
923 SD_RESOLVED_NO_SEARCH
|
924 (DNS_PACKET_DO(p
) ? SD_RESOLVED_REQUIRE_PRIMARY
: 0)|
925 SD_RESOLVED_CLAMP_TTL
);
927 log_error_errno(r
, "Failed to generate query object: %m");
928 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
932 q
->request_packet
= dns_packet_ref(p
);
933 q
->request_stream
= dns_stream_ref(s
); /* make sure the stream stays around until we can send a reply through it */
934 q
->stub_listener_extra
= l
;
935 q
->complete
= dns_stub_query_complete
;
938 /* Remember which queries belong to this stream, so that we can cancel them when the stream
939 * is disconnected early */
941 r
= set_ensure_put(&s
->queries
, NULL
, q
);
949 /* Add the query to the hash table we use to determine repeat packets now. We don't care about
950 * failures here, since in the worst case we'll not recognize duplicate incoming requests, which
951 * isn't particularly bad. */
952 (void) hashmap_put(*queries_by_packet
, q
->request_packet
, q
);
956 log_error_errno(r
, "Failed to start query: %m");
957 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
961 log_debug("Processing query...");
965 static int on_dns_stub_packet_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
966 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
969 r
= manager_recv(m
, fd
, DNS_PROTOCOL_DNS
, &p
);
973 if (dns_packet_validate_query(p
) > 0) {
974 log_debug("Got DNS stub UDP query packet for id %u", DNS_PACKET_ID(p
));
976 dns_stub_process_query(m
, l
, NULL
, p
);
978 log_debug("Invalid DNS stub UDP packet, ignoring.");
983 static int on_dns_stub_packet(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
984 return on_dns_stub_packet_internal(s
, fd
, revents
, userdata
, NULL
);
987 static int on_dns_stub_packet_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
988 DnsStubListenerExtra
*l
= userdata
;
992 return on_dns_stub_packet_internal(s
, fd
, revents
, l
->manager
, l
);
995 static int on_dns_stub_stream_packet(DnsStream
*s
) {
996 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1000 p
= dns_stream_take_read_packet(s
);
1003 if (dns_packet_validate_query(p
) > 0) {
1004 log_debug("Got DNS stub TCP query packet for id %u", DNS_PACKET_ID(p
));
1006 dns_stub_process_query(s
->manager
, s
->stub_listener_extra
, s
, p
);
1008 log_debug("Invalid DNS stub TCP packet, ignoring.");
1013 static int on_dns_stub_stream_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1017 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1019 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1025 r
= dns_stream_new(m
, &stream
, DNS_STREAM_STUB
, DNS_PROTOCOL_DNS
, cfd
, NULL
);
1031 stream
->stub_listener_extra
= l
;
1032 stream
->on_packet
= on_dns_stub_stream_packet
;
1033 stream
->complete
= dns_stub_stream_complete
;
1035 /* We let the reference to the stream dangle here, it will be dropped later by the complete callback. */
1040 static int on_dns_stub_stream(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1041 return on_dns_stub_stream_internal(s
, fd
, revents
, userdata
, NULL
);
1044 static int on_dns_stub_stream_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1045 DnsStubListenerExtra
*l
= userdata
;
1048 return on_dns_stub_stream_internal(s
, fd
, revents
, l
->manager
, l
);
1051 static int set_dns_stub_common_socket_options(int fd
, int family
) {
1055 assert(IN_SET(family
, AF_INET
, AF_INET6
));
1057 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_REUSEADDR
, true);
1061 r
= socket_set_recvpktinfo(fd
, family
, true);
1065 r
= socket_set_recvttl(fd
, family
, true);
1072 static int set_dns_stub_common_tcp_socket_options(int fd
) {
1077 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_FASTOPEN
, 5); /* Everybody appears to pick qlen=5, let's do the same here. */
1079 log_debug_errno(r
, "Failed to enable TCP_FASTOPEN on TCP listening socket, ignoring: %m");
1081 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_NODELAY
, true);
1083 log_debug_errno(r
, "Failed to enable TCP_NODELAY mode, ignoring: %m");
1088 static int manager_dns_stub_fd(Manager
*m
, int type
) {
1089 union sockaddr_union sa
= {
1090 .in
.sin_family
= AF_INET
,
1091 .in
.sin_addr
.s_addr
= htobe32(INADDR_DNS_STUB
),
1092 .in
.sin_port
= htobe16(53),
1094 _cleanup_close_
int fd
= -1;
1097 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1099 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &m
->dns_stub_udp_event_source
: &m
->dns_stub_tcp_event_source
;
1101 return sd_event_source_get_io_fd(*event_source
);
1103 fd
= socket(AF_INET
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1107 r
= set_dns_stub_common_socket_options(fd
, AF_INET
);
1111 if (type
== SOCK_STREAM
) {
1112 r
= set_dns_stub_common_tcp_socket_options(fd
);
1117 /* Make sure no traffic from outside the local host can leak to onto this socket */
1118 r
= socket_bind_to_ifindex(fd
, LOOPBACK_IFINDEX
);
1122 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TTL
, 1);
1126 if (bind(fd
, &sa
.sa
, sizeof(sa
.in
)) < 0)
1129 if (type
== SOCK_STREAM
&&
1130 listen(fd
, SOMAXCONN
) < 0)
1133 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1134 type
== SOCK_DGRAM
? on_dns_stub_packet
: on_dns_stub_stream
,
1139 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1143 (void) sd_event_source_set_description(*event_source
,
1144 type
== SOCK_DGRAM
? "dns-stub-udp" : "dns-stub-tcp");
1149 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
) {
1150 _cleanup_free_
char *pretty
= NULL
;
1151 _cleanup_close_
int fd
= -1;
1152 union sockaddr_union sa
;
1156 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1159 return manager_dns_stub_fd(m
, type
);
1161 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &l
->udp_event_source
: &l
->tcp_event_source
;
1163 return sd_event_source_get_io_fd(*event_source
);
1165 if (l
->family
== AF_INET
)
1166 sa
= (union sockaddr_union
) {
1167 .in
.sin_family
= l
->family
,
1168 .in
.sin_port
= htobe16(dns_stub_listener_extra_port(l
)),
1169 .in
.sin_addr
= l
->address
.in
,
1172 sa
= (union sockaddr_union
) {
1173 .in6
.sin6_family
= l
->family
,
1174 .in6
.sin6_port
= htobe16(dns_stub_listener_extra_port(l
)),
1175 .in6
.sin6_addr
= l
->address
.in6
,
1178 fd
= socket(l
->family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1184 r
= set_dns_stub_common_socket_options(fd
, l
->family
);
1188 if (type
== SOCK_STREAM
) {
1189 r
= set_dns_stub_common_tcp_socket_options(fd
);
1194 /* Do not set IP_TTL for extra DNS stub listeners, as the address may not be local and in that case
1195 * people may want ttl > 1. */
1197 r
= socket_set_freebind(fd
, l
->family
, true);
1201 if (type
== SOCK_DGRAM
) {
1202 r
= socket_disable_pmtud(fd
, l
->family
);
1204 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1206 r
= socket_set_recvfragsize(fd
, l
->family
, true);
1208 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1211 if (bind(fd
, &sa
.sa
, SOCKADDR_LEN(sa
)) < 0) {
1216 if (type
== SOCK_STREAM
&&
1217 listen(fd
, SOMAXCONN
) < 0) {
1222 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1223 type
== SOCK_DGRAM
? on_dns_stub_packet_extra
: on_dns_stub_stream_extra
,
1228 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1232 (void) sd_event_source_set_description(*event_source
,
1233 type
== SOCK_DGRAM
? "dns-stub-udp-extra" : "dns-stub-tcp-extra");
1235 if (DEBUG_LOGGING
) {
1236 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1237 log_debug("Listening on %s socket %s.",
1238 type
== SOCK_DGRAM
? "UDP" : "TCP",
1246 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1247 return log_warning_errno(r
,
1248 r
== -EADDRINUSE
? "Another process is already listening on %s socket %s: %m" :
1249 "Failed to listen on %s socket %s: %m",
1250 type
== SOCK_DGRAM
? "UDP" : "TCP",
1254 int manager_dns_stub_start(Manager
*m
) {
1255 const char *t
= "UDP";
1260 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_NO
)
1261 log_debug("Not creating stub listener.");
1263 log_debug("Creating stub listener using %s.",
1264 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
? "UDP" :
1265 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
? "TCP" :
1268 if (FLAGS_SET(m
->dns_stub_listener_mode
, DNS_STUB_LISTENER_UDP
))
1269 r
= manager_dns_stub_fd(m
, SOCK_DGRAM
);
1272 FLAGS_SET(m
->dns_stub_listener_mode
, DNS_STUB_LISTENER_TCP
)) {
1274 r
= manager_dns_stub_fd(m
, SOCK_STREAM
);
1277 if (IN_SET(r
, -EADDRINUSE
, -EPERM
)) {
1278 log_warning_errno(r
,
1279 r
== -EADDRINUSE
? "Another process is already listening on %s socket 127.0.0.53:53.\n"
1280 "Turning off local DNS stub support." :
1281 "Failed to listen on %s socket 127.0.0.53:53: %m.\n"
1282 "Turning off local DNS stub support.",
1284 manager_dns_stub_stop(m
);
1286 return log_error_errno(r
, "Failed to listen on %s socket 127.0.0.53:53: %m", t
);
1288 if (!ordered_set_isempty(m
->dns_extra_stub_listeners
)) {
1289 DnsStubListenerExtra
*l
;
1291 log_debug("Creating extra stub listeners.");
1293 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
) {
1294 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_UDP
))
1295 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
);
1296 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_TCP
))
1297 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_STREAM
);
1304 void manager_dns_stub_stop(Manager
*m
) {
1307 m
->dns_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_stub_udp_event_source
);
1308 m
->dns_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_stub_tcp_event_source
);
1311 static const char* const dns_stub_listener_mode_table
[_DNS_STUB_LISTENER_MODE_MAX
] = {
1312 [DNS_STUB_LISTENER_NO
] = "no",
1313 [DNS_STUB_LISTENER_UDP
] = "udp",
1314 [DNS_STUB_LISTENER_TCP
] = "tcp",
1315 [DNS_STUB_LISTENER_YES
] = "yes",
1317 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(dns_stub_listener_mode
, DnsStubListenerMode
, DNS_STUB_LISTENER_YES
);