blob: 802728f44385482963f22974344445494e712e8d [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
Mike Yu3d5130d2020-12-21 17:57:18 +080021#include <android-base/format.h>
chenbruceaff85842019-05-31 15:46:42 +080022#include <android-base/logging.h>
Mike Yu04f1d482019-08-08 11:09:32 +080023#include <android-base/stringprintf.h>
Luke Huang2fe9c732021-07-06 01:48:02 +080024#include <netdutils/Slice.h>
Mike Yu04f1d482019-08-08 11:09:32 +080025#include <netdutils/ThreadUtil.h>
Mike Yub601ff72018-11-01 20:07:00 +080026#include <sys/socket.h>
27
Bernie Innocentiec4219b2019-01-30 11:16:36 +090028#include "DnsTlsTransport.h"
Mike Yu303b0df2018-12-24 17:05:02 +080029#include "ResolverEventReporter.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080030#include "doh.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +090031#include "netd_resolv/resolv.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080032#include "resolv_private.h"
Mike Yu9c720102019-11-14 11:34:33 +080033#include "util.h"
Mike Yub601ff72018-11-01 20:07:00 +080034
paulhu0664f692020-12-14 16:48:26 +080035using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
36using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
Mike Yucb902c92020-05-20 19:26:56 +080037using android::base::StringPrintf;
38using android::netdutils::setThreadName;
Luke Huang2fe9c732021-07-06 01:48:02 +080039using android::netdutils::Slice;
Mike Yua772c202019-09-23 17:47:21 +080040using std::chrono::milliseconds;
41
Mike Yub601ff72018-11-01 20:07:00 +080042namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080043namespace net {
44
Mike Yub601ff72018-11-01 20:07:00 +080045bool parseServer(const char* server, sockaddr_storage* parsed) {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -070046 addrinfo hints = {
47 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
48 .ai_family = AF_UNSPEC,
49 };
Mike Yub601ff72018-11-01 20:07:00 +080050 addrinfo* res;
51
52 int err = getaddrinfo(server, "853", &hints, &res);
53 if (err != 0) {
chenbruceaff85842019-05-31 15:46:42 +080054 LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
Mike Yub601ff72018-11-01 20:07:00 +080055 return false;
56 }
57
58 memcpy(parsed, res->ai_addr, res->ai_addrlen);
59 freeaddrinfo(res);
60 return true;
61}
62
Mike Yub601ff72018-11-01 20:07:00 +080063int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
64 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080065 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080066 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080067 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080068
69 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080070 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080071 for (const auto& s : servers) {
Mike Yub601ff72018-11-01 20:07:00 +080072 sockaddr_storage parsed;
Mike Yu40e67072019-10-09 21:14:09 +080073 if (!parseServer(s.c_str(), &parsed)) {
Mike Yub601ff72018-11-01 20:07:00 +080074 return -EINVAL;
75 }
Mike Yucf56d232021-04-29 19:37:25 +080076 auto server = std::make_unique<DnsTlsServer>(parsed);
77 server->name = name;
78 server->certificate = caCert;
79 server->mark = mark;
80 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080081 }
82
83 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080084 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080085 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080086 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080087 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
88 } else {
89 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
90 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080091 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080092 return 0;
93 }
94
95 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080096 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080097
Mike Yuf7717f52020-11-24 17:31:12 +080098 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +080099 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +0800100 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +0800101 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +0800102 }
103 }
Mike Yu3334a5e2020-11-19 13:33:17 +0800104
Mike Yuf7717f52020-11-24 17:31:12 +0800105 for (auto& [identity, server] : tracker) {
106 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +0800107 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +0800108
109 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +0800110 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +0800111 updateServerState(identity, Validation::success_but_expired, netId);
112 }
113
Mike Yucf56d232021-04-29 19:37:25 +0800114 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800115 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800116 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800117 }
118 }
Mike Yue655b1d2019-08-28 17:49:59 +0800119
Mike Yu8d9da4a2020-11-09 17:09:14 +0800120 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800121}
122
Mike Yu82ae84b2020-12-02 21:04:40 +0800123PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800124 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800125 std::lock_guard guard(mPrivateDnsLock);
126
127 const auto mode = mPrivateDnsModes.find(netId);
128 if (mode == mPrivateDnsModes.end()) return status;
129 status.mode = mode->second;
130
131 const auto netPair = mPrivateDnsTransports.find(netId);
132 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800133 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800134 if (server->isDot() && server->active()) {
135 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
136 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800137 }
Mike Yucf56d232021-04-29 19:37:25 +0800138 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800139 }
140 }
141
142 return status;
143}
144
Mike Yub601ff72018-11-01 20:07:00 +0800145void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800146 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800147 std::lock_guard guard(mPrivateDnsLock);
148 mPrivateDnsModes.erase(netId);
149 mPrivateDnsTransports.erase(netId);
150}
151
Mike Yu82ae84b2020-12-02 21:04:40 +0800152base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800153 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800154 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800155 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800156
157 // Running revalidation requires to mark the server as in_process, which means the server
158 // won't be used until the validation passes. It's necessary and safe to run revalidation
159 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
160 // all of the private DNS servers are in in_process state.
161 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
162 return Errorf("NetId not found in mPrivateDnsModes");
163 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
164 return Errorf("Private DNS setting is not opportunistic mode");
165 }
166
Mike Yuad96ef82021-02-20 18:35:14 +0800167 auto result = getPrivateDnsLocked(identity, netId);
168 if (!result.ok()) {
169 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800170 }
171
Mike Yucf56d232021-04-29 19:37:25 +0800172 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800173
Mike Yucf56d232021-04-29 19:37:25 +0800174 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800175
Mike Yucf56d232021-04-29 19:37:25 +0800176 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800177 return Errorf("Server validation state mismatched");
178 }
Mike Yue60ab412020-12-01 17:56:12 +0800179
180 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
181 // This is to protect validation from running on unexpected marks.
182 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800183 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800184
185 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800186 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800187 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800188}
189
Mike Yuad96ef82021-02-20 18:35:14 +0800190void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
191 bool isRevalidation) {
192 // This ensures that the thread sends probe at least once in case
193 // the server is removed before the thread starts running.
194 // TODO: consider moving these code to the thread.
195 const auto result = getPrivateDnsLocked(identity, netId);
196 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800197 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800198
199 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
Mike Yucb902c92020-05-20 19:26:56 +0800200 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800201
Mike Yub601ff72018-11-01 20:07:00 +0800202 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
203 //
204 // Start with a 1 minute delay and backoff to once per hour.
205 //
206 // Assumptions:
207 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
208 // [2] Network typically provision clients with <=4 nameservers.
209 // [3] Average month has 30 days.
210 //
211 // Each validation pass in a given hour is ~1.2MB of data. And 24
212 // such validation passes per day is about ~30MB per month, in the
213 // worst case. Otherwise, this will cost ~600 SYNs per month
214 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800215 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800216
Mike Yu7135fbf2021-06-10 20:27:36 +0800217 while (true) {
Mike Yub601ff72018-11-01 20:07:00 +0800218 // ::validate() is a blocking call that performs network operations.
219 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800220 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800221 << std::hex << server.validationMark();
Mike Yu5daa40d2021-06-10 21:34:32 +0800222 const bool success = DnsTlsTransport::validate(server, server.validationMark());
223 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
224 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800225
Mike Yu5daa40d2021-06-10 21:34:32 +0800226 const bool needs_reeval =
227 this->recordPrivateDnsValidation(identity, netId, success, isRevalidation);
Mike Yu82ae84b2020-12-02 21:04:40 +0800228
Mike Yub601ff72018-11-01 20:07:00 +0800229 if (!needs_reeval) {
230 break;
231 }
232
233 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800234 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800235 std::this_thread::sleep_for(backoff.getNextTimeout());
236 } else {
237 break;
238 }
239 }
240 });
241 validate_thread.detach();
242}
243
Mike Yuad96ef82021-02-20 18:35:14 +0800244void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
Luke Huang2fe9c732021-07-06 01:48:02 +0800245 unsigned netId, bool success) const {
paulhu0664f692020-12-14 16:48:26 +0800246 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Luke Huang2fe9c732021-07-06 01:48:02 +0800247 << netId << " for " << identity.sockaddr.toString() << " with hostname {"
Mike Yuad96ef82021-02-20 18:35:14 +0800248 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800249 // Send a validation event to NetdEventListenerService.
250 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
251 if (listeners.empty()) {
252 LOG(ERROR)
253 << "Validation event not sent since no INetdEventListener receiver is available.";
254 }
255 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800256 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
257 success);
paulhu0664f692020-12-14 16:48:26 +0800258 }
259
260 // Send a validation event to unsolicited event listeners.
261 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
262 const PrivateDnsValidationEventParcel validationEvent = {
263 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800264 .ipAddress = identity.sockaddr.ip().toString(),
265 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800266 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
267 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
268 };
269 for (const auto& it : unsolEventListeners) {
270 it->onPrivateDnsValidationEvent(validationEvent);
271 }
272}
273
Mike Yuad96ef82021-02-20 18:35:14 +0800274bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu5daa40d2021-06-10 21:34:32 +0800275 unsigned netId, bool success,
276 bool isRevalidation) {
Mike Yub601ff72018-11-01 20:07:00 +0800277 constexpr bool NEEDS_REEVALUATION = true;
278 constexpr bool DONT_REEVALUATE = false;
279
280 std::lock_guard guard(mPrivateDnsLock);
281
282 auto netPair = mPrivateDnsTransports.find(netId);
283 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800284 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800285 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800286 return DONT_REEVALUATE;
287 }
288
289 const auto mode = mPrivateDnsModes.find(netId);
290 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800291 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800292 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800293 return DONT_REEVALUATE;
294 }
Mike Yub601ff72018-11-01 20:07:00 +0800295
Mike Yu82ae84b2020-12-02 21:04:40 +0800296 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu5daa40d2021-06-10 21:34:32 +0800297 if (success) {
298 reevaluationStatus = DONT_REEVALUATE;
Mike Yu82ae84b2020-12-02 21:04:40 +0800299 } else if (mode->second == PrivateDnsMode::OFF) {
300 reevaluationStatus = DONT_REEVALUATE;
301 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
302 reevaluationStatus = DONT_REEVALUATE;
303 }
Mike Yub601ff72018-11-01 20:07:00 +0800304
305 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800306 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800307 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800308 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800309 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800310 success = false;
311 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800312 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800313 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
314 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800315 success = false;
316 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800317 }
318
Mike Yu1aede812021-05-11 14:49:30 +0800319 // Send private dns validation result to listeners.
Luke Huang2fe9c732021-07-06 01:48:02 +0800320 if (needReportEvent(netId, identity, success)) {
321 sendPrivateDnsValidationEvent(identity, netId, success);
322 }
Mike Yu1aede812021-05-11 14:49:30 +0800323
Mike Yu5daa40d2021-06-10 21:34:32 +0800324 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800325 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800326 } else {
327 // Validation failure is expected if a user is on a captive portal.
328 // TODO: Trigger a second validation attempt after captive portal login
329 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800330 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
331 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800332 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800333 }
Mike Yu5daa40d2021-06-10 21:34:32 +0800334 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800335
336 return reevaluationStatus;
337}
338
Mike Yufa985f72020-11-23 20:24:21 +0800339void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800340 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800341 const auto result = getPrivateDnsLocked(identity, netId);
342 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800343 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800344 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800345 }
346
Mike Yuad96ef82021-02-20 18:35:14 +0800347 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800348
Mike Yuad96ef82021-02-20 18:35:14 +0800349 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800350 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800351
352 RecordEntry record(netId, identity, state);
353 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800354}
355
Mike Yucf56d232021-04-29 19:37:25 +0800356bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800357 // The server is not expected to be used on the network.
358 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500359
Mike Yuf7717f52020-11-24 17:31:12 +0800360 // The server is newly added.
361 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500362
Mike Yuf7717f52020-11-24 17:31:12 +0800363 // The server has failed at least one validation attempt. Give it another try.
364 if (server.validationState() == Validation::fail) return true;
365
366 // The previous validation result might be unreliable.
367 if (server.validationState() == Validation::success_but_expired) return true;
368
369 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800370}
371
Mike Yucf56d232021-04-29 19:37:25 +0800372base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
373 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800374 std::lock_guard guard(mPrivateDnsLock);
375 return getPrivateDnsLocked(identity, netId);
376}
377
Mike Yucf56d232021-04-29 19:37:25 +0800378base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800379 const ServerIdentity& identity, unsigned netId) {
380 auto netPair = mPrivateDnsTransports.find(netId);
381 if (netPair == mPrivateDnsTransports.end()) {
382 return Errorf("Failed to get private DNS: netId {} not found", netId);
383 }
384
385 auto iter = netPair->second.find(identity);
386 if (iter == netPair->second.end()) {
387 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
388 identity.provider);
389 }
390
Mike Yucf56d232021-04-29 19:37:25 +0800391 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800392}
393
Mike Yua6853e82020-12-11 19:47:06 +0800394void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800395 std::lock_guard guard(mPrivateDnsLock);
396 mObserver = observer;
397}
398
Mike Yu453b5e42021-02-19 20:03:07 +0800399void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800400 Validation validation,
401 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800402 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800403 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800404 }
405}
406
Mike Yu3d5130d2020-12-21 17:57:18 +0800407void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
408 dw.println("PrivateDnsLog:");
409 netdutils::ScopedIndent indentStats(dw);
410
411 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800412 dw.println(fmt::format(
413 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
414 record.netId, record.serverIdentity.sockaddr.toString(),
415 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800416 }
417 dw.blankline();
418}
419
Luke Huang2fe9c732021-07-06 01:48:02 +0800420void PrivateDnsConfiguration::initDoh() {
421 std::lock_guard guard(mPrivateDnsLock);
422 initDohLocked();
423}
424
425void PrivateDnsConfiguration::initDohLocked() {
426 if (mDohDispatcher != nullptr) return;
427 mDohDispatcher = doh_dispatcher_new(
428 [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
429 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
430 net_id, success, ip_addr, host);
431 });
432}
433
434int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
435 const std::vector<std::string>& servers,
436 const std::string& name, const std::string& caCert) {
437 if (servers.empty()) return 0;
438 LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
439 << std::dec << ", " << servers.size() << ", " << name << ")";
440 std::lock_guard guard(mPrivateDnsLock);
441
442 initDohLocked();
443
444 // TODO: 1. Improve how to choose the server
445 // TODO: 2. Support multiple servers
446 for (const auto& entry : mAvailableDoHProviders) {
447 const auto& doh = entry.getDohIdentity(servers, name);
448 if (!doh.ok()) continue;
449
450 auto it = mDohTracker.find(netId);
451 // Skip if the same server already exists and its status == success.
452 if (it != mDohTracker.end() && it->second == doh.value() &&
453 it->second.status == Validation::success) {
454 return 0;
455 }
456 const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
457 const auto& dohId = dohIt->second;
458
459 RecordEntry record(netId, {netdutils::IPSockAddr::toIPSockAddr(dohId.ipAddr, 443), name},
460 dohId.status);
461 mPrivateDnsLog.push(std::move(record));
462 return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
463 dohId.ipAddr.c_str(), mark, caCert.c_str(), 3000);
464 }
465
466 LOG(INFO) << __func__ << "No suitable DoH server found";
467 return 0;
468}
469
470void PrivateDnsConfiguration::clearDoh(unsigned netId) {
471 LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
472 std::lock_guard guard(mPrivateDnsLock);
473 if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
474 mDohTracker.erase(netId);
475}
476
477ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
478 uint64_t timeoutMs) {
479 {
480 std::lock_guard guard(mPrivateDnsLock);
481 // It's safe because mDohDispatcher won't be deleted after initializing.
482 if (mDohDispatcher == nullptr) return RESULT_CAN_NOT_SEND;
483 }
484 return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
485 answer.size(), timeoutMs);
486}
487
488void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
489 const char* host) {
490 LOG(INFO) << __func__ << netId << ", " << success << ", " << ipAddr << ", " << host;
491 std::lock_guard guard(mPrivateDnsLock);
492 // Update the server status.
493 auto it = mDohTracker.find(netId);
494 if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
495 LOG(WARNING) << __func__ << "obsolete event";
496 return;
497 }
498 Validation status = success ? Validation::success : Validation::fail;
499 it->second.status = status;
500 // Send the events to registered listeners.
501 ServerIdentity identity = {netdutils::IPSockAddr::toIPSockAddr(ipAddr, 443), host};
502 if (needReportEvent(netId, identity, success)) {
503 sendPrivateDnsValidationEvent(identity, netId, success);
504 }
505 // Add log.
506 RecordEntry record(netId, identity, status);
507 mPrivateDnsLog.push(std::move(record));
508}
509
510bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
511 bool success) const {
512 // If the result is success or DoH is not enable, no concern to report the events.
513 if (success || !isDoHEnabled()) return true;
514 // If the result is failure, check another transport's status to determine if we should report
515 // the event.
516 switch (identity.sockaddr.port()) {
517 // DoH
518 case 443: {
519 auto netPair = mPrivateDnsTransports.find(netId);
520 if (netPair == mPrivateDnsTransports.end()) return true;
521 for (const auto& [id, server] : netPair->second) {
522 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
523 (identity.sockaddr.port() != id.sockaddr.port()) &&
524 (server->validationState() == Validation::success)) {
525 LOG(DEBUG) << __func__
526 << "skip reporting DoH validation failure event, server addr: " +
527 identity.sockaddr.ip().toString();
528 return false;
529 }
530 }
531 break;
532 }
533 // DoT
534 case 853: {
535 auto it = mDohTracker.find(netId);
536 if (it == mDohTracker.end()) return true;
537 if (it->second == identity && it->second.status == Validation::success) {
538 LOG(DEBUG) << __func__
539 << "skip reporting DoT validation failure event, server addr: " +
540 identity.sockaddr.ip().toString();
541 return false;
542 }
543 break;
544 }
545 }
546 return true;
547}
548
Mike Yub601ff72018-11-01 20:07:00 +0800549} // namespace net
550} // namespace android