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