1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "resolv"
18
19 #include "ResolverController.h"
20
21 #include <set>
22 #include <string>
23 #include <vector>
24
25 #include <aidl/android/net/IDnsResolver.h>
26 #include <android-base/logging.h>
27 #include <android-base/strings.h>
28 #include <statslog_resolv.h>
29
30 #include "Dns64Configuration.h"
31 #include "DnsResolver.h"
32 #include "DnsTlsDispatcher.h"
33 #include "PrivateDnsConfiguration.h"
34 #include "ResolverEventReporter.h"
35 #include "ResolverStats.h"
36 #include "resolv_cache.h"
37 #include "stats.h"
38 #include "util.h"
39
40 using aidl::android::net::IDnsResolver;
41 using aidl::android::net::ResolverParamsParcel;
42 using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
43 using aidl::android::net::resolv::aidl::Nat64PrefixEventParcel;
44 using android::base::Join;
45 using android::net::ResolverStats;
46
47 namespace android {
48
49 using netdutils::DumpWriter;
50
51 namespace net {
52
53 namespace {
54
sendNat64PrefixEvent(const Dns64Configuration::Nat64PrefixInfo & args)55 void sendNat64PrefixEvent(const Dns64Configuration::Nat64PrefixInfo& args) {
56 LOG(DEBUG) << "Sending Nat64Prefix " << (args.added ? "added" : "removed") << " event on netId "
57 << args.netId << " with prefix " << args.prefixString << "/"
58 << (int)(args.prefixLength);
59 // Send a nat64 prefix event to NetdEventListenerService.
60 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
61 if (listeners.empty()) {
62 LOG(ERROR) << __func__ << ": No available listener. Skipping NAT64 prefix event";
63 }
64 for (const auto& it : listeners) {
65 it->onNat64PrefixEvent(args.netId, args.added, args.prefixString, args.prefixLength);
66 }
67
68 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
69 const Nat64PrefixEventParcel nat64PrefixEvent = {
70 .netId = static_cast<int32_t>(args.netId),
71 .prefixOperation =
72 args.added ? IDnsResolverUnsolicitedEventListener::PREFIX_OPERATION_ADDED
73 : IDnsResolverUnsolicitedEventListener::PREFIX_OPERATION_REMOVED,
74 .prefixAddress = args.prefixString,
75 .prefixLength = args.prefixLength,
76 };
77 for (const auto& it : unsolEventListeners) {
78 it->onNat64PrefixEvent(nat64PrefixEvent);
79 }
80 }
81
getDnsInfo(unsigned netId,std::vector<std::string> * servers,std::vector<std::string> * domains,res_params * params,std::vector<android::net::ResolverStats> * stats,std::vector<std::string> * interfaceNames,int * wait_for_pending_req_timeout_count)82 int getDnsInfo(unsigned netId, std::vector<std::string>* servers, std::vector<std::string>* domains,
83 res_params* params, std::vector<android::net::ResolverStats>* stats,
84 std::vector<std::string>* interfaceNames, int* wait_for_pending_req_timeout_count) {
85 static_assert(ResolverStats::STATS_SUCCESSES == IDnsResolver::RESOLVER_STATS_SUCCESSES &&
86 ResolverStats::STATS_ERRORS == IDnsResolver::RESOLVER_STATS_ERRORS &&
87 ResolverStats::STATS_TIMEOUTS == IDnsResolver::RESOLVER_STATS_TIMEOUTS &&
88 ResolverStats::STATS_INTERNAL_ERRORS ==
89 IDnsResolver::RESOLVER_STATS_INTERNAL_ERRORS &&
90 ResolverStats::STATS_RTT_AVG == IDnsResolver::RESOLVER_STATS_RTT_AVG &&
91 ResolverStats::STATS_LAST_SAMPLE_TIME ==
92 IDnsResolver::RESOLVER_STATS_LAST_SAMPLE_TIME &&
93 ResolverStats::STATS_USABLE == IDnsResolver::RESOLVER_STATS_USABLE &&
94 ResolverStats::STATS_COUNT == IDnsResolver::RESOLVER_STATS_COUNT,
95 "AIDL and ResolverStats.h out of sync");
96 int nscount = -1;
97 sockaddr_storage res_servers[MAXNS];
98 int dcount = -1;
99 char res_domains[MAXDNSRCH][MAXDNSRCHPATH];
100 res_stats res_stats[MAXNS];
101 servers->clear();
102 domains->clear();
103 interfaceNames->clear();
104 *params = res_params{};
105 stats->clear();
106 int revision_id = android_net_res_stats_get_info_for_net(netId, &nscount, res_servers, &dcount,
107 res_domains, params, res_stats,
108 wait_for_pending_req_timeout_count);
109
110 // If the netId is unknown (which can happen for valid net IDs for which no DNS servers have
111 // yet been configured), there is no revision ID. In this case there is no data to return.
112 if (revision_id < 0) {
113 return 0;
114 }
115
116 // Verify that the returned data is valid.
117 if (nscount < 0 || nscount > MAXNS || dcount < 0 || dcount > MAXDNSRCH) {
118 LOG(ERROR) << __func__ << ": nscount = " << nscount << ", dcount = " << dcount;
119 return -ENOTRECOVERABLE;
120 }
121
122 // Determine which servers are considered usable by the resolver.
123 bool valid_servers[MAXNS];
124 std::fill_n(valid_servers, MAXNS, false);
125 android_net_res_stats_get_usable_servers(params, res_stats, nscount, valid_servers);
126
127 // Convert the server sockaddr structures to std::string.
128 stats->resize(nscount);
129 for (int i = 0; i < nscount; ++i) {
130 char hbuf[NI_MAXHOST];
131 int rv =
132 getnameinfo(reinterpret_cast<const sockaddr*>(&res_servers[i]),
133 sizeof(res_servers[i]), hbuf, sizeof(hbuf), nullptr, 0, NI_NUMERICHOST);
134 std::string server_str;
135 if (rv == 0) {
136 server_str.assign(hbuf);
137 } else {
138 LOG(ERROR) << "getnameinfo() failed for server #" << i << ": " << gai_strerror(rv);
139 server_str.assign("<invalid>");
140 }
141 servers->push_back(std::move(server_str));
142 android::net::ResolverStats& cur_stats = (*stats)[i];
143 android_net_res_stats_aggregate(&res_stats[i], &cur_stats.successes, &cur_stats.errors,
144 &cur_stats.timeouts, &cur_stats.internal_errors,
145 &cur_stats.rtt_avg, &cur_stats.last_sample_time);
146 cur_stats.usable = valid_servers[i];
147 }
148
149 // Convert the stack-allocated search domain strings to std::string.
150 for (int i = 0; i < dcount; ++i) {
151 domains->push_back(res_domains[i]);
152 }
153
154 *interfaceNames = resolv_get_interface_names(netId);
155
156 return 0;
157 }
158
159 } // namespace
160
ResolverController()161 ResolverController::ResolverController()
162 : mDns64Configuration(make_shared<Dns64Configuration>(
163 [](uint32_t netId, uint32_t uid, android_net_context* netcontext) {
164 gResNetdCallbacks.get_network_context(netId, uid, netcontext);
165 },
166 std::bind(sendNat64PrefixEvent, std::placeholders::_1))) {}
167
destroyNetworkCache(unsigned netId)168 void ResolverController::destroyNetworkCache(unsigned netId) {
169 LOG(VERBOSE) << __func__ << ": netId = " << netId;
170
171 // Report NetworkDnsServerSupportReported metrics before the cleanup.
172 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
173 NetworkDnsServerSupportReported event = privateDnsConfiguration.getStatusForMetrics(netId);
174 const std::string str = event.servers().SerializeAsString();
175 stats::BytesField bytesField{str.c_str(), str.size()};
176 android::net::stats::stats_write(android::net::stats::NETWORK_DNS_SERVER_SUPPORT_REPORTED,
177 event.network_type(), event.private_dns_modes(), bytesField);
178
179 resolv_delete_cache_for_net(netId);
180 mDns64Configuration->stopPrefixDiscovery(netId);
181 privateDnsConfiguration.clear(netId);
182
183 // Don't get this instance in PrivateDnsConfiguration. It's probe to deadlock.
184 DnsTlsDispatcher::getInstance().forceCleanup(netId);
185 }
186
createNetworkCache(unsigned netId)187 int ResolverController::createNetworkCache(unsigned netId) {
188 LOG(VERBOSE) << __func__ << ": netId = " << netId;
189
190 return resolv_create_cache_for_net(netId);
191 }
192
flushNetworkCache(unsigned netId)193 int ResolverController::flushNetworkCache(unsigned netId) {
194 LOG(VERBOSE) << __func__ << ": netId = " << netId;
195 return resolv_flush_cache_for_net(netId);
196 }
197
setResolverConfiguration(const ResolverParamsParcel & resolverParams)198 int ResolverController::setResolverConfiguration(const ResolverParamsParcel& resolverParams) {
199 if (!has_named_cache(resolverParams.netId)) {
200 return -ENOENT;
201 }
202
203 // Expect to get the mark with system permission.
204 android_net_context netcontext;
205 gResNetdCallbacks.get_network_context(resolverParams.netId, 0 /* uid */, &netcontext);
206
207 // Allow at most MAXNS private DNS servers in a network to prevent too many broken servers.
208 std::vector<std::string> tlsServers = resolverParams.tlsServers;
209 if (tlsServers.size() > MAXNS) {
210 tlsServers.resize(MAXNS);
211 }
212
213 // Use app_mark for DoT connection. Using dns_mark might result in reaching the DoT servers
214 // through a different network. For example, on a VPN with no DNS servers (Do53), if the VPN
215 // applies to UID 0, dns_mark is assigned for default network rathan the VPN. (note that it's
216 // possible that a VPN doesn't have any DNS servers but DoT servers in DNS strict mode)
217 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
218 int err = privateDnsConfiguration.set(resolverParams.netId, netcontext.app_mark,
219 resolverParams.servers, tlsServers,
220 resolverParams.tlsName, resolverParams.caCertificate);
221
222 if (err != 0) {
223 return err;
224 }
225
226 if (is_mdns_supported_transport_types(resolverParams.transportTypes)) {
227 if (err = resolv_stats_set_addrs(resolverParams.netId, PROTO_MDNS,
228 {"ff02::fb", "224.0.0.251"}, 5353);
229 err != 0) {
230 return err;
231 }
232 }
233
234 return resolv_set_nameservers(resolverParams);
235 }
236
getResolverInfo(int32_t netId,std::vector<std::string> * servers,std::vector<std::string> * domains,std::vector<std::string> * tlsServers,std::vector<std::string> * interfaceNames,std::vector<int32_t> * params,std::vector<int32_t> * stats,int * wait_for_pending_req_timeout_count)237 int ResolverController::getResolverInfo(int32_t netId, std::vector<std::string>* servers,
238 std::vector<std::string>* domains,
239 std::vector<std::string>* tlsServers,
240 std::vector<std::string>* interfaceNames,
241 std::vector<int32_t>* params, std::vector<int32_t>* stats,
242 int* wait_for_pending_req_timeout_count) {
243 res_params res_params;
244 std::vector<ResolverStats> res_stats;
245 int ret = getDnsInfo(netId, servers, domains, &res_params, &res_stats, interfaceNames,
246 wait_for_pending_req_timeout_count);
247 if (ret != 0) {
248 return ret;
249 }
250
251 // Serialize the information for binder.
252 ResolverStats::encodeAll(res_stats, stats);
253
254 const auto privateDnsStatus = PrivateDnsConfiguration::getInstance().getStatus(netId);
255 for (const auto& [server, _] : privateDnsStatus.dotServersMap) {
256 tlsServers->push_back(server.toIpString());
257 }
258
259 params->resize(IDnsResolver::RESOLVER_PARAMS_COUNT);
260 (*params)[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY] = res_params.sample_validity;
261 (*params)[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD] = res_params.success_threshold;
262 (*params)[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES] = res_params.min_samples;
263 (*params)[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES] = res_params.max_samples;
264 (*params)[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC] = res_params.base_timeout_msec;
265 (*params)[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT] = res_params.retry_count;
266 return 0;
267 }
268
startPrefix64Discovery(int32_t netId)269 void ResolverController::startPrefix64Discovery(int32_t netId) {
270 mDns64Configuration->startPrefixDiscovery(netId);
271 }
272
stopPrefix64Discovery(int32_t netId)273 void ResolverController::stopPrefix64Discovery(int32_t netId) {
274 return mDns64Configuration->stopPrefixDiscovery(netId);
275 }
276
277 // TODO: use StatusOr<T> to wrap the result.
getPrefix64(unsigned netId,netdutils::IPPrefix * prefix)278 int ResolverController::getPrefix64(unsigned netId, netdutils::IPPrefix* prefix) {
279 netdutils::IPPrefix p = mDns64Configuration->getPrefix64(netId);
280 if (p.family() != AF_INET6 || p.length() == 0) {
281 return -ENOENT;
282 }
283 *prefix = p;
284 return 0;
285 }
286
dump(DumpWriter & dw,unsigned netId)287 void ResolverController::dump(DumpWriter& dw, unsigned netId) {
288 // No lock needed since Bionic's resolver locks all accessed data structures internally.
289 std::vector<std::string> servers;
290 std::vector<std::string> domains;
291 std::vector<std::string> interfaceNames;
292 res_params params = {};
293 std::vector<ResolverStats> stats;
294 int wait_for_pending_req_timeout_count = 0;
295 time_t now = time(nullptr);
296 int rv = getDnsInfo(netId, &servers, &domains, ¶ms, &stats, &interfaceNames,
297 &wait_for_pending_req_timeout_count);
298 dw.incIndent();
299 if (rv != 0) {
300 dw.println("getDnsInfo() failed for netid %u", netId);
301 } else {
302 if (servers.empty()) {
303 dw.println("No DNS servers defined");
304 } else {
305 dw.println("DnsEvent subsampling map: " +
306 Join(resolv_cache_dump_subsampling_map(netId, false), ' '));
307 dw.println("DnsEvent subsampling map for MDNS: " +
308 Join(resolv_cache_dump_subsampling_map(netId, true), ' '));
309 dw.println(
310 "DNS servers: # IP (total, successes, errors, timeouts, internal errors, "
311 "RTT avg, last sample)");
312 dw.incIndent();
313 for (size_t i = 0; i < servers.size(); ++i) {
314 if (i < stats.size()) {
315 const ResolverStats& s = stats[i];
316 int total = s.successes + s.errors + s.timeouts + s.internal_errors;
317 if (total > 0) {
318 int time_delta = (s.last_sample_time > 0) ? now - s.last_sample_time : -1;
319 dw.println("%s (%d, %d, %d, %d, %d, %dms, %ds)%s", servers[i].c_str(),
320 total, s.successes, s.errors, s.timeouts, s.internal_errors,
321 s.rtt_avg, time_delta, s.usable ? "" : " BROKEN");
322 } else {
323 dw.println("%s <no data>", servers[i].c_str());
324 }
325 } else {
326 dw.println("%s <no stats>", servers[i].c_str());
327 }
328 }
329 dw.decIndent();
330 }
331 std::string ifacenames_str = Join(interfaceNames, ", ");
332 dw.println("Interface names: [%s]", ifacenames_str.c_str());
333 if (domains.empty()) {
334 dw.println("No search domains defined");
335 } else {
336 std::string domains_str = Join(domains, ", ");
337 dw.println("search domains: %s", domains_str.c_str());
338 }
339 if (params.sample_validity != 0) {
340 dw.println(
341 "DNS parameters: sample validity = %us, success threshold = %u%%, "
342 "samples (min, max) = (%u, %u), base_timeout = %dmsec, retry count = "
343 "%dtimes",
344 params.sample_validity, params.success_threshold, params.min_samples,
345 params.max_samples, params.base_timeout_msec, params.retry_count);
346 }
347
348 mDns64Configuration->dump(dw, netId);
349 const auto privateDnsStatus = PrivateDnsConfiguration::getInstance().getStatus(netId);
350 dw.println("Private DNS mode: %s", getPrivateDnsModeString(privateDnsStatus.mode));
351 if (privateDnsStatus.dotServersMap.size() == 0) {
352 dw.println("No Private DNS servers configured");
353 } else {
354 dw.println("Private DNS configuration (%u entries)",
355 static_cast<uint32_t>(privateDnsStatus.dotServersMap.size()));
356 dw.incIndent();
357 for (const auto& [server, validation] : privateDnsStatus.dotServersMap) {
358 dw.println("%s name{%s} status{%s}", server.toIpString().c_str(),
359 server.name.c_str(), validationStatusToString(validation));
360 }
361 dw.decIndent();
362 }
363 dw.println("Concurrent DNS query timeout: %d", wait_for_pending_req_timeout_count);
364 resolv_netconfig_dump(dw, netId);
365 }
366 dw.decIndent();
367 }
368
369 } // namespace net
370 } // namespace android
371