blob: 43596bbab8f02892c9147e858933a84613b7a683 [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
chenbruceaff85842019-05-31 15:46:42 +080021#include <android-base/logging.h>
Mike Yu04f1d482019-08-08 11:09:32 +080022#include <android-base/stringprintf.h>
Mike Yub601ff72018-11-01 20:07:00 +080023#include <netdb.h>
Mike Yu04f1d482019-08-08 11:09:32 +080024#include <netdutils/ThreadUtil.h>
Mike Yub601ff72018-11-01 20:07:00 +080025#include <sys/socket.h>
26
Bernie Innocentiec4219b2019-01-30 11:16:36 +090027#include "DnsTlsTransport.h"
Mike Yu303b0df2018-12-24 17:05:02 +080028#include "ResolverEventReporter.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +090029#include "netd_resolv/resolv.h"
Mike Yub601ff72018-11-01 20:07:00 +080030#include "netdutils/BackoffSequence.h"
Mike Yu9c720102019-11-14 11:34:33 +080031#include "util.h"
Mike Yub601ff72018-11-01 20:07:00 +080032
Mike Yucb902c92020-05-20 19:26:56 +080033using android::base::StringPrintf;
34using android::netdutils::setThreadName;
Mike Yua772c202019-09-23 17:47:21 +080035using std::chrono::milliseconds;
36
Mike Yub601ff72018-11-01 20:07:00 +080037namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080038namespace net {
39
40std::string addrToString(const sockaddr_storage* addr) {
41 char out[INET6_ADDRSTRLEN] = {0};
42 getnameinfo((const sockaddr*) addr, sizeof(sockaddr_storage), out, INET6_ADDRSTRLEN, nullptr, 0,
43 NI_NUMERICHOST);
44 return std::string(out);
45}
46
47bool parseServer(const char* server, sockaddr_storage* parsed) {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -070048 addrinfo hints = {
49 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
50 .ai_family = AF_UNSPEC,
51 };
Mike Yub601ff72018-11-01 20:07:00 +080052 addrinfo* res;
53
54 int err = getaddrinfo(server, "853", &hints, &res);
55 if (err != 0) {
chenbruceaff85842019-05-31 15:46:42 +080056 LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
Mike Yub601ff72018-11-01 20:07:00 +080057 return false;
58 }
59
60 memcpy(parsed, res->ai_addr, res->ai_addrlen);
61 freeaddrinfo(res);
62 return true;
63}
64
Mike Yub601ff72018-11-01 20:07:00 +080065int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
66 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080067 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080068 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080069 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080070
71 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080072 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080073 for (const auto& s : servers) {
Mike Yub601ff72018-11-01 20:07:00 +080074 sockaddr_storage parsed;
Mike Yu40e67072019-10-09 21:14:09 +080075 if (!parseServer(s.c_str(), &parsed)) {
Mike Yub601ff72018-11-01 20:07:00 +080076 return -EINVAL;
77 }
78 DnsTlsServer server(parsed);
79 server.name = name;
waynema0e73c2e2019-07-31 15:04:08 +080080 server.certificate = caCert;
Mike Yufa985f72020-11-23 20:24:21 +080081 tmp[ServerIdentity(server)] = server;
Mike Yub601ff72018-11-01 20:07:00 +080082 }
83
84 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080085 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080086 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080087 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080088 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
89 } else {
90 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
91 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080092 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080093 return 0;
94 }
95
96 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080097 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080098
Mike Yuf7717f52020-11-24 17:31:12 +080099 // Add the servers if not contained in tracker.
Mike Yufa985f72020-11-23 20:24:21 +0800100 for (const auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +0800101 if (tracker.find(identity) == tracker.end()) {
102 tracker[identity] = server;
103 }
104 }
Mike Yu3334a5e2020-11-19 13:33:17 +0800105
Mike Yuf7717f52020-11-24 17:31:12 +0800106 for (auto& [identity, server] : tracker) {
107 const bool active = tmp.find(identity) != tmp.end();
108 server.setActive(active);
109
110 // For simplicity, deem the validation result of inactive servers as unreliable.
111 if (!server.active() && server.validationState() == Validation::success) {
112 updateServerState(identity, Validation::success_but_expired, netId);
113 }
114
115 if (needsValidation(server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800116 updateServerState(identity, Validation::in_process, netId);
Mike Yu3334a5e2020-11-19 13:33:17 +0800117 startValidation(server, netId, mark);
Mike Yub601ff72018-11-01 20:07:00 +0800118 }
119 }
Mike Yue655b1d2019-08-28 17:49:59 +0800120
Mike Yu8d9da4a2020-11-09 17:09:14 +0800121 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800122}
123
124PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) {
125 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800126 std::lock_guard guard(mPrivateDnsLock);
127
128 const auto mode = mPrivateDnsModes.find(netId);
129 if (mode == mPrivateDnsModes.end()) return status;
130 status.mode = mode->second;
131
132 const auto netPair = mPrivateDnsTransports.find(netId);
133 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800134 for (const auto& [_, server] : netPair->second) {
Mike Yuf7717f52020-11-24 17:31:12 +0800135 if (server.active()) {
136 status.serversMap.emplace(server, server.validationState());
137 }
Mike Yub601ff72018-11-01 20:07:00 +0800138 }
139 }
140
141 return status;
142}
143
Mike Yub601ff72018-11-01 20:07:00 +0800144void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800145 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800146 std::lock_guard guard(mPrivateDnsLock);
147 mPrivateDnsModes.erase(netId);
148 mPrivateDnsTransports.erase(netId);
149}
150
Mike Yu3334a5e2020-11-19 13:33:17 +0800151void PrivateDnsConfiguration::startValidation(const DnsTlsServer& server, unsigned netId,
152 uint32_t mark) REQUIRES(mPrivateDnsLock) {
Mike Yub601ff72018-11-01 20:07:00 +0800153 // Note that capturing |server| and |netId| in this lambda create copies.
154 std::thread validate_thread([this, server, netId, mark] {
Mike Yucb902c92020-05-20 19:26:56 +0800155 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800156
Mike Yub601ff72018-11-01 20:07:00 +0800157 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
158 //
159 // Start with a 1 minute delay and backoff to once per hour.
160 //
161 // Assumptions:
162 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
163 // [2] Network typically provision clients with <=4 nameservers.
164 // [3] Average month has 30 days.
165 //
166 // Each validation pass in a given hour is ~1.2MB of data. And 24
167 // such validation passes per day is about ~30MB per month, in the
168 // worst case. Otherwise, this will cost ~600 SYNs per month
169 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Bernie Innocenti23c6e2a2019-05-16 15:18:35 +0900170 auto backoff = netdutils::BackoffSequence<>::Builder()
Mike Yub601ff72018-11-01 20:07:00 +0800171 .withInitialRetransmissionTime(std::chrono::seconds(60))
172 .withMaximumRetransmissionTime(std::chrono::seconds(3600))
173 .build();
174
175 while (true) {
176 // ::validate() is a blocking call that performs network operations.
177 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu04f1d482019-08-08 11:09:32 +0800178 LOG(WARNING) << "Validating DnsTlsServer on netId " << netId;
Mike Yub601ff72018-11-01 20:07:00 +0800179 const bool success = DnsTlsTransport::validate(server, netId, mark);
Mike Yu04f1d482019-08-08 11:09:32 +0800180 LOG(DEBUG) << "validateDnsTlsServer returned " << success << " for "
181 << addrToString(&server.ss);
Mike Yub601ff72018-11-01 20:07:00 +0800182
183 const bool needs_reeval = this->recordPrivateDnsValidation(server, netId, success);
184 if (!needs_reeval) {
185 break;
186 }
187
188 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800189 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800190 std::this_thread::sleep_for(backoff.getNextTimeout());
191 } else {
192 break;
193 }
194 }
195 });
196 validate_thread.detach();
197}
198
199bool PrivateDnsConfiguration::recordPrivateDnsValidation(const DnsTlsServer& server, unsigned netId,
200 bool success) {
201 constexpr bool NEEDS_REEVALUATION = true;
202 constexpr bool DONT_REEVALUATE = false;
Mike Yufa985f72020-11-23 20:24:21 +0800203 const ServerIdentity identity = ServerIdentity(server);
Mike Yub601ff72018-11-01 20:07:00 +0800204
205 std::lock_guard guard(mPrivateDnsLock);
206
207 auto netPair = mPrivateDnsTransports.find(netId);
208 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800209 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yufa985f72020-11-23 20:24:21 +0800210 maybeNotifyObserver(identity.ip.toString(), Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800211 return DONT_REEVALUATE;
212 }
213
214 const auto mode = mPrivateDnsModes.find(netId);
215 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800216 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yufa985f72020-11-23 20:24:21 +0800217 maybeNotifyObserver(identity.ip.toString(), Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800218 return DONT_REEVALUATE;
219 }
220 const bool modeDoesReevaluation = (mode->second == PrivateDnsMode::STRICT);
221
222 bool reevaluationStatus =
223 (success || !modeDoesReevaluation) ? DONT_REEVALUATE : NEEDS_REEVALUATION;
224
225 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800226 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800227 if (serverPair == tracker.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800228 LOG(WARNING) << "Server " << addrToString(&server.ss)
229 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800230 success = false;
231 reevaluationStatus = DONT_REEVALUATE;
Mike Yufa985f72020-11-23 20:24:21 +0800232 } else if (!(serverPair->second == server)) {
Mike Yub601ff72018-11-01 20:07:00 +0800233 // TODO: It doesn't seem correct to overwrite the tracker entry for
234 // |server| down below in this circumstance... Fix this.
chenbruceaff85842019-05-31 15:46:42 +0800235 LOG(WARNING) << "Server " << addrToString(&server.ss)
236 << " was changed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800237 success = false;
238 reevaluationStatus = DONT_REEVALUATE;
Mike Yuf7717f52020-11-24 17:31:12 +0800239 } else if (!serverPair->second.active()) {
240 LOG(WARNING) << "Server " << addrToString(&server.ss)
241 << " was removed from the configuration";
242 success = false;
243 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800244 }
245
Mike Yu303b0df2018-12-24 17:05:02 +0800246 // Send a validation event to NetdEventListenerService.
Hungming Chena32c8c12019-01-25 10:47:40 +0800247 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
248 if (listeners.size() != 0) {
249 for (const auto& it : listeners) {
250 it->onPrivateDnsValidationEvent(netId, addrToString(&server.ss), server.name, success);
251 }
Mike Yu04f1d482019-08-08 11:09:32 +0800252 LOG(DEBUG) << "Sent validation " << (success ? "success" : "failure") << " event on netId "
253 << netId << " for " << addrToString(&server.ss) << " with hostname {"
254 << server.name << "}";
Mike Yu303b0df2018-12-24 17:05:02 +0800255 } else {
chenbruceaff85842019-05-31 15:46:42 +0800256 LOG(ERROR)
257 << "Validation event not sent since no INetdEventListener receiver is available.";
Mike Yub601ff72018-11-01 20:07:00 +0800258 }
259
260 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800261 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800262 } else {
263 // Validation failure is expected if a user is on a captive portal.
264 // TODO: Trigger a second validation attempt after captive portal login
265 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800266 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
267 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800268 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800269 }
Mike Yu04f1d482019-08-08 11:09:32 +0800270 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800271
272 return reevaluationStatus;
273}
274
Mike Yufa985f72020-11-23 20:24:21 +0800275void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800276 uint32_t netId) {
277 auto netPair = mPrivateDnsTransports.find(netId);
Mike Yufa985f72020-11-23 20:24:21 +0800278 if (netPair == mPrivateDnsTransports.end()) {
279 maybeNotifyObserver(identity.ip.toString(), Validation::fail, netId);
280 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800281 }
282
Mike Yufa985f72020-11-23 20:24:21 +0800283 auto& tracker = netPair->second;
284 if (tracker.find(identity) == tracker.end()) {
285 maybeNotifyObserver(identity.ip.toString(), Validation::fail, netId);
286 return;
287 }
288
289 tracker[identity].setValidationState(state);
290 maybeNotifyObserver(identity.ip.toString(), state, netId);
Mike Yu3334a5e2020-11-19 13:33:17 +0800291}
292
Mike Yuf7717f52020-11-24 17:31:12 +0800293bool PrivateDnsConfiguration::needsValidation(const DnsTlsServer& server) {
294 // The server is not expected to be used on the network.
295 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500296
Mike Yuf7717f52020-11-24 17:31:12 +0800297 // The server is newly added.
298 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500299
Mike Yuf7717f52020-11-24 17:31:12 +0800300 // The server has failed at least one validation attempt. Give it another try.
301 if (server.validationState() == Validation::fail) return true;
302
303 // The previous validation result might be unreliable.
304 if (server.validationState() == Validation::success_but_expired) return true;
305
306 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800307}
308
Mike Yu0ee1dc92020-11-09 14:56:54 +0800309void PrivateDnsConfiguration::setObserver(Observer* observer) {
310 std::lock_guard guard(mPrivateDnsLock);
311 mObserver = observer;
312}
313
Mike Yufa985f72020-11-23 20:24:21 +0800314void PrivateDnsConfiguration::maybeNotifyObserver(const std::string& serverIp,
315 Validation validation, uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800316 if (mObserver) {
Mike Yufa985f72020-11-23 20:24:21 +0800317 mObserver->onValidationStateUpdate(serverIp, validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800318 }
319}
320
Mike Yub601ff72018-11-01 20:07:00 +0800321} // namespace net
322} // namespace android