Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 1 | /* |
| 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 18 | //#define LOG_NDEBUG 0 |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 19 | |
Mike Yu | 5ae6154 | 2018-10-19 22:11:43 +0800 | [diff] [blame] | 20 | #include "netd_resolv/DnsTlsSocket.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 21 | |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 22 | #include <arpa/inet.h> |
| 23 | #include <arpa/nameser.h> |
| 24 | #include <errno.h> |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 25 | #include <linux/tcp.h> |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 26 | #include <openssl/err.h> |
Mike Yu | 5ae6154 | 2018-10-19 22:11:43 +0800 | [diff] [blame] | 27 | #include <openssl/sha.h> |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 28 | #include <sys/eventfd.h> |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 29 | #include <sys/poll.h> |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 30 | #include <algorithm> |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 31 | |
Mike Yu | 5ae6154 | 2018-10-19 22:11:43 +0800 | [diff] [blame] | 32 | #include "netd_resolv/DnsTlsSessionCache.h" |
| 33 | #include "netd_resolv/IDnsTlsSocketObserver.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 34 | |
| 35 | #include "log/log.h" |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 36 | #include "netdutils/SocketOption.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 37 | |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 38 | namespace android { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 39 | |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 40 | using netdutils::enableSockopt; |
| 41 | using netdutils::enableTcpKeepAlives; |
| 42 | using netdutils::isOk; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 43 | using netdutils::Status; |
| 44 | |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 45 | namespace net { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 46 | namespace { |
| 47 | |
| 48 | constexpr const char kCaCertDir[] = "/system/etc/security/cacerts"; |
Mike Yu | 5ae6154 | 2018-10-19 22:11:43 +0800 | [diff] [blame] | 49 | constexpr size_t SHA256_SIZE = SHA256_DIGEST_LENGTH; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 50 | |
| 51 | int waitForReading(int fd) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 52 | struct pollfd fds = { .fd = fd, .events = POLLIN }; |
| 53 | const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 54 | return ret; |
| 55 | } |
| 56 | |
| 57 | int waitForWriting(int fd) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 58 | struct pollfd fds = { .fd = fd, .events = POLLOUT }; |
| 59 | const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 60 | return ret; |
| 61 | } |
| 62 | |
| 63 | } // namespace |
| 64 | |
| 65 | Status 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 Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 88 | |
| 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 Innocenti | 6f9fd90 | 2018-10-11 20:50:23 +0900 | [diff] [blame] | 95 | enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError(); |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 96 | |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 97 | 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 | |
| 108 | bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) { |
Yi Kong | bdfd57e | 2018-07-25 13:26:10 -0700 | [diff] [blame] | 109 | int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), nullptr); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 110 | 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 Kong | bdfd57e | 2018-07-25 13:26:10 -0700 | [diff] [blame] | 118 | int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 119 | 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 | |
| 130 | bool 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 Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 133 | std::lock_guard guard(mLock); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 134 | 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 Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 167 | |
| 168 | mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 169 | |
| 170 | // Start the I/O loop. |
| 171 | mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 172 | |
| 173 | return true; |
| 174 | } |
| 175 | |
| 176 | bssl::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 Kline | efc1363 | 2018-03-22 11:19:02 -0700 | [diff] [blame] | 202 | 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 Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 206 | // 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 Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 228 | ALOGW("SSL_connect read error: %d", errno); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 229 | 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 | |
| 299 | void DnsTlsSocket::sslDisconnect() { |
| 300 | if (mSsl) { |
| 301 | SSL_shutdown(mSsl.get()); |
| 302 | mSsl.reset(); |
| 303 | } |
| 304 | mSslFd.reset(); |
| 305 | } |
| 306 | |
| 307 | bool 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 334 | void DnsTlsSocket::loop() { |
Bernie Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 335 | std::lock_guard guard(mLock); |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 336 | std::deque<std::vector<uint8_t>> q; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 337 | |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 338 | const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 339 | while (true) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 340 | // poll() ignores negative fds |
| 341 | struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } }; |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 342 | enum { SSLFD = 0, EVENTFD = 1 }; |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 343 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 344 | // Always listen for a response from server. |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 345 | fds[SSLFD].fd = mSslFd.get(); |
| 346 | fds[SSLFD].events = POLLIN; |
| 347 | |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 348 | // If we have pending queries, wait for space to write one. |
| 349 | // Otherwise, listen for new queries. |
| 350 | if (!q.empty()) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 351 | fds[SSLFD].events |= POLLOUT; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 352 | } else { |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 353 | fds[EVENTFD].fd = mEventFd.get(); |
| 354 | fds[EVENTFD].events = POLLIN; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 355 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 356 | |
Mike Yu | 5ae6154 | 2018-10-19 22:11:43 +0800 | [diff] [blame] | 357 | const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 358 | if (s == 0) { |
| 359 | ALOGV("Idle timeout"); |
| 360 | break; |
| 361 | } |
| 362 | if (s < 0) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 363 | ALOGV("Poll failed: %d", errno); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 364 | break; |
| 365 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 366 | if (fds[SSLFD].revents & (POLLIN | POLLERR)) { |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 367 | if (!readResponse()) { |
| 368 | ALOGV("SSL remote close or read error."); |
| 369 | break; |
| 370 | } |
| 371 | } |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 372 | if (fds[EVENTFD].revents & (POLLIN | POLLERR)) { |
| 373 | int64_t num_queries; |
| 374 | ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 375 | if (res < 0) { |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 376 | ALOGW("Error during eventfd read"); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 377 | break; |
| 378 | } else if (res == 0) { |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 379 | ALOGV("eventfd closed; disconnecting"); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 380 | break; |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 381 | } 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 394 | break; |
| 395 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 396 | } else if (fds[SSLFD].revents & POLLOUT) { |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 397 | // 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 403 | break; |
| 404 | } |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 405 | q.pop_front(); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 406 | } |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 407 | } |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 408 | ALOGV("Closing event FD"); |
| 409 | mEventFd.reset(); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 410 | ALOGV("Disconnecting"); |
| 411 | sslDisconnect(); |
| 412 | ALOGV("Calling onClosed"); |
| 413 | mObserver->onClosed(); |
| 414 | ALOGV("Ending loop"); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 415 | } |
| 416 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 417 | DnsTlsSocket::~DnsTlsSocket() { |
| 418 | ALOGV("Destructor"); |
| 419 | // This will trigger an orderly shutdown in loop(). |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 420 | // 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 426 | { |
| 427 | // Wait for the orderly shutdown to complete. |
Bernie Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 428 | std::lock_guard guard(mLock); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 429 | 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 | |
| 442 | bool DnsTlsSocket::query(uint16_t id, const Slice query) { |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 443 | if (!mEventFd) { |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 444 | return false; |
| 445 | } |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 446 | |
| 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 465 | } |
| 466 | |
| 467 | // Read exactly len bytes into buffer or fail with an SSL error code |
| 468 | int DnsTlsSocket::sslRead(const Slice buffer, bool wait) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 469 | 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 475 | return SSL_ERROR_ZERO_RETURN; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 476 | } |
| 477 | |
| 478 | if (ret < 0) { |
| 479 | const int ssl_err = SSL_get_error(mSsl.get(), ret); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 480 | if (wait && ssl_err == SSL_ERROR_WANT_READ) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 481 | if (waitForReading(mSslFd.get()) != 1) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 482 | ALOGV("Poll failed in sslRead: %d", errno); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 483 | return SSL_ERROR_SYSCALL; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 484 | } |
| 485 | continue; |
| 486 | } else { |
| 487 | ALOGV("SSL_read error %d", ssl_err); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 488 | return ssl_err; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 489 | } |
| 490 | } |
| 491 | |
| 492 | remaining -= ret; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 493 | wait = true; // Once a read is started, try to finish. |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 494 | } |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 495 | return SSL_ERROR_NONE; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 496 | } |
| 497 | |
Ben Schwartz | bfc8d99 | 2019-01-10 14:30:46 -0500 | [diff] [blame^] | 498 | bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 499 | if (!sslWrite(netdutils::makeSlice(buf))) { |
| 500 | return false; |
| 501 | } |
| 502 | ALOGV("%u SSL_write complete", mMark); |
| 503 | return true; |
| 504 | } |
| 505 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 506 | bool DnsTlsSocket::readResponse() { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 507 | ALOGV("reading response"); |
| 508 | uint8_t responseHeader[2]; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 509 | 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 Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 516 | } |
| 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 523 | if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 524 | ALOGV("%u Failed to read %zu bytes", mMark, response.size()); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 525 | return false; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 526 | } |
| 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 531 | if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 532 | ALOGV("%u Failed to discard %zu bytes", mMark, discard.size()); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 533 | return false; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 534 | } |
| 535 | remainingBytes -= discard.size(); |
| 536 | } |
| 537 | ALOGV("%u SSL_read complete", mMark); |
| 538 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 539 | mObserver->onResponse(std::move(response)); |
| 540 | return true; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 541 | } |
| 542 | |
| 543 | } // end of namespace net |
| 544 | } // end of namespace android |