blob: d9b9b12ad90170831afd7c023995ff2e5e7667ff [file] [log] [blame]
Mike Yub601ff72018-11-01 20:07:00 +08001/*
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
Ken Chen5471dca2019-04-15 15:25:35 +080017#define LOG_TAG "resolv"
Mike Yub601ff72018-11-01 20:07:00 +080018
Mike Yu303b0df2018-12-24 17:05:02 +080019#include "PrivateDnsConfiguration.h"
20
Luke Huang53d3eb22021-07-19 15:08:56 +080021#include <algorithm>
22
Mike Yu3d5130d2020-12-21 17:57:18 +080023#include <android-base/format.h>
chenbruceaff85842019-05-31 15:46:42 +080024#include <android-base/logging.h>
Mike Yu5e406a32021-07-06 21:01:17 +080025#include <android/binder_ibinder.h>
Luke Huang2fe9c732021-07-06 01:48:02 +080026#include <netdutils/Slice.h>
Mike Yu04f1d482019-08-08 11:09:32 +080027#include <netdutils/ThreadUtil.h>
Mike Yub601ff72018-11-01 20:07:00 +080028#include <sys/socket.h>
29
Bernie Innocentiec4219b2019-01-30 11:16:36 +090030#include "DnsTlsTransport.h"
Mike Yu303b0df2018-12-24 17:05:02 +080031#include "ResolverEventReporter.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080032#include "doh.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +090033#include "netd_resolv/resolv.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080034#include "resolv_private.h"
Mike Yu9c720102019-11-14 11:34:33 +080035#include "util.h"
Mike Yub601ff72018-11-01 20:07:00 +080036
paulhu0664f692020-12-14 16:48:26 +080037using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
38using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
Luke Huang53d3eb22021-07-19 15:08:56 +080039using android::netdutils::IPAddress;
Mike Yu425d16e2021-05-05 21:40:42 +080040using android::netdutils::IPSockAddr;
Mike Yucb902c92020-05-20 19:26:56 +080041using android::netdutils::setThreadName;
Luke Huang2fe9c732021-07-06 01:48:02 +080042using android::netdutils::Slice;
Mike Yua772c202019-09-23 17:47:21 +080043using std::chrono::milliseconds;
44
Mike Yub601ff72018-11-01 20:07:00 +080045namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080046namespace net {
47
Mike Yub601ff72018-11-01 20:07:00 +080048int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
49 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080050 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080051 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080052 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080053
54 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080055 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080056 for (const auto& s : servers) {
Mike Yu425d16e2021-05-05 21:40:42 +080057 IPAddress ip;
58 if (!IPAddress::forString(s, &ip)) {
59 LOG(WARNING) << "Failed to parse server address (" << s << ")";
Mike Yub601ff72018-11-01 20:07:00 +080060 return -EINVAL;
61 }
Mike Yu425d16e2021-05-05 21:40:42 +080062
63 auto server = std::make_unique<DnsTlsServer>(ip);
Mike Yucf56d232021-04-29 19:37:25 +080064 server->name = name;
65 server->certificate = caCert;
66 server->mark = mark;
67 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080068 }
69
70 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080071 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080072 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080073 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080074 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
75 } else {
76 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
77 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080078 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080079 return 0;
80 }
81
82 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080083 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080084
Mike Yuf7717f52020-11-24 17:31:12 +080085 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +080086 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +080087 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +080088 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +080089 }
90 }
Mike Yu3334a5e2020-11-19 13:33:17 +080091
Mike Yuf7717f52020-11-24 17:31:12 +080092 for (auto& [identity, server] : tracker) {
93 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +080094 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +080095
96 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +080097 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +080098 updateServerState(identity, Validation::success_but_expired, netId);
99 }
100
Mike Yucf56d232021-04-29 19:37:25 +0800101 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800102 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800103 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800104 }
105 }
Mike Yue655b1d2019-08-28 17:49:59 +0800106
Mike Yu8d9da4a2020-11-09 17:09:14 +0800107 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800108}
109
Mike Yu82ae84b2020-12-02 21:04:40 +0800110PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800111 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800112 std::lock_guard guard(mPrivateDnsLock);
113
114 const auto mode = mPrivateDnsModes.find(netId);
115 if (mode == mPrivateDnsModes.end()) return status;
116 status.mode = mode->second;
117
118 const auto netPair = mPrivateDnsTransports.find(netId);
119 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800120 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800121 if (server->isDot() && server->active()) {
122 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
123 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800124 }
Mike Yucf56d232021-04-29 19:37:25 +0800125 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800126 }
127 }
128
129 return status;
130}
131
Mike Yub601ff72018-11-01 20:07:00 +0800132void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800133 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800134 std::lock_guard guard(mPrivateDnsLock);
135 mPrivateDnsModes.erase(netId);
136 mPrivateDnsTransports.erase(netId);
137}
138
Mike Yu82ae84b2020-12-02 21:04:40 +0800139base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800140 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800141 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800142 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800143
144 // Running revalidation requires to mark the server as in_process, which means the server
145 // won't be used until the validation passes. It's necessary and safe to run revalidation
146 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
147 // all of the private DNS servers are in in_process state.
148 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
149 return Errorf("NetId not found in mPrivateDnsModes");
150 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
151 return Errorf("Private DNS setting is not opportunistic mode");
152 }
153
Mike Yuad96ef82021-02-20 18:35:14 +0800154 auto result = getPrivateDnsLocked(identity, netId);
155 if (!result.ok()) {
156 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800157 }
158
Mike Yucf56d232021-04-29 19:37:25 +0800159 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800160
Mike Yucf56d232021-04-29 19:37:25 +0800161 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800162
Mike Yucf56d232021-04-29 19:37:25 +0800163 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800164 return Errorf("Server validation state mismatched");
165 }
Mike Yue60ab412020-12-01 17:56:12 +0800166
167 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
168 // This is to protect validation from running on unexpected marks.
169 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800170 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800171
172 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800173 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800174 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800175}
176
Mike Yuad96ef82021-02-20 18:35:14 +0800177void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
178 bool isRevalidation) {
179 // This ensures that the thread sends probe at least once in case
180 // the server is removed before the thread starts running.
181 // TODO: consider moving these code to the thread.
182 const auto result = getPrivateDnsLocked(identity, netId);
183 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800184 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800185
186 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
chenbruce9b72daa2021-08-20 00:00:49 +0800187 setThreadName(fmt::format("TlsVerify_{}", netId));
Mike Yu04f1d482019-08-08 11:09:32 +0800188
Mike Yub601ff72018-11-01 20:07:00 +0800189 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
190 //
191 // Start with a 1 minute delay and backoff to once per hour.
192 //
193 // Assumptions:
194 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
195 // [2] Network typically provision clients with <=4 nameservers.
196 // [3] Average month has 30 days.
197 //
198 // Each validation pass in a given hour is ~1.2MB of data. And 24
199 // such validation passes per day is about ~30MB per month, in the
200 // worst case. Otherwise, this will cost ~600 SYNs per month
201 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800202 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800203
Mike Yu7135fbf2021-06-10 20:27:36 +0800204 while (true) {
Mike Yub601ff72018-11-01 20:07:00 +0800205 // ::validate() is a blocking call that performs network operations.
206 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800207 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800208 << std::hex << server.validationMark();
Mike Yu5daa40d2021-06-10 21:34:32 +0800209 const bool success = DnsTlsTransport::validate(server, server.validationMark());
210 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
211 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800212
Mike Yu5daa40d2021-06-10 21:34:32 +0800213 const bool needs_reeval =
214 this->recordPrivateDnsValidation(identity, netId, success, isRevalidation);
Mike Yu82ae84b2020-12-02 21:04:40 +0800215
Mike Yub601ff72018-11-01 20:07:00 +0800216 if (!needs_reeval) {
217 break;
218 }
219
220 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800221 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800222 std::this_thread::sleep_for(backoff.getNextTimeout());
223 } else {
224 break;
225 }
226 }
227 });
228 validate_thread.detach();
229}
230
Mike Yuad96ef82021-02-20 18:35:14 +0800231void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
Luke Huang2fe9c732021-07-06 01:48:02 +0800232 unsigned netId, bool success) const {
paulhu0664f692020-12-14 16:48:26 +0800233 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Luke Huang2fe9c732021-07-06 01:48:02 +0800234 << netId << " for " << identity.sockaddr.toString() << " with hostname {"
Mike Yuad96ef82021-02-20 18:35:14 +0800235 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800236 // Send a validation event to NetdEventListenerService.
237 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
238 if (listeners.empty()) {
239 LOG(ERROR)
240 << "Validation event not sent since no INetdEventListener receiver is available.";
241 }
242 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800243 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
244 success);
paulhu0664f692020-12-14 16:48:26 +0800245 }
246
247 // Send a validation event to unsolicited event listeners.
248 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
249 const PrivateDnsValidationEventParcel validationEvent = {
250 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800251 .ipAddress = identity.sockaddr.ip().toString(),
252 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800253 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
254 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
255 };
256 for (const auto& it : unsolEventListeners) {
257 it->onPrivateDnsValidationEvent(validationEvent);
258 }
259}
260
Mike Yuad96ef82021-02-20 18:35:14 +0800261bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu5daa40d2021-06-10 21:34:32 +0800262 unsigned netId, bool success,
263 bool isRevalidation) {
Mike Yub601ff72018-11-01 20:07:00 +0800264 constexpr bool NEEDS_REEVALUATION = true;
265 constexpr bool DONT_REEVALUATE = false;
266
267 std::lock_guard guard(mPrivateDnsLock);
268
269 auto netPair = mPrivateDnsTransports.find(netId);
270 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800271 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800272 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800273 return DONT_REEVALUATE;
274 }
275
276 const auto mode = mPrivateDnsModes.find(netId);
277 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800278 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800279 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800280 return DONT_REEVALUATE;
281 }
Mike Yub601ff72018-11-01 20:07:00 +0800282
Mike Yu82ae84b2020-12-02 21:04:40 +0800283 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu5daa40d2021-06-10 21:34:32 +0800284 if (success) {
285 reevaluationStatus = DONT_REEVALUATE;
Mike Yu82ae84b2020-12-02 21:04:40 +0800286 } else if (mode->second == PrivateDnsMode::OFF) {
287 reevaluationStatus = DONT_REEVALUATE;
288 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
289 reevaluationStatus = DONT_REEVALUATE;
290 }
Mike Yub601ff72018-11-01 20:07:00 +0800291
292 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800293 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800294 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800295 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800296 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800297 success = false;
298 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800299 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800300 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
301 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800302 success = false;
303 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800304 }
305
Mike Yu1aede812021-05-11 14:49:30 +0800306 // Send private dns validation result to listeners.
Luke Huang2fe9c732021-07-06 01:48:02 +0800307 if (needReportEvent(netId, identity, success)) {
308 sendPrivateDnsValidationEvent(identity, netId, success);
309 }
Mike Yu1aede812021-05-11 14:49:30 +0800310
Mike Yu5daa40d2021-06-10 21:34:32 +0800311 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800312 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800313 } else {
314 // Validation failure is expected if a user is on a captive portal.
315 // TODO: Trigger a second validation attempt after captive portal login
316 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800317 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
318 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800319 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800320 }
Mike Yu5daa40d2021-06-10 21:34:32 +0800321 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800322
323 return reevaluationStatus;
324}
325
Mike Yufa985f72020-11-23 20:24:21 +0800326void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800327 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800328 const auto result = getPrivateDnsLocked(identity, netId);
329 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800330 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800331 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800332 }
333
Mike Yuad96ef82021-02-20 18:35:14 +0800334 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800335
Mike Yuad96ef82021-02-20 18:35:14 +0800336 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800337 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800338
339 RecordEntry record(netId, identity, state);
340 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800341}
342
Mike Yucf56d232021-04-29 19:37:25 +0800343bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800344 // The server is not expected to be used on the network.
345 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500346
Mike Yuf7717f52020-11-24 17:31:12 +0800347 // The server is newly added.
348 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500349
Mike Yuf7717f52020-11-24 17:31:12 +0800350 // The server has failed at least one validation attempt. Give it another try.
351 if (server.validationState() == Validation::fail) return true;
352
353 // The previous validation result might be unreliable.
354 if (server.validationState() == Validation::success_but_expired) return true;
355
356 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800357}
358
Mike Yucf56d232021-04-29 19:37:25 +0800359base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
360 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800361 std::lock_guard guard(mPrivateDnsLock);
362 return getPrivateDnsLocked(identity, netId);
363}
364
Mike Yucf56d232021-04-29 19:37:25 +0800365base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800366 const ServerIdentity& identity, unsigned netId) {
367 auto netPair = mPrivateDnsTransports.find(netId);
368 if (netPair == mPrivateDnsTransports.end()) {
369 return Errorf("Failed to get private DNS: netId {} not found", netId);
370 }
371
372 auto iter = netPair->second.find(identity);
373 if (iter == netPair->second.end()) {
374 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
375 identity.provider);
376 }
377
Mike Yucf56d232021-04-29 19:37:25 +0800378 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800379}
380
Mike Yua6853e82020-12-11 19:47:06 +0800381void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800382 std::lock_guard guard(mPrivateDnsLock);
383 mObserver = observer;
384}
385
Mike Yu453b5e42021-02-19 20:03:07 +0800386void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800387 Validation validation,
388 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800389 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800390 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800391 }
392}
393
Mike Yu3d5130d2020-12-21 17:57:18 +0800394void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
395 dw.println("PrivateDnsLog:");
396 netdutils::ScopedIndent indentStats(dw);
397
398 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800399 dw.println(fmt::format(
400 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
401 record.netId, record.serverIdentity.sockaddr.toString(),
402 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800403 }
404 dw.blankline();
405}
406
Luke Huang2fe9c732021-07-06 01:48:02 +0800407void PrivateDnsConfiguration::initDoh() {
408 std::lock_guard guard(mPrivateDnsLock);
409 initDohLocked();
410}
411
412void PrivateDnsConfiguration::initDohLocked() {
413 if (mDohDispatcher != nullptr) return;
414 mDohDispatcher = doh_dispatcher_new(
415 [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
416 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
417 net_id, success, ip_addr, host);
418 });
419}
420
421int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
422 const std::vector<std::string>& servers,
423 const std::string& name, const std::string& caCert) {
424 if (servers.empty()) return 0;
425 LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
426 << std::dec << ", " << servers.size() << ", " << name << ")";
427 std::lock_guard guard(mPrivateDnsLock);
428
Luke Huang53d3eb22021-07-19 15:08:56 +0800429 // Sort the input servers to ensure that we could get the server vector at the same order.
430 std::vector<std::string> sortedServers = servers;
431 // Prefer ipv6.
432 std::sort(sortedServers.begin(), sortedServers.end(), [](std::string a, std::string b) {
433 IPAddress ipa = IPAddress::forString(a);
434 IPAddress ipb = IPAddress::forString(b);
435 return ipa > ipb;
436 });
437
Luke Huang2fe9c732021-07-06 01:48:02 +0800438 initDohLocked();
439
440 // TODO: 1. Improve how to choose the server
441 // TODO: 2. Support multiple servers
442 for (const auto& entry : mAvailableDoHProviders) {
Luke Huang53d3eb22021-07-19 15:08:56 +0800443 const auto& doh = entry.getDohIdentity(sortedServers, name);
Luke Huang2fe9c732021-07-06 01:48:02 +0800444 if (!doh.ok()) continue;
445
Mike Yu5e406a32021-07-06 21:01:17 +0800446 // The internal tests are supposed to have root permission.
447 if (entry.forTesting && AIBinder_getCallingUid() != AID_ROOT) continue;
448
Luke Huang2fe9c732021-07-06 01:48:02 +0800449 auto it = mDohTracker.find(netId);
450 // Skip if the same server already exists and its status == success.
451 if (it != mDohTracker.end() && it->second == doh.value() &&
452 it->second.status == Validation::success) {
453 return 0;
454 }
455 const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
456 const auto& dohId = dohIt->second;
457
458 RecordEntry record(netId, {netdutils::IPSockAddr::toIPSockAddr(dohId.ipAddr, 443), name},
459 dohId.status);
460 mPrivateDnsLog.push(std::move(record));
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000461 LOG(INFO) << __func__ << ": Upgrading server to DoH: " << name;
462
Luke Huangdce6cbf2021-08-13 14:53:37 +0800463 int probeTimeout = Experiments::getInstance()->getFlag("doh_probe_timeout_ms",
464 kDohProbeDefaultTimeoutMs);
465 if (probeTimeout < 1000) {
466 probeTimeout = 1000;
467 }
Luke Huang2fe9c732021-07-06 01:48:02 +0800468 return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
Luke Huangdce6cbf2021-08-13 14:53:37 +0800469 dohId.ipAddr.c_str(), mark, caCert.c_str(), probeTimeout);
Luke Huang2fe9c732021-07-06 01:48:02 +0800470 }
471
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000472 LOG(INFO) << __func__ << ": No suitable DoH server found";
Luke Huang2fe9c732021-07-06 01:48:02 +0800473 return 0;
474}
475
476void PrivateDnsConfiguration::clearDoh(unsigned netId) {
477 LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
478 std::lock_guard guard(mPrivateDnsLock);
479 if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
480 mDohTracker.erase(netId);
481}
482
483ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
484 uint64_t timeoutMs) {
485 {
486 std::lock_guard guard(mPrivateDnsLock);
487 // It's safe because mDohDispatcher won't be deleted after initializing.
488 if (mDohDispatcher == nullptr) return RESULT_CAN_NOT_SEND;
489 }
490 return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
491 answer.size(), timeoutMs);
492}
493
494void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
495 const char* host) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000496 LOG(INFO) << __func__ << ": " << netId << ", " << success << ", " << ipAddr << ", " << host;
Luke Huang2fe9c732021-07-06 01:48:02 +0800497 std::lock_guard guard(mPrivateDnsLock);
498 // Update the server status.
499 auto it = mDohTracker.find(netId);
500 if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000501 LOG(WARNING) << __func__ << ": Obsolete event";
Luke Huang2fe9c732021-07-06 01:48:02 +0800502 return;
503 }
504 Validation status = success ? Validation::success : Validation::fail;
505 it->second.status = status;
506 // Send the events to registered listeners.
507 ServerIdentity identity = {netdutils::IPSockAddr::toIPSockAddr(ipAddr, 443), host};
508 if (needReportEvent(netId, identity, success)) {
509 sendPrivateDnsValidationEvent(identity, netId, success);
510 }
511 // Add log.
512 RecordEntry record(netId, identity, status);
513 mPrivateDnsLog.push(std::move(record));
514}
515
516bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
517 bool success) const {
518 // If the result is success or DoH is not enable, no concern to report the events.
519 if (success || !isDoHEnabled()) return true;
520 // If the result is failure, check another transport's status to determine if we should report
521 // the event.
522 switch (identity.sockaddr.port()) {
523 // DoH
524 case 443: {
525 auto netPair = mPrivateDnsTransports.find(netId);
526 if (netPair == mPrivateDnsTransports.end()) return true;
527 for (const auto& [id, server] : netPair->second) {
528 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
529 (identity.sockaddr.port() != id.sockaddr.port()) &&
530 (server->validationState() == Validation::success)) {
531 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000532 << ": Skip reporting DoH validation failure event, server addr: "
533 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800534 return false;
535 }
536 }
537 break;
538 }
539 // DoT
540 case 853: {
541 auto it = mDohTracker.find(netId);
542 if (it == mDohTracker.end()) return true;
543 if (it->second == identity && it->second.status == Validation::success) {
544 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000545 << ": Skip reporting DoT validation failure event, server addr: "
546 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800547 return false;
548 }
549 break;
550 }
551 }
552 return true;
553}
554
Mike Yub601ff72018-11-01 20:07:00 +0800555} // namespace net
556} // namespace android