blob: 75dd24fd221fe599e75e23b6cd3ba42b74805c53 [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>
Mike Yu5e406a32021-07-06 21:01:17 +080026#include <android/binder_ibinder.h>
Luke Huang2fe9c732021-07-06 01:48:02 +080027#include <netdutils/Slice.h>
Mike Yu04f1d482019-08-08 11:09:32 +080028#include <netdutils/ThreadUtil.h>
Mike Yub601ff72018-11-01 20:07:00 +080029#include <sys/socket.h>
30
Bernie Innocentiec4219b2019-01-30 11:16:36 +090031#include "DnsTlsTransport.h"
Mike Yu303b0df2018-12-24 17:05:02 +080032#include "ResolverEventReporter.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080033#include "doh.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +090034#include "netd_resolv/resolv.h"
Luke Huang2fe9c732021-07-06 01:48:02 +080035#include "resolv_private.h"
Mike Yu9c720102019-11-14 11:34:33 +080036#include "util.h"
Mike Yub601ff72018-11-01 20:07:00 +080037
paulhu0664f692020-12-14 16:48:26 +080038using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
39using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
Mike Yucb902c92020-05-20 19:26:56 +080040using android::base::StringPrintf;
Luke Huang53d3eb22021-07-19 15:08:56 +080041using android::netdutils::IPAddress;
Mike Yu425d16e2021-05-05 21:40:42 +080042using android::netdutils::IPSockAddr;
Mike Yucb902c92020-05-20 19:26:56 +080043using android::netdutils::setThreadName;
Luke Huang2fe9c732021-07-06 01:48:02 +080044using android::netdutils::Slice;
Mike Yua772c202019-09-23 17:47:21 +080045using std::chrono::milliseconds;
46
Mike Yub601ff72018-11-01 20:07:00 +080047namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080048namespace net {
49
Mike Yub601ff72018-11-01 20:07:00 +080050int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
51 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080052 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080053 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080054 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080055
56 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080057 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080058 for (const auto& s : servers) {
Mike Yu425d16e2021-05-05 21:40:42 +080059 IPAddress ip;
60 if (!IPAddress::forString(s, &ip)) {
61 LOG(WARNING) << "Failed to parse server address (" << s << ")";
Mike Yub601ff72018-11-01 20:07:00 +080062 return -EINVAL;
63 }
Mike Yu425d16e2021-05-05 21:40:42 +080064
65 auto server = std::make_unique<DnsTlsServer>(ip);
Mike Yucf56d232021-04-29 19:37:25 +080066 server->name = name;
67 server->certificate = caCert;
68 server->mark = mark;
69 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080070 }
71
72 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080073 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080074 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080075 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080076 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
77 } else {
78 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
79 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080080 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080081 return 0;
82 }
83
84 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080085 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080086
Mike Yuf7717f52020-11-24 17:31:12 +080087 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +080088 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +080089 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +080090 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +080091 }
92 }
Mike Yu3334a5e2020-11-19 13:33:17 +080093
Mike Yuf7717f52020-11-24 17:31:12 +080094 for (auto& [identity, server] : tracker) {
95 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +080096 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +080097
98 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +080099 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +0800100 updateServerState(identity, Validation::success_but_expired, netId);
101 }
102
Mike Yucf56d232021-04-29 19:37:25 +0800103 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800104 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800105 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800106 }
107 }
Mike Yue655b1d2019-08-28 17:49:59 +0800108
Mike Yu8d9da4a2020-11-09 17:09:14 +0800109 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800110}
111
Mike Yu82ae84b2020-12-02 21:04:40 +0800112PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800113 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800114 std::lock_guard guard(mPrivateDnsLock);
115
116 const auto mode = mPrivateDnsModes.find(netId);
117 if (mode == mPrivateDnsModes.end()) return status;
118 status.mode = mode->second;
119
120 const auto netPair = mPrivateDnsTransports.find(netId);
121 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800122 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800123 if (server->isDot() && server->active()) {
124 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
125 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800126 }
Mike Yucf56d232021-04-29 19:37:25 +0800127 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800128 }
129 }
130
131 return status;
132}
133
Mike Yub601ff72018-11-01 20:07:00 +0800134void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800135 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800136 std::lock_guard guard(mPrivateDnsLock);
137 mPrivateDnsModes.erase(netId);
138 mPrivateDnsTransports.erase(netId);
139}
140
Mike Yu82ae84b2020-12-02 21:04:40 +0800141base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800142 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800143 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800144 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800145
146 // Running revalidation requires to mark the server as in_process, which means the server
147 // won't be used until the validation passes. It's necessary and safe to run revalidation
148 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
149 // all of the private DNS servers are in in_process state.
150 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
151 return Errorf("NetId not found in mPrivateDnsModes");
152 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
153 return Errorf("Private DNS setting is not opportunistic mode");
154 }
155
Mike Yuad96ef82021-02-20 18:35:14 +0800156 auto result = getPrivateDnsLocked(identity, netId);
157 if (!result.ok()) {
158 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800159 }
160
Mike Yucf56d232021-04-29 19:37:25 +0800161 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800162
Mike Yucf56d232021-04-29 19:37:25 +0800163 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800164
Mike Yucf56d232021-04-29 19:37:25 +0800165 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800166 return Errorf("Server validation state mismatched");
167 }
Mike Yue60ab412020-12-01 17:56:12 +0800168
169 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
170 // This is to protect validation from running on unexpected marks.
171 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800172 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800173
174 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800175 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800176 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800177}
178
Mike Yuad96ef82021-02-20 18:35:14 +0800179void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
180 bool isRevalidation) {
181 // This ensures that the thread sends probe at least once in case
182 // the server is removed before the thread starts running.
183 // TODO: consider moving these code to the thread.
184 const auto result = getPrivateDnsLocked(identity, netId);
185 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800186 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800187
188 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
Mike Yucb902c92020-05-20 19:26:56 +0800189 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800190
Mike Yub601ff72018-11-01 20:07:00 +0800191 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
192 //
193 // Start with a 1 minute delay and backoff to once per hour.
194 //
195 // Assumptions:
196 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
197 // [2] Network typically provision clients with <=4 nameservers.
198 // [3] Average month has 30 days.
199 //
200 // Each validation pass in a given hour is ~1.2MB of data. And 24
201 // such validation passes per day is about ~30MB per month, in the
202 // worst case. Otherwise, this will cost ~600 SYNs per month
203 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800204 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800205
Mike Yu7135fbf2021-06-10 20:27:36 +0800206 while (true) {
Mike Yub601ff72018-11-01 20:07:00 +0800207 // ::validate() is a blocking call that performs network operations.
208 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800209 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800210 << std::hex << server.validationMark();
Mike Yu5daa40d2021-06-10 21:34:32 +0800211 const bool success = DnsTlsTransport::validate(server, server.validationMark());
212 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
213 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800214
Mike Yu5daa40d2021-06-10 21:34:32 +0800215 const bool needs_reeval =
216 this->recordPrivateDnsValidation(identity, netId, success, isRevalidation);
Mike Yu82ae84b2020-12-02 21:04:40 +0800217
Mike Yub601ff72018-11-01 20:07:00 +0800218 if (!needs_reeval) {
219 break;
220 }
221
222 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800223 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800224 std::this_thread::sleep_for(backoff.getNextTimeout());
225 } else {
226 break;
227 }
228 }
229 });
230 validate_thread.detach();
231}
232
Mike Yuad96ef82021-02-20 18:35:14 +0800233void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
Luke Huang2fe9c732021-07-06 01:48:02 +0800234 unsigned netId, bool success) const {
paulhu0664f692020-12-14 16:48:26 +0800235 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Luke Huang2fe9c732021-07-06 01:48:02 +0800236 << netId << " for " << identity.sockaddr.toString() << " with hostname {"
Mike Yuad96ef82021-02-20 18:35:14 +0800237 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800238 // Send a validation event to NetdEventListenerService.
239 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
240 if (listeners.empty()) {
241 LOG(ERROR)
242 << "Validation event not sent since no INetdEventListener receiver is available.";
243 }
244 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800245 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
246 success);
paulhu0664f692020-12-14 16:48:26 +0800247 }
248
249 // Send a validation event to unsolicited event listeners.
250 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
251 const PrivateDnsValidationEventParcel validationEvent = {
252 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800253 .ipAddress = identity.sockaddr.ip().toString(),
254 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800255 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
256 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
257 };
258 for (const auto& it : unsolEventListeners) {
259 it->onPrivateDnsValidationEvent(validationEvent);
260 }
261}
262
Mike Yuad96ef82021-02-20 18:35:14 +0800263bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu5daa40d2021-06-10 21:34:32 +0800264 unsigned netId, bool success,
265 bool isRevalidation) {
Mike Yub601ff72018-11-01 20:07:00 +0800266 constexpr bool NEEDS_REEVALUATION = true;
267 constexpr bool DONT_REEVALUATE = false;
268
269 std::lock_guard guard(mPrivateDnsLock);
270
271 auto netPair = mPrivateDnsTransports.find(netId);
272 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800273 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800274 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800275 return DONT_REEVALUATE;
276 }
277
278 const auto mode = mPrivateDnsModes.find(netId);
279 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800280 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800281 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800282 return DONT_REEVALUATE;
283 }
Mike Yub601ff72018-11-01 20:07:00 +0800284
Mike Yu82ae84b2020-12-02 21:04:40 +0800285 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu5daa40d2021-06-10 21:34:32 +0800286 if (success) {
287 reevaluationStatus = DONT_REEVALUATE;
Mike Yu82ae84b2020-12-02 21:04:40 +0800288 } else if (mode->second == PrivateDnsMode::OFF) {
289 reevaluationStatus = DONT_REEVALUATE;
290 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
291 reevaluationStatus = DONT_REEVALUATE;
292 }
Mike Yub601ff72018-11-01 20:07:00 +0800293
294 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800295 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800296 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800297 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800298 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800299 success = false;
300 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800301 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800302 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
303 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800304 success = false;
305 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800306 }
307
Mike Yu1aede812021-05-11 14:49:30 +0800308 // Send private dns validation result to listeners.
Luke Huang2fe9c732021-07-06 01:48:02 +0800309 if (needReportEvent(netId, identity, success)) {
310 sendPrivateDnsValidationEvent(identity, netId, success);
311 }
Mike Yu1aede812021-05-11 14:49:30 +0800312
Mike Yu5daa40d2021-06-10 21:34:32 +0800313 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800314 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800315 } else {
316 // Validation failure is expected if a user is on a captive portal.
317 // TODO: Trigger a second validation attempt after captive portal login
318 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800319 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
320 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800321 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800322 }
Mike Yu5daa40d2021-06-10 21:34:32 +0800323 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800324
325 return reevaluationStatus;
326}
327
Mike Yufa985f72020-11-23 20:24:21 +0800328void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800329 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800330 const auto result = getPrivateDnsLocked(identity, netId);
331 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800332 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800333 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800334 }
335
Mike Yuad96ef82021-02-20 18:35:14 +0800336 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800337
Mike Yuad96ef82021-02-20 18:35:14 +0800338 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800339 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800340
341 RecordEntry record(netId, identity, state);
342 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800343}
344
Mike Yucf56d232021-04-29 19:37:25 +0800345bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800346 // The server is not expected to be used on the network.
347 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500348
Mike Yuf7717f52020-11-24 17:31:12 +0800349 // The server is newly added.
350 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500351
Mike Yuf7717f52020-11-24 17:31:12 +0800352 // The server has failed at least one validation attempt. Give it another try.
353 if (server.validationState() == Validation::fail) return true;
354
355 // The previous validation result might be unreliable.
356 if (server.validationState() == Validation::success_but_expired) return true;
357
358 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800359}
360
Mike Yucf56d232021-04-29 19:37:25 +0800361base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
362 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800363 std::lock_guard guard(mPrivateDnsLock);
364 return getPrivateDnsLocked(identity, netId);
365}
366
Mike Yucf56d232021-04-29 19:37:25 +0800367base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800368 const ServerIdentity& identity, unsigned netId) {
369 auto netPair = mPrivateDnsTransports.find(netId);
370 if (netPair == mPrivateDnsTransports.end()) {
371 return Errorf("Failed to get private DNS: netId {} not found", netId);
372 }
373
374 auto iter = netPair->second.find(identity);
375 if (iter == netPair->second.end()) {
376 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
377 identity.provider);
378 }
379
Mike Yucf56d232021-04-29 19:37:25 +0800380 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800381}
382
Mike Yua6853e82020-12-11 19:47:06 +0800383void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800384 std::lock_guard guard(mPrivateDnsLock);
385 mObserver = observer;
386}
387
Mike Yu453b5e42021-02-19 20:03:07 +0800388void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800389 Validation validation,
390 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800391 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800392 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800393 }
394}
395
Mike Yu3d5130d2020-12-21 17:57:18 +0800396void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
397 dw.println("PrivateDnsLog:");
398 netdutils::ScopedIndent indentStats(dw);
399
400 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800401 dw.println(fmt::format(
402 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
403 record.netId, record.serverIdentity.sockaddr.toString(),
404 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800405 }
406 dw.blankline();
407}
408
Luke Huang2fe9c732021-07-06 01:48:02 +0800409void PrivateDnsConfiguration::initDoh() {
410 std::lock_guard guard(mPrivateDnsLock);
411 initDohLocked();
412}
413
414void PrivateDnsConfiguration::initDohLocked() {
415 if (mDohDispatcher != nullptr) return;
416 mDohDispatcher = doh_dispatcher_new(
417 [](uint32_t net_id, bool success, const char* ip_addr, const char* host) {
418 android::net::PrivateDnsConfiguration::getInstance().onDohStatusUpdate(
419 net_id, success, ip_addr, host);
420 });
421}
422
423int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
424 const std::vector<std::string>& servers,
425 const std::string& name, const std::string& caCert) {
426 if (servers.empty()) return 0;
427 LOG(DEBUG) << "PrivateDnsConfiguration::setDoh(" << netId << ", 0x" << std::hex << mark
428 << std::dec << ", " << servers.size() << ", " << name << ")";
429 std::lock_guard guard(mPrivateDnsLock);
430
Luke Huang53d3eb22021-07-19 15:08:56 +0800431 // Sort the input servers to ensure that we could get the server vector at the same order.
432 std::vector<std::string> sortedServers = servers;
433 // Prefer ipv6.
434 std::sort(sortedServers.begin(), sortedServers.end(), [](std::string a, std::string b) {
435 IPAddress ipa = IPAddress::forString(a);
436 IPAddress ipb = IPAddress::forString(b);
437 return ipa > ipb;
438 });
439
Luke Huang2fe9c732021-07-06 01:48:02 +0800440 initDohLocked();
441
442 // TODO: 1. Improve how to choose the server
443 // TODO: 2. Support multiple servers
444 for (const auto& entry : mAvailableDoHProviders) {
Luke Huang53d3eb22021-07-19 15:08:56 +0800445 const auto& doh = entry.getDohIdentity(sortedServers, name);
Luke Huang2fe9c732021-07-06 01:48:02 +0800446 if (!doh.ok()) continue;
447
Mike Yu5e406a32021-07-06 21:01:17 +0800448 // The internal tests are supposed to have root permission.
449 if (entry.forTesting && AIBinder_getCallingUid() != AID_ROOT) continue;
450
Luke Huang2fe9c732021-07-06 01:48:02 +0800451 auto it = mDohTracker.find(netId);
452 // Skip if the same server already exists and its status == success.
453 if (it != mDohTracker.end() && it->second == doh.value() &&
454 it->second.status == Validation::success) {
455 return 0;
456 }
457 const auto& [dohIt, _] = mDohTracker.insert_or_assign(netId, doh.value());
458 const auto& dohId = dohIt->second;
459
460 RecordEntry record(netId, {netdutils::IPSockAddr::toIPSockAddr(dohId.ipAddr, 443), name},
461 dohId.status);
462 mPrivateDnsLog.push(std::move(record));
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000463 LOG(INFO) << __func__ << ": Upgrading server to DoH: " << name;
464
Luke Huangdce6cbf2021-08-13 14:53:37 +0800465 int probeTimeout = Experiments::getInstance()->getFlag("doh_probe_timeout_ms",
466 kDohProbeDefaultTimeoutMs);
467 if (probeTimeout < 1000) {
468 probeTimeout = 1000;
469 }
Luke Huang2fe9c732021-07-06 01:48:02 +0800470 return doh_net_new(mDohDispatcher, netId, dohId.httpsTemplate.c_str(), dohId.host.c_str(),
Luke Huangdce6cbf2021-08-13 14:53:37 +0800471 dohId.ipAddr.c_str(), mark, caCert.c_str(), probeTimeout);
Luke Huang2fe9c732021-07-06 01:48:02 +0800472 }
473
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000474 LOG(INFO) << __func__ << ": No suitable DoH server found";
Luke Huang2fe9c732021-07-06 01:48:02 +0800475 return 0;
476}
477
478void PrivateDnsConfiguration::clearDoh(unsigned netId) {
479 LOG(DEBUG) << "PrivateDnsConfiguration::clearDoh (" << netId << ")";
480 std::lock_guard guard(mPrivateDnsLock);
481 if (mDohDispatcher != nullptr) doh_net_delete(mDohDispatcher, netId);
482 mDohTracker.erase(netId);
483}
484
485ssize_t PrivateDnsConfiguration::dohQuery(unsigned netId, const Slice query, const Slice answer,
486 uint64_t timeoutMs) {
487 {
488 std::lock_guard guard(mPrivateDnsLock);
489 // It's safe because mDohDispatcher won't be deleted after initializing.
490 if (mDohDispatcher == nullptr) return RESULT_CAN_NOT_SEND;
491 }
492 return doh_query(mDohDispatcher, netId, query.base(), query.size(), answer.base(),
493 answer.size(), timeoutMs);
494}
495
496void PrivateDnsConfiguration::onDohStatusUpdate(uint32_t netId, bool success, const char* ipAddr,
497 const char* host) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000498 LOG(INFO) << __func__ << ": " << netId << ", " << success << ", " << ipAddr << ", " << host;
Luke Huang2fe9c732021-07-06 01:48:02 +0800499 std::lock_guard guard(mPrivateDnsLock);
500 // Update the server status.
501 auto it = mDohTracker.find(netId);
502 if (it == mDohTracker.end() || (it->second.ipAddr != ipAddr && it->second.host != host)) {
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000503 LOG(WARNING) << __func__ << ": Obsolete event";
Luke Huang2fe9c732021-07-06 01:48:02 +0800504 return;
505 }
506 Validation status = success ? Validation::success : Validation::fail;
507 it->second.status = status;
508 // Send the events to registered listeners.
509 ServerIdentity identity = {netdutils::IPSockAddr::toIPSockAddr(ipAddr, 443), host};
510 if (needReportEvent(netId, identity, success)) {
511 sendPrivateDnsValidationEvent(identity, netId, success);
512 }
513 // Add log.
514 RecordEntry record(netId, identity, status);
515 mPrivateDnsLog.push(std::move(record));
516}
517
518bool PrivateDnsConfiguration::needReportEvent(uint32_t netId, ServerIdentity identity,
519 bool success) const {
520 // If the result is success or DoH is not enable, no concern to report the events.
521 if (success || !isDoHEnabled()) return true;
522 // If the result is failure, check another transport's status to determine if we should report
523 // the event.
524 switch (identity.sockaddr.port()) {
525 // DoH
526 case 443: {
527 auto netPair = mPrivateDnsTransports.find(netId);
528 if (netPair == mPrivateDnsTransports.end()) return true;
529 for (const auto& [id, server] : netPair->second) {
530 if ((identity.sockaddr.ip() == id.sockaddr.ip()) &&
531 (identity.sockaddr.port() != id.sockaddr.port()) &&
532 (server->validationState() == Validation::success)) {
533 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000534 << ": Skip reporting DoH validation failure event, server addr: "
535 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800536 return false;
537 }
538 }
539 break;
540 }
541 // DoT
542 case 853: {
543 auto it = mDohTracker.find(netId);
544 if (it == mDohTracker.end()) return true;
545 if (it->second == identity && it->second.status == Validation::success) {
546 LOG(DEBUG) << __func__
Bernie Innocenti44cb6082021-07-29 11:58:11 +0000547 << ": Skip reporting DoT validation failure event, server addr: "
548 << identity.sockaddr.ip().toString();
Luke Huang2fe9c732021-07-06 01:48:02 +0800549 return false;
550 }
551 break;
552 }
553 }
554 return true;
555}
556
Mike Yub601ff72018-11-01 20:07:00 +0800557} // namespace net
558} // namespace android