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