blob: 8f3b8365619523eb978c25914f2ee207358f9751 [file] [log] [blame]
Mike Yub601ff72018-11-01 20:07:00 +08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ken Chen5471dca2019-04-15 15:25:35 +080017#define LOG_TAG "resolv"
Mike Yub601ff72018-11-01 20:07:00 +080018
Mike Yu303b0df2018-12-24 17:05:02 +080019#include "PrivateDnsConfiguration.h"
20
Mike Yu3d5130d2020-12-21 17:57:18 +080021#include <android-base/format.h>
chenbruceaff85842019-05-31 15:46:42 +080022#include <android-base/logging.h>
Mike Yu04f1d482019-08-08 11:09:32 +080023#include <android-base/stringprintf.h>
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
Mike Yub601ff72018-11-01 20:07:00 +080040bool parseServer(const char* server, sockaddr_storage* parsed) {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -070041 addrinfo hints = {
42 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
43 .ai_family = AF_UNSPEC,
44 };
Mike Yub601ff72018-11-01 20:07:00 +080045 addrinfo* res;
46
47 int err = getaddrinfo(server, "853", &hints, &res);
48 if (err != 0) {
chenbruceaff85842019-05-31 15:46:42 +080049 LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
Mike Yub601ff72018-11-01 20:07:00 +080050 return false;
51 }
52
53 memcpy(parsed, res->ai_addr, res->ai_addrlen);
54 freeaddrinfo(res);
55 return true;
56}
57
Mike Yub601ff72018-11-01 20:07:00 +080058int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
59 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080060 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080061 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080062 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080063
64 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080065 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080066 for (const auto& s : servers) {
Mike Yub601ff72018-11-01 20:07:00 +080067 sockaddr_storage parsed;
Mike Yu40e67072019-10-09 21:14:09 +080068 if (!parseServer(s.c_str(), &parsed)) {
Mike Yub601ff72018-11-01 20:07:00 +080069 return -EINVAL;
70 }
71 DnsTlsServer server(parsed);
72 server.name = name;
waynema0e73c2e2019-07-31 15:04:08 +080073 server.certificate = caCert;
Mike Yue60ab412020-12-01 17:56:12 +080074 server.mark = mark;
Mike Yufa985f72020-11-23 20:24:21 +080075 tmp[ServerIdentity(server)] = server;
Mike Yub601ff72018-11-01 20:07:00 +080076 }
77
78 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080079 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080080 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080081 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080082 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
83 } else {
84 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
85 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080086 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080087 return 0;
88 }
89
90 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080091 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080092
Mike Yuf7717f52020-11-24 17:31:12 +080093 // Add the servers if not contained in tracker.
Mike Yufa985f72020-11-23 20:24:21 +080094 for (const auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +080095 if (tracker.find(identity) == tracker.end()) {
96 tracker[identity] = server;
97 }
98 }
Mike Yu3334a5e2020-11-19 13:33:17 +080099
Mike Yuf7717f52020-11-24 17:31:12 +0800100 for (auto& [identity, server] : tracker) {
101 const bool active = tmp.find(identity) != tmp.end();
102 server.setActive(active);
103
104 // For simplicity, deem the validation result of inactive servers as unreliable.
105 if (!server.active() && server.validationState() == Validation::success) {
106 updateServerState(identity, Validation::success_but_expired, netId);
107 }
108
109 if (needsValidation(server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800110 updateServerState(identity, Validation::in_process, netId);
Mike Yu74770542020-12-15 14:25:21 +0800111 startValidation(server, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800112 }
113 }
Mike Yue655b1d2019-08-28 17:49:59 +0800114
Mike Yu8d9da4a2020-11-09 17:09:14 +0800115 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800116}
117
118PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) {
119 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800120 std::lock_guard guard(mPrivateDnsLock);
121
122 const auto mode = mPrivateDnsModes.find(netId);
123 if (mode == mPrivateDnsModes.end()) return status;
124 status.mode = mode->second;
125
126 const auto netPair = mPrivateDnsTransports.find(netId);
127 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800128 for (const auto& [_, server] : netPair->second) {
Mike Yuf7717f52020-11-24 17:31:12 +0800129 if (server.active()) {
130 status.serversMap.emplace(server, server.validationState());
131 }
Mike Yub601ff72018-11-01 20:07:00 +0800132 }
133 }
134
135 return status;
136}
137
Mike Yub601ff72018-11-01 20:07:00 +0800138void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800139 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800140 std::lock_guard guard(mPrivateDnsLock);
141 mPrivateDnsModes.erase(netId);
142 mPrivateDnsTransports.erase(netId);
143}
144
Mike Yue60ab412020-12-01 17:56:12 +0800145bool PrivateDnsConfiguration::requestValidation(unsigned netId, const DnsTlsServer& server,
146 uint32_t mark) {
147 std::lock_guard guard(mPrivateDnsLock);
148 auto netPair = mPrivateDnsTransports.find(netId);
149 if (netPair == mPrivateDnsTransports.end()) {
150 return false;
151 }
152
153 auto& tracker = netPair->second;
154 const ServerIdentity identity = ServerIdentity(server);
155 auto it = tracker.find(identity);
156 if (it == tracker.end()) {
157 return false;
158 }
159
160 const DnsTlsServer& target = it->second;
161
162 if (!target.active()) return false;
163
164 if (target.validationState() != Validation::success) return false;
165
166 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
167 // This is to protect validation from running on unexpected marks.
168 // Validation should be associated with a mark gotten by system permission.
169 if (target.mark != mark) return false;
170
171 updateServerState(identity, Validation::in_process, netId);
Mike Yu74770542020-12-15 14:25:21 +0800172 startValidation(target, netId);
Mike Yue60ab412020-12-01 17:56:12 +0800173 return true;
174}
175
Mike Yu74770542020-12-15 14:25:21 +0800176void PrivateDnsConfiguration::startValidation(const DnsTlsServer& server, unsigned netId)
177 REQUIRES(mPrivateDnsLock) {
Mike Yub601ff72018-11-01 20:07:00 +0800178 // Note that capturing |server| and |netId| in this lambda create copies.
Mike Yu74770542020-12-15 14:25:21 +0800179 std::thread validate_thread([this, server, netId] {
Mike Yucb902c92020-05-20 19:26:56 +0800180 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800181
Mike Yub601ff72018-11-01 20:07:00 +0800182 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
183 //
184 // Start with a 1 minute delay and backoff to once per hour.
185 //
186 // Assumptions:
187 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
188 // [2] Network typically provision clients with <=4 nameservers.
189 // [3] Average month has 30 days.
190 //
191 // Each validation pass in a given hour is ~1.2MB of data. And 24
192 // such validation passes per day is about ~30MB per month, in the
193 // worst case. Otherwise, this will cost ~600 SYNs per month
194 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Bernie Innocenti23c6e2a2019-05-16 15:18:35 +0900195 auto backoff = netdutils::BackoffSequence<>::Builder()
Mike Yub601ff72018-11-01 20:07:00 +0800196 .withInitialRetransmissionTime(std::chrono::seconds(60))
197 .withMaximumRetransmissionTime(std::chrono::seconds(3600))
198 .build();
199
200 while (true) {
201 // ::validate() is a blocking call that performs network operations.
202 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800203 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
204 << std::hex << server.mark;
205 const bool success = DnsTlsTransport::validate(server, server.mark);
206 LOG(WARNING) << "validateDnsTlsServer returned " << success << " for "
207 << server.toIpString();
Mike Yub601ff72018-11-01 20:07:00 +0800208
209 const bool needs_reeval = this->recordPrivateDnsValidation(server, netId, success);
210 if (!needs_reeval) {
211 break;
212 }
213
214 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800215 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800216 std::this_thread::sleep_for(backoff.getNextTimeout());
217 } else {
218 break;
219 }
220 }
221 });
222 validate_thread.detach();
223}
224
225bool PrivateDnsConfiguration::recordPrivateDnsValidation(const DnsTlsServer& server, unsigned netId,
226 bool success) {
227 constexpr bool NEEDS_REEVALUATION = true;
228 constexpr bool DONT_REEVALUATE = false;
Mike Yufa985f72020-11-23 20:24:21 +0800229 const ServerIdentity identity = ServerIdentity(server);
Mike Yub601ff72018-11-01 20:07:00 +0800230
231 std::lock_guard guard(mPrivateDnsLock);
232
233 auto netPair = mPrivateDnsTransports.find(netId);
234 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800235 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu74770542020-12-15 14:25:21 +0800236 notifyValidationStateUpdate(identity.ip.toString(), Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800237 return DONT_REEVALUATE;
238 }
239
240 const auto mode = mPrivateDnsModes.find(netId);
241 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800242 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu74770542020-12-15 14:25:21 +0800243 notifyValidationStateUpdate(identity.ip.toString(), Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800244 return DONT_REEVALUATE;
245 }
246 const bool modeDoesReevaluation = (mode->second == PrivateDnsMode::STRICT);
247
248 bool reevaluationStatus =
249 (success || !modeDoesReevaluation) ? DONT_REEVALUATE : NEEDS_REEVALUATION;
250
251 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800252 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800253 if (serverPair == tracker.end()) {
Mike Yu4499ee32020-11-24 20:05:18 +0800254 LOG(WARNING) << "Server " << server.toIpString()
chenbruceaff85842019-05-31 15:46:42 +0800255 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800256 success = false;
257 reevaluationStatus = DONT_REEVALUATE;
Mike Yufa985f72020-11-23 20:24:21 +0800258 } else if (!(serverPair->second == server)) {
Mike Yub601ff72018-11-01 20:07:00 +0800259 // TODO: It doesn't seem correct to overwrite the tracker entry for
260 // |server| down below in this circumstance... Fix this.
Mike Yu4499ee32020-11-24 20:05:18 +0800261 LOG(WARNING) << "Server " << server.toIpString()
chenbruceaff85842019-05-31 15:46:42 +0800262 << " was changed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800263 success = false;
264 reevaluationStatus = DONT_REEVALUATE;
Mike Yuf7717f52020-11-24 17:31:12 +0800265 } else if (!serverPair->second.active()) {
Mike Yu4499ee32020-11-24 20:05:18 +0800266 LOG(WARNING) << "Server " << server.toIpString() << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800267 success = false;
268 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800269 }
270
Mike Yu303b0df2018-12-24 17:05:02 +0800271 // Send a validation event to NetdEventListenerService.
Hungming Chena32c8c12019-01-25 10:47:40 +0800272 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
273 if (listeners.size() != 0) {
274 for (const auto& it : listeners) {
Mike Yu4499ee32020-11-24 20:05:18 +0800275 it->onPrivateDnsValidationEvent(netId, server.toIpString(), server.name, success);
Hungming Chena32c8c12019-01-25 10:47:40 +0800276 }
Mike Yu04f1d482019-08-08 11:09:32 +0800277 LOG(DEBUG) << "Sent validation " << (success ? "success" : "failure") << " event on netId "
Mike Yu4499ee32020-11-24 20:05:18 +0800278 << netId << " for " << server.toIpString() << " with hostname {" << server.name
279 << "}";
Mike Yu303b0df2018-12-24 17:05:02 +0800280 } else {
chenbruceaff85842019-05-31 15:46:42 +0800281 LOG(ERROR)
282 << "Validation event not sent since no INetdEventListener receiver is available.";
Mike Yub601ff72018-11-01 20:07:00 +0800283 }
284
285 if (success) {
Mike Yufa985f72020-11-23 20:24:21 +0800286 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800287 } else {
288 // Validation failure is expected if a user is on a captive portal.
289 // TODO: Trigger a second validation attempt after captive portal login
290 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800291 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
292 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800293 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800294 }
Mike Yu04f1d482019-08-08 11:09:32 +0800295 LOG(WARNING) << "Validation " << (success ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800296
297 return reevaluationStatus;
298}
299
Mike Yufa985f72020-11-23 20:24:21 +0800300void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800301 uint32_t netId) {
302 auto netPair = mPrivateDnsTransports.find(netId);
Mike Yufa985f72020-11-23 20:24:21 +0800303 if (netPair == mPrivateDnsTransports.end()) {
Mike Yu74770542020-12-15 14:25:21 +0800304 notifyValidationStateUpdate(identity.ip.toString(), Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800305 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800306 }
307
Mike Yufa985f72020-11-23 20:24:21 +0800308 auto& tracker = netPair->second;
309 if (tracker.find(identity) == tracker.end()) {
Mike Yu74770542020-12-15 14:25:21 +0800310 notifyValidationStateUpdate(identity.ip.toString(), Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800311 return;
312 }
313
314 tracker[identity].setValidationState(state);
Mike Yu74770542020-12-15 14:25:21 +0800315 notifyValidationStateUpdate(identity.ip.toString(), state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800316
317 RecordEntry record(netId, identity, state);
318 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800319}
320
Mike Yuf7717f52020-11-24 17:31:12 +0800321bool PrivateDnsConfiguration::needsValidation(const DnsTlsServer& server) {
322 // The server is not expected to be used on the network.
323 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500324
Mike Yuf7717f52020-11-24 17:31:12 +0800325 // The server is newly added.
326 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500327
Mike Yuf7717f52020-11-24 17:31:12 +0800328 // The server has failed at least one validation attempt. Give it another try.
329 if (server.validationState() == Validation::fail) return true;
330
331 // The previous validation result might be unreliable.
332 if (server.validationState() == Validation::success_but_expired) return true;
333
334 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800335}
336
Mike Yua6853e82020-12-11 19:47:06 +0800337void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800338 std::lock_guard guard(mPrivateDnsLock);
339 mObserver = observer;
340}
341
Mike Yu74770542020-12-15 14:25:21 +0800342void PrivateDnsConfiguration::notifyValidationStateUpdate(const std::string& serverIp,
343 Validation validation,
344 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800345 if (mObserver) {
Mike Yufa985f72020-11-23 20:24:21 +0800346 mObserver->onValidationStateUpdate(serverIp, validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800347 }
348}
349
Mike Yu3d5130d2020-12-21 17:57:18 +0800350void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
351 dw.println("PrivateDnsLog:");
352 netdutils::ScopedIndent indentStats(dw);
353
354 for (const auto& record : mPrivateDnsLog.copy()) {
355 dw.println(fmt::format("{} - netId={} PrivateDns={{{}/{}}} state={}",
356 timestampToString(record.timestamp), record.netId,
357 record.serverIdentity.ip.toString(), record.serverIdentity.name,
358 validationStatusToString(record.state)));
359 }
360 dw.blankline();
361}
362
Mike Yub601ff72018-11-01 20:07:00 +0800363} // namespace net
364} // namespace android