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