blob: a8a2de57ee39df8247f6ea95d491d48d0ea6c8a8 [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 Yu425d16e2021-05-05 21:40:42 +080041using android::netdutils::IPSockAddr;
Mike Yucb902c92020-05-20 19:26:56 +080042using android::netdutils::setThreadName;
Luke Huang2fe9c732021-07-06 01:48:02 +080043using android::netdutils::Slice;
Mike Yua772c202019-09-23 17:47:21 +080044using std::chrono::milliseconds;
45
Mike Yub601ff72018-11-01 20:07:00 +080046namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080047namespace net {
48
Mike Yub601ff72018-11-01 20:07:00 +080049int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
50 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080051 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080052 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080053 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080054
55 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080056 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080057 for (const auto& s : servers) {
Mike Yu425d16e2021-05-05 21:40:42 +080058 IPAddress ip;
59 if (!IPAddress::forString(s, &ip)) {
60 LOG(WARNING) << "Failed to parse server address (" << s << ")";
Mike Yub601ff72018-11-01 20:07:00 +080061 return -EINVAL;
62 }
Mike Yu425d16e2021-05-05 21:40:42 +080063
64 auto server = std::make_unique<DnsTlsServer>(ip);
Mike Yucf56d232021-04-29 19:37:25 +080065 server->name = name;
66 server->certificate = caCert;
67 server->mark = mark;
68 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080069 }
70
71 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080072 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080073 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080074 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080075 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
76 } else {
77 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
78 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080079 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080080 return 0;
81 }
82
83 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080084 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080085
Mike Yuf7717f52020-11-24 17:31:12 +080086 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +080087 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +080088 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +080089 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +080090 }
91 }
Mike Yu3334a5e2020-11-19 13:33:17 +080092
Mike Yuf7717f52020-11-24 17:31:12 +080093 for (auto& [identity, server] : tracker) {
94 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +080095 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +080096
97 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +080098 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +080099 updateServerState(identity, Validation::success_but_expired, netId);
100 }
101
Mike Yucf56d232021-04-29 19:37:25 +0800102 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800103 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800104 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800105 }
106 }
Mike Yue655b1d2019-08-28 17:49:59 +0800107
Mike Yu8d9da4a2020-11-09 17:09:14 +0800108 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800109}
110
Mike Yu82ae84b2020-12-02 21:04:40 +0800111PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800112 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800113 std::lock_guard guard(mPrivateDnsLock);
114
115 const auto mode = mPrivateDnsModes.find(netId);
116 if (mode == mPrivateDnsModes.end()) return status;
117 status.mode = mode->second;
118
119 const auto netPair = mPrivateDnsTransports.find(netId);
120 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800121 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800122 if (server->isDot() && server->active()) {
123 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
124 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800125 }
Mike Yucf56d232021-04-29 19:37:25 +0800126 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800127 }
128 }
129
130 return status;
131}
132
Mike Yub601ff72018-11-01 20:07:00 +0800133void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800134 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800135 std::lock_guard guard(mPrivateDnsLock);
136 mPrivateDnsModes.erase(netId);
137 mPrivateDnsTransports.erase(netId);
138}
139
Mike Yu82ae84b2020-12-02 21:04:40 +0800140base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800141 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800142 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800143 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800144
145 // Running revalidation requires to mark the server as in_process, which means the server
146 // won't be used until the validation passes. It's necessary and safe to run revalidation
147 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
148 // all of the private DNS servers are in in_process state.
149 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
150 return Errorf("NetId not found in mPrivateDnsModes");
151 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
152 return Errorf("Private DNS setting is not opportunistic mode");
153 }
154
Mike Yuad96ef82021-02-20 18:35:14 +0800155 auto result = getPrivateDnsLocked(identity, netId);
156 if (!result.ok()) {
157 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800158 }
159
Mike Yucf56d232021-04-29 19:37:25 +0800160 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800161
Mike Yucf56d232021-04-29 19:37:25 +0800162 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800163
Mike Yucf56d232021-04-29 19:37:25 +0800164 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800165 return Errorf("Server validation state mismatched");
166 }
Mike Yue60ab412020-12-01 17:56:12 +0800167
168 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
169 // This is to protect validation from running on unexpected marks.
170 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800171 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800172
173 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800174 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800175 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800176}
177
Mike Yuad96ef82021-02-20 18:35:14 +0800178void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
179 bool isRevalidation) {
180 // This ensures that the thread sends probe at least once in case
181 // the server is removed before the thread starts running.
182 // TODO: consider moving these code to the thread.
183 const auto result = getPrivateDnsLocked(identity, netId);
184 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800185 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800186
187 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
Mike Yucb902c92020-05-20 19:26:56 +0800188 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800189
Mike Yub601ff72018-11-01 20:07:00 +0800190 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
191 //
192 // Start with a 1 minute delay and backoff to once per hour.
193 //
194 // Assumptions:
195 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
196 // [2] Network typically provision clients with <=4 nameservers.
197 // [3] Average month has 30 days.
198 //
199 // Each validation pass in a given hour is ~1.2MB of data. And 24
200 // such validation passes per day is about ~30MB per month, in the
201 // worst case. Otherwise, this will cost ~600 SYNs per month
202 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800203 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800204
Mike Yu7135fbf2021-06-10 20:27:36 +0800205 while (true) {
Mike Yub601ff72018-11-01 20:07:00 +0800206 // ::validate() is a blocking call that performs network operations.
207 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800208 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800209 << std::hex << server.validationMark();
Mike Yu5daa40d2021-06-10 21:34:32 +0800210 const bool success = DnsTlsTransport::validate(server, server.validationMark());
211 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
212 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800213
Mike Yu5daa40d2021-06-10 21:34:32 +0800214 const bool needs_reeval =
215 this->recordPrivateDnsValidation(identity, netId, success, isRevalidation);
Mike Yu82ae84b2020-12-02 21:04:40 +0800216
Mike Yub601ff72018-11-01 20:07:00 +0800217 if (!needs_reeval) {
218 break;
219 }
220
221 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800222 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800223 std::this_thread::sleep_for(backoff.getNextTimeout());
224 } else {
225 break;
226 }
227 }
228 });
229 validate_thread.detach();
230}
231
Mike Yuad96ef82021-02-20 18:35:14 +0800232void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
Luke Huang2fe9c732021-07-06 01:48:02 +0800233 unsigned netId, bool success) const {
paulhu0664f692020-12-14 16:48:26 +0800234 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Luke Huang2fe9c732021-07-06 01:48:02 +0800235 << netId << " for " << identity.sockaddr.toString() << " with hostname {"
Mike Yuad96ef82021-02-20 18:35:14 +0800236 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800237 // Send a validation event to NetdEventListenerService.
238 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
239 if (listeners.empty()) {
240 LOG(ERROR)
241 << "Validation event not sent since no INetdEventListener receiver is available.";
242 }
243 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800244 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
245 success);
paulhu0664f692020-12-14 16:48:26 +0800246 }
247
248 // Send a validation event to unsolicited event listeners.
249 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
250 const PrivateDnsValidationEventParcel validationEvent = {
251 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800252 .ipAddress = identity.sockaddr.ip().toString(),
253 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800254 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
255 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
256 };
257 for (const auto& it : unsolEventListeners) {
258 it->onPrivateDnsValidationEvent(validationEvent);
259 }
260}
261
Mike Yuad96ef82021-02-20 18:35:14 +0800262bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu5daa40d2021-06-10 21:34:32 +0800263 unsigned netId, bool success,
264 bool isRevalidation) {
Mike Yub601ff72018-11-01 20:07:00 +0800265 constexpr bool NEEDS_REEVALUATION = true;
266 constexpr bool DONT_REEVALUATE = false;
267
268 std::lock_guard guard(mPrivateDnsLock);
269
270 auto netPair = mPrivateDnsTransports.find(netId);
271 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800272 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800273 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800274 return DONT_REEVALUATE;
275 }
276
277 const auto mode = mPrivateDnsModes.find(netId);
278 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800279 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800280 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800281 return DONT_REEVALUATE;
282 }
Mike Yub601ff72018-11-01 20:07:00 +0800283
Mike Yu82ae84b2020-12-02 21:04:40 +0800284 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu5daa40d2021-06-10 21:34:32 +0800285 if (success) {
286 reevaluationStatus = DONT_REEVALUATE;
Mike Yu82ae84b2020-12-02 21:04:40 +0800287 } else if (mode->second == PrivateDnsMode::OFF) {
288 reevaluationStatus = DONT_REEVALUATE;
289 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
290 reevaluationStatus = DONT_REEVALUATE;
291 }
Mike Yub601ff72018-11-01 20:07:00 +0800292
293 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800294 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800295 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800296 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800297 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800298 success = false;
299 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800300 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800301 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
302 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800303 success = false;
304 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800305 }
306
Mike Yu1aede812021-05-11 14:49:30 +0800307 // Send private dns validation result to listeners.
Luke Huang2fe9c732021-07-06 01:48:02 +0800308 if (needReportEvent(netId, identity, success)) {
309 sendPrivateDnsValidationEvent(identity, netId, success);
310 }
Mike Yu1aede812021-05-11 14:49:30 +0800311
Mike Yu5daa40d2021-06-10 21:34:32 +0800312 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800313 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800314 } else {
315 // Validation failure is expected if a user is on a captive portal.
316 // TODO: Trigger a second validation attempt after captive portal login
317 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800318 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
319 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800320 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800321 }
Mike Yu5daa40d2021-06-10 21:34:32 +0800322 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800323
324 return reevaluationStatus;
325}
326
Mike Yufa985f72020-11-23 20:24:21 +0800327void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800328 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800329 const auto result = getPrivateDnsLocked(identity, netId);
330 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800331 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800332 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800333 }
334
Mike Yuad96ef82021-02-20 18:35:14 +0800335 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800336
Mike Yuad96ef82021-02-20 18:35:14 +0800337 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800338 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800339
340 RecordEntry record(netId, identity, state);
341 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800342}
343
Mike Yucf56d232021-04-29 19:37:25 +0800344bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800345 // The server is not expected to be used on the network.
346 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500347
Mike Yuf7717f52020-11-24 17:31:12 +0800348 // The server is newly added.
349 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500350
Mike Yuf7717f52020-11-24 17:31:12 +0800351 // The server has failed at least one validation attempt. Give it another try.
352 if (server.validationState() == Validation::fail) return true;
353
354 // The previous validation result might be unreliable.
355 if (server.validationState() == Validation::success_but_expired) return true;
356
357 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800358}
359
Mike Yucf56d232021-04-29 19:37:25 +0800360base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
361 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800362 std::lock_guard guard(mPrivateDnsLock);
363 return getPrivateDnsLocked(identity, netId);
364}
365
Mike Yucf56d232021-04-29 19:37:25 +0800366base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800367 const ServerIdentity& identity, unsigned netId) {
368 auto netPair = mPrivateDnsTransports.find(netId);
369 if (netPair == mPrivateDnsTransports.end()) {
370 return Errorf("Failed to get private DNS: netId {} not found", netId);
371 }
372
373 auto iter = netPair->second.find(identity);
374 if (iter == netPair->second.end()) {
375 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
376 identity.provider);
377 }
378
Mike Yucf56d232021-04-29 19:37:25 +0800379 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800380}
381
Mike Yua6853e82020-12-11 19:47:06 +0800382void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800383 std::lock_guard guard(mPrivateDnsLock);
384 mObserver = observer;
385}
386
Mike Yu453b5e42021-02-19 20:03:07 +0800387void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800388 Validation validation,
389 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800390 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800391 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800392 }
393}
394
Mike Yu3d5130d2020-12-21 17:57:18 +0800395void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
396 dw.println("PrivateDnsLog:");
397 netdutils::ScopedIndent indentStats(dw);
398
399 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800400 dw.println(fmt::format(
401 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
402 record.netId, record.serverIdentity.sockaddr.toString(),
403 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800404 }
405 dw.blankline();
406}
407
Luke Huang2fe9c732021-07-06 01:48:02 +0800408void PrivateDnsConfiguration::initDoh() {
409 std::lock_guard guard(mPrivateDnsLock);
410 initDohLocked();
411}
412
413void PrivateDnsConfiguration::initDohLocked() {
414 if (mDohDispatcher != nullptr) return;
415 mDohDispatcher = doh_dispatcher_new(
416 [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
417 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
418 net_id, success, ip_addr, host);
419 });
420}
421
422int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
423 const std::vector<std::string>& servers,
424 const std::string& name, const std::string& caCert) {
425 if (servers.empty()) return 0;
426 LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
427 << std::dec << ", " << servers.size() << ", " << name << ")";
428 std::lock_guard guard(mPrivateDnsLock);
429
Luke Huang53d3eb22021-07-19 15:08:56 +0800430 // Sort the input servers to ensure that we could get the server vector at the same order.
431 std::vector<std::string> sortedServers = servers;
432 // Prefer ipv6.
433 std::sort(sortedServers.begin(), sortedServers.end(), [](std::string a, std::string b) {
434 IPAddress ipa = IPAddress::forString(a);
435 IPAddress ipb = IPAddress::forString(b);
436 return ipa > ipb;
437 });
438
Luke Huang2fe9c732021-07-06 01:48:02 +0800439 initDohLocked();
440
441 // TODO: 1. Improve how to choose the server
442 // TODO: 2. Support multiple servers
443 for (const auto& entry : mAvailableDoHProviders) {
Luke Huang53d3eb22021-07-19 15:08:56 +0800444 const auto& doh = entry.getDohIdentity(sortedServers, name);
Luke Huang2fe9c732021-07-06 01:48:02 +0800445 if (!doh.ok()) continue;
446
447 auto it = mDohTracker.find(netId);
448 // Skip if the same server already exists and its status == success.
449 if (it != mDohTracker.end() && it->second == doh.value() &&
450 it->second.status == Validation::success) {
451 return 0;
452 }
453 const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
454 const auto& dohId = dohIt->second;
455
456 RecordEntry record(netId, {netdutils::IPSockAddr::toIPSockAddr(dohId.ipAddr, 443), name},
457 dohId.status);
458 mPrivateDnsLog.push(std::move(record));
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000459 LOG(INFO) << __func__ << ": Upgrading server to DoH: " << name;
460
Luke Huang2fe9c732021-07-06 01:48:02 +0800461 return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
462 dohId.ipAddr.c_str(), mark, caCert.c_str(), 3000);
463 }
464
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000465 LOG(INFO) << __func__ << ": No suitable DoH server found";
Luke Huang2fe9c732021-07-06 01:48:02 +0800466 return 0;
467}
468
469void PrivateDnsConfiguration::clearDoh(unsigned netId) {
470 LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
471 std::lock_guard guard(mPrivateDnsLock);
472 if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
473 mDohTracker.erase(netId);
474}
475
476ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
477 uint64_t timeoutMs) {
478 {
479 std::lock_guard guard(mPrivateDnsLock);
480 // It's safe because mDohDispatcher won't be deleted after initializing.
481 if (mDohDispatcher == nullptr) return RESULT_CAN_NOT_SEND;
482 }
483 return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
484 answer.size(), timeoutMs);
485}
486
487void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
488 const char* host) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000489 LOG(INFO) << __func__ << ": " << netId << ", " << success << ", " << ipAddr << ", " << host;
Luke Huang2fe9c732021-07-06 01:48:02 +0800490 std::lock_guard guard(mPrivateDnsLock);
491 // Update the server status.
492 auto it = mDohTracker.find(netId);
493 if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000494 LOG(WARNING) << __func__ << ": Obsolete event";
Luke Huang2fe9c732021-07-06 01:48:02 +0800495 return;
496 }
497 Validation status = success ? Validation::success : Validation::fail;
498 it->second.status = status;
499 // Send the events to registered listeners.
500 ServerIdentity identity = {netdutils::IPSockAddr::toIPSockAddr(ipAddr, 443), host};
501 if (needReportEvent(netId, identity, success)) {
502 sendPrivateDnsValidationEvent(identity, netId, success);
503 }
504 // Add log.
505 RecordEntry record(netId, identity, status);
506 mPrivateDnsLog.push(std::move(record));
507}
508
509bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
510 bool success) const {
511 // If the result is success or DoH is not enable, no concern to report the events.
512 if (success || !isDoHEnabled()) return true;
513 // If the result is failure, check another transport's status to determine if we should report
514 // the event.
515 switch (identity.sockaddr.port()) {
516 // DoH
517 case 443: {
518 auto netPair = mPrivateDnsTransports.find(netId);
519 if (netPair == mPrivateDnsTransports.end()) return true;
520 for (const auto& [id, server] : netPair->second) {
521 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
522 (identity.sockaddr.port() != id.sockaddr.port()) &&
523 (server->validationState() == Validation::success)) {
524 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000525 << ": Skip reporting DoH validation failure event, server addr: "
526 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800527 return false;
528 }
529 }
530 break;
531 }
532 // DoT
533 case 853: {
534 auto it = mDohTracker.find(netId);
535 if (it == mDohTracker.end()) return true;
536 if (it->second == identity && it->second.status == Validation::success) {
537 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000538 << ": Skip reporting DoT validation failure event, server addr: "
539 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800540 return false;
541 }
542 break;
543 }
544 }
545 return true;
546}
547
Mike Yub601ff72018-11-01 20:07:00 +0800548} // namespace net
549} // namespace android