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 | |
| 20 | #include "dns/DnsTlsSocket.h" |
| 21 | |
| 22 | #include <algorithm> |
| 23 | #include <arpa/inet.h> |
| 24 | #include <arpa/nameser.h> |
| 25 | #include <errno.h> |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 26 | #include <linux/tcp.h> |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 27 | #include <openssl/err.h> |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 28 | #include <sys/poll.h> |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 29 | |
| 30 | #include "dns/DnsTlsSessionCache.h" |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 31 | #include "dns/IDnsTlsSocketObserver.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 32 | |
| 33 | #include "log/log.h" |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 34 | #include "netdutils/SocketOption.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 35 | #include "Fwmark.h" |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 36 | #include "NetdConstants.h" |
| 37 | #include "Permission.h" |
| 38 | |
| 39 | |
| 40 | namespace android { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 41 | |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 42 | using netdutils::enableSockopt; |
| 43 | using netdutils::enableTcpKeepAlives; |
| 44 | using netdutils::isOk; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 45 | using netdutils::Status; |
| 46 | |
Erik Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 47 | namespace net { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 48 | namespace { |
| 49 | |
| 50 | constexpr const char kCaCertDir[] = "/system/etc/security/cacerts"; |
| 51 | |
| 52 | int waitForReading(int fd) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 53 | struct pollfd fds = { .fd = fd, .events = POLLIN }; |
| 54 | const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 55 | return ret; |
| 56 | } |
| 57 | |
| 58 | int waitForWriting(int fd) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 59 | struct pollfd fds = { .fd = fd, .events = POLLOUT }; |
| 60 | const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 61 | return ret; |
| 62 | } |
| 63 | |
| 64 | } // namespace |
| 65 | |
| 66 | Status 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 Kline | d150307 | 2018-02-22 23:55:40 -0800 | [diff] [blame] | 89 | |
| 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. |
| 96 | enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U); |
| 97 | |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 98 | 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 | |
| 109 | bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) { |
Yi Kong | bdfd57e | 2018-07-25 13:26:10 -0700 | [diff] [blame] | 110 | int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), nullptr); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 111 | 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 Kong | bdfd57e | 2018-07-25 13:26:10 -0700 | [diff] [blame] | 119 | 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] | 120 | 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 | |
| 131 | bool 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 Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 134 | std::lock_guard guard(mLock); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 135 | 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 Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 168 | int sv[2]; |
| 169 | if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, sv)) { |
| 170 | return false; |
| 171 | } |
| 172 | // The two sockets are perfectly symmetrical, so the choice of which one is |
| 173 | // "in" and which one is "out" is arbitrary. |
| 174 | mIpcInFd.reset(sv[0]); |
| 175 | mIpcOutFd.reset(sv[1]); |
| 176 | |
| 177 | // Start the I/O loop. |
| 178 | mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this)); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 179 | |
| 180 | return true; |
| 181 | } |
| 182 | |
| 183 | bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) { |
| 184 | if (!mSslCtx) { |
| 185 | ALOGE("Internal error: context is null in sslConnect"); |
| 186 | return nullptr; |
| 187 | } |
| 188 | if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) { |
| 189 | ALOGE("Failed to set minimum TLS version"); |
| 190 | return nullptr; |
| 191 | } |
| 192 | |
| 193 | bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get())); |
| 194 | // This file descriptor is owned by mSslFd, so don't let libssl close it. |
| 195 | bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE)); |
| 196 | SSL_set_bio(ssl.get(), bio.get(), bio.get()); |
| 197 | bio.release(); |
| 198 | |
| 199 | if (!mCache->prepareSsl(ssl.get())) { |
| 200 | return nullptr; |
| 201 | } |
| 202 | |
| 203 | if (!mServer.name.empty()) { |
| 204 | if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) { |
| 205 | ALOGE("Failed to set SNI to %s", mServer.name.c_str()); |
| 206 | return nullptr; |
| 207 | } |
| 208 | X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get()); |
Erik Kline | efc1363 | 2018-03-22 11:19:02 -0700 | [diff] [blame] | 209 | if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) { |
| 210 | ALOGE("Failed to set verify host param to %s", mServer.name.c_str()); |
| 211 | return nullptr; |
| 212 | } |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 213 | // This will cause the handshake to fail if certificate verification fails. |
| 214 | SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr); |
| 215 | } |
| 216 | |
| 217 | bssl::UniquePtr<SSL_SESSION> session = mCache->getSession(); |
| 218 | if (session) { |
| 219 | ALOGV("Setting session"); |
| 220 | SSL_set_session(ssl.get(), session.get()); |
| 221 | } else { |
| 222 | ALOGV("No session available"); |
| 223 | } |
| 224 | |
| 225 | for (;;) { |
| 226 | ALOGV("%u Calling SSL_connect", mMark); |
| 227 | int ret = SSL_connect(ssl.get()); |
| 228 | ALOGV("%u SSL_connect returned %d", mMark, ret); |
| 229 | if (ret == 1) break; // SSL handshake complete; |
| 230 | |
| 231 | const int ssl_err = SSL_get_error(ssl.get(), ret); |
| 232 | switch (ssl_err) { |
| 233 | case SSL_ERROR_WANT_READ: |
| 234 | if (waitForReading(fd) != 1) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 235 | ALOGW("SSL_connect read error: %d", errno); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 236 | return nullptr; |
| 237 | } |
| 238 | break; |
| 239 | case SSL_ERROR_WANT_WRITE: |
| 240 | if (waitForWriting(fd) != 1) { |
| 241 | ALOGW("SSL_connect write error"); |
| 242 | return nullptr; |
| 243 | } |
| 244 | break; |
| 245 | default: |
| 246 | ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno); |
| 247 | return nullptr; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // TODO: Call SSL_shutdown before discarding the session if validation fails. |
| 252 | if (!mServer.fingerprints.empty()) { |
| 253 | ALOGV("Checking DNS over TLS fingerprint"); |
| 254 | |
| 255 | // We only care that the chain is internally self-consistent, not that |
| 256 | // it chains to a trusted root, so we can ignore some kinds of errors. |
| 257 | // TODO: Add a CA root verification mode that respects these errors. |
| 258 | int verify_result = SSL_get_verify_result(ssl.get()); |
| 259 | switch (verify_result) { |
| 260 | case X509_V_OK: |
| 261 | case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: |
| 262 | case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: |
| 263 | case X509_V_ERR_CERT_UNTRUSTED: |
| 264 | break; |
| 265 | default: |
| 266 | ALOGW("Invalid certificate chain, error %d", verify_result); |
| 267 | return nullptr; |
| 268 | } |
| 269 | |
| 270 | STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get()); |
| 271 | if (!chain) { |
| 272 | ALOGW("Server has null certificate"); |
| 273 | return nullptr; |
| 274 | } |
| 275 | // Chain and its contents are owned by ssl, so we don't need to free explicitly. |
| 276 | bool matched = false; |
| 277 | for (size_t i = 0; i < sk_X509_num(chain); ++i) { |
| 278 | // This appears to be O(N^2), but there doesn't seem to be a straightforward |
| 279 | // way to walk a STACK_OF nondestructively in linear time. |
| 280 | X509* cert = sk_X509_value(chain, i); |
| 281 | std::vector<uint8_t> digest; |
| 282 | if (!getSPKIDigest(cert, &digest)) { |
| 283 | ALOGE("Digest computation failed"); |
| 284 | return nullptr; |
| 285 | } |
| 286 | |
| 287 | if (mServer.fingerprints.count(digest) > 0) { |
| 288 | matched = true; |
| 289 | break; |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | if (!matched) { |
| 294 | ALOGW("No matching fingerprint"); |
| 295 | return nullptr; |
| 296 | } |
| 297 | |
| 298 | ALOGV("DNS over TLS fingerprint is correct"); |
| 299 | } |
| 300 | |
| 301 | ALOGV("%u handshake complete", mMark); |
| 302 | |
| 303 | return ssl; |
| 304 | } |
| 305 | |
| 306 | void DnsTlsSocket::sslDisconnect() { |
| 307 | if (mSsl) { |
| 308 | SSL_shutdown(mSsl.get()); |
| 309 | mSsl.reset(); |
| 310 | } |
| 311 | mSslFd.reset(); |
| 312 | } |
| 313 | |
| 314 | bool DnsTlsSocket::sslWrite(const Slice buffer) { |
| 315 | ALOGV("%u Writing %zu bytes", mMark, buffer.size()); |
| 316 | for (;;) { |
| 317 | int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size()); |
| 318 | if (ret == int(buffer.size())) break; // SSL write complete; |
| 319 | |
| 320 | if (ret < 1) { |
| 321 | const int ssl_err = SSL_get_error(mSsl.get(), ret); |
| 322 | switch (ssl_err) { |
| 323 | case SSL_ERROR_WANT_WRITE: |
| 324 | if (waitForWriting(mSslFd.get()) != 1) { |
| 325 | ALOGV("SSL_write error"); |
| 326 | return false; |
| 327 | } |
| 328 | continue; |
| 329 | case 0: |
| 330 | break; // SSL write complete; |
| 331 | default: |
| 332 | ALOGV("SSL_write error %d", ssl_err); |
| 333 | return false; |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | ALOGV("%u Wrote %zu bytes", mMark, buffer.size()); |
| 338 | return true; |
| 339 | } |
| 340 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 341 | void DnsTlsSocket::loop() { |
Bernie Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 342 | std::lock_guard guard(mLock); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 343 | // Buffer at most one query. |
| 344 | Query q; |
| 345 | |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 346 | const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 347 | while (true) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 348 | // poll() ignores negative fds |
| 349 | struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } }; |
| 350 | enum { SSLFD = 0, IPCFD = 1 }; |
| 351 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 352 | // Always listen for a response from server. |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 353 | fds[SSLFD].fd = mSslFd.get(); |
| 354 | fds[SSLFD].events = POLLIN; |
| 355 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 356 | // If we have a pending query, also wait for space |
| 357 | // to write it, otherwise listen for a new query. |
| 358 | if (!q.query.empty()) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 359 | fds[SSLFD].events |= POLLOUT; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 360 | } else { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 361 | fds[IPCFD].fd = mIpcOutFd.get(); |
| 362 | fds[IPCFD].events = POLLIN; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 363 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 364 | |
| 365 | const int s = TEMP_FAILURE_RETRY(poll(fds, ARRAY_SIZE(fds), timeout_msecs)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 366 | if (s == 0) { |
| 367 | ALOGV("Idle timeout"); |
| 368 | break; |
| 369 | } |
| 370 | if (s < 0) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 371 | ALOGV("Poll failed: %d", errno); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 372 | break; |
| 373 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 374 | if (fds[SSLFD].revents & (POLLIN | POLLERR)) { |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 375 | if (!readResponse()) { |
| 376 | ALOGV("SSL remote close or read error."); |
| 377 | break; |
| 378 | } |
| 379 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 380 | if (fds[IPCFD].revents & (POLLIN | POLLERR)) { |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 381 | int res = read(mIpcOutFd.get(), &q, sizeof(q)); |
| 382 | if (res < 0) { |
| 383 | ALOGW("Error during IPC read"); |
| 384 | break; |
| 385 | } else if (res == 0) { |
| 386 | ALOGV("IPC channel closed; disconnecting"); |
| 387 | break; |
| 388 | } else if (res != sizeof(q)) { |
| 389 | ALOGE("Struct size mismatch: %d != %zu", res, sizeof(q)); |
| 390 | break; |
| 391 | } |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 392 | } else if (fds[SSLFD].revents & POLLOUT) { |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 393 | // query cannot be null here. |
| 394 | if (!sendQuery(q)) { |
| 395 | break; |
| 396 | } |
| 397 | q = Query(); // Reset q to empty |
| 398 | } |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 399 | } |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 400 | ALOGV("Closing IPC read FD"); |
| 401 | mIpcOutFd.reset(); |
| 402 | ALOGV("Disconnecting"); |
| 403 | sslDisconnect(); |
| 404 | ALOGV("Calling onClosed"); |
| 405 | mObserver->onClosed(); |
| 406 | ALOGV("Ending loop"); |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 407 | } |
| 408 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 409 | DnsTlsSocket::~DnsTlsSocket() { |
| 410 | ALOGV("Destructor"); |
| 411 | // This will trigger an orderly shutdown in loop(). |
| 412 | mIpcInFd.reset(); |
| 413 | { |
| 414 | // Wait for the orderly shutdown to complete. |
Bernie Innocenti | abf8a34 | 2018-08-10 15:17:16 +0900 | [diff] [blame] | 415 | std::lock_guard guard(mLock); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 416 | if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) { |
| 417 | ALOGE("Violation of re-entrance precondition"); |
| 418 | return; |
| 419 | } |
| 420 | } |
| 421 | if (mLoopThread) { |
| 422 | ALOGV("Waiting for loop thread to terminate"); |
| 423 | mLoopThread->join(); |
| 424 | mLoopThread.reset(); |
| 425 | } |
| 426 | ALOGV("Destructor completed"); |
| 427 | } |
| 428 | |
| 429 | bool DnsTlsSocket::query(uint16_t id, const Slice query) { |
| 430 | const Query q = { .id = id, .query = query }; |
| 431 | if (!mIpcInFd) { |
| 432 | return false; |
| 433 | } |
| 434 | int written = write(mIpcInFd.get(), &q, sizeof(q)); |
| 435 | return written == sizeof(q); |
| 436 | } |
| 437 | |
| 438 | // Read exactly len bytes into buffer or fail with an SSL error code |
| 439 | int DnsTlsSocket::sslRead(const Slice buffer, bool wait) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 440 | size_t remaining = buffer.size(); |
| 441 | while (remaining > 0) { |
| 442 | int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining); |
| 443 | if (ret == 0) { |
| 444 | ALOGW_IF(remaining < buffer.size(), "SSL closed with %zu of %zu bytes remaining", |
| 445 | remaining, buffer.size()); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 446 | return SSL_ERROR_ZERO_RETURN; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 447 | } |
| 448 | |
| 449 | if (ret < 0) { |
| 450 | const int ssl_err = SSL_get_error(mSsl.get(), ret); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 451 | if (wait && ssl_err == SSL_ERROR_WANT_READ) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 452 | if (waitForReading(mSslFd.get()) != 1) { |
Bernie Innocenti | f944a9c | 2018-05-18 20:50:25 +0900 | [diff] [blame] | 453 | ALOGV("Poll failed in sslRead: %d", errno); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 454 | return SSL_ERROR_SYSCALL; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 455 | } |
| 456 | continue; |
| 457 | } else { |
| 458 | ALOGV("SSL_read error %d", ssl_err); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 459 | return ssl_err; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 460 | } |
| 461 | } |
| 462 | |
| 463 | remaining -= ret; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 464 | wait = true; // Once a read is started, try to finish. |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 465 | } |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 466 | return SSL_ERROR_NONE; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 467 | } |
| 468 | |
| 469 | bool DnsTlsSocket::sendQuery(const Query& q) { |
| 470 | ALOGV("sending query"); |
| 471 | // Compose the entire message in a single buffer, so that it can be |
| 472 | // sent as a single TLS record. |
| 473 | std::vector<uint8_t> buf(q.query.size() + 4); |
| 474 | // Write 2-byte length |
| 475 | uint16_t len = q.query.size() + 2; // + 2 for the ID. |
| 476 | buf[0] = len >> 8; |
| 477 | buf[1] = len; |
| 478 | // Write 2-byte ID |
| 479 | buf[2] = q.id >> 8; |
| 480 | buf[3] = q.id; |
| 481 | // Copy body |
| 482 | std::memcpy(buf.data() + 4, q.query.base(), q.query.size()); |
| 483 | if (!sslWrite(netdutils::makeSlice(buf))) { |
| 484 | return false; |
| 485 | } |
| 486 | ALOGV("%u SSL_write complete", mMark); |
| 487 | return true; |
| 488 | } |
| 489 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 490 | bool DnsTlsSocket::readResponse() { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 491 | ALOGV("reading response"); |
| 492 | uint8_t responseHeader[2]; |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 493 | int err = sslRead(Slice(responseHeader, 2), false); |
| 494 | if (err == SSL_ERROR_WANT_READ) { |
| 495 | ALOGV("Ignoring spurious wakeup from server"); |
| 496 | return true; |
| 497 | } |
| 498 | if (err != SSL_ERROR_NONE) { |
| 499 | return false; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 500 | } |
| 501 | // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is |
| 502 | // always invalid when truncated, so the response will be treated as an error. |
| 503 | constexpr uint16_t MAX_SIZE = 8192; |
| 504 | const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1]; |
| 505 | ALOGV("%u Expecting response of size %i", mMark, responseSize); |
| 506 | std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 507 | if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 508 | ALOGV("%u Failed to read %zu bytes", mMark, response.size()); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 509 | return false; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 510 | } |
| 511 | uint16_t remainingBytes = responseSize - response.size(); |
| 512 | while (remainingBytes > 0) { |
| 513 | constexpr uint16_t CHUNK_SIZE = 2048; |
| 514 | std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE)); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 515 | if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) { |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 516 | ALOGV("%u Failed to discard %zu bytes", mMark, discard.size()); |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 517 | return false; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 518 | } |
| 519 | remainingBytes -= discard.size(); |
| 520 | } |
| 521 | ALOGV("%u SSL_read complete", mMark); |
| 522 | |
Ben Schwartz | 3386076 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 523 | mObserver->onResponse(std::move(response)); |
| 524 | return true; |
Ben Schwartz | ded1b70 | 2017-10-25 14:41:02 -0400 | [diff] [blame] | 525 | } |
| 526 | |
| 527 | } // end of namespace net |
| 528 | } // end of namespace android |