blob: 6b9c4606ac651eeda37343669ed28dd6b09070ec [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 Yu04f1d482019-08-08 11:09:32 +080025#include <android-base/stringprintf.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;
Mike Yucb902c92020-05-20 19:26:56 +080039using android::base::StringPrintf;
Luke Huang53d3eb22021-07-19 15:08:56 +080040using android::netdutils::IPAddress;
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 +080048bool parseServer(const char* server, sockaddr_storage* parsed) {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -070049 addrinfo hints = {
50 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
51 .ai_family = AF_UNSPEC,
52 };
Mike Yub601ff72018-11-01 20:07:00 +080053 addrinfo* res;
54
55 int err = getaddrinfo(server, "853", &hints, &res);
56 if (err != 0) {
chenbruceaff85842019-05-31 15:46:42 +080057 LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
Mike Yub601ff72018-11-01 20:07:00 +080058 return false;
59 }
60
61 memcpy(parsed, res->ai_addr, res->ai_addrlen);
62 freeaddrinfo(res);
63 return true;
64}
65
Mike Yub601ff72018-11-01 20:07:00 +080066int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
67 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080068 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080069 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080070 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080071
72 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080073 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080074 for (const auto& s : servers) {
Mike Yub601ff72018-11-01 20:07:00 +080075 sockaddr_storage parsed;
Mike Yu40e67072019-10-09 21:14:09 +080076 if (!parseServer(s.c_str(), &parsed)) {
Mike Yub601ff72018-11-01 20:07:00 +080077 return -EINVAL;
78 }
Mike Yucf56d232021-04-29 19:37:25 +080079 auto server = std::make_unique<DnsTlsServer>(parsed);
80 server->name = name;
81 server->certificate = caCert;
82 server->mark = mark;
83 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080084 }
85
86 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080087 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080088 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080089 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080090 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
91 } else {
92 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
93 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080094 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080095 return 0;
96 }
97
98 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080099 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +0800100
Mike Yuf7717f52020-11-24 17:31:12 +0800101 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +0800102 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +0800103 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +0800104 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +0800105 }
106 }
Mike Yu3334a5e2020-11-19 13:33:17 +0800107
Mike Yuf7717f52020-11-24 17:31:12 +0800108 for (auto& [identity, server] : tracker) {
109 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +0800110 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +0800111
112 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +0800113 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +0800114 updateServerState(identity, Validation::success_but_expired, netId);
115 }
116
Mike Yucf56d232021-04-29 19:37:25 +0800117 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800118 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800119 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800120 }
121 }
Mike Yue655b1d2019-08-28 17:49:59 +0800122
Mike Yu8d9da4a2020-11-09 17:09:14 +0800123 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800124}
125
Mike Yu82ae84b2020-12-02 21:04:40 +0800126PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800127 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800128 std::lock_guard guard(mPrivateDnsLock);
129
130 const auto mode = mPrivateDnsModes.find(netId);
131 if (mode == mPrivateDnsModes.end()) return status;
132 status.mode = mode->second;
133
134 const auto netPair = mPrivateDnsTransports.find(netId);
135 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800136 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800137 if (server->isDot() && server->active()) {
138 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
139 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800140 }
Mike Yucf56d232021-04-29 19:37:25 +0800141 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800142 }
143 }
144
145 return status;
146}
147
Mike Yub601ff72018-11-01 20:07:00 +0800148void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800149 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800150 std::lock_guard guard(mPrivateDnsLock);
151 mPrivateDnsModes.erase(netId);
152 mPrivateDnsTransports.erase(netId);
153}
154
Mike Yu82ae84b2020-12-02 21:04:40 +0800155base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800156 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800157 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800158 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800159
160 // Running revalidation requires to mark the server as in_process, which means the server
161 // won't be used until the validation passes. It's necessary and safe to run revalidation
162 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
163 // all of the private DNS servers are in in_process state.
164 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
165 return Errorf("NetId not found in mPrivateDnsModes");
166 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
167 return Errorf("Private DNS setting is not opportunistic mode");
168 }
169
Mike Yuad96ef82021-02-20 18:35:14 +0800170 auto result = getPrivateDnsLocked(identity, netId);
171 if (!result.ok()) {
172 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800173 }
174
Mike Yucf56d232021-04-29 19:37:25 +0800175 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800176
Mike Yucf56d232021-04-29 19:37:25 +0800177 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800178
Mike Yucf56d232021-04-29 19:37:25 +0800179 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800180 return Errorf("Server validation state mismatched");
181 }
Mike Yue60ab412020-12-01 17:56:12 +0800182
183 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
184 // This is to protect validation from running on unexpected marks.
185 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800186 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800187
188 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800189 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800190 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800191}
192
Mike Yuad96ef82021-02-20 18:35:14 +0800193void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
194 bool isRevalidation) {
195 // This ensures that the thread sends probe at least once in case
196 // the server is removed before the thread starts running.
197 // TODO: consider moving these code to the thread.
198 const auto result = getPrivateDnsLocked(identity, netId);
199 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800200 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800201
202 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
Mike Yucb902c92020-05-20 19:26:56 +0800203 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800204
Mike Yub601ff72018-11-01 20:07:00 +0800205 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
206 //
207 // Start with a 1 minute delay and backoff to once per hour.
208 //
209 // Assumptions:
210 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
211 // [2] Network typically provision clients with <=4 nameservers.
212 // [3] Average month has 30 days.
213 //
214 // Each validation pass in a given hour is ~1.2MB of data. And 24
215 // such validation passes per day is about ~30MB per month, in the
216 // worst case. Otherwise, this will cost ~600 SYNs per month
217 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800218 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800219
Mike Yu7135fbf2021-06-10 20:27:36 +0800220 while (true) {
Mike Yub601ff72018-11-01 20:07:00 +0800221 // ::validate() is a blocking call that performs network operations.
222 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800223 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800224 << std::hex << server.validationMark();
Mike Yu5daa40d2021-06-10 21:34:32 +0800225 const bool success = DnsTlsTransport::validate(server, server.validationMark());
226 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
227 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800228
Mike Yu5daa40d2021-06-10 21:34:32 +0800229 const bool needs_reeval =
230 this->recordPrivateDnsValidation(identity, netId, success, isRevalidation);
Mike Yu82ae84b2020-12-02 21:04:40 +0800231
Mike Yub601ff72018-11-01 20:07:00 +0800232 if (!needs_reeval) {
233 break;
234 }
235
236 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800237 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800238 std::this_thread::sleep_for(backoff.getNextTimeout());
239 } else {
240 break;
241 }
242 }
243 });
244 validate_thread.detach();
245}
246
Mike Yuad96ef82021-02-20 18:35:14 +0800247void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
Luke Huang2fe9c732021-07-06 01:48:02 +0800248 unsigned netId, bool success) const {
paulhu0664f692020-12-14 16:48:26 +0800249 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Luke Huang2fe9c732021-07-06 01:48:02 +0800250 << netId << " for " << identity.sockaddr.toString() << " with hostname {"
Mike Yuad96ef82021-02-20 18:35:14 +0800251 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800252 // Send a validation event to NetdEventListenerService.
253 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
254 if (listeners.empty()) {
255 LOG(ERROR)
256 << "Validation event not sent since no INetdEventListener receiver is available.";
257 }
258 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800259 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
260 success);
paulhu0664f692020-12-14 16:48:26 +0800261 }
262
263 // Send a validation event to unsolicited event listeners.
264 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
265 const PrivateDnsValidationEventParcel validationEvent = {
266 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800267 .ipAddress = identity.sockaddr.ip().toString(),
268 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800269 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
270 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
271 };
272 for (const auto& it : unsolEventListeners) {
273 it->onPrivateDnsValidationEvent(validationEvent);
274 }
275}
276
Mike Yuad96ef82021-02-20 18:35:14 +0800277bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu5daa40d2021-06-10 21:34:32 +0800278 unsigned netId, bool success,
279 bool isRevalidation) {
Mike Yub601ff72018-11-01 20:07:00 +0800280 constexpr bool NEEDS_REEVALUATION = true;
281 constexpr bool DONT_REEVALUATE = false;
282
283 std::lock_guard guard(mPrivateDnsLock);
284
285 auto netPair = mPrivateDnsTransports.find(netId);
286 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800287 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800288 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800289 return DONT_REEVALUATE;
290 }
291
292 const auto mode = mPrivateDnsModes.find(netId);
293 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800294 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800295 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800296 return DONT_REEVALUATE;
297 }
Mike Yub601ff72018-11-01 20:07:00 +0800298
Mike Yu82ae84b2020-12-02 21:04:40 +0800299 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu5daa40d2021-06-10 21:34:32 +0800300 if (success) {
301 reevaluationStatus = DONT_REEVALUATE;
Mike Yu82ae84b2020-12-02 21:04:40 +0800302 } else if (mode->second == PrivateDnsMode::OFF) {
303 reevaluationStatus = DONT_REEVALUATE;
304 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
305 reevaluationStatus = DONT_REEVALUATE;
306 }
Mike Yub601ff72018-11-01 20:07:00 +0800307
308 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800309 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800310 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800311 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800312 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800313 success = false;
314 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800315 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800316 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
317 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800318 success = false;
319 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800320 }
321
Mike Yu1aede812021-05-11 14:49:30 +0800322 // Send private dns validation result to listeners.
Luke Huang2fe9c732021-07-06 01:48:02 +0800323 if (needReportEvent(netId, identity, success)) {
324 sendPrivateDnsValidationEvent(identity, netId, success);
325 }
Mike Yu1aede812021-05-11 14:49:30 +0800326
Mike Yu5daa40d2021-06-10 21:34:32 +0800327 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800328 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800329 } else {
330 // Validation failure is expected if a user is on a captive portal.
331 // TODO: Trigger a second validation attempt after captive portal login
332 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800333 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
334 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800335 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800336 }
Mike Yu5daa40d2021-06-10 21:34:32 +0800337 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800338
339 return reevaluationStatus;
340}
341
Mike Yufa985f72020-11-23 20:24:21 +0800342void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800343 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800344 const auto result = getPrivateDnsLocked(identity, netId);
345 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800346 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800347 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800348 }
349
Mike Yuad96ef82021-02-20 18:35:14 +0800350 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800351
Mike Yuad96ef82021-02-20 18:35:14 +0800352 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800353 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800354
355 RecordEntry record(netId, identity, state);
356 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800357}
358
Mike Yucf56d232021-04-29 19:37:25 +0800359bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800360 // The server is not expected to be used on the network.
361 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500362
Mike Yuf7717f52020-11-24 17:31:12 +0800363 // The server is newly added.
364 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500365
Mike Yuf7717f52020-11-24 17:31:12 +0800366 // The server has failed at least one validation attempt. Give it another try.
367 if (server.validationState() == Validation::fail) return true;
368
369 // The previous validation result might be unreliable.
370 if (server.validationState() == Validation::success_but_expired) return true;
371
372 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800373}
374
Mike Yucf56d232021-04-29 19:37:25 +0800375base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
376 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800377 std::lock_guard guard(mPrivateDnsLock);
378 return getPrivateDnsLocked(identity, netId);
379}
380
Mike Yucf56d232021-04-29 19:37:25 +0800381base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800382 const ServerIdentity& identity, unsigned netId) {
383 auto netPair = mPrivateDnsTransports.find(netId);
384 if (netPair == mPrivateDnsTransports.end()) {
385 return Errorf("Failed to get private DNS: netId {} not found", netId);
386 }
387
388 auto iter = netPair->second.find(identity);
389 if (iter == netPair->second.end()) {
390 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
391 identity.provider);
392 }
393
Mike Yucf56d232021-04-29 19:37:25 +0800394 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800395}
396
Mike Yua6853e82020-12-11 19:47:06 +0800397void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800398 std::lock_guard guard(mPrivateDnsLock);
399 mObserver = observer;
400}
401
Mike Yu453b5e42021-02-19 20:03:07 +0800402void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800403 Validation validation,
404 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800405 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800406 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800407 }
408}
409
Mike Yu3d5130d2020-12-21 17:57:18 +0800410void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
411 dw.println("PrivateDnsLog:");
412 netdutils::ScopedIndent indentStats(dw);
413
414 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800415 dw.println(fmt::format(
416 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
417 record.netId, record.serverIdentity.sockaddr.toString(),
418 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800419 }
420 dw.blankline();
421}
422
Luke Huang2fe9c732021-07-06 01:48:02 +0800423void PrivateDnsConfiguration::initDoh() {
424 std::lock_guard guard(mPrivateDnsLock);
425 initDohLocked();
426}
427
428void PrivateDnsConfiguration::initDohLocked() {
429 if (mDohDispatcher != nullptr) return;
430 mDohDispatcher = doh_dispatcher_new(
431 [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
432 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
433 net_id, success, ip_addr, host);
434 });
435}
436
437int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
438 const std::vector<std::string>& servers,
439 const std::string& name, const std::string& caCert) {
440 if (servers.empty()) return 0;
441 LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
442 << std::dec << ", " << servers.size() << ", " << name << ")";
443 std::lock_guard guard(mPrivateDnsLock);
444
Luke Huang53d3eb22021-07-19 15:08:56 +0800445 // Sort the input servers to ensure that we could get the server vector at the same order.
446 std::vector<std::string> sortedServers = servers;
447 // Prefer ipv6.
448 std::sort(sortedServers.begin(), sortedServers.end(), [](std::string a, std::string b) {
449 IPAddress ipa = IPAddress::forString(a);
450 IPAddress ipb = IPAddress::forString(b);
451 return ipa > ipb;
452 });
453
Luke Huang2fe9c732021-07-06 01:48:02 +0800454 initDohLocked();
455
456 // TODO: 1. Improve how to choose the server
457 // TODO: 2. Support multiple servers
458 for (const auto& entry : mAvailableDoHProviders) {
Luke Huang53d3eb22021-07-19 15:08:56 +0800459 const auto& doh = entry.getDohIdentity(sortedServers, name);
Luke Huang2fe9c732021-07-06 01:48:02 +0800460 if (!doh.ok()) continue;
461
462 auto it = mDohTracker.find(netId);
463 // Skip if the same server already exists and its status == success.
464 if (it != mDohTracker.end() && it->second == doh.value() &&
465 it->second.status == Validation::success) {
466 return 0;
467 }
468 const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
469 const auto& dohId = dohIt->second;
470
471 RecordEntry record(netId, {netdutils::IPSockAddr::toIPSockAddr(dohId.ipAddr, 443), name},
472 dohId.status);
473 mPrivateDnsLog.push(std::move(record));
474 return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
475 dohId.ipAddr.c_str(), mark, caCert.c_str(), 3000);
476 }
477
478 LOG(INFO) << __func__ << "No suitable DoH server found";
479 return 0;
480}
481
482void PrivateDnsConfiguration::clearDoh(unsigned netId) {
483 LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
484 std::lock_guard guard(mPrivateDnsLock);
485 if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
486 mDohTracker.erase(netId);
487}
488
489ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
490 uint64_t timeoutMs) {
491 {
492 std::lock_guard guard(mPrivateDnsLock);
493 // It's safe because mDohDispatcher won't be deleted after initializing.
494 if (mDohDispatcher == nullptr) return RESULT_CAN_NOT_SEND;
495 }
496 return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
497 answer.size(), timeoutMs);
498}
499
500void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
501 const char* host) {
502 LOG(INFO) << __func__ << netId << ", " << success << ", " << ipAddr << ", " << host;
503 std::lock_guard guard(mPrivateDnsLock);
504 // Update the server status.
505 auto it = mDohTracker.find(netId);
506 if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
507 LOG(WARNING) << __func__ << "obsolete event";
508 return;
509 }
510 Validation status = success ? Validation::success : Validation::fail;
511 it->second.status = status;
512 // Send the events to registered listeners.
513 ServerIdentity identity = {netdutils::IPSockAddr::toIPSockAddr(ipAddr, 443), host};
514 if (needReportEvent(netId, identity, success)) {
515 sendPrivateDnsValidationEvent(identity, netId, success);
516 }
517 // Add log.
518 RecordEntry record(netId, identity, status);
519 mPrivateDnsLog.push(std::move(record));
520}
521
522bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
523 bool success) const {
524 // If the result is success or DoH is not enable, no concern to report the events.
525 if (success || !isDoHEnabled()) return true;
526 // If the result is failure, check another transport's status to determine if we should report
527 // the event.
528 switch (identity.sockaddr.port()) {
529 // DoH
530 case 443: {
531 auto netPair = mPrivateDnsTransports.find(netId);
532 if (netPair == mPrivateDnsTransports.end()) return true;
533 for (const auto& [id, server] : netPair->second) {
534 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
535 (identity.sockaddr.port() != id.sockaddr.port()) &&
536 (server->validationState() == Validation::success)) {
537 LOG(DEBUG) << __func__
538 << "skip reporting DoH validation failure event, server addr: " +
539 identity.sockaddr.ip().toString();
540 return false;
541 }
542 }
543 break;
544 }
545 // DoT
546 case 853: {
547 auto it = mDohTracker.find(netId);
548 if (it == mDohTracker.end()) return true;
549 if (it->second == identity && it->second.status == Validation::success) {
550 LOG(DEBUG) << __func__
551 << "skip reporting DoT validation failure event, server addr: " +
552 identity.sockaddr.ip().toString();
553 return false;
554 }
555 break;
556 }
557 }
558 return true;
559}
560
Mike Yub601ff72018-11-01 20:07:00 +0800561} // namespace net
562} // namespace android