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