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