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 add_opt
, /* add an OPT RR to this packet? */
437 bool edns0_do
, /* set the EDNS0 DNSSEC OK bit? */
438 bool ad
, /* set the DNSSEC authenticated data bit? */
439 bool cd
, /* set the DNSSEC checking disabled bit? */
440 uint16_t max_udp_size
, /* The maximum UDP datagram size to advertise to clients */
441 bool nsid
) { /* whether to add NSID */
448 r
= dns_packet_append_opt(p
, max_udp_size
, edns0_do
, /* include_rfc6975 = */ false, nsid
? nsid_string() : NULL
, rcode
, NULL
);
449 if (r
== -EMSGSIZE
) /* Hit the size limit? then indicate truncation */
454 /* If the client can't to EDNS0, don't do DO either */
457 /* If we don't do EDNS, clamp the rcode to 4 bit */
459 rcode
= DNS_RCODE_SERVFAIL
;
462 /* Don't set the CD bit unless DO is on, too */
466 /* Note that we allow the AD bit to be set even if client didn't signal DO, as per RFC 6840, section
469 DNS_PACKET_HEADER(p
)->id
= id
;
471 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
485 static int dns_stub_send(
487 DnsStubListenerExtra
*l
,
499 r
= dns_stream_write_packet(s
, reply
);
501 /* Note that it is essential here that we explicitly choose the source IP address for this packet. This
502 * is because otherwise the kernel will choose it automatically based on the routing table and will
503 * thus pick 127.0.0.1 rather than 127.0.0.53. */
505 manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
),
506 l
? p
->ifindex
: LOOPBACK_IFINDEX
, /* force loopback iface if this is the main listener stub */
507 p
->family
, &p
->sender
, p
->sender_port
, &p
->destination
,
510 return log_debug_errno(r
, "Failed to send reply packet: %m");
515 static int dns_stub_reply_with_edns0_do(DnsQuery
*q
) {
518 /* Reply with DNSSEC DO set? Only if client supports it; and we did any DNSSEC verification
519 * ourselves, or consider the data fully authenticated because we generated it locally, or the client
522 return DNS_PACKET_DO(q
->request_packet
) &&
523 (q
->answer_dnssec_result
>= 0 || /* we did proper DNSSEC validation … */
524 dns_query_fully_authenticated(q
) || /* … or we considered it authentic otherwise … */
525 DNS_PACKET_CD(q
->request_packet
)); /* … or client set CD */
528 static void dns_stub_suppress_duplicate_section_rrs(DnsQuery
*q
) {
529 /* If we follow a CNAME/DNAME chain we might end up populating our sections with redundant RRs
530 * because we built up the sections from multiple reply packets (one from each CNAME/DNAME chain
531 * element). E.g. it could be that an RR that was included in the first reply's additional section
532 * ends up being relevant as main answer in a subsequent reply in the chain. Let's clean this up, and
533 * remove everything in the "higher priority" sections from the "lower priority" sections.
535 * Note that this removal matches by RR keys instead of the full RRs. This is because RRsets should
536 * always end up in one section fully or not at all, but never be split among sections.
538 * Specifically: we remove ANSWER section RRs from the AUTHORITATIVE and ADDITIONAL sections, as well
539 * as AUTHORITATIVE section RRs from the ADDITIONAL section. */
541 dns_answer_remove_by_answer_keys(&q
->reply_authoritative
, q
->reply_answer
);
542 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_answer
);
543 dns_answer_remove_by_answer_keys(&q
->reply_additional
, q
->reply_authoritative
);
546 static int dns_stub_send_reply(
550 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
551 bool truncated
, edns0_do
;
556 edns0_do
= dns_stub_reply_with_edns0_do(q
); /* let's check if we shall reply with EDNS0 DO? */
558 r
= dns_stub_make_reply_packet(
560 DNS_PACKET_PAYLOAD_SIZE_MAX(q
->request_packet
),
561 q
->request_packet
->question
,
564 return log_debug_errno(r
, "Failed to build reply packet: %m");
566 dns_stub_suppress_duplicate_section_rrs(q
);
568 r
= dns_stub_add_reply_packet_body(
571 q
->reply_authoritative
,
576 return log_debug_errno(r
, "Failed to append reply packet body: %m");
578 r
= dns_stub_finish_reply_packet(
580 DNS_PACKET_ID(q
->request_packet
),
583 dns_query_fully_authoritative(q
),
584 !!q
->request_packet
->opt
,
586 DNS_PACKET_AD(q
->request_packet
) && dns_query_fully_authenticated(q
),
587 DNS_PACKET_CD(q
->request_packet
),
588 q
->stub_listener_extra
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
589 dns_packet_has_nsid_request(q
->request_packet
) > 0 && !q
->stub_listener_extra
);
591 return log_debug_errno(r
, "Failed to build failure packet: %m");
593 return dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
596 static int dns_stub_send_failure(
598 DnsStubListenerExtra
*l
,
602 bool authenticated
) {
604 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
611 r
= dns_stub_make_reply_packet(
613 DNS_PACKET_PAYLOAD_SIZE_MAX(p
),
617 return log_debug_errno(r
, "Failed to make failure packet: %m");
619 r
= dns_stub_finish_reply_packet(
627 DNS_PACKET_AD(p
) && authenticated
,
629 l
? ADVERTISE_EXTRA_DATAGRAM_SIZE_MAX
: ADVERTISE_DATAGRAM_SIZE_MAX
,
630 dns_packet_has_nsid_request(p
) > 0 && !l
);
632 return log_debug_errno(r
, "Failed to build failure packet: %m");
634 return dns_stub_send(m
, l
, s
, p
, reply
);
637 static int dns_stub_patch_bypass_reply_packet(
638 DnsPacket
**ret
, /* Where to place the patched packet */
639 DnsPacket
*original
, /* The packet to patch */
640 DnsPacket
*request
) { /* The packet the patched packet shall look like a reply to */
641 _cleanup_(dns_packet_unrefp
) DnsPacket
*c
= NULL
;
648 r
= dns_packet_dup(&c
, original
);
652 /* Extract the packet, so that we know where the OPT field is */
653 r
= dns_packet_extract(c
);
657 /* Copy over the original client request ID, so that we can make the upstream query look like our own reply. */
658 DNS_PACKET_HEADER(c
)->id
= DNS_PACKET_HEADER(request
)->id
;
660 /* Patch in our own maximum datagram size, if EDNS0 was on */
661 r
= dns_packet_patch_max_udp_size(c
, ADVERTISE_DATAGRAM_SIZE_MAX
);
665 /* Lower all TTLs by the time passed since we received the datagram. */
666 if (timestamp_is_set(original
->timestamp
)) {
667 r
= dns_packet_patch_ttls(c
, original
->timestamp
);
672 /* Our upstream connection might have supported larger DNS requests than our downstream one, hence
673 * set the TC bit if our reply is larger than what the client supports, and truncate. */
674 if (c
->size
> DNS_PACKET_PAYLOAD_SIZE_MAX(request
)) {
675 log_debug("Artificially truncating stub response, as advertised size of client is smaller than upstream one.");
676 dns_packet_truncate(c
, DNS_PACKET_PAYLOAD_SIZE_MAX(request
));
677 DNS_PACKET_HEADER(c
)->flags
= htobe16(be16toh(DNS_PACKET_HEADER(c
)->flags
) | DNS_PACKET_FLAG_TC
);
684 static void dns_stub_query_complete(DnsQuery
*q
) {
688 assert(q
->request_packet
);
690 if (q
->question_bypass
) {
691 /* This is a bypass reply. If so, let's propagate the upstream packet, if we have it and it
692 * is regular DNS. (We can't do this if the upstream packet is LLMNR or mDNS, since the
693 * packets are not 100% compatible.) */
695 if (q
->answer_full_packet
&&
696 q
->answer_full_packet
->protocol
== DNS_PROTOCOL_DNS
) {
697 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
699 r
= dns_stub_patch_bypass_reply_packet(&reply
, q
->answer_full_packet
, q
->request_packet
);
701 log_debug_errno(r
, "Failed to patch bypass reply packet: %m");
703 (void) dns_stub_send(q
->manager
, q
->stub_listener_extra
, q
->request_stream
, q
->request_packet
, reply
);
710 /* Take all data from the current reply, and merge it into the three reply sections we are building
711 * up. We do this before processing CNAME redirects, so that we gradually build up our sections, and
712 * and keep adding all RRs in the CNAME chain. */
713 r
= dns_stub_assign_sections(
715 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
716 dns_stub_reply_with_edns0_do(q
));
718 log_debug_errno(r
, "Failed to assign sections: %m");
725 case DNS_TRANSACTION_SUCCESS
: {
731 cname_result
= dns_query_process_cname_one(q
);
732 if (cname_result
== -ELOOP
) { /* CNAME loop, let's send what we already have */
733 log_debug_errno(r
, "Detected CNAME loop, returning what we already have.");
734 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
737 if (cname_result
< 0) {
738 log_debug_errno(cname_result
, "Failed to process CNAME: %m");
742 if (cname_result
== DNS_QUERY_NOMATCH
) {
743 /* This answer doesn't contain any RR that would answer our question
744 * positively, i.e. neither directly nor via CNAME. */
746 if (first
) /* We never followed a CNAME and the answer doesn't match our
747 * question at all? Then this is final, the empty answer is the
751 /* Otherwise, we already followed a CNAME once within this packet, and the
752 * packet doesn't answer our question. In that case let's restart the query,
753 * now with the redirected question. We'll */
756 log_debug_errno(r
, "Failed to restart query: %m");
761 r
= dns_stub_assign_sections(
763 dns_query_question_for_protocol(q
, DNS_PROTOCOL_DNS
),
764 dns_stub_reply_with_edns0_do(q
));
766 log_debug_errno(r
, "Failed to assign sections: %m");
771 if (cname_result
== DNS_QUERY_MATCH
) /* A match? Then we are done, let's return what we got */
774 /* We followed a CNAME. and collected the RRs that answer the redirected question
775 * successfully. Let's not try to do this again. */
776 assert(cname_result
== DNS_QUERY_CNAME
);
783 case DNS_TRANSACTION_RCODE_FAILURE
:
784 (void) dns_stub_send_reply(q
, q
->answer_rcode
);
787 case DNS_TRANSACTION_NOT_FOUND
:
788 (void) dns_stub_send_reply(q
, DNS_RCODE_NXDOMAIN
);
791 case DNS_TRANSACTION_TIMEOUT
:
792 case DNS_TRANSACTION_ATTEMPTS_MAX_REACHED
:
793 /* Propagate a timeout as a no packet, i.e. that the client also gets a timeout */
796 case DNS_TRANSACTION_NO_SERVERS
:
797 case DNS_TRANSACTION_INVALID_REPLY
:
798 case DNS_TRANSACTION_ERRNO
:
799 case DNS_TRANSACTION_ABORTED
:
800 case DNS_TRANSACTION_DNSSEC_FAILED
:
801 case DNS_TRANSACTION_NO_TRUST_ANCHOR
:
802 case DNS_TRANSACTION_RR_TYPE_UNSUPPORTED
:
803 case DNS_TRANSACTION_NETWORK_DOWN
:
804 case DNS_TRANSACTION_NO_SOURCE
:
805 case DNS_TRANSACTION_STUB_LOOP
:
806 (void) dns_stub_send_reply(q
, DNS_RCODE_SERVFAIL
);
809 case DNS_TRANSACTION_NULL
:
810 case DNS_TRANSACTION_PENDING
:
811 case DNS_TRANSACTION_VALIDATING
:
813 assert_not_reached("Impossible state");
819 static int dns_stub_stream_complete(DnsStream
*s
, int error
) {
822 log_debug_errno(error
, "DNS TCP connection terminated, destroying queries: %m");
827 q
= set_first(s
->queries
);
834 /* This drops the implicit ref we keep around since it was allocated, as incoming stub connections
835 * should be kept as long as the client wants to. */
840 static void dns_stub_process_query(Manager
*m
, DnsStubListenerExtra
*l
, DnsStream
*s
, DnsPacket
*p
) {
841 _cleanup_(dns_query_freep
) DnsQuery
*q
= NULL
;
842 Hashmap
**queries_by_packet
;
848 assert(p
->protocol
== DNS_PROTOCOL_DNS
);
850 if (!l
&& /* l == NULL if this is the main stub */
851 (in_addr_is_localhost(p
->family
, &p
->sender
) <= 0 ||
852 in_addr_is_localhost(p
->family
, &p
->destination
) <= 0)) {
853 log_warning("Got packet on unexpected (i.e. non-localhost) IP range, ignoring.");
857 if (manager_packet_from_our_transaction(m
, p
)) {
858 log_debug("Got our own packet looped back, ignoring.");
862 queries_by_packet
= l
? &l
->queries_by_packet
: &m
->stub_queries_by_packet
;
863 existing
= hashmap_get(*queries_by_packet
, p
);
864 if (existing
&& dns_packet_equal(existing
->request_packet
, p
)) {
865 log_debug("Got repeat packet from client, ignoring.");
869 r
= dns_packet_extract(p
);
871 log_debug_errno(r
, "Failed to extract resources from incoming packet, ignoring packet: %m");
872 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_FORMERR
, false);
876 if (!DNS_PACKET_VERSION_SUPPORTED(p
)) {
877 log_debug("Got EDNS OPT field with unsupported version number.");
878 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_BADVERS
, false);
882 if (dns_type_is_obsolete(p
->question
->keys
[0]->type
)) {
883 log_debug("Got message with obsolete key type, refusing.");
884 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
888 if (dns_type_is_zone_transer(p
->question
->keys
[0]->type
)) {
889 log_debug("Got request for zone transfer, refusing.");
890 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
894 if (!DNS_PACKET_RD(p
)) {
895 /* If the "rd" bit is off (i.e. recursion was not requested), then refuse operation */
896 log_debug("Got request with recursion disabled, refusing.");
897 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_REFUSED
, false);
901 r
= hashmap_ensure_allocated(queries_by_packet
, &stub_packet_hash_ops
);
907 if (DNS_PACKET_DO(p
) && DNS_PACKET_CD(p
)) {
908 log_debug("Got request with DNSSEC checking disabled, enabling bypass logic.");
910 r
= dns_query_new(m
, &q
, NULL
, NULL
, p
, 0,
911 SD_RESOLVED_PROTOCOLS_ALL
|
912 SD_RESOLVED_NO_CNAME
|
913 SD_RESOLVED_NO_SEARCH
|
914 SD_RESOLVED_NO_VALIDATE
|
915 SD_RESOLVED_REQUIRE_PRIMARY
|
916 SD_RESOLVED_CLAMP_TTL
);
918 r
= dns_query_new(m
, &q
, p
->question
, p
->question
, NULL
, 0,
919 SD_RESOLVED_PROTOCOLS_ALL
|
920 SD_RESOLVED_NO_SEARCH
|
921 (DNS_PACKET_DO(p
) ? SD_RESOLVED_REQUIRE_PRIMARY
: 0)|
922 SD_RESOLVED_CLAMP_TTL
);
924 log_error_errno(r
, "Failed to generate query object: %m");
925 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
929 q
->request_packet
= dns_packet_ref(p
);
930 q
->request_stream
= dns_stream_ref(s
); /* make sure the stream stays around until we can send a reply through it */
931 q
->stub_listener_extra
= l
;
932 q
->complete
= dns_stub_query_complete
;
935 /* Remember which queries belong to this stream, so that we can cancel them when the stream
936 * is disconnected early */
938 r
= set_ensure_put(&s
->queries
, NULL
, q
);
946 /* Add the query to the hash table we use to determine repeat packets now. We don't care about
947 * failures here, since in the worst case we'll not recognize duplicate incoming requests, which
948 * isn't particularly bad. */
949 (void) hashmap_put(*queries_by_packet
, q
->request_packet
, q
);
953 log_error_errno(r
, "Failed to start query: %m");
954 dns_stub_send_failure(m
, l
, s
, p
, DNS_RCODE_SERVFAIL
, false);
958 log_debug("Processing query...");
962 static int on_dns_stub_packet_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
963 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
966 r
= manager_recv(m
, fd
, DNS_PROTOCOL_DNS
, &p
);
970 if (dns_packet_validate_query(p
) > 0) {
971 log_debug("Got DNS stub UDP query packet for id %u", DNS_PACKET_ID(p
));
973 dns_stub_process_query(m
, l
, NULL
, p
);
975 log_debug("Invalid DNS stub UDP packet, ignoring.");
980 static int on_dns_stub_packet(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
981 return on_dns_stub_packet_internal(s
, fd
, revents
, userdata
, NULL
);
984 static int on_dns_stub_packet_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
985 DnsStubListenerExtra
*l
= userdata
;
989 return on_dns_stub_packet_internal(s
, fd
, revents
, l
->manager
, l
);
992 static int on_dns_stub_stream_packet(DnsStream
*s
) {
993 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
997 p
= dns_stream_take_read_packet(s
);
1000 if (dns_packet_validate_query(p
) > 0) {
1001 log_debug("Got DNS stub TCP query packet for id %u", DNS_PACKET_ID(p
));
1003 dns_stub_process_query(s
->manager
, s
->stub_listener_extra
, s
, p
);
1005 log_debug("Invalid DNS stub TCP packet, ignoring.");
1010 static int on_dns_stub_stream_internal(sd_event_source
*s
, int fd
, uint32_t revents
, Manager
*m
, DnsStubListenerExtra
*l
) {
1014 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
1016 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
1022 r
= dns_stream_new(m
, &stream
, DNS_STREAM_STUB
, DNS_PROTOCOL_DNS
, cfd
, NULL
);
1028 stream
->stub_listener_extra
= l
;
1029 stream
->on_packet
= on_dns_stub_stream_packet
;
1030 stream
->complete
= dns_stub_stream_complete
;
1032 /* We let the reference to the stream dangle here, it will be dropped later by the complete callback. */
1037 static int on_dns_stub_stream(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1038 return on_dns_stub_stream_internal(s
, fd
, revents
, userdata
, NULL
);
1041 static int on_dns_stub_stream_extra(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1042 DnsStubListenerExtra
*l
= userdata
;
1045 return on_dns_stub_stream_internal(s
, fd
, revents
, l
->manager
, l
);
1048 static int set_dns_stub_common_socket_options(int fd
, int family
) {
1052 assert(IN_SET(family
, AF_INET
, AF_INET6
));
1054 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_REUSEADDR
, true);
1058 r
= socket_set_recvpktinfo(fd
, family
, true);
1062 r
= socket_set_recvttl(fd
, family
, true);
1069 static int set_dns_stub_common_tcp_socket_options(int fd
) {
1074 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_FASTOPEN
, 5); /* Everybody appears to pick qlen=5, let's do the same here. */
1076 log_debug_errno(r
, "Failed to enable TCP_FASTOPEN on TCP listening socket, ignoring: %m");
1078 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_NODELAY
, true);
1080 log_debug_errno(r
, "Failed to enable TCP_NODELAY mode, ignoring: %m");
1085 static int manager_dns_stub_fd(Manager
*m
, int type
) {
1086 union sockaddr_union sa
= {
1087 .in
.sin_family
= AF_INET
,
1088 .in
.sin_addr
.s_addr
= htobe32(INADDR_DNS_STUB
),
1089 .in
.sin_port
= htobe16(53),
1091 _cleanup_close_
int fd
= -1;
1094 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1096 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &m
->dns_stub_udp_event_source
: &m
->dns_stub_tcp_event_source
;
1098 return sd_event_source_get_io_fd(*event_source
);
1100 fd
= socket(AF_INET
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1104 r
= set_dns_stub_common_socket_options(fd
, AF_INET
);
1108 if (type
== SOCK_STREAM
) {
1109 r
= set_dns_stub_common_tcp_socket_options(fd
);
1114 /* Make sure no traffic from outside the local host can leak to onto this socket */
1115 r
= socket_bind_to_ifindex(fd
, LOOPBACK_IFINDEX
);
1119 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TTL
, 1);
1123 if (bind(fd
, &sa
.sa
, sizeof(sa
.in
)) < 0)
1126 if (type
== SOCK_STREAM
&&
1127 listen(fd
, SOMAXCONN
) < 0)
1130 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1131 type
== SOCK_DGRAM
? on_dns_stub_packet
: on_dns_stub_stream
,
1136 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1140 (void) sd_event_source_set_description(*event_source
,
1141 type
== SOCK_DGRAM
? "dns-stub-udp" : "dns-stub-tcp");
1146 static int manager_dns_stub_fd_extra(Manager
*m
, DnsStubListenerExtra
*l
, int type
) {
1147 _cleanup_free_
char *pretty
= NULL
;
1148 _cleanup_close_
int fd
= -1;
1149 union sockaddr_union sa
;
1153 assert(IN_SET(type
, SOCK_DGRAM
, SOCK_STREAM
));
1156 return manager_dns_stub_fd(m
, type
);
1158 sd_event_source
**event_source
= type
== SOCK_DGRAM
? &l
->udp_event_source
: &l
->tcp_event_source
;
1160 return sd_event_source_get_io_fd(*event_source
);
1162 if (l
->family
== AF_INET
)
1163 sa
= (union sockaddr_union
) {
1164 .in
.sin_family
= l
->family
,
1165 .in
.sin_port
= htobe16(dns_stub_listener_extra_port(l
)),
1166 .in
.sin_addr
= l
->address
.in
,
1169 sa
= (union sockaddr_union
) {
1170 .in6
.sin6_family
= l
->family
,
1171 .in6
.sin6_port
= htobe16(dns_stub_listener_extra_port(l
)),
1172 .in6
.sin6_addr
= l
->address
.in6
,
1175 fd
= socket(l
->family
, type
| SOCK_CLOEXEC
| SOCK_NONBLOCK
, 0);
1181 r
= set_dns_stub_common_socket_options(fd
, l
->family
);
1185 if (type
== SOCK_STREAM
) {
1186 r
= set_dns_stub_common_tcp_socket_options(fd
);
1191 /* Do not set IP_TTL for extra DNS stub listeners, as the address may not be local and in that case
1192 * people may want ttl > 1. */
1194 r
= socket_set_freebind(fd
, l
->family
, true);
1198 if (type
== SOCK_DGRAM
) {
1199 r
= socket_disable_pmtud(fd
, l
->family
);
1201 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
1203 r
= socket_set_recvfragsize(fd
, l
->family
, true);
1205 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
1208 if (bind(fd
, &sa
.sa
, SOCKADDR_LEN(sa
)) < 0) {
1213 if (type
== SOCK_STREAM
&&
1214 listen(fd
, SOMAXCONN
) < 0) {
1219 r
= sd_event_add_io(m
->event
, event_source
, fd
, EPOLLIN
,
1220 type
== SOCK_DGRAM
? on_dns_stub_packet_extra
: on_dns_stub_stream_extra
,
1225 r
= sd_event_source_set_io_fd_own(*event_source
, true);
1229 (void) sd_event_source_set_description(*event_source
,
1230 type
== SOCK_DGRAM
? "dns-stub-udp-extra" : "dns-stub-tcp-extra");
1232 if (DEBUG_LOGGING
) {
1233 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1234 log_debug("Listening on %s socket %s.",
1235 type
== SOCK_DGRAM
? "UDP" : "TCP",
1243 (void) in_addr_port_to_string(l
->family
, &l
->address
, l
->port
, &pretty
);
1244 return log_warning_errno(r
,
1245 r
== -EADDRINUSE
? "Another process is already listening on %s socket %s: %m" :
1246 "Failed to listen on %s socket %s: %m",
1247 type
== SOCK_DGRAM
? "UDP" : "TCP",
1251 int manager_dns_stub_start(Manager
*m
) {
1252 const char *t
= "UDP";
1257 if (m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_NO
)
1258 log_debug("Not creating stub listener.");
1260 log_debug("Creating stub listener using %s.",
1261 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_UDP
? "UDP" :
1262 m
->dns_stub_listener_mode
== DNS_STUB_LISTENER_TCP
? "TCP" :
1265 if (FLAGS_SET(m
->dns_stub_listener_mode
, DNS_STUB_LISTENER_UDP
))
1266 r
= manager_dns_stub_fd(m
, SOCK_DGRAM
);
1269 FLAGS_SET(m
->dns_stub_listener_mode
, DNS_STUB_LISTENER_TCP
)) {
1271 r
= manager_dns_stub_fd(m
, SOCK_STREAM
);
1274 if (IN_SET(r
, -EADDRINUSE
, -EPERM
)) {
1275 log_warning_errno(r
,
1276 r
== -EADDRINUSE
? "Another process is already listening on %s socket 127.0.0.53:53.\n"
1277 "Turning off local DNS stub support." :
1278 "Failed to listen on %s socket 127.0.0.53:53: %m.\n"
1279 "Turning off local DNS stub support.",
1281 manager_dns_stub_stop(m
);
1283 return log_error_errno(r
, "Failed to listen on %s socket 127.0.0.53:53: %m", t
);
1285 if (!ordered_set_isempty(m
->dns_extra_stub_listeners
)) {
1286 DnsStubListenerExtra
*l
;
1288 log_debug("Creating extra stub listeners.");
1290 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
) {
1291 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_UDP
))
1292 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_DGRAM
);
1293 if (FLAGS_SET(l
->mode
, DNS_STUB_LISTENER_TCP
))
1294 (void) manager_dns_stub_fd_extra(m
, l
, SOCK_STREAM
);
1301 void manager_dns_stub_stop(Manager
*m
) {
1304 m
->dns_stub_udp_event_source
= sd_event_source_disable_unref(m
->dns_stub_udp_event_source
);
1305 m
->dns_stub_tcp_event_source
= sd_event_source_disable_unref(m
->dns_stub_tcp_event_source
);
1308 static const char* const dns_stub_listener_mode_table
[_DNS_STUB_LISTENER_MODE_MAX
] = {
1309 [DNS_STUB_LISTENER_NO
] = "no",
1310 [DNS_STUB_LISTENER_UDP
] = "udp",
1311 [DNS_STUB_LISTENER_TCP
] = "tcp",
1312 [DNS_STUB_LISTENER_YES
] = "yes",
1314 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(dns_stub_listener_mode
, DnsStubListenerMode
, DNS_STUB_LISTENER_YES
);