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