blob: b20373103c3e0232ff22c28a6118ee0f2e649ba6 [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
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090020#include "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
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090032#include "DnsTlsSessionCache.h"
33#include "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;
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090043using netdutils::Slice;
Ben Schwartzded1b702017-10-25 14:41:02 -040044using netdutils::Status;
45
Erik Klined1503072018-02-22 23:55:40 -080046namespace net {
Ben Schwartzded1b702017-10-25 14:41:02 -040047namespace {
48
49constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
Mike Yu5ae61542018-10-19 22:11:43 +080050constexpr size_t SHA256_SIZE = SHA256_DIGEST_LENGTH;
Ben Schwartzded1b702017-10-25 14:41:02 -040051
52int waitForReading(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090053 struct pollfd fds = { .fd = fd, .events = POLLIN };
54 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040055 return ret;
56}
57
58int waitForWriting(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090059 struct pollfd fds = { .fd = fd, .events = POLLOUT };
60 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040061 return ret;
62}
63
64} // namespace
65
66Status DnsTlsSocket::tcpConnect() {
67 ALOGV("%u connecting TCP socket", mMark);
68 int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
69 switch (mServer.protocol) {
70 case IPPROTO_TCP:
71 type |= SOCK_STREAM;
72 break;
73 default:
74 return Status(EPROTONOSUPPORT);
75 }
76
77 mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
78 if (mSslFd.get() == -1) {
79 ALOGE("Failed to create socket");
80 return Status(errno);
81 }
82
83 const socklen_t len = sizeof(mMark);
84 if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
85 ALOGE("Failed to set socket mark");
86 mSslFd.reset();
87 return Status(errno);
88 }
Erik Klined1503072018-02-22 23:55:40 -080089
90 const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
91 if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
92 ALOGI("Failed to enable TFO: %s", tfo.msg().c_str());
93 }
94
95 // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
Bernie Innocenti6f9fd902018-10-11 20:50:23 +090096 enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
Erik Klined1503072018-02-22 23:55:40 -080097
Ben Schwartzded1b702017-10-25 14:41:02 -040098 if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
99 sizeof(mServer.ss)) != 0 &&
100 errno != EINPROGRESS) {
101 ALOGV("Socket failed to connect");
102 mSslFd.reset();
103 return Status(errno);
104 }
105
106 return netdutils::status::ok;
107}
108
109bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700110 int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400111 unsigned char spki[spki_len];
112 unsigned char* temp = spki;
113 if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) {
114 ALOGW("SPKI length mismatch");
115 return false;
116 }
117 out->resize(SHA256_SIZE);
118 unsigned int digest_len = 0;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700119 int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400120 if (ret != 1) {
121 ALOGW("Server cert digest extraction failed");
122 return false;
123 }
124 if (digest_len != out->size()) {
125 ALOGW("Wrong digest length: %d", digest_len);
126 return false;
127 }
128 return true;
129}
130
131bool DnsTlsSocket::initialize() {
132 // This method should only be called once, at the beginning, so locking should be
133 // unnecessary. This lock only serves to help catch bugs in code that calls this method.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900134 std::lock_guard guard(mLock);
Ben Schwartzded1b702017-10-25 14:41:02 -0400135 if (mSslCtx) {
136 // This is a bug in the caller.
137 return false;
138 }
139 mSslCtx.reset(SSL_CTX_new(TLS_method()));
140 if (!mSslCtx) {
141 return false;
142 }
143
144 // Load system CA certs for hostname verification.
145 //
146 // For discussion of alternative, sustainable approaches see b/71909242.
147 if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
148 ALOGE("Failed to load CA cert dir: %s", kCaCertDir);
149 return false;
150 }
151
152 // Enable TLS false start
153 SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
154 SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
155
156 // Enable session cache
157 mCache->prepareSslContext(mSslCtx.get());
158
159 // Connect
160 Status status = tcpConnect();
161 if (!status.ok()) {
162 return false;
163 }
164 mSsl = sslConnect(mSslFd.get());
165 if (!mSsl) {
166 return false;
167 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500168
169 mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Ben Schwartz33860762017-10-25 14:41:02 -0400170
171 // Start the I/O loop.
172 mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
Ben Schwartzded1b702017-10-25 14:41:02 -0400173
174 return true;
175}
176
177bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
178 if (!mSslCtx) {
179 ALOGE("Internal error: context is null in sslConnect");
180 return nullptr;
181 }
182 if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
183 ALOGE("Failed to set minimum TLS version");
184 return nullptr;
185 }
186
187 bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
188 // This file descriptor is owned by mSslFd, so don't let libssl close it.
189 bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
190 SSL_set_bio(ssl.get(), bio.get(), bio.get());
191 bio.release();
192
193 if (!mCache->prepareSsl(ssl.get())) {
194 return nullptr;
195 }
196
197 if (!mServer.name.empty()) {
198 if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
199 ALOGE("Failed to set SNI to %s", mServer.name.c_str());
200 return nullptr;
201 }
202 X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
Erik Klineefc13632018-03-22 11:19:02 -0700203 if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
204 ALOGE("Failed to set verify host param to %s", mServer.name.c_str());
205 return nullptr;
206 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400207 // This will cause the handshake to fail if certificate verification fails.
208 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
209 }
210
211 bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
212 if (session) {
213 ALOGV("Setting session");
214 SSL_set_session(ssl.get(), session.get());
215 } else {
216 ALOGV("No session available");
217 }
218
219 for (;;) {
220 ALOGV("%u Calling SSL_connect", mMark);
221 int ret = SSL_connect(ssl.get());
222 ALOGV("%u SSL_connect returned %d", mMark, ret);
223 if (ret == 1) break; // SSL handshake complete;
224
225 const int ssl_err = SSL_get_error(ssl.get(), ret);
226 switch (ssl_err) {
227 case SSL_ERROR_WANT_READ:
228 if (waitForReading(fd) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900229 ALOGW("SSL_connect read error: %d", errno);
Ben Schwartzded1b702017-10-25 14:41:02 -0400230 return nullptr;
231 }
232 break;
233 case SSL_ERROR_WANT_WRITE:
234 if (waitForWriting(fd) != 1) {
235 ALOGW("SSL_connect write error");
236 return nullptr;
237 }
238 break;
239 default:
240 ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno);
241 return nullptr;
242 }
243 }
244
245 // TODO: Call SSL_shutdown before discarding the session if validation fails.
246 if (!mServer.fingerprints.empty()) {
247 ALOGV("Checking DNS over TLS fingerprint");
248
249 // We only care that the chain is internally self-consistent, not that
250 // it chains to a trusted root, so we can ignore some kinds of errors.
251 // TODO: Add a CA root verification mode that respects these errors.
252 int verify_result = SSL_get_verify_result(ssl.get());
253 switch (verify_result) {
254 case X509_V_OK:
255 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
256 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
257 case X509_V_ERR_CERT_UNTRUSTED:
258 break;
259 default:
260 ALOGW("Invalid certificate chain, error %d", verify_result);
261 return nullptr;
262 }
263
264 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get());
265 if (!chain) {
266 ALOGW("Server has null certificate");
267 return nullptr;
268 }
269 // Chain and its contents are owned by ssl, so we don't need to free explicitly.
270 bool matched = false;
271 for (size_t i = 0; i < sk_X509_num(chain); ++i) {
272 // This appears to be O(N^2), but there doesn't seem to be a straightforward
273 // way to walk a STACK_OF nondestructively in linear time.
274 X509* cert = sk_X509_value(chain, i);
275 std::vector<uint8_t> digest;
276 if (!getSPKIDigest(cert, &digest)) {
277 ALOGE("Digest computation failed");
278 return nullptr;
279 }
280
281 if (mServer.fingerprints.count(digest) > 0) {
282 matched = true;
283 break;
284 }
285 }
286
287 if (!matched) {
288 ALOGW("No matching fingerprint");
289 return nullptr;
290 }
291
292 ALOGV("DNS over TLS fingerprint is correct");
293 }
294
295 ALOGV("%u handshake complete", mMark);
296
297 return ssl;
298}
299
300void DnsTlsSocket::sslDisconnect() {
301 if (mSsl) {
302 SSL_shutdown(mSsl.get());
303 mSsl.reset();
304 }
305 mSslFd.reset();
306}
307
308bool DnsTlsSocket::sslWrite(const Slice buffer) {
309 ALOGV("%u Writing %zu bytes", mMark, buffer.size());
310 for (;;) {
311 int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
312 if (ret == int(buffer.size())) break; // SSL write complete;
313
314 if (ret < 1) {
315 const int ssl_err = SSL_get_error(mSsl.get(), ret);
316 switch (ssl_err) {
317 case SSL_ERROR_WANT_WRITE:
318 if (waitForWriting(mSslFd.get()) != 1) {
319 ALOGV("SSL_write error");
320 return false;
321 }
322 continue;
323 case 0:
324 break; // SSL write complete;
325 default:
326 ALOGV("SSL_write error %d", ssl_err);
327 return false;
328 }
329 }
330 }
331 ALOGV("%u Wrote %zu bytes", mMark, buffer.size());
332 return true;
333}
334
Ben Schwartz33860762017-10-25 14:41:02 -0400335void DnsTlsSocket::loop() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900336 std::lock_guard guard(mLock);
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500337 std::deque<std::vector<uint8_t>> q;
Ben Schwartz33860762017-10-25 14:41:02 -0400338
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900339 const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
Ben Schwartz33860762017-10-25 14:41:02 -0400340 while (true) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900341 // poll() ignores negative fds
342 struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500343 enum { SSLFD = 0, EVENTFD = 1 };
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900344
Ben Schwartz33860762017-10-25 14:41:02 -0400345 // Always listen for a response from server.
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900346 fds[SSLFD].fd = mSslFd.get();
347 fds[SSLFD].events = POLLIN;
348
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500349 // If we have pending queries, wait for space to write one.
350 // Otherwise, listen for new queries.
351 if (!q.empty()) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900352 fds[SSLFD].events |= POLLOUT;
Ben Schwartz33860762017-10-25 14:41:02 -0400353 } else {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500354 fds[EVENTFD].fd = mEventFd.get();
355 fds[EVENTFD].events = POLLIN;
Ben Schwartz33860762017-10-25 14:41:02 -0400356 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900357
Mike Yu5ae61542018-10-19 22:11:43 +0800358 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
Ben Schwartz33860762017-10-25 14:41:02 -0400359 if (s == 0) {
360 ALOGV("Idle timeout");
361 break;
362 }
363 if (s < 0) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900364 ALOGV("Poll failed: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400365 break;
366 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900367 if (fds[SSLFD].revents & (POLLIN | POLLERR)) {
Ben Schwartz33860762017-10-25 14:41:02 -0400368 if (!readResponse()) {
369 ALOGV("SSL remote close or read error.");
370 break;
371 }
372 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500373 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
374 int64_t num_queries;
375 ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
Ben Schwartz33860762017-10-25 14:41:02 -0400376 if (res < 0) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500377 ALOGW("Error during eventfd read");
Ben Schwartz33860762017-10-25 14:41:02 -0400378 break;
379 } else if (res == 0) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500380 ALOGV("eventfd closed; disconnecting");
Ben Schwartz33860762017-10-25 14:41:02 -0400381 break;
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500382 } else if (res != sizeof(num_queries)) {
383 ALOGE("Int size mismatch: %zd != %zu", res, sizeof(num_queries));
384 break;
385 } else if (num_queries <= 0) {
386 ALOGE("eventfd reads should always be positive");
387 break;
388 }
389 // Take ownership of all pending queries. (q is always empty here.)
390 mQueue.swap(q);
391 // The writing thread writes to mQueue and then increments mEventFd, so
392 // there should be at least num_queries entries in mQueue.
393 if (q.size() < (uint64_t) num_queries) {
394 ALOGE("Synchronization error");
Ben Schwartz33860762017-10-25 14:41:02 -0400395 break;
396 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900397 } else if (fds[SSLFD].revents & POLLOUT) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500398 // q cannot be empty here.
399 // Sending the entire queue here would risk a TCP flow control deadlock, so
400 // we only send a single query on each cycle of this loop.
401 // TODO: Coalesce multiple pending queries if there is enough space in the
402 // write buffer.
403 if (!sendQuery(q.front())) {
Ben Schwartz33860762017-10-25 14:41:02 -0400404 break;
405 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500406 q.pop_front();
Ben Schwartz33860762017-10-25 14:41:02 -0400407 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400408 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500409 ALOGV("Closing event FD");
410 mEventFd.reset();
Ben Schwartz33860762017-10-25 14:41:02 -0400411 ALOGV("Disconnecting");
412 sslDisconnect();
413 ALOGV("Calling onClosed");
414 mObserver->onClosed();
415 ALOGV("Ending loop");
Ben Schwartzded1b702017-10-25 14:41:02 -0400416}
417
Ben Schwartz33860762017-10-25 14:41:02 -0400418DnsTlsSocket::~DnsTlsSocket() {
419 ALOGV("Destructor");
420 // This will trigger an orderly shutdown in loop().
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500421 // In principle there is a data race here: If there is an I/O error in the network thread
422 // simultaneous with a call to the destructor in a different thread, both threads could
423 // attempt to call mEventFd.reset() at the same time. However, the implementation of
424 // UniqueFd::reset appears to be thread-safe, and neither thread reads or writes mEventFd
425 // after this point, so we don't expect an issue in practice.
426 mEventFd.reset();
Ben Schwartz33860762017-10-25 14:41:02 -0400427 {
428 // Wait for the orderly shutdown to complete.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900429 std::lock_guard guard(mLock);
Ben Schwartz33860762017-10-25 14:41:02 -0400430 if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
431 ALOGE("Violation of re-entrance precondition");
432 return;
433 }
434 }
435 if (mLoopThread) {
436 ALOGV("Waiting for loop thread to terminate");
437 mLoopThread->join();
438 mLoopThread.reset();
439 }
440 ALOGV("Destructor completed");
441}
442
443bool DnsTlsSocket::query(uint16_t id, const Slice query) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500444 if (!mEventFd) {
Ben Schwartz33860762017-10-25 14:41:02 -0400445 return false;
446 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500447
448 // Compose the entire message in a single buffer, so that it can be
449 // sent as a single TLS record.
450 std::vector<uint8_t> buf(query.size() + 4);
451 // Write 2-byte length
452 uint16_t len = query.size() + 2; // + 2 for the ID.
453 buf[0] = len >> 8;
454 buf[1] = len;
455 // Write 2-byte ID
456 buf[2] = id >> 8;
457 buf[3] = id;
458 // Copy body
459 std::memcpy(buf.data() + 4, query.base(), query.size());
460
461 mQueue.push(std::move(buf));
462 // Increment the mEventFd counter by 1.
463 constexpr int64_t num_queries = 1;
464 int written = write(mEventFd.get(), &num_queries, sizeof(num_queries));
465 return written == sizeof(num_queries);
Ben Schwartz33860762017-10-25 14:41:02 -0400466}
467
468// Read exactly len bytes into buffer or fail with an SSL error code
469int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400470 size_t remaining = buffer.size();
471 while (remaining > 0) {
472 int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
473 if (ret == 0) {
474 ALOGW_IF(remaining < buffer.size(), "SSL closed with %zu of %zu bytes remaining",
475 remaining, buffer.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400476 return SSL_ERROR_ZERO_RETURN;
Ben Schwartzded1b702017-10-25 14:41:02 -0400477 }
478
479 if (ret < 0) {
480 const int ssl_err = SSL_get_error(mSsl.get(), ret);
Ben Schwartz33860762017-10-25 14:41:02 -0400481 if (wait && ssl_err == SSL_ERROR_WANT_READ) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400482 if (waitForReading(mSslFd.get()) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900483 ALOGV("Poll failed in sslRead: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400484 return SSL_ERROR_SYSCALL;
Ben Schwartzded1b702017-10-25 14:41:02 -0400485 }
486 continue;
487 } else {
488 ALOGV("SSL_read error %d", ssl_err);
Ben Schwartz33860762017-10-25 14:41:02 -0400489 return ssl_err;
Ben Schwartzded1b702017-10-25 14:41:02 -0400490 }
491 }
492
493 remaining -= ret;
Ben Schwartz33860762017-10-25 14:41:02 -0400494 wait = true; // Once a read is started, try to finish.
Ben Schwartzded1b702017-10-25 14:41:02 -0400495 }
Ben Schwartz33860762017-10-25 14:41:02 -0400496 return SSL_ERROR_NONE;
Ben Schwartzded1b702017-10-25 14:41:02 -0400497}
498
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500499bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400500 if (!sslWrite(netdutils::makeSlice(buf))) {
501 return false;
502 }
503 ALOGV("%u SSL_write complete", mMark);
504 return true;
505}
506
Ben Schwartz33860762017-10-25 14:41:02 -0400507bool DnsTlsSocket::readResponse() {
Ben Schwartzded1b702017-10-25 14:41:02 -0400508 ALOGV("reading response");
509 uint8_t responseHeader[2];
Ben Schwartz33860762017-10-25 14:41:02 -0400510 int err = sslRead(Slice(responseHeader, 2), false);
511 if (err == SSL_ERROR_WANT_READ) {
512 ALOGV("Ignoring spurious wakeup from server");
513 return true;
514 }
515 if (err != SSL_ERROR_NONE) {
516 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400517 }
518 // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is
519 // always invalid when truncated, so the response will be treated as an error.
520 constexpr uint16_t MAX_SIZE = 8192;
521 const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
522 ALOGV("%u Expecting response of size %i", mMark, responseSize);
523 std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400524 if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400525 ALOGV("%u Failed to read %zu bytes", mMark, response.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400526 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400527 }
528 uint16_t remainingBytes = responseSize - response.size();
529 while (remainingBytes > 0) {
530 constexpr uint16_t CHUNK_SIZE = 2048;
531 std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400532 if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400533 ALOGV("%u Failed to discard %zu bytes", mMark, discard.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400534 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400535 }
536 remainingBytes -= discard.size();
537 }
538 ALOGV("%u SSL_read complete", mMark);
539
Ben Schwartz33860762017-10-25 14:41:02 -0400540 mObserver->onResponse(std::move(response));
541 return true;
Ben Schwartzded1b702017-10-25 14:41:02 -0400542}
543
544} // end of namespace net
545} // end of namespace android