Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 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 "RpcTransportTls" |
| 18 | #include <log/log.h> |
| 19 | |
| 20 | #include <poll.h> |
| 21 | |
| 22 | #include <openssl/bn.h> |
| 23 | #include <openssl/ssl.h> |
| 24 | |
Yifan Hong | bb24eea | 2021-09-17 18:21:56 -0700 | [diff] [blame] | 25 | #include <binder/RpcTlsUtils.h> |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 26 | #include <binder/RpcTransportTls.h> |
| 27 | |
| 28 | #include "FdTrigger.h" |
| 29 | #include "RpcState.h" |
Yifan Hong | 18ac947 | 2021-09-09 19:55:38 -0700 | [diff] [blame] | 30 | #include "Utils.h" |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 31 | |
| 32 | #define SHOULD_LOG_TLS_DETAIL false |
| 33 | |
| 34 | #if SHOULD_LOG_TLS_DETAIL |
| 35 | #define LOG_TLS_DETAIL(...) ALOGI(__VA_ARGS__) |
| 36 | #else |
| 37 | #define LOG_TLS_DETAIL(...) ALOGV(__VA_ARGS__) // for type checking |
| 38 | #endif |
| 39 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 40 | using android::base::ErrnoError; |
| 41 | using android::base::Error; |
| 42 | using android::base::Result; |
| 43 | |
| 44 | namespace android { |
| 45 | namespace { |
| 46 | |
| 47 | constexpr const int kCertValidDays = 30; |
| 48 | |
Yifan Hong | d17353c | 2021-06-24 21:56:38 -0700 | [diff] [blame] | 49 | // Implement BIO for socket that ignores SIGPIPE. |
| 50 | int socketNew(BIO* bio) { |
| 51 | BIO_set_data(bio, reinterpret_cast<void*>(-1)); |
| 52 | BIO_set_init(bio, 0); |
| 53 | return 1; |
| 54 | } |
| 55 | int socketFree(BIO* bio) { |
| 56 | LOG_ALWAYS_FATAL_IF(bio == nullptr); |
| 57 | return 1; |
| 58 | } |
| 59 | int socketRead(BIO* bio, char* buf, int size) { |
| 60 | android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio)))); |
| 61 | int ret = TEMP_FAILURE_RETRY(::recv(fd.get(), buf, size, MSG_NOSIGNAL)); |
| 62 | BIO_clear_retry_flags(bio); |
| 63 | if (errno == EAGAIN || errno == EWOULDBLOCK) { |
| 64 | BIO_set_retry_read(bio); |
| 65 | } |
| 66 | return ret; |
| 67 | } |
| 68 | |
| 69 | int socketWrite(BIO* bio, const char* buf, int size) { |
| 70 | android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio)))); |
| 71 | int ret = TEMP_FAILURE_RETRY(::send(fd.get(), buf, size, MSG_NOSIGNAL)); |
| 72 | BIO_clear_retry_flags(bio); |
| 73 | if (errno == EAGAIN || errno == EWOULDBLOCK) { |
| 74 | BIO_set_retry_write(bio); |
| 75 | } |
| 76 | return ret; |
| 77 | } |
| 78 | |
| 79 | long socketCtrl(BIO* bio, int cmd, long num, void*) { // NOLINT |
| 80 | android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio)))); |
| 81 | if (cmd == BIO_CTRL_FLUSH) return 1; |
| 82 | LOG_ALWAYS_FATAL("sockCtrl(fd=%d, %d, %ld)", fd.get(), cmd, num); |
| 83 | return 0; |
| 84 | } |
| 85 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 86 | bssl::UniquePtr<BIO> newSocketBio(android::base::borrowed_fd fd) { |
Yifan Hong | d17353c | 2021-06-24 21:56:38 -0700 | [diff] [blame] | 87 | static const BIO_METHOD* gMethods = ([] { |
| 88 | auto methods = BIO_meth_new(BIO_get_new_index(), "socket_no_signal"); |
| 89 | LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_write(methods, socketWrite), "BIO_meth_set_write"); |
| 90 | LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_read(methods, socketRead), "BIO_meth_set_read"); |
| 91 | LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_ctrl(methods, socketCtrl), "BIO_meth_set_ctrl"); |
| 92 | LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_create(methods, socketNew), "BIO_meth_set_create"); |
| 93 | LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_destroy(methods, socketFree), "BIO_meth_set_destroy"); |
| 94 | return methods; |
| 95 | })(); |
| 96 | bssl::UniquePtr<BIO> ret(BIO_new(gMethods)); |
| 97 | if (ret == nullptr) return nullptr; |
| 98 | BIO_set_data(ret.get(), reinterpret_cast<void*>(fd.get())); |
| 99 | BIO_set_init(ret.get(), 1); |
| 100 | return ret; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 101 | } |
| 102 | |
| 103 | bssl::UniquePtr<EVP_PKEY> makeKeyPairForSelfSignedCert() { |
| 104 | bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); |
| 105 | if (ec_key == nullptr || !EC_KEY_generate_key(ec_key.get())) { |
| 106 | ALOGE("Failed to generate key pair."); |
| 107 | return nullptr; |
| 108 | } |
| 109 | bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new()); |
| 110 | // Use set1 instead of assign to avoid leaking ec_key when assign fails. set1 increments |
| 111 | // the refcount of the ec_key, so it is okay to release it at the end of this function. |
| 112 | if (evp_pkey == nullptr || !EVP_PKEY_set1_EC_KEY(evp_pkey.get(), ec_key.get())) { |
| 113 | ALOGE("Failed to assign key pair."); |
| 114 | return nullptr; |
| 115 | } |
| 116 | return evp_pkey; |
| 117 | } |
| 118 | |
| 119 | bssl::UniquePtr<X509> makeSelfSignedCert(EVP_PKEY* evp_pkey, const int valid_days) { |
| 120 | bssl::UniquePtr<X509> x509(X509_new()); |
| 121 | bssl::UniquePtr<BIGNUM> serial(BN_new()); |
| 122 | bssl::UniquePtr<BIGNUM> serialLimit(BN_new()); |
| 123 | TEST_AND_RETURN(nullptr, BN_lshift(serialLimit.get(), BN_value_one(), 128)); |
| 124 | TEST_AND_RETURN(nullptr, BN_rand_range(serial.get(), serialLimit.get())); |
| 125 | TEST_AND_RETURN(nullptr, BN_to_ASN1_INTEGER(serial.get(), X509_get_serialNumber(x509.get()))); |
| 126 | TEST_AND_RETURN(nullptr, X509_gmtime_adj(X509_getm_notBefore(x509.get()), 0)); |
| 127 | TEST_AND_RETURN(nullptr, |
| 128 | X509_gmtime_adj(X509_getm_notAfter(x509.get()), 60 * 60 * 24 * valid_days)); |
| 129 | |
| 130 | X509_NAME* subject = X509_get_subject_name(x509.get()); |
| 131 | TEST_AND_RETURN(nullptr, |
| 132 | X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC, |
| 133 | reinterpret_cast<const uint8_t*>("Android"), -1, -1, |
| 134 | 0)); |
| 135 | TEST_AND_RETURN(nullptr, |
| 136 | X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC, |
| 137 | reinterpret_cast<const uint8_t*>("BinderRPC"), -1, |
| 138 | -1, 0)); |
| 139 | TEST_AND_RETURN(nullptr, X509_set_issuer_name(x509.get(), subject)); |
| 140 | |
| 141 | TEST_AND_RETURN(nullptr, X509_set_pubkey(x509.get(), evp_pkey)); |
| 142 | TEST_AND_RETURN(nullptr, X509_sign(x509.get(), evp_pkey, EVP_sha256())); |
| 143 | return x509; |
| 144 | } |
| 145 | |
| 146 | [[maybe_unused]] void sslDebugLog(const SSL* ssl, int type, int value) { |
| 147 | switch (type) { |
| 148 | case SSL_CB_HANDSHAKE_START: |
| 149 | LOG_TLS_DETAIL("Handshake started."); |
| 150 | break; |
| 151 | case SSL_CB_HANDSHAKE_DONE: |
| 152 | LOG_TLS_DETAIL("Handshake done."); |
| 153 | break; |
| 154 | case SSL_CB_ACCEPT_LOOP: |
| 155 | LOG_TLS_DETAIL("Handshake progress: %s", SSL_state_string_long(ssl)); |
| 156 | break; |
| 157 | default: |
| 158 | LOG_TLS_DETAIL("SSL Debug Log: type = %d, value = %d", type, value); |
| 159 | break; |
| 160 | } |
| 161 | } |
| 162 | |
Yifan Hong | 87a379c | 2021-08-12 18:53:24 -0700 | [diff] [blame] | 163 | // Helper class to ErrorQueue::toString |
| 164 | class ErrorQueueString { |
| 165 | public: |
| 166 | static std::string toString() { |
| 167 | ErrorQueueString thiz; |
| 168 | ERR_print_errors_cb(staticCallback, &thiz); |
| 169 | return thiz.mSs.str(); |
| 170 | } |
| 171 | |
| 172 | private: |
| 173 | static int staticCallback(const char* str, size_t len, void* ctx) { |
| 174 | return reinterpret_cast<ErrorQueueString*>(ctx)->callback(str, len); |
| 175 | } |
| 176 | int callback(const char* str, size_t len) { |
| 177 | if (len == 0) return 1; // continue |
| 178 | // ERR_print_errors_cb place a new line at the end, but it doesn't say so in the API. |
| 179 | if (str[len - 1] == '\n') len -= 1; |
| 180 | if (!mIsFirst) { |
| 181 | mSs << '\n'; |
| 182 | } |
| 183 | mSs << std::string_view(str, len); |
| 184 | mIsFirst = false; |
| 185 | return 1; // continue |
| 186 | } |
| 187 | std::stringstream mSs; |
| 188 | bool mIsFirst = true; |
| 189 | }; |
| 190 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 191 | // Handles libssl's error queue. |
| 192 | // |
| 193 | // Call into any of its member functions to ensure the error queue is properly handled or cleared. |
| 194 | // If the error queue is not handled or cleared, the destructor will abort. |
| 195 | class ErrorQueue { |
| 196 | public: |
| 197 | ~ErrorQueue() { LOG_ALWAYS_FATAL_IF(!mHandled); } |
| 198 | |
| 199 | // Clear the error queue. |
| 200 | void clear() { |
| 201 | ERR_clear_error(); |
| 202 | mHandled = true; |
| 203 | } |
| 204 | |
| 205 | // Stores the error queue in |ssl| into a string, then clears the error queue. |
| 206 | std::string toString() { |
Yifan Hong | 87a379c | 2021-08-12 18:53:24 -0700 | [diff] [blame] | 207 | auto ret = ErrorQueueString::toString(); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 208 | // Though ERR_print_errors_cb should have cleared it, it is okay to clear again. |
| 209 | clear(); |
Yifan Hong | 87a379c | 2021-08-12 18:53:24 -0700 | [diff] [blame] | 210 | return ret; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 211 | } |
| 212 | |
| 213 | // |sslError| should be from Ssl::getError(). |
| 214 | // If |sslError| is WANT_READ / WANT_WRITE, poll for POLLIN / POLLOUT respectively. Otherwise |
| 215 | // return error. Also return error if |fdTrigger| is triggered before or during poll(). |
| 216 | status_t pollForSslError(android::base::borrowed_fd fd, int sslError, FdTrigger* fdTrigger, |
| 217 | const char* fnString, int additionalEvent = 0) { |
| 218 | switch (sslError) { |
| 219 | case SSL_ERROR_WANT_READ: |
| 220 | return handlePoll(POLLIN | additionalEvent, fd, fdTrigger, fnString); |
| 221 | case SSL_ERROR_WANT_WRITE: |
| 222 | return handlePoll(POLLOUT | additionalEvent, fd, fdTrigger, fnString); |
| 223 | case SSL_ERROR_SYSCALL: { |
| 224 | auto queue = toString(); |
| 225 | LOG_TLS_DETAIL("%s(): %s. Treating as DEAD_OBJECT. Error queue: %s", fnString, |
| 226 | SSL_error_description(sslError), queue.c_str()); |
| 227 | return DEAD_OBJECT; |
| 228 | } |
| 229 | default: { |
| 230 | auto queue = toString(); |
| 231 | ALOGE("%s(): %s. Error queue: %s", fnString, SSL_error_description(sslError), |
| 232 | queue.c_str()); |
| 233 | return UNKNOWN_ERROR; |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | private: |
| 239 | bool mHandled = false; |
| 240 | |
| 241 | status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger, |
| 242 | const char* fnString) { |
| 243 | status_t ret = fdTrigger->triggerablePoll(fd, event); |
Steven Moreland | c591b47 | 2021-09-16 13:56:11 -0700 | [diff] [blame] | 244 | if (ret != OK && ret != DEAD_OBJECT) { |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 245 | ALOGE("triggerablePoll error while poll()-ing after %s(): %s", fnString, |
| 246 | statusToString(ret).c_str()); |
| 247 | } |
| 248 | clear(); |
| 249 | return ret; |
| 250 | } |
| 251 | }; |
| 252 | |
| 253 | // Helper to call a function, with its return value instantiable. |
| 254 | template <typename Fn, typename... Args> |
| 255 | struct FuncCaller { |
| 256 | struct Monostate {}; |
| 257 | static constexpr bool sIsVoid = std::is_void_v<std::invoke_result_t<Fn, Args...>>; |
| 258 | using Result = std::conditional_t<sIsVoid, Monostate, std::invoke_result_t<Fn, Args...>>; |
| 259 | static inline Result call(Fn fn, Args&&... args) { |
| 260 | if constexpr (std::is_void_v<std::invoke_result_t<Fn, Args...>>) { |
| 261 | std::invoke(fn, std::forward<Args>(args)...); |
| 262 | return {}; |
| 263 | } else { |
| 264 | return std::invoke(fn, std::forward<Args>(args)...); |
| 265 | } |
| 266 | } |
| 267 | }; |
| 268 | |
| 269 | // Helper to Ssl::call(). Returns the result to the SSL_* function as well as an ErrorQueue object. |
| 270 | template <typename Fn, typename... Args> |
| 271 | struct SslCaller { |
| 272 | using RawCaller = FuncCaller<Fn, SSL*, Args...>; |
| 273 | struct ResultAndErrorQueue { |
| 274 | typename RawCaller::Result result; |
| 275 | ErrorQueue errorQueue; |
| 276 | }; |
| 277 | static inline ResultAndErrorQueue call(Fn fn, SSL* ssl, Args&&... args) { |
| 278 | LOG_ALWAYS_FATAL_IF(ssl == nullptr); |
| 279 | auto result = RawCaller::call(fn, std::forward<SSL*>(ssl), std::forward<Args>(args)...); |
| 280 | return ResultAndErrorQueue{std::move(result), ErrorQueue()}; |
| 281 | } |
| 282 | }; |
| 283 | |
| 284 | // A wrapper over bssl::UniquePtr<SSL>. This class ensures that all SSL_* functions are called |
| 285 | // through call(), which returns an ErrorQueue object that requires the caller to either handle |
| 286 | // or clear it. |
| 287 | // Example: |
| 288 | // auto [ret, errorQueue] = ssl.call(SSL_read, buf, size); |
| 289 | // if (ret >= 0) errorQueue.clear(); |
| 290 | // else ALOGE("%s", errorQueue.toString().c_str()); |
| 291 | class Ssl { |
| 292 | public: |
| 293 | explicit Ssl(bssl::UniquePtr<SSL> ssl) : mSsl(std::move(ssl)) { |
| 294 | LOG_ALWAYS_FATAL_IF(mSsl == nullptr); |
| 295 | } |
| 296 | |
| 297 | template <typename Fn, typename... Args> |
| 298 | inline typename SslCaller<Fn, Args...>::ResultAndErrorQueue call(Fn fn, Args&&... args) { |
| 299 | return SslCaller<Fn, Args...>::call(fn, mSsl.get(), std::forward<Args>(args)...); |
| 300 | } |
| 301 | |
| 302 | int getError(int ret) { |
| 303 | LOG_ALWAYS_FATAL_IF(mSsl == nullptr); |
| 304 | return SSL_get_error(mSsl.get(), ret); |
| 305 | } |
| 306 | |
| 307 | private: |
| 308 | bssl::UniquePtr<SSL> mSsl; |
| 309 | }; |
| 310 | |
| 311 | class RpcTransportTls : public RpcTransport { |
| 312 | public: |
| 313 | RpcTransportTls(android::base::unique_fd socket, Ssl ssl) |
| 314 | : mSocket(std::move(socket)), mSsl(std::move(ssl)) {} |
| 315 | Result<size_t> peek(void* buf, size_t size) override; |
| 316 | status_t interruptableWriteFully(FdTrigger* fdTrigger, const void* data, size_t size) override; |
| 317 | status_t interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) override; |
| 318 | |
| 319 | private: |
| 320 | android::base::unique_fd mSocket; |
| 321 | Ssl mSsl; |
| 322 | }; |
| 323 | |
| 324 | // Error code is errno. |
| 325 | Result<size_t> RpcTransportTls::peek(void* buf, size_t size) { |
| 326 | size_t todo = std::min<size_t>(size, std::numeric_limits<int>::max()); |
| 327 | auto [ret, errorQueue] = mSsl.call(SSL_peek, buf, static_cast<int>(todo)); |
| 328 | if (ret < 0) { |
| 329 | int err = mSsl.getError(ret); |
| 330 | if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { |
| 331 | // Seen EAGAIN / EWOULDBLOCK on recv(2) / send(2). |
| 332 | // Like RpcTransportRaw::peek(), don't handle it here. |
| 333 | return Error(EWOULDBLOCK) << "SSL_peek(): " << errorQueue.toString(); |
| 334 | } |
| 335 | return Error() << "SSL_peek(): " << errorQueue.toString(); |
| 336 | } |
| 337 | errorQueue.clear(); |
| 338 | LOG_TLS_DETAIL("TLS: Peeked %d bytes!", ret); |
| 339 | return ret; |
| 340 | } |
| 341 | |
| 342 | status_t RpcTransportTls::interruptableWriteFully(FdTrigger* fdTrigger, const void* data, |
| 343 | size_t size) { |
| 344 | auto buffer = reinterpret_cast<const uint8_t*>(data); |
| 345 | const uint8_t* end = buffer + size; |
| 346 | |
| 347 | MAYBE_WAIT_IN_FLAKE_MODE; |
| 348 | |
Yifan Hong | 15fff8c | 2021-08-10 15:07:56 -0700 | [diff] [blame] | 349 | // Before doing any I/O, check trigger once. This ensures the trigger is checked at least |
| 350 | // once. The trigger is also checked via triggerablePoll() after every SSL_write(). |
Steven Moreland | c591b47 | 2021-09-16 13:56:11 -0700 | [diff] [blame] | 351 | if (fdTrigger->isTriggered()) return DEAD_OBJECT; |
Yifan Hong | 15fff8c | 2021-08-10 15:07:56 -0700 | [diff] [blame] | 352 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 353 | while (buffer < end) { |
| 354 | size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max()); |
| 355 | auto [writeSize, errorQueue] = mSsl.call(SSL_write, buffer, todo); |
| 356 | if (writeSize > 0) { |
| 357 | buffer += writeSize; |
| 358 | errorQueue.clear(); |
| 359 | continue; |
| 360 | } |
| 361 | // SSL_write() should never return 0 unless BIO_write were to return 0. |
| 362 | int sslError = mSsl.getError(writeSize); |
| 363 | // TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be |
| 364 | // triggerablePoll()-ed. Then additionalEvent is no longer necessary. |
| 365 | status_t pollStatus = |
| 366 | errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_write", POLLIN); |
| 367 | if (pollStatus != OK) return pollStatus; |
| 368 | // Do not advance buffer. Try SSL_write() again. |
| 369 | } |
| 370 | LOG_TLS_DETAIL("TLS: Sent %zu bytes!", size); |
| 371 | return OK; |
| 372 | } |
| 373 | |
| 374 | status_t RpcTransportTls::interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) { |
| 375 | auto buffer = reinterpret_cast<uint8_t*>(data); |
| 376 | uint8_t* end = buffer + size; |
| 377 | |
| 378 | MAYBE_WAIT_IN_FLAKE_MODE; |
| 379 | |
Yifan Hong | 15fff8c | 2021-08-10 15:07:56 -0700 | [diff] [blame] | 380 | // Before doing any I/O, check trigger once. This ensures the trigger is checked at least |
| 381 | // once. The trigger is also checked via triggerablePoll() after every SSL_write(). |
Steven Moreland | c591b47 | 2021-09-16 13:56:11 -0700 | [diff] [blame] | 382 | if (fdTrigger->isTriggered()) return DEAD_OBJECT; |
Yifan Hong | 15fff8c | 2021-08-10 15:07:56 -0700 | [diff] [blame] | 383 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 384 | while (buffer < end) { |
| 385 | size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max()); |
| 386 | auto [readSize, errorQueue] = mSsl.call(SSL_read, buffer, todo); |
| 387 | if (readSize > 0) { |
| 388 | buffer += readSize; |
| 389 | errorQueue.clear(); |
| 390 | continue; |
| 391 | } |
| 392 | if (readSize == 0) { |
| 393 | // SSL_read() only returns 0 on EOF. |
| 394 | errorQueue.clear(); |
| 395 | return DEAD_OBJECT; |
| 396 | } |
| 397 | int sslError = mSsl.getError(readSize); |
| 398 | status_t pollStatus = |
| 399 | errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_read"); |
| 400 | if (pollStatus != OK) return pollStatus; |
| 401 | // Do not advance buffer. Try SSL_read() again. |
| 402 | } |
| 403 | LOG_TLS_DETAIL("TLS: Received %zu bytes!", size); |
| 404 | return OK; |
| 405 | } |
| 406 | |
| 407 | // For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|. |
| 408 | bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) { |
| 409 | bssl::UniquePtr<BIO> bio = newSocketBio(fd); |
| 410 | TEST_AND_RETURN(false, bio != nullptr); |
| 411 | auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get()); |
| 412 | (void)bio.release(); // SSL_set_bio takes ownership. |
| 413 | errorQueue.clear(); |
| 414 | |
| 415 | MAYBE_WAIT_IN_FLAKE_MODE; |
| 416 | |
| 417 | while (true) { |
| 418 | auto [ret, errorQueue] = ssl->call(SSL_do_handshake); |
| 419 | if (ret > 0) { |
| 420 | errorQueue.clear(); |
| 421 | return true; |
| 422 | } |
| 423 | if (ret == 0) { |
| 424 | // SSL_do_handshake() only returns 0 on EOF. |
| 425 | ALOGE("SSL_do_handshake(): EOF: %s", errorQueue.toString().c_str()); |
| 426 | return false; |
| 427 | } |
| 428 | int sslError = ssl->getError(ret); |
| 429 | status_t pollStatus = |
| 430 | errorQueue.pollForSslError(fd, sslError, fdTrigger, "SSL_do_handshake"); |
| 431 | if (pollStatus != OK) return false; |
| 432 | } |
| 433 | } |
| 434 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 435 | class RpcTransportCtxTls : public RpcTransportCtx { |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 436 | public: |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 437 | template <typename Impl, |
| 438 | typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>> |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 439 | static std::unique_ptr<RpcTransportCtxTls> create( |
| 440 | std::shared_ptr<RpcCertificateVerifier> verifier); |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 441 | std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd, |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 442 | FdTrigger* fdTrigger) const override; |
Yifan Hong | 9734cfc | 2021-09-13 16:14:09 -0700 | [diff] [blame] | 443 | std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 444 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 445 | protected: |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 446 | static ssl_verify_result_t sslCustomVerify(SSL* ssl, uint8_t* outAlert); |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 447 | virtual void preHandshake(Ssl* ssl) const = 0; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 448 | bssl::UniquePtr<SSL_CTX> mCtx; |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 449 | std::shared_ptr<RpcCertificateVerifier> mCertVerifier; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 450 | }; |
| 451 | |
Yifan Hong | 9734cfc | 2021-09-13 16:14:09 -0700 | [diff] [blame] | 452 | std::vector<uint8_t> RpcTransportCtxTls::getCertificate(RpcCertificateFormat format) const { |
Yifan Hong | 1deca4b | 2021-09-10 16:16:44 -0700 | [diff] [blame] | 453 | X509* x509 = SSL_CTX_get0_certificate(mCtx.get()); // does not own |
| 454 | return serializeCertificate(x509, format); |
Yifan Hong | 588d59c | 2021-08-16 17:13:58 -0700 | [diff] [blame] | 455 | } |
| 456 | |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 457 | // Verify by comparing the leaf of peer certificate with every certificate in |
| 458 | // mTrustedPeerCertificates. Does not support certificate chains. |
| 459 | ssl_verify_result_t RpcTransportCtxTls::sslCustomVerify(SSL* ssl, uint8_t* outAlert) { |
| 460 | LOG_ALWAYS_FATAL_IF(outAlert == nullptr); |
| 461 | const char* logPrefix = SSL_is_server(ssl) ? "Server" : "Client"; |
| 462 | |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 463 | auto ctx = SSL_get_SSL_CTX(ssl); // Does not set error queue |
| 464 | LOG_ALWAYS_FATAL_IF(ctx == nullptr); |
| 465 | // void* -> RpcTransportCtxTls* |
| 466 | auto rpcTransportCtxTls = reinterpret_cast<RpcTransportCtxTls*>(SSL_CTX_get_app_data(ctx)); |
| 467 | LOG_ALWAYS_FATAL_IF(rpcTransportCtxTls == nullptr); |
| 468 | |
Yifan Hong | b160f8c | 2021-09-17 22:59:11 -0700 | [diff] [blame^] | 469 | status_t verifyStatus = rpcTransportCtxTls->mCertVerifier->verify(ssl, outAlert); |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 470 | if (verifyStatus == OK) { |
| 471 | return ssl_verify_ok; |
| 472 | } |
| 473 | LOG_TLS_DETAIL("%s: Failed to verify client: status = %s, alert = %s", logPrefix, |
| 474 | statusToString(verifyStatus).c_str(), SSL_alert_desc_string_long(*outAlert)); |
| 475 | return ssl_verify_invalid; |
| 476 | } |
| 477 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 478 | // Common implementation for creating server and client contexts. The child class, |Impl|, is |
| 479 | // provided as a template argument so that this function can initialize an |Impl| object. |
| 480 | template <typename Impl, typename> |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 481 | std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create( |
| 482 | std::shared_ptr<RpcCertificateVerifier> verifier) { |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 483 | bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method())); |
| 484 | TEST_AND_RETURN(nullptr, ctx != nullptr); |
| 485 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 486 | auto evp_pkey = makeKeyPairForSelfSignedCert(); |
| 487 | TEST_AND_RETURN(nullptr, evp_pkey != nullptr); |
| 488 | auto cert = makeSelfSignedCert(evp_pkey.get(), kCertValidDays); |
| 489 | TEST_AND_RETURN(nullptr, cert != nullptr); |
| 490 | TEST_AND_RETURN(nullptr, SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())); |
| 491 | TEST_AND_RETURN(nullptr, SSL_CTX_use_certificate(ctx.get(), cert.get())); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 492 | |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 493 | // Enable two-way authentication by setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT on server. |
| 494 | // Client ignores SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag. |
| 495 | SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, |
| 496 | sslCustomVerify); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 497 | |
| 498 | // Require at least TLS 1.3 |
| 499 | TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION)); |
| 500 | |
| 501 | if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT |
| 502 | SSL_CTX_set_info_callback(ctx.get(), sslDebugLog); |
| 503 | } |
| 504 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 505 | auto ret = std::make_unique<Impl>(); |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 506 | // RpcTransportCtxTls* -> void* |
| 507 | TEST_AND_RETURN(nullptr, SSL_CTX_set_app_data(ctx.get(), reinterpret_cast<void*>(ret.get()))); |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 508 | ret->mCtx = std::move(ctx); |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 509 | ret->mCertVerifier = std::move(verifier); |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 510 | return ret; |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 511 | } |
| 512 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 513 | std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd, |
| 514 | FdTrigger* fdTrigger) const { |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 515 | bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get())); |
| 516 | TEST_AND_RETURN(nullptr, ssl != nullptr); |
| 517 | Ssl wrapped(std::move(ssl)); |
| 518 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 519 | preHandshake(&wrapped); |
| 520 | TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger)); |
| 521 | return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped)); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 522 | } |
| 523 | |
Yifan Hong | 1af4858 | 2021-08-16 17:13:30 -0700 | [diff] [blame] | 524 | class RpcTransportCtxTlsServer : public RpcTransportCtxTls { |
| 525 | protected: |
| 526 | void preHandshake(Ssl* ssl) const override { |
| 527 | ssl->call(SSL_set_accept_state).errorQueue.clear(); |
| 528 | } |
| 529 | }; |
| 530 | |
| 531 | class RpcTransportCtxTlsClient : public RpcTransportCtxTls { |
| 532 | protected: |
| 533 | void preHandshake(Ssl* ssl) const override { |
| 534 | ssl->call(SSL_set_connect_state).errorQueue.clear(); |
| 535 | } |
| 536 | }; |
| 537 | |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 538 | } // namespace |
| 539 | |
| 540 | std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const { |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 541 | return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>(mCertVerifier); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 542 | } |
| 543 | |
| 544 | std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const { |
Yifan Hong | 180c2da | 2021-09-09 15:36:30 -0700 | [diff] [blame] | 545 | return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>(mCertVerifier); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 546 | } |
| 547 | |
| 548 | const char* RpcTransportCtxFactoryTls::toCString() const { |
| 549 | return "tls"; |
| 550 | } |
| 551 | |
Yifan Hong | 13c9006 | 2021-09-09 14:59:53 -0700 | [diff] [blame] | 552 | std::unique_ptr<RpcTransportCtxFactory> RpcTransportCtxFactoryTls::make( |
| 553 | std::shared_ptr<RpcCertificateVerifier> verifier) { |
| 554 | if (verifier == nullptr) { |
| 555 | ALOGE("%s: Must provide a certificate verifier", __PRETTY_FUNCTION__); |
| 556 | return nullptr; |
| 557 | } |
| 558 | return std::unique_ptr<RpcTransportCtxFactoryTls>( |
| 559 | new RpcTransportCtxFactoryTls(std::move(verifier))); |
Yifan Hong | e8212f2 | 2021-06-28 15:49:08 -0700 | [diff] [blame] | 560 | } |
| 561 | |
| 562 | } // namespace android |