blob: c05ea1512f9ddc88ccf4912ed7f42595500d84d8 [file] [log] [blame]
Yifan Honge8212f22021-06-28 15:49:08 -07001/*
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 Hongbb24eea2021-09-17 18:21:56 -070025#include <binder/RpcTlsUtils.h>
Yifan Honge8212f22021-06-28 15:49:08 -070026#include <binder/RpcTransportTls.h>
27
28#include "FdTrigger.h"
29#include "RpcState.h"
Yifan Hong18ac9472021-09-09 19:55:38 -070030#include "Utils.h"
Yifan Honge8212f22021-06-28 15:49:08 -070031
32#define SHOULD_LOG_TLS_DETAIL false
33
34#if SHOULD_LOG_TLS_DETAIL
35#define LOG_TLS_DETAIL(...) ALOGI(__VA_ARGS__)
36#else
37#define LOG_TLS_DETAIL(...) ALOGV(__VA_ARGS__) // for type checking
38#endif
39
Yifan Honge8212f22021-06-28 15:49:08 -070040using android::base::ErrnoError;
41using android::base::Error;
42using android::base::Result;
43
44namespace android {
45namespace {
46
Yifan Hongd17353c2021-06-24 21:56:38 -070047// Implement BIO for socket that ignores SIGPIPE.
48int socketNew(BIO* bio) {
49 BIO_set_data(bio, reinterpret_cast<void*>(-1));
50 BIO_set_init(bio, 0);
51 return 1;
52}
53int socketFree(BIO* bio) {
54 LOG_ALWAYS_FATAL_IF(bio == nullptr);
55 return 1;
56}
57int socketRead(BIO* bio, char* buf, int size) {
58 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
59 int ret = TEMP_FAILURE_RETRY(::recv(fd.get(), buf, size, MSG_NOSIGNAL));
60 BIO_clear_retry_flags(bio);
61 if (errno == EAGAIN || errno == EWOULDBLOCK) {
62 BIO_set_retry_read(bio);
63 }
64 return ret;
65}
66
67int socketWrite(BIO* bio, const char* buf, int size) {
68 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
69 int ret = TEMP_FAILURE_RETRY(::send(fd.get(), buf, size, MSG_NOSIGNAL));
70 BIO_clear_retry_flags(bio);
71 if (errno == EAGAIN || errno == EWOULDBLOCK) {
72 BIO_set_retry_write(bio);
73 }
74 return ret;
75}
76
77long socketCtrl(BIO* bio, int cmd, long num, void*) { // NOLINT
78 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
79 if (cmd == BIO_CTRL_FLUSH) return 1;
80 LOG_ALWAYS_FATAL("sockCtrl(fd=%d, %d, %ld)", fd.get(), cmd, num);
81 return 0;
82}
83
Yifan Honge8212f22021-06-28 15:49:08 -070084bssl::UniquePtr<BIO> newSocketBio(android::base::borrowed_fd fd) {
Yifan Hongd17353c2021-06-24 21:56:38 -070085 static const BIO_METHOD* gMethods = ([] {
86 auto methods = BIO_meth_new(BIO_get_new_index(), "socket_no_signal");
87 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_write(methods, socketWrite), "BIO_meth_set_write");
88 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_read(methods, socketRead), "BIO_meth_set_read");
89 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_ctrl(methods, socketCtrl), "BIO_meth_set_ctrl");
90 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_create(methods, socketNew), "BIO_meth_set_create");
91 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_destroy(methods, socketFree), "BIO_meth_set_destroy");
92 return methods;
93 })();
94 bssl::UniquePtr<BIO> ret(BIO_new(gMethods));
95 if (ret == nullptr) return nullptr;
96 BIO_set_data(ret.get(), reinterpret_cast<void*>(fd.get()));
97 BIO_set_init(ret.get(), 1);
98 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -070099}
100
Yifan Honge8212f22021-06-28 15:49:08 -0700101[[maybe_unused]] void sslDebugLog(const SSL* ssl, int type, int value) {
102 switch (type) {
103 case SSL_CB_HANDSHAKE_START:
104 LOG_TLS_DETAIL("Handshake started.");
105 break;
106 case SSL_CB_HANDSHAKE_DONE:
107 LOG_TLS_DETAIL("Handshake done.");
108 break;
109 case SSL_CB_ACCEPT_LOOP:
110 LOG_TLS_DETAIL("Handshake progress: %s", SSL_state_string_long(ssl));
111 break;
112 default:
113 LOG_TLS_DETAIL("SSL Debug Log: type = %d, value = %d", type, value);
114 break;
115 }
116}
117
Yifan Hong87a379c2021-08-12 18:53:24 -0700118// Helper class to ErrorQueue::toString
119class ErrorQueueString {
120public:
121 static std::string toString() {
122 ErrorQueueString thiz;
123 ERR_print_errors_cb(staticCallback, &thiz);
124 return thiz.mSs.str();
125 }
126
127private:
128 static int staticCallback(const char* str, size_t len, void* ctx) {
129 return reinterpret_cast<ErrorQueueString*>(ctx)->callback(str, len);
130 }
131 int callback(const char* str, size_t len) {
132 if (len == 0) return 1; // continue
133 // ERR_print_errors_cb place a new line at the end, but it doesn't say so in the API.
134 if (str[len - 1] == '\n') len -= 1;
135 if (!mIsFirst) {
136 mSs << '\n';
137 }
138 mSs << std::string_view(str, len);
139 mIsFirst = false;
140 return 1; // continue
141 }
142 std::stringstream mSs;
143 bool mIsFirst = true;
144};
145
Yifan Honge8212f22021-06-28 15:49:08 -0700146// Handles libssl's error queue.
147//
148// Call into any of its member functions to ensure the error queue is properly handled or cleared.
149// If the error queue is not handled or cleared, the destructor will abort.
150class ErrorQueue {
151public:
152 ~ErrorQueue() { LOG_ALWAYS_FATAL_IF(!mHandled); }
153
154 // Clear the error queue.
155 void clear() {
156 ERR_clear_error();
157 mHandled = true;
158 }
159
160 // Stores the error queue in |ssl| into a string, then clears the error queue.
161 std::string toString() {
Yifan Hong87a379c2021-08-12 18:53:24 -0700162 auto ret = ErrorQueueString::toString();
Yifan Honge8212f22021-06-28 15:49:08 -0700163 // Though ERR_print_errors_cb should have cleared it, it is okay to clear again.
164 clear();
Yifan Hong87a379c2021-08-12 18:53:24 -0700165 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700166 }
167
168 // |sslError| should be from Ssl::getError().
169 // If |sslError| is WANT_READ / WANT_WRITE, poll for POLLIN / POLLOUT respectively. Otherwise
170 // return error. Also return error if |fdTrigger| is triggered before or during poll().
171 status_t pollForSslError(android::base::borrowed_fd fd, int sslError, FdTrigger* fdTrigger,
Steven Moreland43921d52021-09-27 17:15:56 -0700172 const char* fnString, int additionalEvent,
173 const std::function<status_t()>& altPoll) {
Yifan Honge8212f22021-06-28 15:49:08 -0700174 switch (sslError) {
175 case SSL_ERROR_WANT_READ:
Steven Moreland43921d52021-09-27 17:15:56 -0700176 return handlePoll(POLLIN | additionalEvent, fd, fdTrigger, fnString, altPoll);
Yifan Honge8212f22021-06-28 15:49:08 -0700177 case SSL_ERROR_WANT_WRITE:
Steven Moreland43921d52021-09-27 17:15:56 -0700178 return handlePoll(POLLOUT | additionalEvent, fd, fdTrigger, fnString, altPoll);
Yifan Honge8212f22021-06-28 15:49:08 -0700179 case SSL_ERROR_SYSCALL: {
180 auto queue = toString();
181 LOG_TLS_DETAIL("%s(): %s. Treating as DEAD_OBJECT. Error queue: %s", fnString,
182 SSL_error_description(sslError), queue.c_str());
183 return DEAD_OBJECT;
184 }
185 default: {
186 auto queue = toString();
187 ALOGE("%s(): %s. Error queue: %s", fnString, SSL_error_description(sslError),
188 queue.c_str());
189 return UNKNOWN_ERROR;
190 }
191 }
192 }
193
194private:
195 bool mHandled = false;
196
197 status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger,
Steven Moreland43921d52021-09-27 17:15:56 -0700198 const char* fnString, const std::function<status_t()>& altPoll) {
199 status_t ret;
200 if (altPoll) {
201 ret = altPoll();
202 if (fdTrigger->isTriggered()) ret = DEAD_OBJECT;
203 } else {
204 ret = fdTrigger->triggerablePoll(fd, event);
205 }
206
Steven Morelandc591b472021-09-16 13:56:11 -0700207 if (ret != OK && ret != DEAD_OBJECT) {
Steven Moreland43921d52021-09-27 17:15:56 -0700208 ALOGE("poll error while after %s(): %s", fnString, statusToString(ret).c_str());
Yifan Honge8212f22021-06-28 15:49:08 -0700209 }
210 clear();
211 return ret;
212 }
213};
214
215// Helper to call a function, with its return value instantiable.
216template <typename Fn, typename... Args>
217struct FuncCaller {
218 struct Monostate {};
219 static constexpr bool sIsVoid = std::is_void_v<std::invoke_result_t<Fn, Args...>>;
220 using Result = std::conditional_t<sIsVoid, Monostate, std::invoke_result_t<Fn, Args...>>;
221 static inline Result call(Fn fn, Args&&... args) {
222 if constexpr (std::is_void_v<std::invoke_result_t<Fn, Args...>>) {
223 std::invoke(fn, std::forward<Args>(args)...);
224 return {};
225 } else {
226 return std::invoke(fn, std::forward<Args>(args)...);
227 }
228 }
229};
230
231// Helper to Ssl::call(). Returns the result to the SSL_* function as well as an ErrorQueue object.
232template <typename Fn, typename... Args>
233struct SslCaller {
234 using RawCaller = FuncCaller<Fn, SSL*, Args...>;
235 struct ResultAndErrorQueue {
236 typename RawCaller::Result result;
237 ErrorQueue errorQueue;
238 };
239 static inline ResultAndErrorQueue call(Fn fn, SSL* ssl, Args&&... args) {
240 LOG_ALWAYS_FATAL_IF(ssl == nullptr);
241 auto result = RawCaller::call(fn, std::forward<SSL*>(ssl), std::forward<Args>(args)...);
242 return ResultAndErrorQueue{std::move(result), ErrorQueue()};
243 }
244};
245
246// A wrapper over bssl::UniquePtr<SSL>. This class ensures that all SSL_* functions are called
247// through call(), which returns an ErrorQueue object that requires the caller to either handle
248// or clear it.
249// Example:
250// auto [ret, errorQueue] = ssl.call(SSL_read, buf, size);
251// if (ret >= 0) errorQueue.clear();
252// else ALOGE("%s", errorQueue.toString().c_str());
253class Ssl {
254public:
255 explicit Ssl(bssl::UniquePtr<SSL> ssl) : mSsl(std::move(ssl)) {
256 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
257 }
258
259 template <typename Fn, typename... Args>
260 inline typename SslCaller<Fn, Args...>::ResultAndErrorQueue call(Fn fn, Args&&... args) {
261 return SslCaller<Fn, Args...>::call(fn, mSsl.get(), std::forward<Args>(args)...);
262 }
263
264 int getError(int ret) {
265 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
266 return SSL_get_error(mSsl.get(), ret);
267 }
268
269private:
270 bssl::UniquePtr<SSL> mSsl;
271};
272
273class RpcTransportTls : public RpcTransport {
274public:
275 RpcTransportTls(android::base::unique_fd socket, Ssl ssl)
276 : mSocket(std::move(socket)), mSsl(std::move(ssl)) {}
277 Result<size_t> peek(void* buf, size_t size) override;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000278 status_t interruptableWriteFully(FdTrigger* fdTrigger, iovec* iovs, size_t niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700279 const std::function<status_t()>& altPoll) override;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000280 status_t interruptableReadFully(FdTrigger* fdTrigger, iovec* iovs, size_t niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700281 const std::function<status_t()>& altPoll) override;
Yifan Honge8212f22021-06-28 15:49:08 -0700282
283private:
284 android::base::unique_fd mSocket;
285 Ssl mSsl;
286};
287
288// Error code is errno.
289Result<size_t> RpcTransportTls::peek(void* buf, size_t size) {
290 size_t todo = std::min<size_t>(size, std::numeric_limits<int>::max());
291 auto [ret, errorQueue] = mSsl.call(SSL_peek, buf, static_cast<int>(todo));
292 if (ret < 0) {
293 int err = mSsl.getError(ret);
294 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
295 // Seen EAGAIN / EWOULDBLOCK on recv(2) / send(2).
296 // Like RpcTransportRaw::peek(), don't handle it here.
297 return Error(EWOULDBLOCK) << "SSL_peek(): " << errorQueue.toString();
298 }
299 return Error() << "SSL_peek(): " << errorQueue.toString();
300 }
301 errorQueue.clear();
302 LOG_TLS_DETAIL("TLS: Peeked %d bytes!", ret);
303 return ret;
304}
305
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000306status_t RpcTransportTls::interruptableWriteFully(FdTrigger* fdTrigger, iovec* iovs, size_t niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700307 const std::function<status_t()>& altPoll) {
Yifan Honge8212f22021-06-28 15:49:08 -0700308 MAYBE_WAIT_IN_FLAKE_MODE;
309
Yifan Hong15fff8c2021-08-10 15:07:56 -0700310 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
311 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700312 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700313
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000314 size_t size = 0;
315 for (size_t i = 0; i < niovs; i++) {
316 const iovec& iov = iovs[i];
317 if (iov.iov_len == 0) {
Yifan Honge8212f22021-06-28 15:49:08 -0700318 continue;
319 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000320 size += iov.iov_len;
321
322 auto buffer = reinterpret_cast<const uint8_t*>(iov.iov_base);
323 const uint8_t* end = buffer + iov.iov_len;
324 while (buffer < end) {
325 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
326 auto [writeSize, errorQueue] = mSsl.call(SSL_write, buffer, todo);
327 if (writeSize > 0) {
328 buffer += writeSize;
329 errorQueue.clear();
330 continue;
331 }
332 // SSL_write() should never return 0 unless BIO_write were to return 0.
333 int sslError = mSsl.getError(writeSize);
334 // TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be
335 // triggerablePoll()-ed. Then additionalEvent is no longer necessary.
336 status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
337 "SSL_write", POLLIN, altPoll);
338 if (pollStatus != OK) return pollStatus;
339 // Do not advance buffer. Try SSL_write() again.
340 }
Yifan Honge8212f22021-06-28 15:49:08 -0700341 }
342 LOG_TLS_DETAIL("TLS: Sent %zu bytes!", size);
343 return OK;
344}
345
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000346status_t RpcTransportTls::interruptableReadFully(FdTrigger* fdTrigger, iovec* iovs, size_t niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700347 const std::function<status_t()>& altPoll) {
Yifan Honge8212f22021-06-28 15:49:08 -0700348 MAYBE_WAIT_IN_FLAKE_MODE;
349
Yifan Hong15fff8c2021-08-10 15:07:56 -0700350 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
351 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700352 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700353
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000354 size_t size = 0;
355 for (size_t i = 0; i < niovs; i++) {
356 const iovec& iov = iovs[i];
357 if (iov.iov_len == 0) {
Yifan Honge8212f22021-06-28 15:49:08 -0700358 continue;
359 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000360 size += iov.iov_len;
361
362 auto buffer = reinterpret_cast<uint8_t*>(iov.iov_base);
363 const uint8_t* end = buffer + iov.iov_len;
364 while (buffer < end) {
365 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
366 auto [readSize, errorQueue] = mSsl.call(SSL_read, buffer, todo);
367 if (readSize > 0) {
368 buffer += readSize;
369 errorQueue.clear();
370 continue;
371 }
372 if (readSize == 0) {
373 // SSL_read() only returns 0 on EOF.
374 errorQueue.clear();
375 return DEAD_OBJECT;
376 }
377 int sslError = mSsl.getError(readSize);
378 status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
379 "SSL_read", 0, altPoll);
380 if (pollStatus != OK) return pollStatus;
381 // Do not advance buffer. Try SSL_read() again.
Yifan Honge8212f22021-06-28 15:49:08 -0700382 }
Yifan Honge8212f22021-06-28 15:49:08 -0700383 }
384 LOG_TLS_DETAIL("TLS: Received %zu bytes!", size);
385 return OK;
386}
387
388// For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|.
389bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) {
390 bssl::UniquePtr<BIO> bio = newSocketBio(fd);
391 TEST_AND_RETURN(false, bio != nullptr);
392 auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get());
393 (void)bio.release(); // SSL_set_bio takes ownership.
394 errorQueue.clear();
395
396 MAYBE_WAIT_IN_FLAKE_MODE;
397
398 while (true) {
399 auto [ret, errorQueue] = ssl->call(SSL_do_handshake);
400 if (ret > 0) {
401 errorQueue.clear();
402 return true;
403 }
404 if (ret == 0) {
405 // SSL_do_handshake() only returns 0 on EOF.
406 ALOGE("SSL_do_handshake(): EOF: %s", errorQueue.toString().c_str());
407 return false;
408 }
409 int sslError = ssl->getError(ret);
410 status_t pollStatus =
Steven Moreland43921d52021-09-27 17:15:56 -0700411 errorQueue.pollForSslError(fd, sslError, fdTrigger, "SSL_do_handshake", 0, {});
Yifan Honge8212f22021-06-28 15:49:08 -0700412 if (pollStatus != OK) return false;
413 }
414}
415
Yifan Hong1af48582021-08-16 17:13:30 -0700416class RpcTransportCtxTls : public RpcTransportCtx {
Yifan Honge8212f22021-06-28 15:49:08 -0700417public:
Yifan Hong1af48582021-08-16 17:13:30 -0700418 template <typename Impl,
419 typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
Yifan Hong180c2da2021-09-09 15:36:30 -0700420 static std::unique_ptr<RpcTransportCtxTls> create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700421 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth);
Yifan Hong1af48582021-08-16 17:13:30 -0700422 std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
Yifan Honge8212f22021-06-28 15:49:08 -0700423 FdTrigger* fdTrigger) const override;
Yifan Hong9734cfc2021-09-13 16:14:09 -0700424 std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override;
Yifan Honge8212f22021-06-28 15:49:08 -0700425
Yifan Hong1af48582021-08-16 17:13:30 -0700426protected:
Yifan Hong180c2da2021-09-09 15:36:30 -0700427 static ssl_verify_result_t sslCustomVerify(SSL* ssl, uint8_t* outAlert);
Yifan Hong1af48582021-08-16 17:13:30 -0700428 virtual void preHandshake(Ssl* ssl) const = 0;
Yifan Honge8212f22021-06-28 15:49:08 -0700429 bssl::UniquePtr<SSL_CTX> mCtx;
Yifan Hong180c2da2021-09-09 15:36:30 -0700430 std::shared_ptr<RpcCertificateVerifier> mCertVerifier;
Yifan Honge8212f22021-06-28 15:49:08 -0700431};
432
Yifan Hong9734cfc2021-09-13 16:14:09 -0700433std::vector<uint8_t> RpcTransportCtxTls::getCertificate(RpcCertificateFormat format) const {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700434 X509* x509 = SSL_CTX_get0_certificate(mCtx.get()); // does not own
435 return serializeCertificate(x509, format);
Yifan Hong588d59c2021-08-16 17:13:58 -0700436}
437
Yifan Hong180c2da2021-09-09 15:36:30 -0700438// Verify by comparing the leaf of peer certificate with every certificate in
439// mTrustedPeerCertificates. Does not support certificate chains.
440ssl_verify_result_t RpcTransportCtxTls::sslCustomVerify(SSL* ssl, uint8_t* outAlert) {
441 LOG_ALWAYS_FATAL_IF(outAlert == nullptr);
442 const char* logPrefix = SSL_is_server(ssl) ? "Server" : "Client";
443
Yifan Hong180c2da2021-09-09 15:36:30 -0700444 auto ctx = SSL_get_SSL_CTX(ssl); // Does not set error queue
445 LOG_ALWAYS_FATAL_IF(ctx == nullptr);
446 // void* -> RpcTransportCtxTls*
447 auto rpcTransportCtxTls = reinterpret_cast<RpcTransportCtxTls*>(SSL_CTX_get_app_data(ctx));
448 LOG_ALWAYS_FATAL_IF(rpcTransportCtxTls == nullptr);
449
Yifan Hongb160f8c2021-09-17 22:59:11 -0700450 status_t verifyStatus = rpcTransportCtxTls->mCertVerifier->verify(ssl, outAlert);
Yifan Hong180c2da2021-09-09 15:36:30 -0700451 if (verifyStatus == OK) {
452 return ssl_verify_ok;
453 }
454 LOG_TLS_DETAIL("%s: Failed to verify client: status = %s, alert = %s", logPrefix,
455 statusToString(verifyStatus).c_str(), SSL_alert_desc_string_long(*outAlert));
456 return ssl_verify_invalid;
457}
458
Yifan Hong1af48582021-08-16 17:13:30 -0700459// Common implementation for creating server and client contexts. The child class, |Impl|, is
460// provided as a template argument so that this function can initialize an |Impl| object.
461template <typename Impl, typename>
Yifan Hong180c2da2021-09-09 15:36:30 -0700462std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700463 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth) {
Yifan Honge8212f22021-06-28 15:49:08 -0700464 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
465 TEST_AND_RETURN(nullptr, ctx != nullptr);
466
Yifan Hongffdaf952021-09-17 18:08:38 -0700467 if (status_t authStatus = auth->configure(ctx.get()); authStatus != OK) {
468 ALOGE("%s: Failed to configure auth info: %s", __PRETTY_FUNCTION__,
469 statusToString(authStatus).c_str());
470 return nullptr;
471 };
Yifan Honge8212f22021-06-28 15:49:08 -0700472
Yifan Hong180c2da2021-09-09 15:36:30 -0700473 // Enable two-way authentication by setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT on server.
474 // Client ignores SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag.
475 SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
476 sslCustomVerify);
Yifan Honge8212f22021-06-28 15:49:08 -0700477
478 // Require at least TLS 1.3
479 TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
480
481 if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT
482 SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
483 }
484
Yifan Hong1af48582021-08-16 17:13:30 -0700485 auto ret = std::make_unique<Impl>();
Yifan Hong180c2da2021-09-09 15:36:30 -0700486 // RpcTransportCtxTls* -> void*
487 TEST_AND_RETURN(nullptr, SSL_CTX_set_app_data(ctx.get(), reinterpret_cast<void*>(ret.get())));
Yifan Hong1af48582021-08-16 17:13:30 -0700488 ret->mCtx = std::move(ctx);
Yifan Hong180c2da2021-09-09 15:36:30 -0700489 ret->mCertVerifier = std::move(verifier);
Yifan Hong1af48582021-08-16 17:13:30 -0700490 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700491}
492
Yifan Hong1af48582021-08-16 17:13:30 -0700493std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
494 FdTrigger* fdTrigger) const {
Yifan Honge8212f22021-06-28 15:49:08 -0700495 bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
496 TEST_AND_RETURN(nullptr, ssl != nullptr);
497 Ssl wrapped(std::move(ssl));
498
Yifan Hong1af48582021-08-16 17:13:30 -0700499 preHandshake(&wrapped);
500 TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
501 return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
Yifan Honge8212f22021-06-28 15:49:08 -0700502}
503
Yifan Hong1af48582021-08-16 17:13:30 -0700504class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
505protected:
506 void preHandshake(Ssl* ssl) const override {
507 ssl->call(SSL_set_accept_state).errorQueue.clear();
508 }
509};
510
511class RpcTransportCtxTlsClient : public RpcTransportCtxTls {
512protected:
513 void preHandshake(Ssl* ssl) const override {
514 ssl->call(SSL_set_connect_state).errorQueue.clear();
515 }
516};
517
Yifan Honge8212f22021-06-28 15:49:08 -0700518} // namespace
519
520std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700521 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>(mCertVerifier,
522 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700523}
524
525std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700526 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>(mCertVerifier,
527 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700528}
529
530const char* RpcTransportCtxFactoryTls::toCString() const {
531 return "tls";
532}
533
Yifan Hong13c90062021-09-09 14:59:53 -0700534std::unique_ptr<RpcTransportCtxFactory> RpcTransportCtxFactoryTls::make(
Yifan Hongffdaf952021-09-17 18:08:38 -0700535 std::shared_ptr<RpcCertificateVerifier> verifier, std::unique_ptr<RpcAuth> auth) {
Yifan Hong13c90062021-09-09 14:59:53 -0700536 if (verifier == nullptr) {
537 ALOGE("%s: Must provide a certificate verifier", __PRETTY_FUNCTION__);
538 return nullptr;
539 }
Yifan Hongffdaf952021-09-17 18:08:38 -0700540 if (auth == nullptr) {
541 ALOGE("%s: Must provide an auth provider", __PRETTY_FUNCTION__);
542 return nullptr;
543 }
Yifan Hong13c90062021-09-09 14:59:53 -0700544 return std::unique_ptr<RpcTransportCtxFactoryTls>(
Yifan Hongffdaf952021-09-17 18:08:38 -0700545 new RpcTransportCtxFactoryTls(std::move(verifier), std::move(auth)));
Yifan Honge8212f22021-06-28 15:49:08 -0700546}
547
548} // namespace android