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
);
24 static int manager_dns_stub_fd(Manager
*m
, int family
, const union in_addr_union
*listen_address
, int type
);
26 static void dns_stub_listener_extra_hash_func(const DnsStubListenerExtra
*a
, struct siphash
*state
) {
29 siphash24_compress(&a
->mode
, sizeof(a
->mode
), state
);
30 siphash24_compress(&a
->family
, sizeof(a
->family
), state
);
31 siphash24_compress(&a
->address
, FAMILY_ADDRESS_SIZE(a
->family
), state
);
32 siphash24_compress(&a
->port
, sizeof(a
->port
), state
);
35 static int dns_stub_listener_extra_compare_func(const DnsStubListenerExtra
*a
, const DnsStubListenerExtra
*b
) {
41 r
= CMP(a
->mode
, b
->mode
);
45 r
= CMP(a
->family
, b
->family
);
49 r
= memcmp(&a
->address
, &b
->address
, FAMILY_ADDRESS_SIZE(a
->family
));
53 return CMP(a
->port
, b
->port
);
56 DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(
57 dns_stub_listener_extra_hash_ops
,
59 dns_stub_listener_extra_hash_func
,
60 dns_stub_listener_extra_compare_func
,
61 dns_stub_listener_extra_free
);
63 int dns_stub_listener_extra_new(
65 DnsStubListenerExtra
**ret
) {
67 DnsStubListenerExtra
*l
;
69 l
= new(DnsStubListenerExtra
, 1);
73 *l
= (DnsStubListenerExtra
) {
81 DnsStubListenerExtra
*dns_stub_listener_extra_free(DnsStubListenerExtra
*p
) {
85 p
->udp_event_source
= sd_event_source_disable_unref(p
->udp_event_source
);
86 p
->tcp_event_source
= sd_event_source_disable_unref(p
->tcp_event_source
);
88 hashmap_free(p
->queries_by_packet
);
93 static void stub_packet_hash_func(const DnsPacket
*p
, struct siphash
*state
) {
96 siphash24_compress(&p
->protocol
, sizeof(p
->protocol
), state
);
97 siphash24_compress(&p
->family
, sizeof(p
->family
), state
);
98 siphash24_compress(&p
->sender
, sizeof(p
->sender
), state
);
99 siphash24_compress(&p
->ipproto
, sizeof(p
->ipproto
), state
);
100 siphash24_compress(&p
->sender_port
, sizeof(p
->sender_port
), state
);
101 siphash24_compress(DNS_PACKET_HEADER(p
), sizeof(DnsPacketHeader
), state
);
103 /* We don't bother hashing the full packet here, just the header */
106 static int stub_packet_compare_func(const DnsPacket
*x
, const DnsPacket
*y
) {
109 r
= CMP(x
->protocol
, y
->protocol
);
113 r
= CMP(x
->family
, y
->family
);
117 r
= memcmp(&x
->sender
, &y
->sender
, sizeof(x
->sender
));
121 r
= CMP(x
->ipproto
, y
->ipproto
);
125 r
= CMP(x
->sender_port
, y
->sender_port
);
129 return memcmp(DNS_PACKET_HEADER(x
), DNS_PACKET_HEADER(y
), sizeof(DnsPacketHeader
));
132 DEFINE_HASH_OPS(stub_packet_hash_ops
, DnsPacket
, stub_packet_hash_func
, stub_packet_compare_func
);
134 static int reply_add_with_rrsig(
136 DnsResourceRecord
*rr
,
138 DnsAnswerFlags flags
,
139 DnsResourceRecord
*rrsig
,
146 r
= dns_answer_add_extend(reply
, rr
, ifindex
, flags
, rrsig
);
150 if (with_rrsig
&& rrsig
) {
151 r
= dns_answer_add_extend(reply
, rrsig
, ifindex
, flags
, NULL
);
159 static int dns_stub_collect_answer_by_question(
162 DnsQuestion
*question
,
163 bool with_rrsig
) { /* Add RRSIG RR matching each RR */
170 /* Copies all RRs from 'answer' into 'reply', if they match 'question'. */
172 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
174 /* We have a question, let's see if this RR matches it */
175 r
= dns_question_matches_rr(question
, item
->rr
, NULL
);
179 /* Maybe there's a CNAME/DNAME in here? If so, that's an answer too */
180 r
= dns_question_matches_cname_or_dname(question
, item
->rr
, NULL
);
187 /* Mask the section info, we want the primary answers to always go without section
188 * info, so that it is added to the answer section when we synthesize a reply. */
190 r
= reply_add_with_rrsig(
194 item
->flags
& ~DNS_ANSWER_MASK_SECTIONS
,
204 static int dns_stub_collect_answer_by_section(
207 DnsAnswerFlags section
,
210 bool with_dnssec
) { /* Include DNSSEC RRs. RRSIG, NSEC, … */
217 /* Copies all RRs from 'answer' into 'reply', if they originate from the specified section. Also,
218 * avoid any RRs listed in 'exclude'. */
220 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
222 if (dns_answer_contains(exclude1
, item
->rr
) ||
223 dns_answer_contains(exclude2
, item
->rr
))
227 dns_type_is_dnssec(item
->rr
->key
->type
))
230 if (((item
->flags
^ section
) & DNS_ANSWER_MASK_SECTIONS
) != 0)
233 r
= reply_add_with_rrsig(
247 static int dns_stub_assign_sections(
249 DnsQuestion
*question
,
257 /* Let's assign the 'answer' RRs we collected to their respective sections in the reply datagram. We
258 * try to reproduce a section assignment similar to what the upstream DNS server responded to us. We
259 * use the DNS_ANSWER_SECTION_xyz flags to match things up, which is where the original upstream's
260 * packet section assignment is stored in the DnsAnswer object. Not all RRs in the 'answer' objects
261 * come with section information though (for example, because they were synthesized locally, and not
262 * from a DNS packet). To deal with that we extend the assignment logic a bit: anything from the
263 * 'answer' object that directly matches the original question is always put in the ANSWER section,
264 * regardless if it carries section info, or what that section info says. Then, anything from the
265 * 'answer' objects that is from the ANSWER or AUTHORITY sections, and wasn't already added to the
266 * ANSWER section is placed in the AUTHORITY section. Everything else from either object is added to
267 * the ADDITIONAL section. */
269 /* Include all RRs that directly answer the question in the answer section */
270 r
= dns_stub_collect_answer_by_question(
278 /* Include all RRs that originate from the authority sections, and aren't already listed in the
279 * answer section, in the authority section */
280 r
= dns_stub_collect_answer_by_section(
281 &q
->reply_authoritative
,
283 DNS_ANSWER_SECTION_AUTHORITY
,
284 q
->reply_answer
, NULL
,
289 /* Include all RRs that originate from the answer or additional sections in the additional section
290 * (except if already listed in the other two sections). Also add all RRs with no section marking. */
291 r
= dns_stub_collect_answer_by_section(
292 &q
->reply_additional
,
294 DNS_ANSWER_SECTION_ANSWER
,
295 q
->reply_answer
, q
->reply_authoritative
,
299 r
= dns_stub_collect_answer_by_section(
300 &q
->reply_additional
,
302 DNS_ANSWER_SECTION_ADDITIONAL
,
303 q
->reply_answer
, q
->reply_authoritative
,
307 r
= dns_stub_collect_answer_by_section(
308 &q
->reply_additional
,
311 q
->reply_answer
, q
->reply_authoritative
,
319 static int dns_stub_make_reply_packet(
323 bool *ret_truncated
) {
325 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
331 r
= dns_packet_new(&p
, DNS_PROTOCOL_DNS
, 0, max_size
);
335 r
= dns_packet_append_question(p
, q
);
346 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(dns_question_size(q
));
352 static int dns_stub_add_reply_packet_body(
355 DnsAnswer
*authoritative
,
356 DnsAnswer
*additional
,
357 bool edns0_do
, /* Client expects DNSSEC RRs? */
360 unsigned n_answer
= 0, n_authoritative
= 0, n_additional
= 0;
366 /* Add the three sections to the packet. If the answer section doesn't fit we'll signal that as
367 * truncation. If the authoritative section doesn't fit and we are in DNSSEC mode, also signal
368 * truncation. In all other cases where things don't fit don't signal truncation, as for those cases
369 * the dropped RRs should not be essential. */
371 r
= dns_packet_append_answer(p
, answer
, &n_answer
);
377 r
= dns_packet_append_answer(p
, authoritative
, &n_authoritative
);
378 if (r
== -EMSGSIZE
) {
384 r
= dns_packet_append_answer(p
, additional
, &n_additional
);
385 if (r
< 0 && r
!= -EMSGSIZE
)
397 DNS_PACKET_HEADER(p
)->ancount
= htobe16(n_answer
);
398 DNS_PACKET_HEADER(p
)->nscount
= htobe16(n_authoritative
);
399 DNS_PACKET_HEADER(p
)->arcount
= htobe16(n_additional
);
403 static const char *nsid_string(void) {
404 static char buffer
[SD_ID128_STRING_MAX
+ STRLEN(".resolved.systemd.io")] = "";
408 /* Let's generate a string that we can use as RFC5001 NSID identifier. The string shall identify us
409 * as systemd-resolved, and return a different string for each resolved instance without leaking host
410 * identity. Hence let's use a fixed suffix that identifies resolved, and a prefix generated from the
411 * machine ID but from which the machine ID cannot be determined.
413 * Clients can use this to determine whether an answer is originating locally or is proxied from
416 if (!isempty(buffer
))
419 r
= sd_id128_get_machine_app_specific(
420 SD_ID128_MAKE(ed
,d3
,12,5d
,16,b9
,41,f9
,a1
,49,5f
,ab
,15,62,ab
,27),
423 log_debug_errno(r
, "Failed to determine machine ID, ignoring: %m");
427 xsprintf(buffer
, SD_ID128_FORMAT_STR
".resolved.systemd.io", SD_ID128_FORMAT_VAL(id
));
431 static int dns_stub_finish_reply_packet(
435 bool tc
, /* set the Truncated bit? */
436 bool aa
, /* set the Authoritative Answer bit? */
437 bool rd
, /* set the Recursion Desired bit? */
438 bool add_opt
, /* add an OPT RR to this packet? */
439 bool edns0_do
, /* set the EDNS0 DNSSEC OK bit? */
440 bool ad
, /* set the DNSSEC authenticated data bit? */
441 bool cd
, /* set the DNSSEC checking disabled bit? */
442 uint16_t max_udp_size
, /* The maximum UDP datagram size to advertise to clients */
443 bool nsid
) { /* whether to add NSID */
450 r
= dns_packet_append_opt(p
, max_udp_size
, edns0_do
, /* include_rfc6975 = */ false, nsid
? nsid_string() : NULL
, rcode
, NULL
);
451 if (r
== -EMSGSIZE
) /* Hit the size limit? then indicate truncation */
456 /* If the client can't to EDNS0, don't do DO either */
459 /* If we don't do EDNS, clamp the rcode to 4 bit */
461 rcode
= DNS_RCODE_SERVFAIL
;
464 /* Don't set the CD bit unless DO is on, too */
468 /* Note that we allow the AD bit to be set even if client didn't signal DO, as per RFC 6840, section
471 DNS_PACKET_HEADER(p
)->id
= id
;
473 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
487 static bool address_is_proxy(int family
, const union in_addr_union
*a
) {
490 /* Returns true if the specified address is the DNS "proxy" stub, i.e. where we unconditionally enable bypass mode */
492 if (family
!= AF_INET
)
495 return be32toh(a
->in
.s_addr
) == INADDR_DNS_PROXY_STUB
;
498 static int find_socket_fd(
500 DnsStubListenerExtra
*l
,
502 const union in_addr_union
*listen_address
,
507 /* Finds the right socket to use for sending. If we know the extra listener, otherwise go via the
508 * address to send from */
510 return manager_dns_stub_fd_extra(m
, l
, type
);
512 return manager_dns_stub_fd(m
, family
, listen_address
, type
);
515 static int dns_stub_send(
517 DnsStubListenerExtra
*l
,
529 r
= dns_stream_write_packet(s
, reply
);
533 fd
= find_socket_fd(m
, l
, p
->family
, &p
->sender
, SOCK_DGRAM
);
537 /* Note that it is essential here that we explicitly choose the source IP address for this
538 * packet. This is because otherwise the kernel will choose it automatically based on the
539 * routing table and will thus pick 127.0.0.1 rather than 127.0.0.53. */
542 l
|| address_is_proxy(p
->family
, &p
->destination
) ? p
->ifindex
: LOOPBACK_IFINDEX
, /* force loopback iface if this is the main listener stub */
543 p
->family
, &p
->sender
, p
->sender_port
, &p
->destination
,
547 return log_debug_errno(r
, "Failed to send reply packet: %m");
552 static int dns_stub_reply_with_edns0_do(DnsQuery
*q
) {
555 /* Reply with DNSSEC DO set? Only if client supports it; and we did any DNSSEC verification
556 * ourselves, or consider the data fully authenticated because we generated it locally, or the client
559 return DNS_PACKET_DO(q
->request_packet
) &&
560 (q
->answer_dnssec_result
>= 0 || /* we did proper DNSSEC validation … */
561 dns_query_fully_authenticated(q
) || /* … or we considered it authentic otherwise … */
562 DNS_PACKET_CD(q
->request_packet
)); /* … or client set CD */
565 static void dns_stub_suppress_duplicate_section_rrs(DnsQuery
*q
) {
566 /* If we follow a CNAME/DNAME chain we might end up populating our sections with redundant RRs
567 * because we built up the sections from multiple reply packets (one from each CNAME/DNAME chain
568 * element). E.g. it could be that an RR that was included in the first reply's additional section
569 * ends up being relevant as main answer in a subsequent reply in the chain. Let's clean this up, and
570 * remove everything in the "higher priority" sections from the "lower priority" sections.
572 * Note that this removal matches by RR keys instead of the full RRs. This is because RRsets should
573 * always end up in one section fully or not at all, but never be split among sections.
575 * Specifically: we remove ANSWER section RRs from the AUTHORITATIVE and ADDITIONAL sections, as well
576 * as AUTHORITATIVE section RRs from the ADDITIONAL section. */
578 dns_answer_remove_by_answer_keys(&q
->reply_authoritative
, q
->reply_answer
);
579 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_answer
);
580 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_authoritative
);
583 static int dns_stub_send_reply(
587 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
588 bool truncated
, edns0_do
;
593 edns0_do
= dns_stub_reply_with_edns0_do(q
); /* let's check if we shall reply with EDNS0 DO? */
595 r
= dns_stub_make_reply_packet(
597 DNS_PACKET_PAYLOAD_SIZE_MAX(q
->request_packet
),
598 q
->request_packet
->question
,
601 return log_debug_errno(r
, "Failed to build reply packet: %m");
603 dns_stub_suppress_duplicate_section_rrs(q
);
605 r
= dns_stub_add_reply_packet_body(
608 q
->reply_authoritative
,
613 return log_debug_errno(r
, "Failed to append reply packet body: %m");
615 r
= dns_stub_finish_reply_packet(
617 DNS_PACKET_ID(q
->request_packet
),
620 dns_query_fully_authoritative(q
),
621 DNS_PACKET_RD(q
->request_packet
),
622 !!q
->request_packet
->opt
,
624 (DNS_PACKET_AD(q
->request_packet
) || DNS_PACKET_DO(q
->request_packet
)) && dns_query_fully_authenticated(q
),
625 DNS_PACKET_CD(q
->request_packet
),
626 q
->stub_listener_extra
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
627 dns_packet_has_nsid_request(q
->request_packet
) > 0 && !q
->stub_listener_extra
);
629 return log_debug_errno(r
, "Failed to build failure packet: %m");
631 return dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
634 static int dns_stub_send_failure(
636 DnsStubListenerExtra
*l
,
640 bool authenticated
) {
642 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
649 r
= dns_stub_make_reply_packet(
651 DNS_PACKET_PAYLOAD_SIZE_MAX(p
),
655 return log_debug_errno(r
, "Failed to make failure packet: %m");
657 r
= dns_stub_finish_reply_packet(
666 (DNS_PACKET_AD(p
) || DNS_PACKET_DO(p
)) && authenticated
,
668 l
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
669 dns_packet_has_nsid_request(p
) > 0 && !l
);
671 return log_debug_errno(r
, "Failed to build failure packet: %m");
673 return dns_stub_send(m
, l
, s
, p
, reply
);
676 static int dns_stub_patch_bypass_reply_packet(
677 DnsPacket
**ret
, /* Where to place the patched packet */
678 DnsPacket
*original
, /* The packet to patch */
679 DnsPacket
*request
) { /* The packet the patched packet shall look like a reply to */
680 _cleanup_(dns_packet_unrefp
) DnsPacket
*c
= NULL
;
687 r
= dns_packet_dup(&c
, original
);
691 /* Extract the packet, so that we know where the OPT field is */
692 r
= dns_packet_extract(c
);
696 /* Copy over the original client request ID, so that we can make the upstream query look like our own reply. */
697 DNS_PACKET_HEADER(c
)->id
= DNS_PACKET_HEADER(request
)->id
;
699 /* Patch in our own maximum datagram size, if EDNS0 was on */
700 r
= dns_packet_patch_max_udp_size(c
, ADVERTISE_DATAGRAM_SIZE_MAX
);
704 /* Lower all TTLs by the time passed since we received the datagram. */
705 if (timestamp_is_set(original
->timestamp
)) {
706 r
= dns_packet_patch_ttls(c
, original
->timestamp
);
711 /* Our upstream connection might have supported larger DNS requests than our downstream one, hence
712 * set the TC bit if our reply is larger than what the client supports, and truncate. */
713 if (c
->size
> DNS_PACKET_PAYLOAD_SIZE_MAX(request
)) {
714 log_debug("Artificially truncating stub response, as advertised size of client is smaller than upstream one.");
715 dns_packet_truncate(c
, DNS_PACKET_PAYLOAD_SIZE_MAX(request
));
716 DNS_PACKET_HEADER(c
)->flags
= htobe16(be16toh(DNS_PACKET_HEADER(c
)->flags
) | DNS_PACKET_FLAG_TC
);
723 static void dns_stub_query_complete(DnsQuery
*q
) {
727 assert(q
->request_packet
);
729 if (q
->question_bypass
) {
730 /* This is a bypass reply. If so, let's propagate the upstream packet, if we have it and it
731 * is regular DNS. (We can't do this if the upstream packet is LLMNR or mDNS, since the
732 * packets are not 100% compatible.) */
734 if (q
->answer_full_packet
&&
735 q
->answer_full_packet
->protocol
== DNS_PROTOCOL_DNS
) {
736 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
738 r
= dns_stub_patch_bypass_reply_packet(&reply
, q
->answer_full_packet
, q
->request_packet
);
740 log_debug_errno(r
, "Failed to patch bypass reply packet: %m");
742 (void) dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
749 /* Take all data from the current reply, and merge it into the three reply sections we are building
750 * up. We do this before processing CNAME redirects, so that we gradually build up our sections, and
751 * and keep adding all RRs in the CNAME chain. */
752 r
= dns_stub_assign_sections(
754 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
755 dns_stub_reply_with_edns0_do(q
));
757 log_debug_errno(r
, "Failed to assign sections: %m");
764 case DNS_TRANSACTION_SUCCESS
: {
770 cname_result
= dns_query_process_cname_one(q
);
771 if (cname_result
== -ELOOP
) { /* CNAME loop, let's send what we already have */
772 log_debug_errno(r
, "Detected CNAME loop, returning what we already have.");
773 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
776 if (cname_result
< 0) {
777 log_debug_errno(cname_result
, "Failed to process CNAME: %m");
781 if (cname_result
== DNS_QUERY_NOMATCH
) {
782 /* This answer doesn't contain any RR that would answer our question
783 * positively, i.e. neither directly nor via CNAME. */
785 if (first
) /* We never followed a CNAME and the answer doesn't match our
786 * question at all? Then this is final, the empty answer is the
790 /* Otherwise, we already followed a CNAME once within this packet, and the
791 * packet doesn't answer our question. In that case let's restart the query,
792 * now with the redirected question. We'll */
795 log_debug_errno(r
, "Failed to restart query: %m");
800 r
= dns_stub_assign_sections(
802 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
803 dns_stub_reply_with_edns0_do(q
));
805 log_debug_errno(r
, "Failed to assign sections: %m");
810 if (cname_result
== DNS_QUERY_MATCH
) /* A match? Then we are done, let's return what we got */
813 /* We followed a CNAME. and collected the RRs that answer the redirected question
814 * successfully. Let's not try to do this again. */
815 assert(cname_result
== DNS_QUERY_CNAME
);
822 case DNS_TRANSACTION_RCODE_FAILURE
:
823 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
826 case DNS_TRANSACTION_NOT_FOUND
:
827 (void) dns_stub_send_reply(q
, DNS_RCODE_NXDOMAIN
);
830 case DNS_TRANSACTION_TIMEOUT
:
831 case DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
:
832 /* Propagate a timeout as a no packet, i.e. that the client also gets a timeout */
835 case DNS_TRANSACTION_NO_SERVERS
:
836 case DNS_TRANSACTION_INVALID_REPLY
:
837 case DNS_TRANSACTION_ERRNO
:
838 case DNS_TRANSACTION_ABORTED
:
839 case DNS_TRANSACTION_DNSSEC_FAILED
:
840 case DNS_TRANSACTION_NO_TRUST_ANCHOR
:
841 case DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
:
842 case DNS_TRANSACTION_NETWORK_DOWN
:
843 case DNS_TRANSACTION_NO_SOURCE
:
844 case DNS_TRANSACTION_STUB_LOOP
:
845 (void) dns_stub_send_reply(q
, DNS_RCODE_SERVFAIL
);
848 case DNS_TRANSACTION_NULL
:
849 case DNS_TRANSACTION_PENDING
:
850 case DNS_TRANSACTION_VALIDATING
:
852 assert_not_reached();
858 static int dns_stub_stream_complete(DnsStream
*s
, int error
) {
861 log_debug_errno(error
, "DNS TCP connection terminated, destroying queries: %m");
866 q
= set_first(s
->queries
);
873 /* This drops the implicit ref we keep around since it was allocated, as incoming stub connections
874 * should be kept as long as the client wants to. */
879 static void dns_stub_process_query(Manager
*m
, DnsStubListenerExtra
*l
, DnsStream
*s
, DnsPacket
*p
) {
880 uint64_t protocol_flags
= SD_RESOLVED_PROTOCOLS_ALL
;
881 _cleanup_(dns_query_freep
) DnsQuery
*q
= NULL
;
882 Hashmap
**queries_by_packet
;
889 assert(p
->protocol
== DNS_PROTOCOL_DNS
);
891 if (!l
&& /* l == NULL if this is the main stub */
892 !address_is_proxy(p
->family
, &p
->destination
) && /* don't restrict needlessly for 127.0.0.54 */
893 (in_addr_is_localhost(p
->family
, &p
->sender
) <= 0 ||
894 in_addr_is_localhost(p
->family
, &p
->destination
) <= 0)) {
895 log_warning("Got packet on unexpected (i.e. non-localhost) IP range, ignoring.");
899 if (manager_packet_from_our_transaction(m
, p
)) {
900 log_debug("Got our own packet looped back, ignoring.");
904 queries_by_packet
= l
? &l
->queries_by_packet
: &m
->stub_queries_by_packet
;
905 existing
= hashmap_get(*queries_by_packet
, p
);
906 if (existing
&& dns_packet_equal(existing
->request_packet
, p
)) {
907 log_debug("Got repeat packet from client, ignoring.");
911 r
= dns_packet_extract(p
);
913 log_debug_errno(r
, "Failed to extract resources from incoming packet, ignoring packet: %m");
914 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_FORMERR
, false);
918 if (!DNS_PACKET_VERSION_SUPPORTED(p
)) {
919 log_debug("Got EDNS OPT field with unsupported version number.");
920 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_BADVERS
, false);
924 if (dns_type_is_obsolete(dns_question_first_key(p
->question
)->type
)) {
925 log_debug("Got message with obsolete key type, refusing.");
926 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
930 if (dns_type_is_zone_transer(dns_question_first_key(p
->question
)->type
)) {
931 log_debug("Got request for zone transfer, refusing.");
932 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
936 if (!DNS_PACKET_RD(p
)) {
937 /* If the "rd" bit is off (i.e. recursion was not requested), then refuse operation */
938 log_debug("Got request with recursion disabled, refusing.");
939 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
943 r
= hashmap_ensure_allocated(queries_by_packet
, &stub_packet_hash_ops
);
949 if (address_is_proxy(p
->family
, &p
->destination
)) {
950 _cleanup_free_
char *dipa
= NULL
;
952 r
= in_addr_to_string(p
->family
, &p
->destination
, &dipa
);
954 return (void) log_error_errno(r
, "Failed to format destination address: %m");
956 log_debug("Got request to DNS proxy address 127.0.0.54, enabling bypass logic.");
958 protocol_flags
= SD_RESOLVED_DNS
|SD_RESOLVED_NO_ZONE
; /* Turn off mDNS/LLMNR for proxy stub. */
959 } else if ((DNS_PACKET_DO(p
) && DNS_PACKET_CD(p
))) {
960 log_debug("Got request with DNSSEC checking disabled, enabling bypass logic.");
965 r
= dns_query_new(m
, &q
, NULL
, NULL
, p
, 0,
967 SD_RESOLVED_NO_CNAME
|
968 SD_RESOLVED_NO_SEARCH
|
969 SD_RESOLVED_NO_VALIDATE
|
970 SD_RESOLVED_REQUIRE_PRIMARY
|
971 SD_RESOLVED_CLAMP_TTL
);
973 r
= dns_query_new(m
, &q
, p
->question
, p
->question
, NULL
, 0,
975 SD_RESOLVED_NO_SEARCH
|
976 (DNS_PACKET_DO(p
) ? SD_RESOLVED_REQUIRE_PRIMARY
: 0)|
977 SD_RESOLVED_CLAMP_TTL
);
979 log_error_errno(r
, "Failed to generate query object: %m");
980 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
984 q
->request_packet
= dns_packet_ref(p
);
985 q
->request_stream
= dns_stream_ref(s
); /* make sure the stream stays around until we can send a reply through it */
986 q
->stub_listener_extra
= l
;
987 q
->complete
= dns_stub_query_complete
;
990 /* Remember which queries belong to this stream, so that we can cancel them when the stream
991 * is disconnected early */
993 r
= set_ensure_put(&s
->queries
, NULL
, q
);
1001 /* Add the query to the hash table we use to determine repeat packets now. We don't care about
1002 * failures here, since in the worst case we'll not recognize duplicate incoming requests, which
1003 * isn't particularly bad. */
1004 (void) hashmap_put(*queries_by_packet
, q
->request_packet
, q
);
1006 r
= dns_query_go(q
);
1008 log_error_errno(r
, "Failed to start query: %m");
1009 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
1013 log_debug("Processing query...");
1017 static int on_dns_stub_packet_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1018 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1021 r
= manager_recv(m
, fd
, DNS_PROTOCOL_DNS
, &p
);
1025 if (dns_packet_validate_query(p
) > 0) {
1026 log_debug("Got DNS stub UDP query packet for id %u", DNS_PACKET_ID(p
));
1028 dns_stub_process_query(m
, l
, NULL
, p
);
1030 log_debug("Invalid DNS stub UDP packet, ignoring.");
1035 static int on_dns_stub_packet(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1036 return on_dns_stub_packet_internal(s
, fd
, revents
, userdata
, NULL
);
1039 static int on_dns_stub_packet_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1040 DnsStubListenerExtra
*l
= userdata
;
1044 return on_dns_stub_packet_internal(s
, fd
, revents
, l
->manager
, l
);
1047 static int on_dns_stub_stream_packet(DnsStream
*s
) {
1048 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1052 p
= dns_stream_take_read_packet(s
);
1055 if (dns_packet_validate_query(p
) > 0) {
1056 log_debug("Got DNS stub TCP query packet for id %u", DNS_PACKET_ID(p
));
1058 dns_stub_process_query(s
->manager
, s
->stub_listener_extra
, s
, p
);
1060 log_debug("Invalid DNS stub TCP packet, ignoring.");
1065 static int on_dns_stub_stream_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1069 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1071 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1077 r
= dns_stream_new(m
, &stream
, DNS_STREAM_STUB
, DNS_PROTOCOL_DNS
, cfd
, NULL
, DNS_STREAM_STUB_TIMEOUT_USEC
);
1083 stream
->stub_listener_extra
= l
;
1084 stream
->on_packet
= on_dns_stub_stream_packet
;
1085 stream
->complete
= dns_stub_stream_complete
;
1087 /* We let the reference to the stream dangle here, it will be dropped later by the complete callback. */
1092 static int on_dns_stub_stream(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1093 return on_dns_stub_stream_internal(s
, fd
, revents
, userdata
, NULL
);
1096 static int on_dns_stub_stream_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1097 DnsStubListenerExtra
*l
= userdata
;
1100 return on_dns_stub_stream_internal(s
, fd
, revents
, l
->manager
, l
);
1103 static int set_dns_stub_common_socket_options(int fd
, int family
) {
1107 assert(IN_SET(family
, AF_INET
, AF_INET6
));
1109 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_REUSEADDR
, true);
1113 r
= socket_set_recvpktinfo(fd
, family
, true);
1117 r
= socket_set_recvttl(fd
, family
, true);
1124 static int set_dns_stub_common_tcp_socket_options(int fd
) {
1129 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_FASTOPEN
, 5); /* Everybody appears to pick qlen=5, let's do the same here. */
1131 log_debug_errno(r
, "Failed to enable TCP_FASTOPEN on TCP listening socket, ignoring: %m");
1133 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_NODELAY
, true);
1135 log_debug_errno(r
, "Failed to enable TCP_NODELAY mode, ignoring: %m");
1140 static int manager_dns_stub_fd(
1143 const union in_addr_union
*listen_addr
,
1146 sd_event_source
**event_source
;
1147 _cleanup_close_
int fd
= -1;
1148 union sockaddr_union sa
;
1152 assert(listen_addr
);
1154 if (type
== SOCK_DGRAM
)
1155 event_source
= address_is_proxy(family
, listen_addr
) ? &m
->dns_proxy_stub_udp_event_source
: &m
->dns_stub_udp_event_source
;
1156 else if (type
== SOCK_STREAM
)
1157 event_source
= address_is_proxy(family
, listen_addr
) ? &m
->dns_proxy_stub_tcp_event_source
: &m
->dns_stub_tcp_event_source
;
1159 return -EPROTONOSUPPORT
;
1162 return sd_event_source_get_io_fd(*event_source
);
1164 fd
= socket(family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1168 r
= set_dns_stub_common_socket_options(fd
, family
);
1172 if (type
== SOCK_STREAM
) {
1173 r
= set_dns_stub_common_tcp_socket_options(fd
);
1178 /* Set slightly different socket options for the non-proxy and the proxy binding. The former we want
1179 * to be accessible only from the local host, for the latter it's OK if people use NAT redirects or
1180 * so to redirect external traffic to it. */
1182 if (!address_is_proxy(family
, listen_addr
)) {
1183 /* Make sure no traffic from outside the local host can leak to onto this socket */
1184 r
= socket_bind_to_ifindex(fd
, LOOPBACK_IFINDEX
);
1188 r
= socket_set_ttl(fd
, family
, 1);
1191 } else if (type
== SOCK_DGRAM
) {
1192 /* Turn off Path MTU Discovery for UDP, for security reasons. See socket_disable_pmtud() for
1193 * a longer discussion. (We only do this for sockets that are potentially externally
1194 * accessible, i.e. the proxy stub one. For the non-proxy one we instead set the TTL to 1,
1195 * see above, so that packets don't get routed at all.) */
1196 r
= socket_disable_pmtud(fd
, family
);
1198 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1200 r
= socket_set_recvfragsize(fd
, family
, true);
1202 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1205 r
= sockaddr_set_in_addr(&sa
, family
, listen_addr
, 53);
1209 if (bind(fd
, &sa
.sa
, sizeof(sa
.in
)) < 0)
1212 if (type
== SOCK_STREAM
&&
1213 listen(fd
, SOMAXCONN
) < 0)
1216 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1217 type
== SOCK_DGRAM
? on_dns_stub_packet
: on_dns_stub_stream
,
1222 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1226 (void) sd_event_source_set_description(*event_source
,
1227 type
== SOCK_DGRAM
? "dns-stub-udp" : "dns-stub-tcp");
1232 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
) {
1233 _cleanup_free_
char *pretty
= NULL
;
1234 _cleanup_close_
int fd
= -1;
1235 union sockaddr_union sa
;
1240 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1242 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &l
->udp_event_source
: &l
->tcp_event_source
;
1244 return sd_event_source_get_io_fd(*event_source
);
1246 if (l
->family
== AF_INET
)
1247 sa
= (union sockaddr_union
) {
1248 .in
.sin_family
= l
->family
,
1249 .in
.sin_port
= htobe16(dns_stub_listener_extra_port(l
)),
1250 .in
.sin_addr
= l
->address
.in
,
1253 sa
= (union sockaddr_union
) {
1254 .in6
.sin6_family
= l
->family
,
1255 .in6
.sin6_port
= htobe16(dns_stub_listener_extra_port(l
)),
1256 .in6
.sin6_addr
= l
->address
.in6
,
1259 fd
= socket(l
->family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1265 r
= set_dns_stub_common_socket_options(fd
, l
->family
);
1269 if (type
== SOCK_STREAM
) {
1270 r
= set_dns_stub_common_tcp_socket_options(fd
);
1275 /* Do not set IP_TTL for extra DNS stub listeners, as the address may not be local and in that case
1276 * people may want ttl > 1. */
1278 r
= socket_set_freebind(fd
, l
->family
, true);
1282 if (type
== SOCK_DGRAM
) {
1283 r
= socket_disable_pmtud(fd
, l
->family
);
1285 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1287 r
= socket_set_recvfragsize(fd
, l
->family
, true);
1289 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1292 r
= RET_NERRNO(bind(fd
, &sa
.sa
, SOCKADDR_LEN(sa
)));
1296 if (type
== SOCK_STREAM
&&
1297 listen(fd
, SOMAXCONN
) < 0) {
1302 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1303 type
== SOCK_DGRAM
? on_dns_stub_packet_extra
: on_dns_stub_stream_extra
,
1308 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1312 (void) sd_event_source_set_description(*event_source
,
1313 type
== SOCK_DGRAM
? "dns-stub-udp-extra" : "dns-stub-tcp-extra");
1315 if (DEBUG_LOGGING
) {
1316 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1317 log_debug("Listening on %s socket %s.",
1318 type
== SOCK_DGRAM
? "UDP" : "TCP",
1326 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1327 return log_warning_errno(r
,
1328 r
== -EADDRINUSE
? "Another process is already listening on %s socket %s: %m" :
1329 "Failed to listen on %s socket %s: %m",
1330 type
== SOCK_DGRAM
? "UDP" : "TCP",
1334 int manager_dns_stub_start(Manager
*m
) {
1339 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_NO
)
1340 log_debug("Not creating stub listener.");
1342 static const struct {
1345 } stub_sockets
[] = {
1346 { INADDR_DNS_STUB
, SOCK_DGRAM
},
1347 { INADDR_DNS_STUB
, SOCK_STREAM
},
1348 { INADDR_DNS_PROXY_STUB
, SOCK_DGRAM
},
1349 { INADDR_DNS_PROXY_STUB
, SOCK_STREAM
},
1352 log_debug("Creating stub listener using %s.",
1353 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
? "UDP" :
1354 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
? "TCP" :
1357 for (size_t i
= 0; i
< ELEMENTSOF(stub_sockets
); i
++) {
1358 union in_addr_union a
= {
1359 .in
.s_addr
= htobe32(stub_sockets
[i
].addr
),
1362 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
&& stub_sockets
[i
].socket_type
== SOCK_STREAM
)
1364 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
&& stub_sockets
[i
].socket_type
== SOCK_DGRAM
)
1367 r
= manager_dns_stub_fd(m
, AF_INET
, &a
, stub_sockets
[i
].socket_type
);
1369 _cleanup_free_
char *busy_socket
= NULL
;
1371 if (asprintf(&busy_socket
,
1372 "%s socket " IPV4_ADDRESS_FMT_STR
":53",
1373 stub_sockets
[i
].socket_type
== SOCK_DGRAM
? "UDP" : "TCP",
1374 IPV4_ADDRESS_FMT_VAL(a
.in
)) < 0)
1377 if (IN_SET(r
, -EADDRINUSE
, -EPERM
)) {
1378 log_warning_errno(r
,
1379 r
== -EADDRINUSE
? "Another process is already listening on %s.\n"
1380 "Turning off local DNS stub support." :
1381 "Failed to listen on %s: %m.\n"
1382 "Turning off local DNS stub support.",
1384 manager_dns_stub_stop(m
);
1388 return log_error_errno(r
, "Failed to listen on %s: %m", busy_socket
);
1393 if (!ordered_set_isempty(m
->dns_extra_stub_listeners
)) {
1394 DnsStubListenerExtra
*l
;
1396 log_debug("Creating extra stub listeners.");
1398 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
) {
1399 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_UDP
))
1400 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
);
1401 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_TCP
))
1402 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_STREAM
);
1409 void manager_dns_stub_stop(Manager
*m
) {
1412 m
->dns_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_stub_udp_event_source
);
1413 m
->dns_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_stub_tcp_event_source
);
1414 m
->dns_proxy_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_proxy_stub_udp_event_source
);
1415 m
->dns_proxy_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_proxy_stub_tcp_event_source
);
1418 static const char* const dns_stub_listener_mode_table
[_DNS_STUB_LISTENER_MODE_MAX
] = {
1419 [DNS_STUB_LISTENER_NO
] = "no",
1420 [DNS_STUB_LISTENER_UDP
] = "udp",
1421 [DNS_STUB_LISTENER_TCP
] = "tcp",
1422 [DNS_STUB_LISTENER_YES
] = "yes",
1424 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(dns_stub_listener_mode
, DnsStubListenerMode
, DNS_STUB_LISTENER_YES
);