1 /*
2  * Copyright (C) 2018 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 "PrivateDnsConfiguration.h"
20 
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23 #include <netdb.h>
24 #include <netdutils/ThreadUtil.h>
25 #include <sys/socket.h>
26 
27 #include "DnsTlsTransport.h"
28 #include "ResolverEventReporter.h"
29 #include "netd_resolv/resolv.h"
30 #include "netdutils/BackoffSequence.h"
31 #include "resolv_cache.h"
32 #include "util.h"
33 
34 using android::base::StringPrintf;
35 using android::netdutils::setThreadName;
36 using std::chrono::milliseconds;
37 
38 namespace android {
39 namespace net {
40 
41 namespace {
42 
getExperimentTimeout(const std::string & flagName,const milliseconds defaultValue)43 milliseconds getExperimentTimeout(const std::string& flagName, const milliseconds defaultValue) {
44     int val = getExperimentFlagInt(flagName, defaultValue.count());
45     return milliseconds((val < 1000) ? 1000 : val);
46 }
47 
48 }  // namespace
49 
addrToString(const sockaddr_storage * addr)50 std::string addrToString(const sockaddr_storage* addr) {
51     char out[INET6_ADDRSTRLEN] = {0};
52     getnameinfo((const sockaddr*) addr, sizeof(sockaddr_storage), out, INET6_ADDRSTRLEN, nullptr, 0,
53                 NI_NUMERICHOST);
54     return std::string(out);
55 }
56 
parseServer(const char * server,sockaddr_storage * parsed)57 bool parseServer(const char* server, sockaddr_storage* parsed) {
58     addrinfo hints = {
59             .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
60             .ai_family = AF_UNSPEC,
61     };
62     addrinfo* res;
63 
64     int err = getaddrinfo(server, "853", &hints, &res);
65     if (err != 0) {
66         LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
67         return false;
68     }
69 
70     memcpy(parsed, res->ai_addr, res->ai_addrlen);
71     freeaddrinfo(res);
72     return true;
73 }
74 
set(int32_t netId,uint32_t mark,const std::vector<std::string> & servers,const std::string & name,const std::string & caCert)75 int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
76                                  const std::vector<std::string>& servers, const std::string& name,
77                                  const std::string& caCert) {
78     LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
79                << ", " << servers.size() << ", " << name << ")";
80 
81     // Parse the list of servers that has been passed in
82     std::set<DnsTlsServer> tlsServers;
83     for (const auto& s : servers) {
84         sockaddr_storage parsed;
85         if (!parseServer(s.c_str(), &parsed)) {
86             return -EINVAL;
87         }
88         DnsTlsServer server(parsed);
89         server.name = name;
90         server.certificate = caCert;
91         server.connectTimeout =
92                 getExperimentTimeout("dot_connect_timeout_ms", DnsTlsServer::kDotConnectTimeoutMs);
93         tlsServers.insert(server);
94         LOG(DEBUG) << "Set DoT connect timeout " << server.connectTimeout.count() << "ms for " << s;
95     }
96 
97     std::lock_guard guard(mPrivateDnsLock);
98     if (!name.empty()) {
99         mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
100     } else if (!tlsServers.empty()) {
101         mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
102     } else {
103         mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
104         mPrivateDnsTransports.erase(netId);
105         resolv_stats_set_servers_for_dot(netId, {});
106         mPrivateDnsValidateThreads.erase(netId);
107         // TODO: As mPrivateDnsValidateThreads is reset, validation threads which haven't yet
108         // finished are considered outdated. Consider signaling the outdated validation threads to
109         // stop them from updating the state of PrivateDnsConfiguration (possibly disallow them to
110         // report onPrivateDnsValidationEvent).
111         return 0;
112     }
113 
114     // Create the tracker if it was not present
115     auto netPair = mPrivateDnsTransports.find(netId);
116     if (netPair == mPrivateDnsTransports.end()) {
117         // No TLS tracker yet for this netId.
118         bool added;
119         std::tie(netPair, added) = mPrivateDnsTransports.emplace(netId, PrivateDnsTracker());
120         if (!added) {
121             LOG(ERROR) << "Memory error while recording private DNS for netId " << netId;
122             return -ENOMEM;
123         }
124     }
125     auto& tracker = netPair->second;
126 
127     // Remove any servers from the tracker that are not in |servers| exactly.
128     for (auto it = tracker.begin(); it != tracker.end();) {
129         if (tlsServers.count(it->first) == 0) {
130             it = tracker.erase(it);
131         } else {
132             ++it;
133         }
134     }
135 
136     // Add any new or changed servers to the tracker, and initiate async checks for them.
137     for (const auto& server : tlsServers) {
138         if (needsValidation(tracker, server)) {
139             validatePrivateDnsProvider(server, tracker, netId, mark);
140         }
141     }
142 
143     return resolv_stats_set_servers_for_dot(netId, servers);
144 }
145 
getStatus(unsigned netId)146 PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) {
147     PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
148     std::lock_guard guard(mPrivateDnsLock);
149 
150     const auto mode = mPrivateDnsModes.find(netId);
151     if (mode == mPrivateDnsModes.end()) return status;
152     status.mode = mode->second;
153 
154     const auto netPair = mPrivateDnsTransports.find(netId);
155     if (netPair != mPrivateDnsTransports.end()) {
156         for (const auto& serverPair : netPair->second) {
157             status.serversMap.emplace(serverPair.first, serverPair.second);
158         }
159     }
160 
161     return status;
162 }
163 
clear(unsigned netId)164 void PrivateDnsConfiguration::clear(unsigned netId) {
165     LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
166     std::lock_guard guard(mPrivateDnsLock);
167     mPrivateDnsModes.erase(netId);
168     mPrivateDnsTransports.erase(netId);
169     mPrivateDnsValidateThreads.erase(netId);
170 }
171 
validatePrivateDnsProvider(const DnsTlsServer & server,PrivateDnsTracker & tracker,unsigned netId,uint32_t mark)172 void PrivateDnsConfiguration::validatePrivateDnsProvider(const DnsTlsServer& server,
173                                                          PrivateDnsTracker& tracker, unsigned netId,
174                                                          uint32_t mark) REQUIRES(mPrivateDnsLock) {
175     tracker[server] = Validation::in_process;
176     LOG(DEBUG) << "Server " << addrToString(&server.ss) << " marked as in_process on netId "
177                << netId << ". Tracker now has size " << tracker.size();
178     // This judge must be after "tracker[server] = Validation::in_process;"
179     if (!needValidateThread(server, netId)) {
180         return;
181     }
182 
183     // Note that capturing |server| and |netId| in this lambda create copies.
184     std::thread validate_thread([this, server, netId, mark] {
185         setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
186 
187         // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
188         //
189         // Start with a 1 minute delay and backoff to once per hour.
190         //
191         // Assumptions:
192         //     [1] Each TLS validation is ~10KB of certs+handshake+payload.
193         //     [2] Network typically provision clients with <=4 nameservers.
194         //     [3] Average month has 30 days.
195         //
196         // Each validation pass in a given hour is ~1.2MB of data. And 24
197         // such validation passes per day is about ~30MB per month, in the
198         // worst case. Otherwise, this will cost ~600 SYNs per month
199         // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
200         auto backoff = netdutils::BackoffSequence<>::Builder()
201                                .withInitialRetransmissionTime(std::chrono::seconds(60))
202                                .withMaximumRetransmissionTime(std::chrono::seconds(3600))
203                                .build();
204 
205         while (true) {
206             // ::validate() is a blocking call that performs network operations.
207             // It can take milliseconds to minutes, up to the SYN retry limit.
208             LOG(WARNING) << "Validating DnsTlsServer on netId " << netId;
209             const bool success = DnsTlsTransport::validate(server, netId, mark);
210             LOG(DEBUG) << "validateDnsTlsServer returned " << success << " for "
211                        << addrToString(&server.ss);
212 
213             const bool needs_reeval = this->recordPrivateDnsValidation(server, netId, success);
214             if (!needs_reeval) {
215                 break;
216             }
217 
218             if (backoff.hasNextTimeout()) {
219                 std::this_thread::sleep_for(backoff.getNextTimeout());
220             } else {
221                 break;
222             }
223         }
224         this->cleanValidateThreadTracker(server, netId);
225     });
226     validate_thread.detach();
227 }
228 
recordPrivateDnsValidation(const DnsTlsServer & server,unsigned netId,bool success)229 bool PrivateDnsConfiguration::recordPrivateDnsValidation(const DnsTlsServer& server, unsigned netId,
230                                                          bool success) {
231     constexpr bool NEEDS_REEVALUATION = true;
232     constexpr bool DONT_REEVALUATE = false;
233 
234     std::lock_guard guard(mPrivateDnsLock);
235 
236     auto netPair = mPrivateDnsTransports.find(netId);
237     if (netPair == mPrivateDnsTransports.end()) {
238         LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
239         return DONT_REEVALUATE;
240     }
241 
242     const auto mode = mPrivateDnsModes.find(netId);
243     if (mode == mPrivateDnsModes.end()) {
244         LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
245         return DONT_REEVALUATE;
246     }
247     const bool modeDoesReevaluation = (mode->second == PrivateDnsMode::STRICT);
248 
249     bool reevaluationStatus =
250             (success || !modeDoesReevaluation) ? DONT_REEVALUATE : NEEDS_REEVALUATION;
251 
252     auto& tracker = netPair->second;
253     auto serverPair = tracker.find(server);
254     if (serverPair == tracker.end()) {
255         // TODO: Consider not adding this server to the tracker since this server is not expected
256         // to be one of the private DNS servers for this network now. This could prevent this
257         // server from being included when dumping status.
258         LOG(WARNING) << "Server " << addrToString(&server.ss)
259                      << " was removed during private DNS validation";
260         success = false;
261         reevaluationStatus = DONT_REEVALUATE;
262     } else if (!(serverPair->first == server)) {
263         // TODO: It doesn't seem correct to overwrite the tracker entry for
264         // |server| down below in this circumstance... Fix this.
265         LOG(WARNING) << "Server " << addrToString(&server.ss)
266                      << " was changed during private DNS validation";
267         success = false;
268         reevaluationStatus = DONT_REEVALUATE;
269     }
270 
271     // Send a validation event to NetdEventListenerService.
272     const auto& listeners = ResolverEventReporter::getInstance().getListeners();
273     if (listeners.size() != 0) {
274         for (const auto& it : listeners) {
275             it->onPrivateDnsValidationEvent(netId, addrToString(&server.ss), server.name, success);
276         }
277         LOG(DEBUG) << "Sent validation " << (success ? "success" : "failure") << " event on netId "
278                    << netId << " for " << addrToString(&server.ss) << " with hostname {"
279                    << server.name << "}";
280     } else {
281         LOG(ERROR)
282                 << "Validation event not sent since no INetdEventListener receiver is available.";
283     }
284 
285     if (success) {
286         tracker[server] = Validation::success;
287     } else {
288         // Validation failure is expected if a user is on a captive portal.
289         // TODO: Trigger a second validation attempt after captive portal login
290         // succeeds.
291         tracker[server] = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
292                                                                      : Validation::fail;
293     }
294     LOG(WARNING) << "Validation " << (success ? "success" : "failed");
295 
296     return reevaluationStatus;
297 }
298 
needValidateThread(const DnsTlsServer & server,unsigned netId)299 bool PrivateDnsConfiguration::needValidateThread(const DnsTlsServer& server, unsigned netId)
300         REQUIRES(mPrivateDnsLock) {
301     // Create the thread tracker if it was not present
302     auto threadPair = mPrivateDnsValidateThreads.find(netId);
303     if (threadPair == mPrivateDnsValidateThreads.end()) {
304         // No thread tracker yet for this netId.
305         bool added;
306         std::tie(threadPair, added) = mPrivateDnsValidateThreads.emplace(netId, ThreadTracker());
307         if (!added) {
308             LOG(ERROR) << "Memory error while needValidateThread for netId " << netId;
309             return true;
310         }
311     }
312     auto& threadTracker = threadPair->second;
313     if (threadTracker.count(server)) {
314         LOG(DEBUG) << "Server " << addrToString(&(server.ss))
315                    << " validate thread is already running. Thread tracker now has size "
316                    << threadTracker.size();
317         return false;
318     } else {
319         threadTracker.insert(server);
320         LOG(DEBUG) << "Server " << addrToString(&(server.ss))
321                    << " validate thread is not running. Thread tracker now has size "
322                    << threadTracker.size();
323         return true;
324     }
325 }
326 
cleanValidateThreadTracker(const DnsTlsServer & server,unsigned netId)327 void PrivateDnsConfiguration::cleanValidateThreadTracker(const DnsTlsServer& server,
328                                                          unsigned netId) {
329     std::lock_guard<std::mutex> guard(mPrivateDnsLock);
330     LOG(DEBUG) << "cleanValidateThreadTracker Server " << addrToString(&(server.ss))
331                << " validate thread is stopped.";
332 
333     auto threadPair = mPrivateDnsValidateThreads.find(netId);
334     if (threadPair != mPrivateDnsValidateThreads.end()) {
335         auto& threadTracker = threadPair->second;
336         threadTracker.erase(server);
337         LOG(DEBUG) << "Server " << addrToString(&(server.ss))
338                    << " validate thread is stopped. Thread tracker now has size "
339                    << threadTracker.size();
340     }
341 }
342 
343 // Start validation for newly added servers as well as any servers that have
344 // landed in Validation::fail state. Note that servers that have failed
345 // multiple validation attempts but for which there is still a validating
346 // thread running are marked as being Validation::in_process.
needsValidation(const PrivateDnsTracker & tracker,const DnsTlsServer & server)347 bool PrivateDnsConfiguration::needsValidation(const PrivateDnsTracker& tracker,
348                                               const DnsTlsServer& server) {
349     const auto& iter = tracker.find(server);
350     return (iter == tracker.end()) || (iter->second == Validation::fail);
351 }
352 
353 PrivateDnsConfiguration gPrivateDnsConfiguration;
354 
355 }  // namespace net
356 }  // namespace android
357