1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <net/if_arp.h>
4 #include <netinet/tcp.h>
6 #include "capability-util.h"
7 #include "errno-util.h"
9 #include "missing_network.h"
10 #include "missing_socket.h"
11 #include "resolved-dns-stub.h"
12 #include "socket-netlink.h"
13 #include "socket-util.h"
14 #include "stdio-util.h"
15 #include "string-table.h"
17 /* The MTU of the loopback device is 64K on Linux, advertise that as maximum datagram size, but subtract the Ethernet,
18 * IP and UDP header sizes */
19 #define ADVERTISE_DATAGRAM_SIZE_MAX (65536U-14U-20U-8U)
21 /* On the extra stubs, use a more conservative choice */
22 #define ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX DNS_PACKET_UNICAST_SIZE_LARGE_MAX
24 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
);
25 static int manager_dns_stub_fd(Manager
*m
, int family
, const union in_addr_union
*listen_address
, int type
);
27 static void dns_stub_listener_extra_hash_func(const DnsStubListenerExtra
*a
, struct siphash
*state
) {
30 siphash24_compress(&a
->mode
, sizeof(a
->mode
), state
);
31 siphash24_compress(&a
->family
, sizeof(a
->family
), state
);
32 siphash24_compress(&a
->address
, FAMILY_ADDRESS_SIZE(a
->family
), state
);
33 siphash24_compress(&a
->port
, sizeof(a
->port
), state
);
36 static int dns_stub_listener_extra_compare_func(const DnsStubListenerExtra
*a
, const DnsStubListenerExtra
*b
) {
42 r
= CMP(a
->mode
, b
->mode
);
46 r
= CMP(a
->family
, b
->family
);
50 r
= memcmp(&a
->address
, &b
->address
, FAMILY_ADDRESS_SIZE(a
->family
));
54 return CMP(a
->port
, b
->port
);
57 DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(
58 dns_stub_listener_extra_hash_ops
,
60 dns_stub_listener_extra_hash_func
,
61 dns_stub_listener_extra_compare_func
,
62 dns_stub_listener_extra_free
);
64 int dns_stub_listener_extra_new(
66 DnsStubListenerExtra
**ret
) {
68 DnsStubListenerExtra
*l
;
70 l
= new(DnsStubListenerExtra
, 1);
74 *l
= (DnsStubListenerExtra
) {
82 DnsStubListenerExtra
*dns_stub_listener_extra_free(DnsStubListenerExtra
*p
) {
86 p
->udp_event_source
= sd_event_source_disable_unref(p
->udp_event_source
);
87 p
->tcp_event_source
= sd_event_source_disable_unref(p
->tcp_event_source
);
89 hashmap_free(p
->queries_by_packet
);
94 static void stub_packet_hash_func(const DnsPacket
*p
, struct siphash
*state
) {
97 siphash24_compress(&p
->protocol
, sizeof(p
->protocol
), state
);
98 siphash24_compress(&p
->family
, sizeof(p
->family
), state
);
99 siphash24_compress(&p
->sender
, sizeof(p
->sender
), state
);
100 siphash24_compress(&p
->ipproto
, sizeof(p
->ipproto
), state
);
101 siphash24_compress(&p
->sender_port
, sizeof(p
->sender_port
), state
);
102 siphash24_compress(DNS_PACKET_HEADER(p
), sizeof(DnsPacketHeader
), state
);
104 /* We don't bother hashing the full packet here, just the header */
107 static int stub_packet_compare_func(const DnsPacket
*x
, const DnsPacket
*y
) {
110 r
= CMP(x
->protocol
, y
->protocol
);
114 r
= CMP(x
->family
, y
->family
);
118 r
= memcmp(&x
->sender
, &y
->sender
, sizeof(x
->sender
));
122 r
= CMP(x
->ipproto
, y
->ipproto
);
126 r
= CMP(x
->sender_port
, y
->sender_port
);
130 return memcmp(DNS_PACKET_HEADER(x
), DNS_PACKET_HEADER(y
), sizeof(DnsPacketHeader
));
133 DEFINE_HASH_OPS(stub_packet_hash_ops
, DnsPacket
, stub_packet_hash_func
, stub_packet_compare_func
);
135 static int reply_add_with_rrsig(
137 DnsResourceRecord
*rr
,
139 DnsAnswerFlags flags
,
140 DnsResourceRecord
*rrsig
,
147 r
= dns_answer_add_extend(reply
, rr
, ifindex
, flags
, rrsig
);
151 if (with_rrsig
&& rrsig
) {
152 r
= dns_answer_add_extend(reply
, rrsig
, ifindex
, flags
, NULL
);
160 static int dns_stub_collect_answer_by_question(
163 DnsQuestion
*question
,
164 bool with_rrsig
) { /* Add RRSIG RR matching each RR */
171 /* Copies all RRs from 'answer' into 'reply', if they match 'question'. */
173 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
175 /* We have a question, let's see if this RR matches it */
176 r
= dns_question_matches_rr(question
, item
->rr
, NULL
);
180 /* Maybe there's a CNAME/DNAME in here? If so, that's an answer too */
181 r
= dns_question_matches_cname_or_dname(question
, item
->rr
, NULL
);
188 /* Mask the section info, we want the primary answers to always go without section
189 * info, so that it is added to the answer section when we synthesize a reply. */
191 r
= reply_add_with_rrsig(
195 item
->flags
& ~DNS_ANSWER_MASK_SECTIONS
,
205 static int dns_stub_collect_answer_by_section(
208 DnsAnswerFlags section
,
211 bool with_dnssec
) { /* Include DNSSEC RRs. RRSIG, NSEC, … */
218 /* Copies all RRs from 'answer' into 'reply', if they originate from the specified section. Also,
219 * avoid any RRs listed in 'exclude'. */
221 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
223 if (dns_answer_contains(exclude1
, item
->rr
) ||
224 dns_answer_contains(exclude2
, item
->rr
))
228 dns_type_is_dnssec(item
->rr
->key
->type
))
231 if (((item
->flags
^ section
) & DNS_ANSWER_MASK_SECTIONS
) != 0)
234 r
= reply_add_with_rrsig(
248 static int dns_stub_assign_sections(
250 DnsQuestion
*question
,
258 /* Let's assign the 'answer' RRs we collected to their respective sections in the reply datagram. We
259 * try to reproduce a section assignment similar to what the upstream DNS server responded to us. We
260 * use the DNS_ANSWER_SECTION_xyz flags to match things up, which is where the original upstream's
261 * packet section assignment is stored in the DnsAnswer object. Not all RRs in the 'answer' objects
262 * come with section information though (for example, because they were synthesized locally, and not
263 * from a DNS packet). To deal with that we extend the assignment logic a bit: anything from the
264 * 'answer' object that directly matches the original question is always put in the ANSWER section,
265 * regardless if it carries section info, or what that section info says. Then, anything from the
266 * 'answer' objects that is from the ANSWER or AUTHORITY sections, and wasn't already added to the
267 * ANSWER section is placed in the AUTHORITY section. Everything else from either object is added to
268 * the ADDITIONAL section. */
270 /* Include all RRs that directly answer the question in the answer section */
271 r
= dns_stub_collect_answer_by_question(
279 /* Include all RRs that originate from the authority sections, and aren't already listed in the
280 * answer section, in the authority section */
281 r
= dns_stub_collect_answer_by_section(
282 &q
->reply_authoritative
,
284 DNS_ANSWER_SECTION_AUTHORITY
,
285 q
->reply_answer
, NULL
,
290 /* Include all RRs that originate from the answer or additional sections in the additional section
291 * (except if already listed in the other two sections). Also add all RRs with no section marking. */
292 r
= dns_stub_collect_answer_by_section(
293 &q
->reply_additional
,
295 DNS_ANSWER_SECTION_ANSWER
,
296 q
->reply_answer
, q
->reply_authoritative
,
300 r
= dns_stub_collect_answer_by_section(
301 &q
->reply_additional
,
303 DNS_ANSWER_SECTION_ADDITIONAL
,
304 q
->reply_answer
, q
->reply_authoritative
,
308 r
= dns_stub_collect_answer_by_section(
309 &q
->reply_additional
,
312 q
->reply_answer
, q
->reply_authoritative
,
320 static int dns_stub_make_reply_packet(
324 bool *ret_truncated
) {
326 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
332 r
= dns_packet_new(&p
, DNS_PROTOCOL_DNS
, 0, max_size
);
336 r
= dns_packet_append_question(p
, q
);
347 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(dns_question_size(q
));
353 static int dns_stub_add_reply_packet_body(
356 DnsAnswer
*authoritative
,
357 DnsAnswer
*additional
,
358 bool edns0_do
, /* Client expects DNSSEC RRs? */
361 unsigned n_answer
= 0, n_authoritative
= 0, n_additional
= 0;
367 /* Add the three sections to the packet. If the answer section doesn't fit we'll signal that as
368 * truncation. If the authoritative section doesn't fit and we are in DNSSEC mode, also signal
369 * truncation. In all other cases where things don't fit don't signal truncation, as for those cases
370 * the dropped RRs should not be essential. */
372 r
= dns_packet_append_answer(p
, answer
, &n_answer
);
378 r
= dns_packet_append_answer(p
, authoritative
, &n_authoritative
);
379 if (r
== -EMSGSIZE
) {
385 r
= dns_packet_append_answer(p
, additional
, &n_additional
);
386 if (r
< 0 && r
!= -EMSGSIZE
)
398 DNS_PACKET_HEADER(p
)->ancount
= htobe16(n_answer
);
399 DNS_PACKET_HEADER(p
)->nscount
= htobe16(n_authoritative
);
400 DNS_PACKET_HEADER(p
)->arcount
= htobe16(n_additional
);
404 static const char *nsid_string(void) {
405 static char buffer
[SD_ID128_STRING_MAX
+ STRLEN(".resolved.systemd.io")] = "";
409 /* Let's generate a string that we can use as RFC5001 NSID identifier. The string shall identify us
410 * as systemd-resolved, and return a different string for each resolved instance without leaking host
411 * identity. Hence let's use a fixed suffix that identifies resolved, and a prefix generated from the
412 * machine ID but from which the machine ID cannot be determined.
414 * Clients can use this to determine whether an answer is originating locally or is proxied from
417 if (!isempty(buffer
))
420 r
= sd_id128_get_machine_app_specific(
421 SD_ID128_MAKE(ed
,d3
,12,5d
,16,b9
,41,f9
,a1
,49,5f
,ab
,15,62,ab
,27),
424 log_debug_errno(r
, "Failed to determine machine ID, ignoring: %m");
428 xsprintf(buffer
, SD_ID128_FORMAT_STR
".resolved.systemd.io", SD_ID128_FORMAT_VAL(id
));
432 static int dns_stub_finish_reply_packet(
436 bool tc
, /* set the Truncated bit? */
437 bool aa
, /* set the Authoritative Answer bit? */
438 bool rd
, /* set the Recursion Desired bit? */
439 bool add_opt
, /* add an OPT RR to this packet? */
440 bool edns0_do
, /* set the EDNS0 DNSSEC OK bit? */
441 bool ad
, /* set the DNSSEC authenticated data bit? */
442 bool cd
, /* set the DNSSEC checking disabled bit? */
443 uint16_t max_udp_size
, /* The maximum UDP datagram size to advertise to clients */
444 bool nsid
) { /* whether to add NSID */
451 r
= dns_packet_append_opt(p
, max_udp_size
, edns0_do
, /* include_rfc6975 = */ false, nsid
? nsid_string() : NULL
, rcode
, NULL
);
452 if (r
== -EMSGSIZE
) /* Hit the size limit? then indicate truncation */
457 /* If the client can't to EDNS0, don't do DO either */
460 /* If we don't do EDNS, clamp the rcode to 4 bit */
462 rcode
= DNS_RCODE_SERVFAIL
;
465 /* Don't set the CD bit unless DO is on, too */
469 /* Note that we allow the AD bit to be set even if client didn't signal DO, as per RFC 6840, section
472 DNS_PACKET_HEADER(p
)->id
= id
;
474 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
488 static bool address_is_proxy(int family
, const union in_addr_union
*a
) {
491 /* Returns true if the specified address is the DNS "proxy" stub, i.e. where we unconditionally enable bypass mode */
493 if (family
!= AF_INET
)
496 return be32toh(a
->in
.s_addr
) == INADDR_DNS_PROXY_STUB
;
499 static int find_socket_fd(
501 DnsStubListenerExtra
*l
,
503 const union in_addr_union
*listen_address
,
508 /* Finds the right socket to use for sending. If we know the extra listener, otherwise go via the
509 * address to send from */
511 return manager_dns_stub_fd_extra(m
, l
, type
);
513 return manager_dns_stub_fd(m
, family
, listen_address
, type
);
516 static int dns_stub_send(
518 DnsStubListenerExtra
*l
,
530 r
= dns_stream_write_packet(s
, reply
);
534 fd
= find_socket_fd(m
, l
, p
->family
, &p
->destination
, SOCK_DGRAM
);
538 if (address_is_proxy(p
->family
, &p
->destination
))
539 /* Force loopback iface if this is the loopback proxy stub
540 * and ifindex was normalized to 0 by manager_recv(). */
541 ifindex
= p
->ifindex
?: LOOPBACK_IFINDEX
;
543 /* Force loopback iface if this is the main listener stub. */
544 ifindex
= l
? p
->ifindex
: LOOPBACK_IFINDEX
;
546 /* Note that it is essential here that we explicitly choose the source IP address for this
547 * packet. This is because otherwise the kernel will choose it automatically based on the
548 * routing table and will thus pick 127.0.0.1 rather than 127.0.0.53/54. */
552 p
->family
, &p
->sender
, p
->sender_port
, &p
->destination
,
556 return log_debug_errno(r
, "Failed to send reply packet: %m");
561 static int dns_stub_reply_with_edns0_do(DnsQuery
*q
) {
564 /* Reply with DNSSEC DO set? Only if client supports it; and we did any DNSSEC verification
565 * ourselves, or consider the data fully authenticated because we generated it locally, or the client
568 return DNS_PACKET_DO(q
->request_packet
) &&
569 (q
->answer_dnssec_result
>= 0 || /* we did proper DNSSEC validation … */
570 dns_query_fully_authenticated(q
) || /* … or we considered it authentic otherwise … */
571 DNS_PACKET_CD(q
->request_packet
)); /* … or client set CD */
574 static void dns_stub_suppress_duplicate_section_rrs(DnsQuery
*q
) {
575 /* If we follow a CNAME/DNAME chain we might end up populating our sections with redundant RRs
576 * because we built up the sections from multiple reply packets (one from each CNAME/DNAME chain
577 * element). E.g. it could be that an RR that was included in the first reply's additional section
578 * ends up being relevant as main answer in a subsequent reply in the chain. Let's clean this up, and
579 * remove everything in the "higher priority" sections from the "lower priority" sections.
581 * Note that this removal matches by RR keys instead of the full RRs. This is because RRsets should
582 * always end up in one section fully or not at all, but never be split among sections.
584 * Specifically: we remove ANSWER section RRs from the AUTHORITATIVE and ADDITIONAL sections, as well
585 * as AUTHORITATIVE section RRs from the ADDITIONAL section. */
587 dns_answer_remove_by_answer_keys(&q
->reply_authoritative
, q
->reply_answer
);
588 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_answer
);
589 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_authoritative
);
592 static int dns_stub_send_reply(
596 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
597 bool truncated
, edns0_do
;
602 edns0_do
= dns_stub_reply_with_edns0_do(q
); /* let's check if we shall reply with EDNS0 DO? */
604 r
= dns_stub_make_reply_packet(
606 DNS_PACKET_PAYLOAD_SIZE_MAX(q
->request_packet
),
607 q
->request_packet
->question
,
610 return log_debug_errno(r
, "Failed to build reply packet: %m");
612 dns_stub_suppress_duplicate_section_rrs(q
);
614 r
= dns_stub_add_reply_packet_body(
617 q
->reply_authoritative
,
622 return log_debug_errno(r
, "Failed to append reply packet body: %m");
624 r
= dns_stub_finish_reply_packet(
626 DNS_PACKET_ID(q
->request_packet
),
629 dns_query_fully_authoritative(q
),
630 DNS_PACKET_RD(q
->request_packet
),
631 !!q
->request_packet
->opt
,
633 (DNS_PACKET_AD(q
->request_packet
) || DNS_PACKET_DO(q
->request_packet
)) && dns_query_fully_authenticated(q
),
634 DNS_PACKET_CD(q
->request_packet
),
635 q
->stub_listener_extra
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
636 dns_packet_has_nsid_request(q
->request_packet
) > 0 && !q
->stub_listener_extra
);
638 return log_debug_errno(r
, "Failed to build failure packet: %m");
640 return dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
643 static int dns_stub_send_failure(
645 DnsStubListenerExtra
*l
,
649 bool authenticated
) {
651 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
658 r
= dns_stub_make_reply_packet(
660 DNS_PACKET_PAYLOAD_SIZE_MAX(p
),
664 return log_debug_errno(r
, "Failed to make failure packet: %m");
666 r
= dns_stub_finish_reply_packet(
675 (DNS_PACKET_AD(p
) || DNS_PACKET_DO(p
)) && authenticated
,
677 l
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
678 dns_packet_has_nsid_request(p
) > 0 && !l
);
680 return log_debug_errno(r
, "Failed to build failure packet: %m");
682 return dns_stub_send(m
, l
, s
, p
, reply
);
685 static int dns_stub_patch_bypass_reply_packet(
686 DnsPacket
**ret
, /* Where to place the patched packet */
687 DnsPacket
*original
, /* The packet to patch */
688 DnsPacket
*request
, /* The packet the patched packet shall look like a reply to */
689 bool authenticated
) {
690 _cleanup_(dns_packet_unrefp
) DnsPacket
*c
= NULL
;
697 r
= dns_packet_dup(&c
, original
);
701 /* Extract the packet, so that we know where the OPT field is */
702 r
= dns_packet_extract(c
);
706 /* Copy over the original client request ID, so that we can make the upstream query look like our own reply. */
707 DNS_PACKET_HEADER(c
)->id
= DNS_PACKET_HEADER(request
)->id
;
709 /* Patch in our own maximum datagram size, if EDNS0 was on */
710 r
= dns_packet_patch_max_udp_size(c
, ADVERTISE_DATAGRAM_SIZE_MAX
);
714 /* Lower all TTLs by the time passed since we received the datagram. */
715 if (timestamp_is_set(original
->timestamp
)) {
716 r
= dns_packet_patch_ttls(c
, original
->timestamp
);
721 /* Our upstream connection might have supported larger DNS requests than our downstream one, hence
722 * set the TC bit if our reply is larger than what the client supports, and truncate. */
723 if (c
->size
> DNS_PACKET_PAYLOAD_SIZE_MAX(request
)) {
724 log_debug("Artificially truncating stub response, as advertised size of client is smaller than upstream one.");
725 dns_packet_truncate(c
, DNS_PACKET_PAYLOAD_SIZE_MAX(request
));
726 DNS_PACKET_HEADER(c
)->flags
= htobe16(be16toh(DNS_PACKET_HEADER(c
)->flags
) | DNS_PACKET_FLAG_TC
);
729 /* Ensure we don't pass along an untrusted ad flag for bypass packets */
731 DNS_PACKET_HEADER(c
)->flags
= htobe16(be16toh(DNS_PACKET_HEADER(c
)->flags
) & ~DNS_PACKET_FLAG_AD
);
737 static void dns_stub_query_complete(DnsQuery
*query
) {
738 _cleanup_(dns_query_freep
) DnsQuery
*q
= query
;
742 assert(q
->request_packet
);
744 if (q
->question_bypass
) {
745 /* This is a bypass reply. If so, let's propagate the upstream packet, if we have it and it
746 * is regular DNS. (We can't do this if the upstream packet is LLMNR or mDNS, since the
747 * packets are not 100% compatible.) */
749 if (q
->answer_full_packet
&&
750 q
->answer_full_packet
->protocol
== DNS_PROTOCOL_DNS
) {
751 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
753 r
= dns_stub_patch_bypass_reply_packet(&reply
, q
->answer_full_packet
, q
->request_packet
,
754 FLAGS_SET(q
->answer_query_flags
, SD_RESOLVED_AUTHENTICATED
));
756 log_debug_errno(r
, "Failed to patch bypass reply packet: %m");
758 (void) dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
764 /* Take all data from the current reply, and merge it into the three reply sections we are building
765 * up. We do this before processing CNAME redirects, so that we gradually build up our sections, and
766 * and keep adding all RRs in the CNAME chain. */
767 r
= dns_stub_assign_sections(
769 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
770 dns_stub_reply_with_edns0_do(q
));
772 return (void) log_debug_errno(r
, "Failed to assign sections: %m");
776 case DNS_TRANSACTION_SUCCESS
: {
782 cname_result
= dns_query_process_cname_one(q
);
783 if (cname_result
== -ELOOP
) { /* CNAME loop, let's send what we already have */
784 log_debug("Detected CNAME loop, returning what we already have.");
785 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
788 if (cname_result
< 0) {
789 log_debug_errno(cname_result
, "Failed to process CNAME: %m");
793 if (cname_result
== DNS_QUERY_NOMATCH
) {
794 /* This answer doesn't contain any RR that would answer our question
795 * positively, i.e. neither directly nor via CNAME. */
797 if (first
) /* We never followed a CNAME and the answer doesn't match our
798 * question at all? Then this is final, the empty answer is the
802 /* Otherwise, we already followed a CNAME once within this packet, and the
803 * packet doesn't answer our question. In that case let's restart the query,
804 * now with the redirected question. We'll */
807 return (void) log_debug_errno(r
, "Failed to restart query: %m");
813 r
= dns_stub_assign_sections(
815 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
816 dns_stub_reply_with_edns0_do(q
));
818 return (void) log_debug_errno(r
, "Failed to assign sections: %m");
820 if (cname_result
== DNS_QUERY_MATCH
) /* A match? Then we are done, let's return what we got */
823 /* We followed a CNAME. and collected the RRs that answer the redirected question
824 * successfully. Let's not try to do this again. */
825 assert(cname_result
== DNS_QUERY_CNAME
);
832 case DNS_TRANSACTION_RCODE_FAILURE
:
833 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
836 case DNS_TRANSACTION_NOT_FOUND
:
837 (void) dns_stub_send_reply(q
, DNS_RCODE_NXDOMAIN
);
840 case DNS_TRANSACTION_TIMEOUT
:
841 case DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
:
842 /* Propagate a timeout as a no packet, i.e. that the client also gets a timeout */
845 case DNS_TRANSACTION_NO_SERVERS
:
846 /* We're not configured to give answers for this question. Refuse it. */
847 (void) dns_stub_send_reply(q
, DNS_RCODE_REFUSED
);
850 case DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
:
851 /* This RR Type is not implemented */
852 (void) dns_stub_send_reply(q
, DNS_RCODE_NOTIMP
);
855 case DNS_TRANSACTION_INVALID_REPLY
:
856 case DNS_TRANSACTION_ERRNO
:
857 case DNS_TRANSACTION_ABORTED
:
858 case DNS_TRANSACTION_DNSSEC_FAILED
:
859 case DNS_TRANSACTION_NO_TRUST_ANCHOR
:
860 case DNS_TRANSACTION_NETWORK_DOWN
:
861 case DNS_TRANSACTION_NO_SOURCE
:
862 case DNS_TRANSACTION_STUB_LOOP
:
863 (void) dns_stub_send_reply(q
, DNS_RCODE_SERVFAIL
);
866 case DNS_TRANSACTION_NULL
:
867 case DNS_TRANSACTION_PENDING
:
868 case DNS_TRANSACTION_VALIDATING
:
870 assert_not_reached();
874 static int dns_stub_stream_complete(DnsStream
*s
, int error
) {
877 log_debug_errno(error
, "DNS TCP connection terminated, destroying queries: %m");
882 q
= set_first(s
->queries
);
889 /* This drops the implicit ref we keep around since it was allocated, as incoming stub connections
890 * should be kept as long as the client wants to. */
895 static void dns_stub_process_query(Manager
*m
, DnsStubListenerExtra
*l
, DnsStream
*s
, DnsPacket
*p
) {
896 uint64_t protocol_flags
= SD_RESOLVED_PROTOCOLS_ALL
;
897 _cleanup_(dns_query_freep
) DnsQuery
*q
= NULL
;
898 Hashmap
**queries_by_packet
;
905 assert(p
->protocol
== DNS_PROTOCOL_DNS
);
907 if (!l
&& /* l == NULL if this is the main stub */
908 !address_is_proxy(p
->family
, &p
->destination
) && /* don't restrict needlessly for 127.0.0.54 */
909 (in_addr_is_localhost(p
->family
, &p
->sender
) <= 0 ||
910 in_addr_is_localhost(p
->family
, &p
->destination
) <= 0)) {
911 log_warning("Got packet on unexpected (i.e. non-localhost) IP range, ignoring.");
915 if (manager_packet_from_our_transaction(m
, p
)) {
916 log_debug("Got our own packet looped back, ignoring.");
920 queries_by_packet
= l
? &l
->queries_by_packet
: &m
->stub_queries_by_packet
;
921 existing
= hashmap_get(*queries_by_packet
, p
);
922 if (existing
&& dns_packet_equal(existing
->request_packet
, p
)) {
923 log_debug("Got repeat packet from client, ignoring.");
927 r
= dns_packet_extract(p
);
929 log_debug_errno(r
, "Failed to extract resources from incoming packet, ignoring packet: %m");
930 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_FORMERR
, false);
934 if (!DNS_PACKET_VERSION_SUPPORTED(p
)) {
935 log_debug("Got EDNS OPT field with unsupported version number.");
936 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_BADVERS
, false);
940 if (dns_type_is_obsolete(dns_question_first_key(p
->question
)->type
)) {
941 log_debug("Got message with obsolete key type, refusing.");
942 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
946 if (dns_type_is_zone_transer(dns_question_first_key(p
->question
)->type
)) {
947 log_debug("Got request for zone transfer, refusing.");
948 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
952 if (!DNS_PACKET_RD(p
)) {
953 /* If the "rd" bit is off (i.e. recursion was not requested), then refuse operation */
954 log_debug("Got request with recursion disabled, refusing.");
955 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
959 r
= hashmap_ensure_allocated(queries_by_packet
, &stub_packet_hash_ops
);
965 if (address_is_proxy(p
->family
, &p
->destination
)) {
966 _cleanup_free_
char *dipa
= NULL
;
968 r
= in_addr_to_string(p
->family
, &p
->destination
, &dipa
);
970 return (void) log_error_errno(r
, "Failed to format destination address: %m");
972 log_debug("Got request to DNS proxy address 127.0.0.54, enabling bypass logic.");
974 protocol_flags
= SD_RESOLVED_DNS
|SD_RESOLVED_NO_ZONE
; /* Turn off mDNS/LLMNR for proxy stub. */
975 } else if ((DNS_PACKET_DO(p
) && DNS_PACKET_CD(p
))) {
976 log_debug("Got request with DNSSEC checking disabled, enabling bypass logic.");
981 r
= dns_query_new(m
, &q
, NULL
, NULL
, p
, 0,
983 SD_RESOLVED_NO_CNAME
|
984 SD_RESOLVED_NO_SEARCH
|
985 SD_RESOLVED_NO_VALIDATE
|
986 SD_RESOLVED_REQUIRE_PRIMARY
|
987 SD_RESOLVED_CLAMP_TTL
);
989 r
= dns_query_new(m
, &q
, p
->question
, p
->question
, NULL
, 0,
991 SD_RESOLVED_NO_SEARCH
|
992 (DNS_PACKET_DO(p
) ? SD_RESOLVED_REQUIRE_PRIMARY
: 0)|
993 SD_RESOLVED_CLAMP_TTL
);
995 log_error_errno(r
, "Failed to generate query object: %m");
996 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
1000 q
->request_packet
= dns_packet_ref(p
);
1001 q
->request_stream
= dns_stream_ref(s
); /* make sure the stream stays around until we can send a reply through it */
1002 q
->stub_listener_extra
= l
;
1003 q
->complete
= dns_stub_query_complete
;
1006 /* Remember which queries belong to this stream, so that we can cancel them when the stream
1007 * is disconnected early */
1009 r
= set_ensure_put(&s
->queries
, NULL
, q
);
1017 /* Add the query to the hash table we use to determine repeat packets now. We don't care about
1018 * failures here, since in the worst case we'll not recognize duplicate incoming requests, which
1019 * isn't particularly bad. */
1020 (void) hashmap_put(*queries_by_packet
, q
->request_packet
, q
);
1022 r
= dns_query_go(q
);
1024 log_error_errno(r
, "Failed to start query: %m");
1025 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
1029 log_debug("Processing query...");
1033 static int on_dns_stub_packet_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1034 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1037 r
= manager_recv(m
, fd
, DNS_PROTOCOL_DNS
, &p
);
1041 if (dns_packet_validate_query(p
) > 0) {
1042 log_debug("Got DNS stub UDP query packet for id %u", DNS_PACKET_ID(p
));
1044 dns_stub_process_query(m
, l
, NULL
, p
);
1046 log_debug("Invalid DNS stub UDP packet, ignoring.");
1051 static int on_dns_stub_packet(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1052 return on_dns_stub_packet_internal(s
, fd
, revents
, userdata
, NULL
);
1055 static int on_dns_stub_packet_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1056 DnsStubListenerExtra
*l
= ASSERT_PTR(userdata
);
1058 return on_dns_stub_packet_internal(s
, fd
, revents
, l
->manager
, l
);
1061 static int on_dns_stub_stream_packet(DnsStream
*s
, DnsPacket
*p
) {
1066 if (dns_packet_validate_query(p
) > 0) {
1067 log_debug("Got DNS stub TCP query packet for id %u", DNS_PACKET_ID(p
));
1069 dns_stub_process_query(s
->manager
, s
->stub_listener_extra
, s
, p
);
1071 log_debug("Invalid DNS stub TCP packet, ignoring.");
1076 static int on_dns_stub_stream_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1080 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1082 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1088 r
= dns_stream_new(m
, &stream
, DNS_STREAM_STUB
, DNS_PROTOCOL_DNS
, cfd
, NULL
,
1089 on_dns_stub_stream_packet
, dns_stub_stream_complete
, DNS_STREAM_STUB_TIMEOUT_USEC
);
1095 stream
->stub_listener_extra
= l
;
1097 /* We let the reference to the stream dangle here, it will be dropped later by the complete callback. */
1102 static int on_dns_stub_stream(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1103 return on_dns_stub_stream_internal(s
, fd
, revents
, userdata
, NULL
);
1106 static int on_dns_stub_stream_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1107 DnsStubListenerExtra
*l
= ASSERT_PTR(userdata
);
1109 return on_dns_stub_stream_internal(s
, fd
, revents
, l
->manager
, l
);
1112 static int set_dns_stub_common_socket_options(int fd
, int family
) {
1116 assert(IN_SET(family
, AF_INET
, AF_INET6
));
1118 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_REUSEADDR
, true);
1122 r
= socket_set_recvpktinfo(fd
, family
, true);
1126 r
= socket_set_recvttl(fd
, family
, true);
1133 static int set_dns_stub_common_tcp_socket_options(int fd
) {
1138 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_FASTOPEN
, 5); /* Everybody appears to pick qlen=5, let's do the same here. */
1140 log_debug_errno(r
, "Failed to enable TCP_FASTOPEN on TCP listening socket, ignoring: %m");
1142 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_NODELAY
, true);
1144 log_debug_errno(r
, "Failed to enable TCP_NODELAY mode, ignoring: %m");
1149 static int manager_dns_stub_fd(
1152 const union in_addr_union
*listen_addr
,
1155 sd_event_source
**event_source
;
1156 _cleanup_close_
int fd
= -EBADF
;
1157 union sockaddr_union sa
;
1161 assert(listen_addr
);
1163 if (type
== SOCK_DGRAM
)
1164 event_source
= address_is_proxy(family
, listen_addr
) ? &m
->dns_proxy_stub_udp_event_source
: &m
->dns_stub_udp_event_source
;
1165 else if (type
== SOCK_STREAM
)
1166 event_source
= address_is_proxy(family
, listen_addr
) ? &m
->dns_proxy_stub_tcp_event_source
: &m
->dns_stub_tcp_event_source
;
1168 return -EPROTONOSUPPORT
;
1171 return sd_event_source_get_io_fd(*event_source
);
1173 fd
= socket(family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1177 r
= set_dns_stub_common_socket_options(fd
, family
);
1181 if (type
== SOCK_STREAM
) {
1182 r
= set_dns_stub_common_tcp_socket_options(fd
);
1187 /* Set slightly different socket options for the non-proxy and the proxy binding. The former we want
1188 * to be accessible only from the local host, for the latter it's OK if people use NAT redirects or
1189 * so to redirect external traffic to it. */
1191 if (!address_is_proxy(family
, listen_addr
)) {
1192 /* Make sure no traffic from outside the local host can leak to onto this socket */
1193 r
= socket_bind_to_ifindex(fd
, LOOPBACK_IFINDEX
);
1197 r
= socket_set_ttl(fd
, family
, 1);
1200 } else if (type
== SOCK_DGRAM
) {
1201 /* Turn off Path MTU Discovery for UDP, for security reasons. See socket_disable_pmtud() for
1202 * a longer discussion. (We only do this for sockets that are potentially externally
1203 * accessible, i.e. the proxy stub one. For the non-proxy one we instead set the TTL to 1,
1204 * see above, so that packets don't get routed at all.) */
1205 r
= socket_disable_pmtud(fd
, family
);
1207 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1209 r
= socket_set_recvfragsize(fd
, family
, true);
1211 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1214 r
= sockaddr_set_in_addr(&sa
, family
, listen_addr
, 53);
1218 if (bind(fd
, &sa
.sa
, sizeof(sa
.in
)) < 0)
1221 if (type
== SOCK_STREAM
&&
1222 listen(fd
, SOMAXCONN_DELUXE
) < 0)
1225 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1226 type
== SOCK_DGRAM
? on_dns_stub_packet
: on_dns_stub_stream
,
1231 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1235 (void) sd_event_source_set_description(*event_source
,
1236 type
== SOCK_DGRAM
? "dns-stub-udp" : "dns-stub-tcp");
1241 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
) {
1242 _cleanup_free_
char *pretty
= NULL
;
1243 _cleanup_close_
int fd
= -EBADF
;
1244 union sockaddr_union sa
;
1249 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1251 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &l
->udp_event_source
: &l
->tcp_event_source
;
1253 return sd_event_source_get_io_fd(*event_source
);
1255 if (!have_effective_cap(CAP_NET_BIND_SERVICE
) && dns_stub_listener_extra_port(l
) < 1024) {
1256 log_warning("Missing CAP_NET_BIND_SERVICE capability, not creating extra stub listener on port %hu.",
1257 dns_stub_listener_extra_port(l
));
1261 if (l
->family
== AF_INET
)
1262 sa
= (union sockaddr_union
) {
1263 .in
.sin_family
= l
->family
,
1264 .in
.sin_port
= htobe16(dns_stub_listener_extra_port(l
)),
1265 .in
.sin_addr
= l
->address
.in
,
1268 sa
= (union sockaddr_union
) {
1269 .in6
.sin6_family
= l
->family
,
1270 .in6
.sin6_port
= htobe16(dns_stub_listener_extra_port(l
)),
1271 .in6
.sin6_addr
= l
->address
.in6
,
1274 fd
= socket(l
->family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1280 r
= set_dns_stub_common_socket_options(fd
, l
->family
);
1284 if (type
== SOCK_STREAM
) {
1285 r
= set_dns_stub_common_tcp_socket_options(fd
);
1290 /* Do not set IP_TTL for extra DNS stub listeners, as the address may not be local and in that case
1291 * people may want ttl > 1. */
1293 r
= socket_set_freebind(fd
, l
->family
, true);
1297 if (type
== SOCK_DGRAM
) {
1298 r
= socket_disable_pmtud(fd
, l
->family
);
1300 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1302 r
= socket_set_recvfragsize(fd
, l
->family
, true);
1304 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1307 r
= RET_NERRNO(bind(fd
, &sa
.sa
, SOCKADDR_LEN(sa
)));
1311 if (type
== SOCK_STREAM
&&
1312 listen(fd
, SOMAXCONN_DELUXE
) < 0) {
1317 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1318 type
== SOCK_DGRAM
? on_dns_stub_packet_extra
: on_dns_stub_stream_extra
,
1323 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1327 (void) sd_event_source_set_description(*event_source
,
1328 type
== SOCK_DGRAM
? "dns-stub-udp-extra" : "dns-stub-tcp-extra");
1330 if (DEBUG_LOGGING
) {
1331 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1332 log_debug("Listening on %s socket %s.",
1333 type
== SOCK_DGRAM
? "UDP" : "TCP",
1341 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1342 return log_warning_errno(r
,
1343 r
== -EADDRINUSE
? "Another process is already listening on %s socket %s: %m" :
1344 "Failed to listen on %s socket %s: %m",
1345 type
== SOCK_DGRAM
? "UDP" : "TCP",
1349 int manager_dns_stub_start(Manager
*m
) {
1354 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_NO
)
1355 log_debug("Not creating stub listener.");
1356 else if (!have_effective_cap(CAP_NET_BIND_SERVICE
))
1357 log_warning("Missing CAP_NET_BIND_SERVICE capability, not creating stub listener on port 53.");
1359 static const struct {
1362 } stub_sockets
[] = {
1363 { INADDR_DNS_STUB
, SOCK_DGRAM
},
1364 { INADDR_DNS_STUB
, SOCK_STREAM
},
1365 { INADDR_DNS_PROXY_STUB
, SOCK_DGRAM
},
1366 { INADDR_DNS_PROXY_STUB
, SOCK_STREAM
},
1369 log_debug("Creating stub listener using %s.",
1370 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
? "UDP" :
1371 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
? "TCP" :
1374 for (size_t i
= 0; i
< ELEMENTSOF(stub_sockets
); i
++) {
1375 union in_addr_union a
= {
1376 .in
.s_addr
= htobe32(stub_sockets
[i
].addr
),
1379 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
&& stub_sockets
[i
].socket_type
== SOCK_STREAM
)
1381 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
&& stub_sockets
[i
].socket_type
== SOCK_DGRAM
)
1384 r
= manager_dns_stub_fd(m
, AF_INET
, &a
, stub_sockets
[i
].socket_type
);
1386 _cleanup_free_
char *busy_socket
= NULL
;
1388 if (asprintf(&busy_socket
,
1389 "%s socket " IPV4_ADDRESS_FMT_STR
":53",
1390 stub_sockets
[i
].socket_type
== SOCK_DGRAM
? "UDP" : "TCP",
1391 IPV4_ADDRESS_FMT_VAL(a
.in
)) < 0)
1394 if (IN_SET(r
, -EADDRINUSE
, -EPERM
)) {
1395 log_warning_errno(r
,
1396 r
== -EADDRINUSE
? "Another process is already listening on %s.\n"
1397 "Turning off local DNS stub support." :
1398 "Failed to listen on %s: %m.\n"
1399 "Turning off local DNS stub support.",
1401 manager_dns_stub_stop(m
);
1405 return log_error_errno(r
, "Failed to listen on %s: %m", busy_socket
);
1410 if (!ordered_set_isempty(m
->dns_extra_stub_listeners
)) {
1411 DnsStubListenerExtra
*l
;
1413 log_debug("Creating extra stub listeners.");
1415 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
) {
1416 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_UDP
))
1417 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
);
1418 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_TCP
))
1419 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_STREAM
);
1426 void manager_dns_stub_stop(Manager
*m
) {
1429 m
->dns_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_stub_udp_event_source
);
1430 m
->dns_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_stub_tcp_event_source
);
1431 m
->dns_proxy_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_proxy_stub_udp_event_source
);
1432 m
->dns_proxy_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_proxy_stub_tcp_event_source
);
1435 static const char* const dns_stub_listener_mode_table
[_DNS_STUB_LISTENER_MODE_MAX
] = {
1436 [DNS_STUB_LISTENER_NO
] = "no",
1437 [DNS_STUB_LISTENER_UDP
] = "udp",
1438 [DNS_STUB_LISTENER_TCP
] = "tcp",
1439 [DNS_STUB_LISTENER_YES
] = "yes",
1441 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(dns_stub_listener_mode
, DnsStubListenerMode
, DNS_STUB_LISTENER_YES
);