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