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 <algorithm>
22 
23 #include <android-base/format.h>
24 #include <android-base/logging.h>
25 #include <android/binder_ibinder.h>
26 #include <netdutils/Slice.h>
27 #include <netdutils/ThreadUtil.h>
28 #include <sys/socket.h>
29 
30 #include "DnsTlsTransport.h"
31 #include "ResolverEventReporter.h"
32 #include "doh.h"
33 #include "netd_resolv/resolv.h"
34 #include "resolv_cache.h"
35 #include "resolv_private.h"
36 #include "util.h"
37 
38 using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
39 using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
40 using android::netdutils::IPAddress;
41 using android::netdutils::IPSockAddr;
42 using android::netdutils::setThreadName;
43 using android::netdutils::Slice;
44 using std::chrono::milliseconds;
45 
46 namespace android {
47 namespace net {
48 
49 namespace {
50 
ensureNoInvalidIp(const std::vector<std::string> & servers)51 bool ensureNoInvalidIp(const std::vector<std::string>& servers) {
52     IPAddress ip;
53     for (const auto& s : servers) {
54         if (!IPAddress::forString(s, &ip)) {
55             LOG(WARNING) << "Invalid IP address: " << s;
56             return false;
57         }
58     }
59     return true;
60 }
61 
makeDohFeatureFlags()62 FeatureFlags makeDohFeatureFlags() {
63     const Experiments* const instance = Experiments::getInstance();
64     const auto getTimeout = [&](const std::string_view key, int defaultValue) -> uint64_t {
65         static constexpr int kMinTimeoutMs = 1000;
66         uint64_t timeout = instance->getFlag(key, defaultValue);
67         if (timeout < kMinTimeoutMs) {
68             timeout = kMinTimeoutMs;
69         }
70         return timeout;
71     };
72 
73     return FeatureFlags{
74             .probe_timeout_ms = getTimeout("doh_probe_timeout_ms",
75                                            PrivateDnsConfiguration::kDohProbeDefaultTimeoutMs),
76             .idle_timeout_ms = getTimeout("doh_idle_timeout_ms",
77                                           PrivateDnsConfiguration::kDohIdleDefaultTimeoutMs),
78             .use_session_resumption = instance->getFlag("doh_session_resumption", 0) == 1,
79             .enable_early_data = instance->getFlag("doh_early_data", 0) == 1,
80     };
81 }
82 
toString(const FeatureFlags & flags)83 std::string toString(const FeatureFlags& flags) {
84     return fmt::format(
85             "probe_timeout_ms={}, idle_timeout_ms={}, use_session_resumption={}, "
86             "enable_early_data={}",
87             flags.probe_timeout_ms, flags.idle_timeout_ms, flags.use_session_resumption,
88             flags.enable_early_data);
89 }
90 
91 // Returns the sorted (sort IPv6 before IPv4) servers.
sortServers(const std::vector<std::string> & servers)92 std::vector<std::string> sortServers(const std::vector<std::string>& servers) {
93     std::vector<std::string> out = servers;
94     std::sort(out.begin(), out.end(), [](std::string a, std::string b) {
95         return IPAddress::forString(a) > IPAddress::forString(b);
96     });
97     return out;
98 }
99 
100 }  // namespace
101 
convertEnumType(PrivateDnsMode mode)102 PrivateDnsModes convertEnumType(PrivateDnsMode mode) {
103     switch (mode) {
104         case PrivateDnsMode::OFF:
105             return PrivateDnsModes::PDM_OFF;
106         case PrivateDnsMode::OPPORTUNISTIC:
107             return PrivateDnsModes::PDM_OPPORTUNISTIC;
108         case PrivateDnsMode::STRICT:
109             return PrivateDnsModes::PDM_STRICT;
110         default:
111             return PrivateDnsModes::PDM_UNKNOWN;
112     }
113 }
114 
set(int32_t netId,uint32_t mark,const std::vector<std::string> & unencryptedServers,const std::vector<std::string> & encryptedServers,const std::string & name,const std::string & caCert)115 int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
116                                  const std::vector<std::string>& unencryptedServers,
117                                  const std::vector<std::string>& encryptedServers,
118                                  const std::string& name, const std::string& caCert) {
119     LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
120                << ", " << encryptedServers.size() << ", " << name << ")";
121 
122     if (!ensureNoInvalidIp(encryptedServers)) return -EINVAL;
123 
124     std::lock_guard guard(mPrivateDnsLock);
125     mUnorderedDnsTracker[netId] = unencryptedServers;
126     mUnorderedDotTracker[netId] = encryptedServers;
127     mUnorderedDohTracker[netId] = encryptedServers;
128 
129     if (!name.empty()) {
130         mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
131     } else if (!encryptedServers.empty()) {
132         mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
133     } else {
134         mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
135         clearDot(netId);
136         clearDoh(netId);
137         return 0;
138         // TODO: signal validation threads to stop.
139     }
140 
141     if (int n = setDot(netId, mark, encryptedServers, name, caCert); n != 0) {
142         return n;
143     }
144 
145     return setDoh(netId, mark, encryptedServers, name, caCert);
146 }
147 
setDot(int32_t netId,uint32_t mark,const std::vector<std::string> & servers,const std::string & name,const std::string & caCert)148 int PrivateDnsConfiguration::setDot(int32_t netId, uint32_t mark,
149                                     const std::vector<std::string>& servers,
150                                     const std::string& name, const std::string& caCert) {
151     // Parse the list of servers that has been passed in
152     std::map<ServerIdentity, DnsTlsServer> tmp;
153     for (const auto& s : servers) {
154         // The IP addresses are guaranteed to be valid.
155         DnsTlsServer server(IPAddress::forString(s));
156         server.name = name;
157         server.certificate = caCert;
158         server.mark = mark;
159         tmp[ServerIdentity(server)] = server;
160     }
161 
162     // Create the tracker if it was not present
163     auto& tracker = mDotTracker[netId];
164 
165     // Add the servers if not contained in tracker.
166     for (const auto& [identity, server] : tmp) {
167         if (tracker.find(identity) == tracker.end()) {
168             tracker[identity] = server;
169         }
170     }
171 
172     for (auto& [identity, server] : tracker) {
173         const bool active = tmp.find(identity) != tmp.end();
174         server.setActive(active);
175 
176         // For simplicity, deem the validation result of inactive servers as unreliable.
177         if (!server.active() && server.validationState() == Validation::success) {
178             updateServerState(identity, Validation::success_but_expired, netId);
179         }
180 
181         if (needsValidation(server)) {
182             updateServerState(identity, Validation::in_process, netId);
183             startDotValidation(identity, netId, false);
184         }
185     }
186 
187     return resolv_stats_set_addrs(netId, PROTO_DOT, servers, kDotPort);
188 }
189 
clearDot(int32_t netId)190 void PrivateDnsConfiguration::clearDot(int32_t netId) {
191     mDotTracker.erase(netId);
192     resolv_stats_set_addrs(netId, PROTO_DOT, {}, kDotPort);
193 }
194 
getStatus(unsigned netId) const195 PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
196     std::lock_guard guard(mPrivateDnsLock);
197     return getStatusLocked(netId);
198 }
199 
getStatusLocked(unsigned netId) const200 PrivateDnsStatus PrivateDnsConfiguration::getStatusLocked(unsigned netId) const {
201     PrivateDnsStatus status{
202             .mode = PrivateDnsMode::OFF,
203             .dotServersMap = {},
204             .dohServersMap = {},
205     };
206 
207     const auto mode = mPrivateDnsModes.find(netId);
208     if (mode == mPrivateDnsModes.end()) return status;
209     status.mode = mode->second;
210 
211     const auto netPair = mDotTracker.find(netId);
212     if (netPair != mDotTracker.end()) {
213         for (const auto& [_, server] : netPair->second) {
214             if (server.active()) {
215                 status.dotServersMap.emplace(server, server.validationState());
216             }
217         }
218     }
219 
220     auto it = mDohTracker.find(netId);
221     if (it != mDohTracker.end()) {
222         status.dohServersMap.emplace(IPSockAddr::toIPSockAddr(it->second.ipAddr, kDohPort),
223                                      it->second.status);
224     }
225 
226     return status;
227 }
228 
getStatusForMetrics(unsigned netId) const229 NetworkDnsServerSupportReported PrivateDnsConfiguration::getStatusForMetrics(unsigned netId) const {
230     const auto networkType = resolv_get_network_types_for_net(netId);
231     std::lock_guard guard(mPrivateDnsLock);
232 
233     if (mPrivateDnsModes.find(netId) == mPrivateDnsModes.end()) {
234         // Return NetworkDnsServerSupportReported with private_dns_modes set to PDM_UNKNOWN.
235         return {};
236     }
237 
238     const PrivateDnsStatus status = getStatusLocked(netId);
239     NetworkDnsServerSupportReported event = {};
240     event.set_network_type(networkType);
241     event.set_private_dns_modes(convertEnumType(status.mode));
242 
243     if (const auto it = mUnorderedDnsTracker.find(netId); it != mUnorderedDnsTracker.end()) {
244         for (size_t i = 0; i < it->second.size(); i++) {
245             Server* server = event.mutable_servers()->add_server();
246             server->set_protocol(PROTO_UDP);
247             server->set_index(i);
248             server->set_validated(false);
249         }
250     }
251 
252     if (const auto it = mUnorderedDotTracker.find(netId); it != mUnorderedDotTracker.end()) {
253         int index = 0;
254         const std::list<DnsTlsServer> validatedServers = status.validatedServers();
255         for (const std::string& s : it->second) {
256             const IPSockAddr target = IPSockAddr::toIPSockAddr(s, kDotPort);
257             bool validated =
258                     std::any_of(validatedServers.begin(), validatedServers.end(),
259                                 [&target](DnsTlsServer server) { return server.addr() == target; });
260             Server* server = event.mutable_servers()->add_server();
261             server->set_protocol(PROTO_DOT);
262             server->set_index(index++);
263             server->set_validated(validated);
264         }
265     }
266 
267     if (const auto it = mUnorderedDohTracker.find(netId); it != mUnorderedDohTracker.end()) {
268         int index = 0;
269         for (const std::string& s : it->second) {
270             const IPSockAddr target = IPSockAddr::toIPSockAddr(s, kDohPort);
271             bool validated = std::any_of(status.dohServersMap.begin(), status.dohServersMap.end(),
272                                          [&target](const auto& entry) {
273                                              return entry.first == target &&
274                                                     entry.second == Validation::success;
275                                          });
276             Server* server = event.mutable_servers()->add_server();
277             server->set_protocol(PROTO_DOH);
278             server->set_index(index++);
279             server->set_validated(validated);
280         }
281     }
282 
283     return event;
284 }
285 
clear(unsigned netId)286 void PrivateDnsConfiguration::clear(unsigned netId) {
287     LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
288     std::lock_guard guard(mPrivateDnsLock);
289     mPrivateDnsModes.erase(netId);
290     mUnorderedDnsTracker.erase(netId);
291     mUnorderedDotTracker.erase(netId);
292     mUnorderedDohTracker.erase(netId);
293     clearDot(netId);
294     clearDoh(netId);
295 
296     // Notify the relevant private DNS validations, if they are waiting, to finish.
297     mCv.notify_all();
298 }
299 
requestDotValidation(unsigned netId,const ServerIdentity & identity,uint32_t mark)300 base::Result<void> PrivateDnsConfiguration::requestDotValidation(unsigned netId,
301                                                                  const ServerIdentity& identity,
302                                                                  uint32_t mark) {
303     std::lock_guard guard(mPrivateDnsLock);
304 
305     // Running revalidation requires to mark the server as in_process, which means the server
306     // won't be used until the validation passes. It's necessary and safe to run revalidation
307     // when in private DNS opportunistic mode, because there's a fallback mechanics even if
308     // all of the private DNS servers are in in_process state.
309     if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
310         return Errorf("NetId not found in mPrivateDnsModes");
311     } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
312         return Errorf("Private DNS setting is not opportunistic mode");
313     }
314 
315     auto result = getDotServerLocked(identity, netId);
316     if (!result.ok()) {
317         return result.error();
318     }
319 
320     const DnsTlsServer* target = result.value();
321 
322     if (!target->active()) return Errorf("Server is not active");
323 
324     if (target->validationState() != Validation::success) {
325         return Errorf("Server validation state mismatched");
326     }
327 
328     // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
329     // This is to protect validation from running on unexpected marks.
330     // Validation should be associated with a mark gotten by system permission.
331     if (target->validationMark() != mark) return Errorf("Socket mark mismatched");
332 
333     updateServerState(identity, Validation::in_process, netId);
334     startDotValidation(identity, netId, true);
335     return {};
336 }
337 
startDotValidation(const ServerIdentity & identity,unsigned netId,bool isRevalidation)338 void PrivateDnsConfiguration::startDotValidation(const ServerIdentity& identity, unsigned netId,
339                                                  bool isRevalidation) {
340     // This ensures that the thread sends probe at least once in case
341     // the server is removed before the thread starts running.
342     // TODO: consider moving these code to the thread.
343     const auto result = getDotServerLocked(identity, netId);
344     if (!result.ok()) return;
345     DnsTlsServer server = *result.value();
346 
347     std::thread validate_thread([this, identity, server, netId, isRevalidation] {
348         setThreadName(fmt::format("TlsVerify_{}", netId));
349 
350         // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
351         //
352         // Start with a 1 minute delay and backoff to once per hour.
353         //
354         // Assumptions:
355         //     [1] Each TLS validation is ~10KB of certs+handshake+payload.
356         //     [2] Network typically provision clients with <=4 nameservers.
357         //     [3] Average month has 30 days.
358         //
359         // Each validation pass in a given hour is ~1.2MB of data. And 24
360         // such validation passes per day is about ~30MB per month, in the
361         // worst case. Otherwise, this will cost ~600 SYNs per month
362         // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
363         auto backoff = mBackoffBuilder.build();
364 
365         while (true) {
366             // ::validate() is a blocking call that performs network operations.
367             // It can take milliseconds to minutes, up to the SYN retry limit.
368             LOG(WARNING) << "Validating DnsTlsServer " << server.toString() << " with mark 0x"
369                          << std::hex << server.validationMark();
370             const bool success = DnsTlsTransport::validate(server, server.validationMark());
371             LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
372                          << server.toString();
373 
374             const bool needs_reeval =
375                     this->recordDotValidation(identity, netId, success, isRevalidation);
376 
377             if (!needs_reeval || !backoff.hasNextTimeout()) {
378                 break;
379             }
380 
381             std::unique_lock<std::mutex> cvGuard(mPrivateDnsLock);
382             // If the timeout expired and the predicate still evaluates to false, wait_for returns
383             // false.
384             if (mCv.wait_for(cvGuard, backoff.getNextTimeout(),
385                              [this, netId]() REQUIRES(mPrivateDnsLock) {
386                                  return mPrivateDnsModes.find(netId) == mPrivateDnsModes.end();
387                              })) {
388                 break;
389             }
390         }
391     });
392     validate_thread.detach();
393 }
394 
sendPrivateDnsValidationEvent(const ServerIdentity & identity,unsigned netId,bool success) const395 void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
396                                                             unsigned netId, bool success) const {
397     LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
398                << netId << " for " << identity.sockaddr.toString() << " with hostname {"
399                << identity.provider << "}";
400     // Send a validation event to NetdEventListenerService.
401     const auto& listeners = ResolverEventReporter::getInstance().getListeners();
402     if (listeners.empty()) {
403         LOG(ERROR)
404                 << "Validation event not sent since no INetdEventListener receiver is available.";
405     }
406     for (const auto& it : listeners) {
407         it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
408                                         success);
409     }
410 
411     // Send a validation event to unsolicited event listeners.
412     const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
413     const PrivateDnsValidationEventParcel validationEvent = {
414             .netId = static_cast<int32_t>(netId),
415             .ipAddress = identity.sockaddr.ip().toString(),
416             .hostname = identity.provider,
417             .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
418                                   : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
419             .protocol = (identity.sockaddr.port() == kDotPort)
420                                 ? IDnsResolverUnsolicitedEventListener::PROTOCOL_DOT
421                                 : IDnsResolverUnsolicitedEventListener::PROTOCOL_DOH,
422     };
423     for (const auto& it : unsolEventListeners) {
424         it->onPrivateDnsValidationEvent(validationEvent);
425     }
426 }
427 
recordDotValidation(const ServerIdentity & identity,unsigned netId,bool success,bool isRevalidation)428 bool PrivateDnsConfiguration::recordDotValidation(const ServerIdentity& identity, unsigned netId,
429                                                   bool success, bool isRevalidation) {
430     constexpr bool NEEDS_REEVALUATION = true;
431     constexpr bool DONT_REEVALUATE = false;
432 
433     std::lock_guard guard(mPrivateDnsLock);
434 
435     auto netPair = mDotTracker.find(netId);
436     if (netPair == mDotTracker.end()) {
437         LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
438         notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
439         return DONT_REEVALUATE;
440     }
441 
442     const auto mode = mPrivateDnsModes.find(netId);
443     if (mode == mPrivateDnsModes.end()) {
444         LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
445         notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
446         return DONT_REEVALUATE;
447     }
448 
449     bool reevaluationStatus = NEEDS_REEVALUATION;
450     if (success || (mode->second == PrivateDnsMode::OFF) ||
451         (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation)) {
452         reevaluationStatus = DONT_REEVALUATE;
453     }
454 
455     auto& tracker = netPair->second;
456     auto serverPair = tracker.find(identity);
457     if (serverPair == tracker.end()) {
458         LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
459                      << " was removed during private DNS validation";
460         success = false;
461         reevaluationStatus = DONT_REEVALUATE;
462     } else if (!serverPair->second.active()) {
463         LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
464                      << " was removed from the configuration";
465         success = false;
466         reevaluationStatus = DONT_REEVALUATE;
467     }
468 
469     // Send private dns validation result to listeners.
470     if (needReportEvent(netId, identity, success)) {
471         sendPrivateDnsValidationEvent(identity, netId, success);
472     }
473 
474     if (success) {
475         updateServerState(identity, Validation::success, netId);
476     } else {
477         // Validation failure is expected if a user is on a captive portal.
478         // TODO: Trigger a second validation attempt after captive portal login
479         // succeeds.
480         const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
481                                                                        : Validation::fail;
482         updateServerState(identity, result, netId);
483     }
484     LOG(WARNING) << "Validation " << (success ? "success" : "failed");
485 
486     return reevaluationStatus;
487 }
488 
updateServerState(const ServerIdentity & identity,Validation state,uint32_t netId)489 void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
490                                                 uint32_t netId) {
491     const auto result = getDotServerLocked(identity, netId);
492     if (!result.ok()) {
493         notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
494         return;
495     }
496 
497     auto* server = result.value();
498 
499     server->setValidationState(state);
500     notifyValidationStateUpdate(identity.sockaddr, state, netId);
501 
502     RecordEntry record(netId, identity, state);
503     mPrivateDnsLog.push(std::move(record));
504 }
505 
needsValidation(const DnsTlsServer & server) const506 bool PrivateDnsConfiguration::needsValidation(const DnsTlsServer& server) const {
507     // The server is not expected to be used on the network.
508     if (!server.active()) return false;
509 
510     // The server is newly added.
511     if (server.validationState() == Validation::unknown_server) return true;
512 
513     // The server has failed at least one validation attempt. Give it another try.
514     if (server.validationState() == Validation::fail) return true;
515 
516     // The previous validation result might be unreliable.
517     if (server.validationState() == Validation::success_but_expired) return true;
518 
519     return false;
520 }
521 
getDotServer(const ServerIdentity & identity,unsigned netId)522 base::Result<DnsTlsServer*> PrivateDnsConfiguration::getDotServer(const ServerIdentity& identity,
523                                                                   unsigned netId) {
524     std::lock_guard guard(mPrivateDnsLock);
525     return getDotServerLocked(identity, netId);
526 }
527 
getDotServerLocked(const ServerIdentity & identity,unsigned netId)528 base::Result<DnsTlsServer*> PrivateDnsConfiguration::getDotServerLocked(
529         const ServerIdentity& identity, unsigned netId) {
530     auto netPair = mDotTracker.find(netId);
531     if (netPair == mDotTracker.end()) {
532         return Errorf("Failed to get private DNS: netId {} not found", netId);
533     }
534 
535     auto iter = netPair->second.find(identity);
536     if (iter == netPair->second.end()) {
537         return Errorf("Failed to get private DNS: server {{{}/{}}} not found",
538                       identity.sockaddr.toString(), identity.provider);
539     }
540 
541     return &iter->second;
542 }
543 
setObserver(PrivateDnsValidationObserver * observer)544 void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
545     std::lock_guard guard(mPrivateDnsLock);
546     mObserver = observer;
547 }
548 
getDohServer(unsigned netId) const549 base::Result<netdutils::IPSockAddr> PrivateDnsConfiguration::getDohServer(unsigned netId) const {
550     std::lock_guard guard(mPrivateDnsLock);
551     auto it = mDohTracker.find(netId);
552     if (it != mDohTracker.end()) {
553         return IPSockAddr::toIPSockAddr(it->second.ipAddr, kDohPort);
554     }
555 
556     return Errorf("Failed to get DoH Server: netId {} not found", netId);
557 }
558 
notifyValidationStateUpdate(const netdutils::IPSockAddr & sockaddr,Validation validation,uint32_t netId) const559 void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
560                                                           Validation validation,
561                                                           uint32_t netId) const {
562     if (mObserver) {
563         mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
564     }
565 }
566 
dump(netdutils::DumpWriter & dw) const567 void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
568     dw.println("PrivateDnsLog:");
569     netdutils::ScopedIndent indentStats(dw);
570 
571     for (const auto& record : mPrivateDnsLog.copy()) {
572         dw.println(fmt::format(
573                 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
574                 record.netId, record.serverIdentity.sockaddr.toString(),
575                 record.serverIdentity.provider, validationStatusToString(record.state)));
576     }
577     dw.blankline();
578 }
579 
initDoh()580 void PrivateDnsConfiguration::initDoh() {
581     std::lock_guard guard(mPrivateDnsLock);
582     initDohLocked();
583 }
584 
initDohLocked()585 void PrivateDnsConfiguration::initDohLocked() {
586     if (mDohDispatcher != nullptr) return;
587     mDohDispatcher = doh_dispatcher_new(
588             [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
589                 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
590                         net_id, success, ip_addr, host);
591             },
592             [](int32_t sock) { resolv_tag_socket(sock, AID_DNS, NET_CONTEXT_INVALID_PID); });
593 }
594 
setDoh(int32_t netId,uint32_t mark,const std::vector<std::string> & servers,const std::string & name,const std::string & caCert)595 int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
596                                     const std::vector<std::string>& servers,
597                                     const std::string& name, const std::string& caCert) {
598     LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
599                << std::dec << ", " << servers.size() << ", " << name << ")";
600     if (servers.empty()) {
601         clearDoh(netId);
602         return 0;
603     }
604 
605     const NetworkType networkType = resolv_get_network_types_for_net(netId);
606     const PrivateDnsStatus status = getStatusLocked(netId);
607 
608     // Sort the input servers to prefer IPv6.
609     const std::vector<std::string> sortedServers = sortServers(servers);
610 
611     initDohLocked();
612 
613     const auto& doh = makeDohIdentity(sortedServers, name);
614     if (!doh.ok()) {
615         LOG(INFO) << __func__ << ": No suitable DoH server found";
616         clearDoh(netId);
617         return 0;
618     }
619 
620     auto it = mDohTracker.find(netId);
621     // Skip if the same server already exists and its status == success.
622     if (it != mDohTracker.end() && it->second == doh.value() &&
623         it->second.status == Validation::success) {
624         return 0;
625     }
626     const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
627     const auto& dohId = dohIt->second;
628 
629     RecordEntry record(netId, {IPSockAddr::toIPSockAddr(dohId.ipAddr, kDohPort), name},
630                        dohId.status);
631     mPrivateDnsLog.push(std::move(record));
632     LOG(INFO) << __func__ << ": Upgrading server to DoH: " << name;
633     resolv_stats_set_addrs(netId, PROTO_DOH, {dohId.ipAddr}, kDohPort);
634 
635     const FeatureFlags flags = makeDohFeatureFlags();
636     LOG(DEBUG) << __func__ << ": " << toString(flags);
637 
638     const PrivateDnsModes privateDnsMode = convertEnumType(status.mode);
639     return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
640                        dohId.ipAddr.c_str(), mark, caCert.c_str(), &flags, networkType,
641                        privateDnsMode);
642 }
643 
clearDoh(unsigned netId)644 void PrivateDnsConfiguration::clearDoh(unsigned netId) {
645     LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
646     if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
647     mDohTracker.erase(netId);
648     resolv_stats_set_addrs(netId, PROTO_DOH, {}, kDohPort);
649 }
650 
makeDohIdentity(const std::vector<std::string> & servers,const std::string & name) const651 base::Result<PrivateDnsConfiguration::DohIdentity> PrivateDnsConfiguration::makeDohIdentity(
652         const std::vector<std::string>& servers, const std::string& name) const {
653     for (const auto& entry : mAvailableDoHProviders) {
654         const auto& dohId = entry.getDohIdentity(servers, name);
655         if (!dohId.ok()) continue;
656 
657         // Since the DnsResolver is expected to be configured by the system server, add the
658         // restriction to prevent ResolverTestProvider from being used other than testing.
659         if (entry.requireRootPermission && AIBinder_getCallingUid() != AID_ROOT) continue;
660 
661         return dohId;
662     }
663     return Errorf("Cannot make a DohIdentity from current DNS configuration");
664 }
665 
dohQuery(unsigned netId,const Slice query,const Slice answer,uint64_t timeoutMs)666 ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
667                                           uint64_t timeoutMs) {
668     {
669         std::lock_guard guard(mPrivateDnsLock);
670         // It's safe because mDohDispatcher won't be deleted after initializing.
671         if (mDohDispatcher == nullptr) return DOH_RESULT_CAN_NOT_SEND;
672     }
673     return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
674                      answer.size(), timeoutMs);
675 }
676 
onDohStatusUpdate(uint32_t netId,bool success,const char * ipAddr,const char * host)677 void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
678                                                 const char* host) {
679     LOG(INFO) << __func__ << ": " << netId << ", " << success << ", " << ipAddr << ", " << host;
680     std::lock_guard guard(mPrivateDnsLock);
681     // Update the server status.
682     auto it = mDohTracker.find(netId);
683     if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
684         LOG(WARNING) << __func__ << ": Obsolete event";
685         return;
686     }
687     Validation status = success ? Validation::success : Validation::fail;
688     it->second.status = status;
689     // Send the events to registered listeners.
690     const ServerIdentity identity = {IPSockAddr::toIPSockAddr(ipAddr, kDohPort), host};
691     if (needReportEvent(netId, identity, success)) {
692         sendPrivateDnsValidationEvent(identity, netId, success);
693     }
694     // Add log.
695     RecordEntry record(netId, identity, status);
696     mPrivateDnsLog.push(std::move(record));
697 }
698 
needReportEvent(uint32_t netId,ServerIdentity identity,bool success) const699 bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
700                                               bool success) const {
701     // If the result is success, no concern to report the events.
702     if (success) return true;
703     // If the result is failure, check another transport's status to determine if we should report
704     // the event.
705     switch (identity.sockaddr.port()) {
706         // DoH
707         case kDohPort: {
708             auto netPair = mDotTracker.find(netId);
709             if (netPair == mDotTracker.end()) return true;
710             for (const auto& [id, server] : netPair->second) {
711                 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
712                     (identity.sockaddr.port() != id.sockaddr.port()) &&
713                     (server.validationState() == Validation::success)) {
714                     LOG(DEBUG) << __func__
715                                << ": Skip reporting DoH validation failure event, server addr: "
716                                << identity.sockaddr.ip().toString();
717                     return false;
718                 }
719             }
720             break;
721         }
722         // DoT
723         case kDotPort: {
724             auto it = mDohTracker.find(netId);
725             if (it == mDohTracker.end()) return true;
726             if (it->second == identity && it->second.status == Validation::success) {
727                 LOG(DEBUG) << __func__
728                            << ": Skip reporting DoT validation failure event, server addr: "
729                            << identity.sockaddr.ip().toString();
730                 return false;
731             }
732             break;
733         }
734     }
735     return true;
736 }
737 
738 }  // namespace net
739 }  // namespace android
740