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