blob: d1455c1e0303af8b13f2feaf10877e16c3cec141 [file] [log] [blame]
Ben Schwartzded1b702017-10-25 14:41:02 -04001/*
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
17#define LOG_TAG "DnsTlsSocket"
Ben Schwartz33860762017-10-25 14:41:02 -040018//#define LOG_NDEBUG 0
Ben Schwartzded1b702017-10-25 14:41:02 -040019
Mike Yu5ae61542018-10-19 22:11:43 +080020#include "netd_resolv/DnsTlsSocket.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040021
Ben Schwartzded1b702017-10-25 14:41:02 -040022#include <arpa/inet.h>
23#include <arpa/nameser.h>
24#include <errno.h>
Erik Klined1503072018-02-22 23:55:40 -080025#include <linux/tcp.h>
Ben Schwartzded1b702017-10-25 14:41:02 -040026#include <openssl/err.h>
Mike Yu5ae61542018-10-19 22:11:43 +080027#include <openssl/sha.h>
Ben Schwartzbfc8d992019-01-10 14:30:46 -050028#include <sys/eventfd.h>
Bernie Innocentif944a9c2018-05-18 20:50:25 +090029#include <sys/poll.h>
Ben Schwartzbfc8d992019-01-10 14:30:46 -050030#include <algorithm>
Ben Schwartzded1b702017-10-25 14:41:02 -040031
Mike Yu5ae61542018-10-19 22:11:43 +080032#include "netd_resolv/DnsTlsSessionCache.h"
33#include "netd_resolv/IDnsTlsSocketObserver.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040034
35#include "log/log.h"
Erik Klined1503072018-02-22 23:55:40 -080036#include "netdutils/SocketOption.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040037
Ben Schwartzded1b702017-10-25 14:41:02 -040038namespace android {
Ben Schwartzded1b702017-10-25 14:41:02 -040039
Erik Klined1503072018-02-22 23:55:40 -080040using netdutils::enableSockopt;
41using netdutils::enableTcpKeepAlives;
42using netdutils::isOk;
Ben Schwartzded1b702017-10-25 14:41:02 -040043using netdutils::Status;
44
Erik Klined1503072018-02-22 23:55:40 -080045namespace net {
Ben Schwartzded1b702017-10-25 14:41:02 -040046namespace {
47
48constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
Mike Yu5ae61542018-10-19 22:11:43 +080049constexpr size_t SHA256_SIZE = SHA256_DIGEST_LENGTH;
Ben Schwartzded1b702017-10-25 14:41:02 -040050
51int waitForReading(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090052 struct pollfd fds = { .fd = fd, .events = POLLIN };
53 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040054 return ret;
55}
56
57int waitForWriting(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090058 struct pollfd fds = { .fd = fd, .events = POLLOUT };
59 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040060 return ret;
61}
62
63} // namespace
64
65Status DnsTlsSocket::tcpConnect() {
66 ALOGV("%u connecting TCP socket", mMark);
67 int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
68 switch (mServer.protocol) {
69 case IPPROTO_TCP:
70 type |= SOCK_STREAM;
71 break;
72 default:
73 return Status(EPROTONOSUPPORT);
74 }
75
76 mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
77 if (mSslFd.get() == -1) {
78 ALOGE("Failed to create socket");
79 return Status(errno);
80 }
81
82 const socklen_t len = sizeof(mMark);
83 if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
84 ALOGE("Failed to set socket mark");
85 mSslFd.reset();
86 return Status(errno);
87 }
Erik Klined1503072018-02-22 23:55:40 -080088
89 const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
90 if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
91 ALOGI("Failed to enable TFO: %s", tfo.msg().c_str());
92 }
93
94 // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
Bernie Innocenti6f9fd902018-10-11 20:50:23 +090095 enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
Erik Klined1503072018-02-22 23:55:40 -080096
Ben Schwartzded1b702017-10-25 14:41:02 -040097 if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
98 sizeof(mServer.ss)) != 0 &&
99 errno != EINPROGRESS) {
100 ALOGV("Socket failed to connect");
101 mSslFd.reset();
102 return Status(errno);
103 }
104
105 return netdutils::status::ok;
106}
107
108bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700109 int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400110 unsigned char spki[spki_len];
111 unsigned char* temp = spki;
112 if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) {
113 ALOGW("SPKI length mismatch");
114 return false;
115 }
116 out->resize(SHA256_SIZE);
117 unsigned int digest_len = 0;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700118 int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400119 if (ret != 1) {
120 ALOGW("Server cert digest extraction failed");
121 return false;
122 }
123 if (digest_len != out->size()) {
124 ALOGW("Wrong digest length: %d", digest_len);
125 return false;
126 }
127 return true;
128}
129
130bool DnsTlsSocket::initialize() {
131 // This method should only be called once, at the beginning, so locking should be
132 // unnecessary. This lock only serves to help catch bugs in code that calls this method.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900133 std::lock_guard guard(mLock);
Ben Schwartzded1b702017-10-25 14:41:02 -0400134 if (mSslCtx) {
135 // This is a bug in the caller.
136 return false;
137 }
138 mSslCtx.reset(SSL_CTX_new(TLS_method()));
139 if (!mSslCtx) {
140 return false;
141 }
142
143 // Load system CA certs for hostname verification.
144 //
145 // For discussion of alternative, sustainable approaches see b/71909242.
146 if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
147 ALOGE("Failed to load CA cert dir: %s", kCaCertDir);
148 return false;
149 }
150
151 // Enable TLS false start
152 SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
153 SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
154
155 // Enable session cache
156 mCache->prepareSslContext(mSslCtx.get());
157
158 // Connect
159 Status status = tcpConnect();
160 if (!status.ok()) {
161 return false;
162 }
163 mSsl = sslConnect(mSslFd.get());
164 if (!mSsl) {
165 return false;
166 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500167
168 mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Ben Schwartz33860762017-10-25 14:41:02 -0400169
170 // Start the I/O loop.
171 mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
Ben Schwartzded1b702017-10-25 14:41:02 -0400172
173 return true;
174}
175
176bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
177 if (!mSslCtx) {
178 ALOGE("Internal error: context is null in sslConnect");
179 return nullptr;
180 }
181 if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
182 ALOGE("Failed to set minimum TLS version");
183 return nullptr;
184 }
185
186 bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
187 // This file descriptor is owned by mSslFd, so don't let libssl close it.
188 bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
189 SSL_set_bio(ssl.get(), bio.get(), bio.get());
190 bio.release();
191
192 if (!mCache->prepareSsl(ssl.get())) {
193 return nullptr;
194 }
195
196 if (!mServer.name.empty()) {
197 if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
198 ALOGE("Failed to set SNI to %s", mServer.name.c_str());
199 return nullptr;
200 }
201 X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
Erik Klineefc13632018-03-22 11:19:02 -0700202 if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
203 ALOGE("Failed to set verify host param to %s", mServer.name.c_str());
204 return nullptr;
205 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400206 // This will cause the handshake to fail if certificate verification fails.
207 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
208 }
209
210 bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
211 if (session) {
212 ALOGV("Setting session");
213 SSL_set_session(ssl.get(), session.get());
214 } else {
215 ALOGV("No session available");
216 }
217
218 for (;;) {
219 ALOGV("%u Calling SSL_connect", mMark);
220 int ret = SSL_connect(ssl.get());
221 ALOGV("%u SSL_connect returned %d", mMark, ret);
222 if (ret == 1) break; // SSL handshake complete;
223
224 const int ssl_err = SSL_get_error(ssl.get(), ret);
225 switch (ssl_err) {
226 case SSL_ERROR_WANT_READ:
227 if (waitForReading(fd) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900228 ALOGW("SSL_connect read error: %d", errno);
Ben Schwartzded1b702017-10-25 14:41:02 -0400229 return nullptr;
230 }
231 break;
232 case SSL_ERROR_WANT_WRITE:
233 if (waitForWriting(fd) != 1) {
234 ALOGW("SSL_connect write error");
235 return nullptr;
236 }
237 break;
238 default:
239 ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno);
240 return nullptr;
241 }
242 }
243
244 // TODO: Call SSL_shutdown before discarding the session if validation fails.
245 if (!mServer.fingerprints.empty()) {
246 ALOGV("Checking DNS over TLS fingerprint");
247
248 // We only care that the chain is internally self-consistent, not that
249 // it chains to a trusted root, so we can ignore some kinds of errors.
250 // TODO: Add a CA root verification mode that respects these errors.
251 int verify_result = SSL_get_verify_result(ssl.get());
252 switch (verify_result) {
253 case X509_V_OK:
254 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
255 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
256 case X509_V_ERR_CERT_UNTRUSTED:
257 break;
258 default:
259 ALOGW("Invalid certificate chain, error %d", verify_result);
260 return nullptr;
261 }
262
263 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get());
264 if (!chain) {
265 ALOGW("Server has null certificate");
266 return nullptr;
267 }
268 // Chain and its contents are owned by ssl, so we don't need to free explicitly.
269 bool matched = false;
270 for (size_t i = 0; i < sk_X509_num(chain); ++i) {
271 // This appears to be O(N^2), but there doesn't seem to be a straightforward
272 // way to walk a STACK_OF nondestructively in linear time.
273 X509* cert = sk_X509_value(chain, i);
274 std::vector<uint8_t> digest;
275 if (!getSPKIDigest(cert, &digest)) {
276 ALOGE("Digest computation failed");
277 return nullptr;
278 }
279
280 if (mServer.fingerprints.count(digest) > 0) {
281 matched = true;
282 break;
283 }
284 }
285
286 if (!matched) {
287 ALOGW("No matching fingerprint");
288 return nullptr;
289 }
290
291 ALOGV("DNS over TLS fingerprint is correct");
292 }
293
294 ALOGV("%u handshake complete", mMark);
295
296 return ssl;
297}
298
299void DnsTlsSocket::sslDisconnect() {
300 if (mSsl) {
301 SSL_shutdown(mSsl.get());
302 mSsl.reset();
303 }
304 mSslFd.reset();
305}
306
307bool DnsTlsSocket::sslWrite(const Slice buffer) {
308 ALOGV("%u Writing %zu bytes", mMark, buffer.size());
309 for (;;) {
310 int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
311 if (ret == int(buffer.size())) break; // SSL write complete;
312
313 if (ret < 1) {
314 const int ssl_err = SSL_get_error(mSsl.get(), ret);
315 switch (ssl_err) {
316 case SSL_ERROR_WANT_WRITE:
317 if (waitForWriting(mSslFd.get()) != 1) {
318 ALOGV("SSL_write error");
319 return false;
320 }
321 continue;
322 case 0:
323 break; // SSL write complete;
324 default:
325 ALOGV("SSL_write error %d", ssl_err);
326 return false;
327 }
328 }
329 }
330 ALOGV("%u Wrote %zu bytes", mMark, buffer.size());
331 return true;
332}
333
Ben Schwartz33860762017-10-25 14:41:02 -0400334void DnsTlsSocket::loop() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900335 std::lock_guard guard(mLock);
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500336 std::deque<std::vector<uint8_t>> q;
Ben Schwartz33860762017-10-25 14:41:02 -0400337
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900338 const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
Ben Schwartz33860762017-10-25 14:41:02 -0400339 while (true) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900340 // poll() ignores negative fds
341 struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500342 enum { SSLFD = 0, EVENTFD = 1 };
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900343
Ben Schwartz33860762017-10-25 14:41:02 -0400344 // Always listen for a response from server.
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900345 fds[SSLFD].fd = mSslFd.get();
346 fds[SSLFD].events = POLLIN;
347
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500348 // If we have pending queries, wait for space to write one.
349 // Otherwise, listen for new queries.
350 if (!q.empty()) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900351 fds[SSLFD].events |= POLLOUT;
Ben Schwartz33860762017-10-25 14:41:02 -0400352 } else {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500353 fds[EVENTFD].fd = mEventFd.get();
354 fds[EVENTFD].events = POLLIN;
Ben Schwartz33860762017-10-25 14:41:02 -0400355 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900356
Mike Yu5ae61542018-10-19 22:11:43 +0800357 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
Ben Schwartz33860762017-10-25 14:41:02 -0400358 if (s == 0) {
359 ALOGV("Idle timeout");
360 break;
361 }
362 if (s < 0) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900363 ALOGV("Poll failed: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400364 break;
365 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900366 if (fds[SSLFD].revents & (POLLIN | POLLERR)) {
Ben Schwartz33860762017-10-25 14:41:02 -0400367 if (!readResponse()) {
368 ALOGV("SSL remote close or read error.");
369 break;
370 }
371 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500372 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
373 int64_t num_queries;
374 ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
Ben Schwartz33860762017-10-25 14:41:02 -0400375 if (res < 0) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500376 ALOGW("Error during eventfd read");
Ben Schwartz33860762017-10-25 14:41:02 -0400377 break;
378 } else if (res == 0) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500379 ALOGV("eventfd closed; disconnecting");
Ben Schwartz33860762017-10-25 14:41:02 -0400380 break;
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500381 } else if (res != sizeof(num_queries)) {
382 ALOGE("Int size mismatch: %zd != %zu", res, sizeof(num_queries));
383 break;
384 } else if (num_queries <= 0) {
385 ALOGE("eventfd reads should always be positive");
386 break;
387 }
388 // Take ownership of all pending queries. (q is always empty here.)
389 mQueue.swap(q);
390 // The writing thread writes to mQueue and then increments mEventFd, so
391 // there should be at least num_queries entries in mQueue.
392 if (q.size() < (uint64_t) num_queries) {
393 ALOGE("Synchronization error");
Ben Schwartz33860762017-10-25 14:41:02 -0400394 break;
395 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900396 } else if (fds[SSLFD].revents & POLLOUT) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500397 // q cannot be empty here.
398 // Sending the entire queue here would risk a TCP flow control deadlock, so
399 // we only send a single query on each cycle of this loop.
400 // TODO: Coalesce multiple pending queries if there is enough space in the
401 // write buffer.
402 if (!sendQuery(q.front())) {
Ben Schwartz33860762017-10-25 14:41:02 -0400403 break;
404 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500405 q.pop_front();
Ben Schwartz33860762017-10-25 14:41:02 -0400406 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400407 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500408 ALOGV("Closing event FD");
409 mEventFd.reset();
Ben Schwartz33860762017-10-25 14:41:02 -0400410 ALOGV("Disconnecting");
411 sslDisconnect();
412 ALOGV("Calling onClosed");
413 mObserver->onClosed();
414 ALOGV("Ending loop");
Ben Schwartzded1b702017-10-25 14:41:02 -0400415}
416
Ben Schwartz33860762017-10-25 14:41:02 -0400417DnsTlsSocket::~DnsTlsSocket() {
418 ALOGV("Destructor");
419 // This will trigger an orderly shutdown in loop().
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500420 // In principle there is a data race here: If there is an I/O error in the network thread
421 // simultaneous with a call to the destructor in a different thread, both threads could
422 // attempt to call mEventFd.reset() at the same time. However, the implementation of
423 // UniqueFd::reset appears to be thread-safe, and neither thread reads or writes mEventFd
424 // after this point, so we don't expect an issue in practice.
425 mEventFd.reset();
Ben Schwartz33860762017-10-25 14:41:02 -0400426 {
427 // Wait for the orderly shutdown to complete.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900428 std::lock_guard guard(mLock);
Ben Schwartz33860762017-10-25 14:41:02 -0400429 if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
430 ALOGE("Violation of re-entrance precondition");
431 return;
432 }
433 }
434 if (mLoopThread) {
435 ALOGV("Waiting for loop thread to terminate");
436 mLoopThread->join();
437 mLoopThread.reset();
438 }
439 ALOGV("Destructor completed");
440}
441
442bool DnsTlsSocket::query(uint16_t id, const Slice query) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500443 if (!mEventFd) {
Ben Schwartz33860762017-10-25 14:41:02 -0400444 return false;
445 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500446
447 // Compose the entire message in a single buffer, so that it can be
448 // sent as a single TLS record.
449 std::vector<uint8_t> buf(query.size() + 4);
450 // Write 2-byte length
451 uint16_t len = query.size() + 2; // + 2 for the ID.
452 buf[0] = len >> 8;
453 buf[1] = len;
454 // Write 2-byte ID
455 buf[2] = id >> 8;
456 buf[3] = id;
457 // Copy body
458 std::memcpy(buf.data() + 4, query.base(), query.size());
459
460 mQueue.push(std::move(buf));
461 // Increment the mEventFd counter by 1.
462 constexpr int64_t num_queries = 1;
463 int written = write(mEventFd.get(), &num_queries, sizeof(num_queries));
464 return written == sizeof(num_queries);
Ben Schwartz33860762017-10-25 14:41:02 -0400465}
466
467// Read exactly len bytes into buffer or fail with an SSL error code
468int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400469 size_t remaining = buffer.size();
470 while (remaining > 0) {
471 int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
472 if (ret == 0) {
473 ALOGW_IF(remaining < buffer.size(), "SSL closed with %zu of %zu bytes remaining",
474 remaining, buffer.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400475 return SSL_ERROR_ZERO_RETURN;
Ben Schwartzded1b702017-10-25 14:41:02 -0400476 }
477
478 if (ret < 0) {
479 const int ssl_err = SSL_get_error(mSsl.get(), ret);
Ben Schwartz33860762017-10-25 14:41:02 -0400480 if (wait && ssl_err == SSL_ERROR_WANT_READ) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400481 if (waitForReading(mSslFd.get()) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900482 ALOGV("Poll failed in sslRead: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400483 return SSL_ERROR_SYSCALL;
Ben Schwartzded1b702017-10-25 14:41:02 -0400484 }
485 continue;
486 } else {
487 ALOGV("SSL_read error %d", ssl_err);
Ben Schwartz33860762017-10-25 14:41:02 -0400488 return ssl_err;
Ben Schwartzded1b702017-10-25 14:41:02 -0400489 }
490 }
491
492 remaining -= ret;
Ben Schwartz33860762017-10-25 14:41:02 -0400493 wait = true; // Once a read is started, try to finish.
Ben Schwartzded1b702017-10-25 14:41:02 -0400494 }
Ben Schwartz33860762017-10-25 14:41:02 -0400495 return SSL_ERROR_NONE;
Ben Schwartzded1b702017-10-25 14:41:02 -0400496}
497
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500498bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400499 if (!sslWrite(netdutils::makeSlice(buf))) {
500 return false;
501 }
502 ALOGV("%u SSL_write complete", mMark);
503 return true;
504}
505
Ben Schwartz33860762017-10-25 14:41:02 -0400506bool DnsTlsSocket::readResponse() {
Ben Schwartzded1b702017-10-25 14:41:02 -0400507 ALOGV("reading response");
508 uint8_t responseHeader[2];
Ben Schwartz33860762017-10-25 14:41:02 -0400509 int err = sslRead(Slice(responseHeader, 2), false);
510 if (err == SSL_ERROR_WANT_READ) {
511 ALOGV("Ignoring spurious wakeup from server");
512 return true;
513 }
514 if (err != SSL_ERROR_NONE) {
515 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400516 }
517 // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is
518 // always invalid when truncated, so the response will be treated as an error.
519 constexpr uint16_t MAX_SIZE = 8192;
520 const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
521 ALOGV("%u Expecting response of size %i", mMark, responseSize);
522 std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400523 if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400524 ALOGV("%u Failed to read %zu bytes", mMark, response.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400525 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400526 }
527 uint16_t remainingBytes = responseSize - response.size();
528 while (remainingBytes > 0) {
529 constexpr uint16_t CHUNK_SIZE = 2048;
530 std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400531 if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400532 ALOGV("%u Failed to discard %zu bytes", mMark, discard.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400533 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400534 }
535 remainingBytes -= discard.size();
536 }
537 ALOGV("%u SSL_read complete", mMark);
538
Ben Schwartz33860762017-10-25 14:41:02 -0400539 mObserver->onResponse(std::move(response));
540 return true;
Ben Schwartzded1b702017-10-25 14:41:02 -0400541}
542
543} // end of namespace net
544} // end of namespace android