Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017 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 | #include "dns/DnsTlsTransport.h" |
| 18 | |
| 19 | #include <arpa/inet.h> |
| 20 | #include <arpa/nameser.h> |
| 21 | #include <errno.h> |
| 22 | #include <openssl/err.h> |
| 23 | #include <openssl/ssl.h> |
| 24 | #include <stdlib.h> |
| 25 | |
| 26 | #define LOG_TAG "DnsTlsTransport" |
| 27 | #define DBG 0 |
| 28 | |
| 29 | #include "log/log.h" |
| 30 | #include "Fwmark.h" |
| 31 | #undef ADD // already defined in nameser.h |
| 32 | #include "NetdConstants.h" |
| 33 | #include "Permission.h" |
| 34 | |
| 35 | |
| 36 | namespace android { |
| 37 | namespace net { |
| 38 | |
| 39 | namespace { |
| 40 | |
| 41 | bool setNonBlocking(int fd, bool enabled) { |
| 42 | int flags = fcntl(fd, F_GETFL); |
| 43 | if (flags < 0) return false; |
| 44 | |
| 45 | if (enabled) { |
| 46 | flags |= O_NONBLOCK; |
| 47 | } else { |
| 48 | flags &= ~O_NONBLOCK; |
| 49 | } |
| 50 | return (fcntl(fd, F_SETFL, flags) == 0); |
| 51 | } |
| 52 | |
| 53 | int waitForReading(int fd) { |
| 54 | fd_set fds; |
| 55 | FD_ZERO(&fds); |
| 56 | FD_SET(fd, &fds); |
| 57 | const int ret = TEMP_FAILURE_RETRY(select(fd + 1, &fds, nullptr, nullptr, nullptr)); |
| 58 | if (DBG && ret <= 0) { |
| 59 | ALOGD("select"); |
| 60 | } |
| 61 | return ret; |
| 62 | } |
| 63 | |
| 64 | int waitForWriting(int fd) { |
| 65 | fd_set fds; |
| 66 | FD_ZERO(&fds); |
| 67 | FD_SET(fd, &fds); |
| 68 | const int ret = TEMP_FAILURE_RETRY(select(fd + 1, nullptr, &fds, nullptr, nullptr)); |
| 69 | if (DBG && ret <= 0) { |
| 70 | ALOGD("select"); |
| 71 | } |
| 72 | return ret; |
| 73 | } |
| 74 | |
| 75 | } // namespace |
| 76 | |
| 77 | android::base::unique_fd DnsTlsTransport::makeConnectedSocket() const { |
| 78 | android::base::unique_fd fd; |
| 79 | int type = SOCK_NONBLOCK | SOCK_CLOEXEC; |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 80 | switch (mServer.protocol) { |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 81 | case IPPROTO_TCP: |
| 82 | type |= SOCK_STREAM; |
| 83 | break; |
| 84 | default: |
| 85 | errno = EPROTONOSUPPORT; |
| 86 | return fd; |
| 87 | } |
| 88 | |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 89 | fd.reset(socket(mServer.ss.ss_family, type, mServer.protocol)); |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 90 | if (fd.get() == -1) { |
| 91 | return fd; |
| 92 | } |
| 93 | |
| 94 | const socklen_t len = sizeof(mMark); |
| 95 | if (setsockopt(fd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) { |
| 96 | fd.reset(); |
| 97 | } else if (connect(fd.get(), |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 98 | reinterpret_cast<const struct sockaddr *>(&mServer.ss), sizeof(mServer.ss)) != 0 |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 99 | && errno != EINPROGRESS) { |
| 100 | fd.reset(); |
| 101 | } |
| 102 | |
| 103 | return fd; |
| 104 | } |
| 105 | |
| 106 | bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) { |
| 107 | int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); |
| 108 | unsigned char spki[spki_len]; |
| 109 | unsigned char* temp = spki; |
| 110 | if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) { |
| 111 | ALOGW("SPKI length mismatch"); |
| 112 | return false; |
| 113 | } |
| 114 | out->resize(SHA256_SIZE); |
| 115 | unsigned int digest_len = 0; |
| 116 | int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), NULL); |
| 117 | if (ret != 1) { |
| 118 | ALOGW("Server cert digest extraction failed"); |
| 119 | return false; |
| 120 | } |
| 121 | if (digest_len != out->size()) { |
| 122 | ALOGW("Wrong digest length: %d", digest_len); |
| 123 | return false; |
| 124 | } |
| 125 | return true; |
| 126 | } |
| 127 | |
| 128 | SSL* DnsTlsTransport::sslConnect(int fd) { |
| 129 | if (fd < 0) { |
| 130 | ALOGD("%u makeConnectedSocket() failed with: %s", mMark, strerror(errno)); |
| 131 | return nullptr; |
| 132 | } |
| 133 | |
| 134 | // Set up TLS context. |
| 135 | bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method())); |
| 136 | if (!SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION) || |
| 137 | !SSL_CTX_set_min_proto_version(ssl_ctx.get(), TLS1_1_VERSION)) { |
| 138 | ALOGD("failed to min/max TLS versions"); |
| 139 | return nullptr; |
| 140 | } |
| 141 | |
| 142 | bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx.get())); |
| 143 | bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_CLOSE)); |
| 144 | SSL_set_bio(ssl.get(), bio.get(), bio.get()); |
| 145 | bio.release(); |
| 146 | |
| 147 | if (!setNonBlocking(fd, false)) { |
| 148 | ALOGE("Failed to disable nonblocking status on DNS-over-TLS fd"); |
| 149 | return nullptr; |
| 150 | } |
| 151 | |
| 152 | for (;;) { |
| 153 | if (DBG) { |
| 154 | ALOGD("%u Calling SSL_connect", mMark); |
| 155 | } |
| 156 | int ret = SSL_connect(ssl.get()); |
| 157 | if (DBG) { |
| 158 | ALOGD("%u SSL_connect returned %d", mMark, ret); |
| 159 | } |
| 160 | if (ret == 1) break; // SSL handshake complete; |
| 161 | |
| 162 | const int ssl_err = SSL_get_error(ssl.get(), ret); |
| 163 | switch (ssl_err) { |
| 164 | case SSL_ERROR_WANT_READ: |
| 165 | if (waitForReading(fd) != 1) { |
| 166 | ALOGW("SSL_connect read error"); |
| 167 | return nullptr; |
| 168 | } |
| 169 | break; |
| 170 | case SSL_ERROR_WANT_WRITE: |
| 171 | if (waitForWriting(fd) != 1) { |
| 172 | ALOGW("SSL_connect write error"); |
| 173 | return nullptr; |
| 174 | } |
| 175 | break; |
| 176 | default: |
| 177 | ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno); |
| 178 | return nullptr; |
| 179 | } |
| 180 | } |
| 181 | |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 182 | if (!mServer.fingerprints.empty()) { |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 183 | if (DBG) { |
| 184 | ALOGD("Checking DNS over TLS fingerprint"); |
| 185 | } |
Ben Schwartz | f028d39 | 2017-07-10 15:07:12 -0400 | [diff] [blame^] | 186 | |
| 187 | // We only care that the chain is internally self-consistent, not that |
| 188 | // it chains to a trusted root, so we can ignore some kinds of errors. |
| 189 | // TODO: Add a CA root verification mode that respects these errors. |
| 190 | int verify_result = SSL_get_verify_result(ssl.get()); |
| 191 | switch (verify_result) { |
| 192 | case X509_V_OK: |
| 193 | case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: |
| 194 | case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: |
| 195 | case X509_V_ERR_CERT_UNTRUSTED: |
| 196 | break; |
| 197 | default: |
| 198 | ALOGW("Invalid certificate chain, error %d", verify_result); |
| 199 | return nullptr; |
| 200 | } |
| 201 | |
| 202 | STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get()); |
| 203 | if (!chain) { |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 204 | ALOGW("Server has null certificate"); |
| 205 | return nullptr; |
| 206 | } |
Ben Schwartz | f028d39 | 2017-07-10 15:07:12 -0400 | [diff] [blame^] | 207 | // Chain and its contents are owned by ssl, so we don't need to free explicitly. |
| 208 | bool matched = false; |
| 209 | for (size_t i = 0; i < sk_X509_num(chain); ++i) { |
| 210 | // This appears to be O(N^2), but there doesn't seem to be a straightforward |
| 211 | // way to walk a STACK_OF nondestructively in linear time. |
| 212 | X509* cert = sk_X509_value(chain, i); |
| 213 | std::vector<uint8_t> digest; |
| 214 | if (!getSPKIDigest(cert, &digest)) { |
| 215 | ALOGE("Digest computation failed"); |
| 216 | return nullptr; |
| 217 | } |
| 218 | |
| 219 | if (mServer.fingerprints.count(digest) > 0) { |
| 220 | matched = true; |
| 221 | break; |
| 222 | } |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 223 | } |
| 224 | |
Ben Schwartz | f028d39 | 2017-07-10 15:07:12 -0400 | [diff] [blame^] | 225 | if (!matched) { |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 226 | ALOGW("No matching fingerprint"); |
| 227 | return nullptr; |
| 228 | } |
Ben Schwartz | f028d39 | 2017-07-10 15:07:12 -0400 | [diff] [blame^] | 229 | |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 230 | if (DBG) { |
| 231 | ALOGD("DNS over TLS fingerprint is correct"); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | if (DBG) { |
| 236 | ALOGD("%u handshake complete", mMark); |
| 237 | } |
| 238 | return ssl.release(); |
| 239 | } |
| 240 | |
| 241 | bool DnsTlsTransport::sslWrite(int fd, SSL *ssl, const uint8_t *buffer, int len) { |
| 242 | if (DBG) { |
| 243 | ALOGD("%u Writing %d bytes", mMark, len); |
| 244 | } |
| 245 | for (;;) { |
| 246 | int ret = SSL_write(ssl, buffer, len); |
| 247 | if (ret == len) break; // SSL write complete; |
| 248 | |
| 249 | if (ret < 1) { |
| 250 | const int ssl_err = SSL_get_error(ssl, ret); |
| 251 | switch (ssl_err) { |
| 252 | case SSL_ERROR_WANT_WRITE: |
| 253 | if (waitForWriting(fd) != 1) { |
| 254 | if (DBG) { |
| 255 | ALOGW("SSL_write error"); |
| 256 | } |
| 257 | return false; |
| 258 | } |
| 259 | continue; |
| 260 | case 0: |
| 261 | break; // SSL write complete; |
| 262 | default: |
| 263 | if (DBG) { |
| 264 | ALOGW("SSL_write error %d", ssl_err); |
| 265 | } |
| 266 | return false; |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | if (DBG) { |
| 271 | ALOGD("%u Wrote %d bytes", mMark, len); |
| 272 | } |
| 273 | return true; |
| 274 | } |
| 275 | |
| 276 | // Read exactly len bytes into buffer or fail |
| 277 | bool DnsTlsTransport::sslRead(int fd, SSL *ssl, uint8_t *buffer, int len) { |
| 278 | int remaining = len; |
| 279 | while (remaining > 0) { |
| 280 | int ret = SSL_read(ssl, buffer + (len - remaining), remaining); |
| 281 | if (ret == 0) { |
| 282 | ALOGE("SSL socket closed with %i of %i bytes remaining", remaining, len); |
| 283 | return false; |
| 284 | } |
| 285 | |
| 286 | if (ret < 0) { |
| 287 | const int ssl_err = SSL_get_error(ssl, ret); |
| 288 | if (ssl_err == SSL_ERROR_WANT_READ) { |
| 289 | if (waitForReading(fd) != 1) { |
| 290 | if (DBG) { |
| 291 | ALOGW("SSL_read error"); |
| 292 | } |
| 293 | return false; |
| 294 | } |
| 295 | continue; |
| 296 | } else { |
| 297 | if (DBG) { |
| 298 | ALOGW("SSL_read error %d", ssl_err); |
| 299 | } |
| 300 | return false; |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | remaining -= ret; |
| 305 | } |
| 306 | return true; |
| 307 | } |
| 308 | |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 309 | // static |
| 310 | DnsTlsTransport::Response DnsTlsTransport::query(const Server& server, unsigned mark, |
| 311 | const uint8_t *query, size_t qlen, uint8_t *response, size_t limit, int *resplen) { |
| 312 | // TODO: Keep a static container of transports instead of constructing a new one |
| 313 | // for every query. |
| 314 | DnsTlsTransport xport(server, mark); |
| 315 | return xport.doQuery(query, qlen, response, limit, resplen); |
| 316 | } |
| 317 | |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 318 | DnsTlsTransport::Response DnsTlsTransport::doQuery(const uint8_t *query, size_t qlen, |
| 319 | uint8_t *response, size_t limit, int *resplen) { |
| 320 | *resplen = 0; // Zero indicates an error. |
| 321 | |
| 322 | if (DBG) { |
| 323 | ALOGD("%u connecting TCP socket", mMark); |
| 324 | } |
| 325 | android::base::unique_fd fd(makeConnectedSocket()); |
| 326 | if (DBG) { |
| 327 | ALOGD("%u connecting SSL", mMark); |
| 328 | } |
| 329 | bssl::UniquePtr<SSL> ssl(sslConnect(fd)); |
| 330 | if (ssl == nullptr) { |
| 331 | if (DBG) { |
| 332 | ALOGW("%u SSL connection failed", mMark); |
| 333 | } |
| 334 | return Response::network_error; |
| 335 | } |
| 336 | |
| 337 | uint8_t queryHeader[2]; |
| 338 | queryHeader[0] = qlen >> 8; |
| 339 | queryHeader[1] = qlen; |
| 340 | if (!sslWrite(fd.get(), ssl.get(), queryHeader, 2)) { |
| 341 | return Response::network_error; |
| 342 | } |
| 343 | if (!sslWrite(fd.get(), ssl.get(), query, qlen)) { |
| 344 | return Response::network_error; |
| 345 | } |
| 346 | if (DBG) { |
| 347 | ALOGD("%u SSL_write complete", mMark); |
| 348 | } |
| 349 | |
| 350 | uint8_t responseHeader[2]; |
| 351 | if (!sslRead(fd.get(), ssl.get(), responseHeader, 2)) { |
| 352 | if (DBG) { |
| 353 | ALOGW("%u Failed to read 2-byte length header", mMark); |
| 354 | } |
| 355 | return Response::network_error; |
| 356 | } |
| 357 | const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1]; |
| 358 | if (DBG) { |
| 359 | ALOGD("%u Expecting response of size %i", mMark, responseSize); |
| 360 | } |
| 361 | if (responseSize > limit) { |
| 362 | ALOGE("%u Response doesn't fit in output buffer: %i", mMark, responseSize); |
| 363 | return Response::limit_error; |
| 364 | } |
| 365 | if (!sslRead(fd.get(), ssl.get(), response, responseSize)) { |
| 366 | if (DBG) { |
| 367 | ALOGW("%u Failed to read %i bytes", mMark, responseSize); |
| 368 | } |
| 369 | return Response::network_error; |
| 370 | } |
| 371 | if (DBG) { |
| 372 | ALOGD("%u SSL_read complete", mMark); |
| 373 | } |
| 374 | |
| 375 | if (response[0] != query[0] || response[1] != query[1]) { |
| 376 | ALOGE("reply query ID != query ID"); |
| 377 | return Response::internal_error; |
| 378 | } |
| 379 | |
| 380 | SSL_shutdown(ssl.get()); |
| 381 | |
| 382 | *resplen = responseSize; |
| 383 | return Response::success; |
| 384 | } |
| 385 | |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 386 | // static |
| 387 | bool DnsTlsTransport::validate(const Server& server, unsigned netid) { |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 388 | if (DBG) { |
| 389 | ALOGD("Beginning validation on %u", netid); |
| 390 | } |
| 391 | // Generate "<random>-dnsotls-ds.metric.gstatic.com", which we will lookup through |ss| in |
| 392 | // order to prove that it is actually a working DNS over TLS server. |
| 393 | static const char kDnsSafeChars[] = |
| 394 | "abcdefhijklmnopqrstuvwxyz" |
| 395 | "ABCDEFHIJKLMNOPQRSTUVWXYZ" |
| 396 | "0123456789"; |
| 397 | const auto c = [](uint8_t rnd) -> uint8_t { |
| 398 | return kDnsSafeChars[(rnd % ARRAY_SIZE(kDnsSafeChars))]; |
| 399 | }; |
| 400 | uint8_t rnd[8]; |
| 401 | arc4random_buf(rnd, ARRAY_SIZE(rnd)); |
| 402 | // We could try to use res_mkquery() here, but it's basically the same. |
| 403 | uint8_t query[] = { |
| 404 | rnd[6], rnd[7], // [0-1] query ID |
| 405 | 1, 0, // [2-3] flags; query[2] = 1 for recursion desired (RD). |
| 406 | 0, 1, // [4-5] QDCOUNT (number of queries) |
| 407 | 0, 0, // [6-7] ANCOUNT (number of answers) |
| 408 | 0, 0, // [8-9] NSCOUNT (number of name server records) |
| 409 | 0, 0, // [10-11] ARCOUNT (number of additional records) |
| 410 | 17, c(rnd[0]), c(rnd[1]), c(rnd[2]), c(rnd[3]), c(rnd[4]), c(rnd[5]), |
| 411 | '-', 'd', 'n', 's', 'o', 't', 'l', 's', '-', 'd', 's', |
| 412 | 6, 'm', 'e', 't', 'r', 'i', 'c', |
| 413 | 7, 'g', 's', 't', 'a', 't', 'i', 'c', |
| 414 | 3, 'c', 'o', 'm', |
| 415 | 0, // null terminator of FQDN (root TLD) |
| 416 | 0, ns_t_aaaa, // QTYPE |
| 417 | 0, ns_c_in // QCLASS |
| 418 | }; |
| 419 | const int qlen = ARRAY_SIZE(query); |
| 420 | |
| 421 | const int kRecvBufSize = 4 * 1024; |
| 422 | uint8_t recvbuf[kRecvBufSize]; |
| 423 | |
| 424 | // At validation time, we only know the netId, so we have to guess/compute the |
| 425 | // corresponding socket mark. |
| 426 | Fwmark fwmark; |
| 427 | fwmark.permission = PERMISSION_SYSTEM; |
| 428 | fwmark.explicitlySelected = true; |
| 429 | fwmark.protectedFromVpn = true; |
| 430 | fwmark.netId = netid; |
| 431 | unsigned mark = fwmark.intValue; |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 432 | int replylen = 0; |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 433 | DnsTlsTransport::query(server, mark, query, qlen, recvbuf, kRecvBufSize, &replylen); |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 434 | if (replylen == 0) { |
| 435 | if (DBG) { |
Ben Schwartz | 5250462 | 2017-07-11 12:21:13 -0400 | [diff] [blame] | 436 | ALOGD("query failed"); |
Ben Schwartz | e760181 | 2017-04-28 16:38:29 -0400 | [diff] [blame] | 437 | } |
| 438 | return false; |
| 439 | } |
| 440 | |
| 441 | if (replylen < NS_HFIXEDSZ) { |
| 442 | if (DBG) { |
| 443 | ALOGW("short response: %d", replylen); |
| 444 | } |
| 445 | return false; |
| 446 | } |
| 447 | |
| 448 | const int qdcount = (recvbuf[4] << 8) | recvbuf[5]; |
| 449 | if (qdcount != 1) { |
| 450 | ALOGW("reply query count != 1: %d", qdcount); |
| 451 | return false; |
| 452 | } |
| 453 | |
| 454 | const int ancount = (recvbuf[6] << 8) | recvbuf[7]; |
| 455 | if (DBG) { |
| 456 | ALOGD("%u answer count: %d", netid, ancount); |
| 457 | } |
| 458 | |
| 459 | // TODO: Further validate the response contents (check for valid AAAA record, ...). |
| 460 | // Note that currently, integration tests rely on this function accepting a |
| 461 | // response with zero records. |
| 462 | #if 0 |
| 463 | for (int i = 0; i < resplen; i++) { |
| 464 | ALOGD("recvbuf[%d] = %d %c", i, recvbuf[i], recvbuf[i]); |
| 465 | } |
| 466 | #endif |
| 467 | return true; |
| 468 | } |
| 469 | |
| 470 | } // namespace net |
| 471 | } // namespace android |