blob: f8cd71d434db40ece741d388d4d26b46ce4f90d4 [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,
172 const char* fnString, int additionalEvent = 0) {
173 switch (sslError) {
174 case SSL_ERROR_WANT_READ:
175 return handlePoll(POLLIN | additionalEvent, fd, fdTrigger, fnString);
176 case SSL_ERROR_WANT_WRITE:
177 return handlePoll(POLLOUT | additionalEvent, fd, fdTrigger, fnString);
178 case SSL_ERROR_SYSCALL: {
179 auto queue = toString();
180 LOG_TLS_DETAIL("%s(): %s. Treating as DEAD_OBJECT. Error queue: %s", fnString,
181 SSL_error_description(sslError), queue.c_str());
182 return DEAD_OBJECT;
183 }
184 default: {
185 auto queue = toString();
186 ALOGE("%s(): %s. Error queue: %s", fnString, SSL_error_description(sslError),
187 queue.c_str());
188 return UNKNOWN_ERROR;
189 }
190 }
191 }
192
193private:
194 bool mHandled = false;
195
196 status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger,
197 const char* fnString) {
198 status_t ret = fdTrigger->triggerablePoll(fd, event);
Steven Morelandc591b472021-09-16 13:56:11 -0700199 if (ret != OK && ret != DEAD_OBJECT) {
Yifan Honge8212f22021-06-28 15:49:08 -0700200 ALOGE("triggerablePoll error while poll()-ing after %s(): %s", fnString,
201 statusToString(ret).c_str());
202 }
203 clear();
204 return ret;
205 }
206};
207
208// Helper to call a function, with its return value instantiable.
209template <typename Fn, typename... Args>
210struct FuncCaller {
211 struct Monostate {};
212 static constexpr bool sIsVoid = std::is_void_v<std::invoke_result_t<Fn, Args...>>;
213 using Result = std::conditional_t<sIsVoid, Monostate, std::invoke_result_t<Fn, Args...>>;
214 static inline Result call(Fn fn, Args&&... args) {
215 if constexpr (std::is_void_v<std::invoke_result_t<Fn, Args...>>) {
216 std::invoke(fn, std::forward<Args>(args)...);
217 return {};
218 } else {
219 return std::invoke(fn, std::forward<Args>(args)...);
220 }
221 }
222};
223
224// Helper to Ssl::call(). Returns the result to the SSL_* function as well as an ErrorQueue object.
225template <typename Fn, typename... Args>
226struct SslCaller {
227 using RawCaller = FuncCaller<Fn, SSL*, Args...>;
228 struct ResultAndErrorQueue {
229 typename RawCaller::Result result;
230 ErrorQueue errorQueue;
231 };
232 static inline ResultAndErrorQueue call(Fn fn, SSL* ssl, Args&&... args) {
233 LOG_ALWAYS_FATAL_IF(ssl == nullptr);
234 auto result = RawCaller::call(fn, std::forward<SSL*>(ssl), std::forward<Args>(args)...);
235 return ResultAndErrorQueue{std::move(result), ErrorQueue()};
236 }
237};
238
239// A wrapper over bssl::UniquePtr<SSL>. This class ensures that all SSL_* functions are called
240// through call(), which returns an ErrorQueue object that requires the caller to either handle
241// or clear it.
242// Example:
243// auto [ret, errorQueue] = ssl.call(SSL_read, buf, size);
244// if (ret >= 0) errorQueue.clear();
245// else ALOGE("%s", errorQueue.toString().c_str());
246class Ssl {
247public:
248 explicit Ssl(bssl::UniquePtr<SSL> ssl) : mSsl(std::move(ssl)) {
249 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
250 }
251
252 template <typename Fn, typename... Args>
253 inline typename SslCaller<Fn, Args...>::ResultAndErrorQueue call(Fn fn, Args&&... args) {
254 return SslCaller<Fn, Args...>::call(fn, mSsl.get(), std::forward<Args>(args)...);
255 }
256
257 int getError(int ret) {
258 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
259 return SSL_get_error(mSsl.get(), ret);
260 }
261
262private:
263 bssl::UniquePtr<SSL> mSsl;
264};
265
266class RpcTransportTls : public RpcTransport {
267public:
268 RpcTransportTls(android::base::unique_fd socket, Ssl ssl)
269 : mSocket(std::move(socket)), mSsl(std::move(ssl)) {}
270 Result<size_t> peek(void* buf, size_t size) override;
271 status_t interruptableWriteFully(FdTrigger* fdTrigger, const void* data, size_t size) override;
272 status_t interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) override;
273
274private:
275 android::base::unique_fd mSocket;
276 Ssl mSsl;
277};
278
279// Error code is errno.
280Result<size_t> RpcTransportTls::peek(void* buf, size_t size) {
281 size_t todo = std::min<size_t>(size, std::numeric_limits<int>::max());
282 auto [ret, errorQueue] = mSsl.call(SSL_peek, buf, static_cast<int>(todo));
283 if (ret < 0) {
284 int err = mSsl.getError(ret);
285 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
286 // Seen EAGAIN / EWOULDBLOCK on recv(2) / send(2).
287 // Like RpcTransportRaw::peek(), don't handle it here.
288 return Error(EWOULDBLOCK) << "SSL_peek(): " << errorQueue.toString();
289 }
290 return Error() << "SSL_peek(): " << errorQueue.toString();
291 }
292 errorQueue.clear();
293 LOG_TLS_DETAIL("TLS: Peeked %d bytes!", ret);
294 return ret;
295}
296
297status_t RpcTransportTls::interruptableWriteFully(FdTrigger* fdTrigger, const void* data,
298 size_t size) {
299 auto buffer = reinterpret_cast<const uint8_t*>(data);
300 const uint8_t* end = buffer + size;
301
302 MAYBE_WAIT_IN_FLAKE_MODE;
303
Yifan Hong15fff8c2021-08-10 15:07:56 -0700304 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
305 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700306 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700307
Yifan Honge8212f22021-06-28 15:49:08 -0700308 while (buffer < end) {
309 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
310 auto [writeSize, errorQueue] = mSsl.call(SSL_write, buffer, todo);
311 if (writeSize > 0) {
312 buffer += writeSize;
313 errorQueue.clear();
314 continue;
315 }
316 // SSL_write() should never return 0 unless BIO_write were to return 0.
317 int sslError = mSsl.getError(writeSize);
318 // TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be
319 // triggerablePoll()-ed. Then additionalEvent is no longer necessary.
320 status_t pollStatus =
321 errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_write", POLLIN);
322 if (pollStatus != OK) return pollStatus;
323 // Do not advance buffer. Try SSL_write() again.
324 }
325 LOG_TLS_DETAIL("TLS: Sent %zu bytes!", size);
326 return OK;
327}
328
329status_t RpcTransportTls::interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) {
330 auto buffer = reinterpret_cast<uint8_t*>(data);
331 uint8_t* end = buffer + size;
332
333 MAYBE_WAIT_IN_FLAKE_MODE;
334
Yifan Hong15fff8c2021-08-10 15:07:56 -0700335 // 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 Morelandc591b472021-09-16 13:56:11 -0700337 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700338
Yifan Honge8212f22021-06-28 15:49:08 -0700339 while (buffer < end) {
340 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
341 auto [readSize, errorQueue] = mSsl.call(SSL_read, buffer, todo);
342 if (readSize > 0) {
343 buffer += readSize;
344 errorQueue.clear();
345 continue;
346 }
347 if (readSize == 0) {
348 // SSL_read() only returns 0 on EOF.
349 errorQueue.clear();
350 return DEAD_OBJECT;
351 }
352 int sslError = mSsl.getError(readSize);
353 status_t pollStatus =
354 errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_read");
355 if (pollStatus != OK) return pollStatus;
356 // Do not advance buffer. Try SSL_read() again.
357 }
358 LOG_TLS_DETAIL("TLS: Received %zu bytes!", size);
359 return OK;
360}
361
362// For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|.
363bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) {
364 bssl::UniquePtr<BIO> bio = newSocketBio(fd);
365 TEST_AND_RETURN(false, bio != nullptr);
366 auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get());
367 (void)bio.release(); // SSL_set_bio takes ownership.
368 errorQueue.clear();
369
370 MAYBE_WAIT_IN_FLAKE_MODE;
371
372 while (true) {
373 auto [ret, errorQueue] = ssl->call(SSL_do_handshake);
374 if (ret > 0) {
375 errorQueue.clear();
376 return true;
377 }
378 if (ret == 0) {
379 // SSL_do_handshake() only returns 0 on EOF.
380 ALOGE("SSL_do_handshake(): EOF: %s", errorQueue.toString().c_str());
381 return false;
382 }
383 int sslError = ssl->getError(ret);
384 status_t pollStatus =
385 errorQueue.pollForSslError(fd, sslError, fdTrigger, "SSL_do_handshake");
386 if (pollStatus != OK) return false;
387 }
388}
389
Yifan Hong1af48582021-08-16 17:13:30 -0700390class RpcTransportCtxTls : public RpcTransportCtx {
Yifan Honge8212f22021-06-28 15:49:08 -0700391public:
Yifan Hong1af48582021-08-16 17:13:30 -0700392 template <typename Impl,
393 typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
Yifan Hong180c2da2021-09-09 15:36:30 -0700394 static std::unique_ptr<RpcTransportCtxTls> create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700395 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth);
Yifan Hong1af48582021-08-16 17:13:30 -0700396 std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
Yifan Honge8212f22021-06-28 15:49:08 -0700397 FdTrigger* fdTrigger) const override;
Yifan Hong9734cfc2021-09-13 16:14:09 -0700398 std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override;
Yifan Honge8212f22021-06-28 15:49:08 -0700399
Yifan Hong1af48582021-08-16 17:13:30 -0700400protected:
Yifan Hong180c2da2021-09-09 15:36:30 -0700401 static ssl_verify_result_t sslCustomVerify(SSL* ssl, uint8_t* outAlert);
Yifan Hong1af48582021-08-16 17:13:30 -0700402 virtual void preHandshake(Ssl* ssl) const = 0;
Yifan Honge8212f22021-06-28 15:49:08 -0700403 bssl::UniquePtr<SSL_CTX> mCtx;
Yifan Hong180c2da2021-09-09 15:36:30 -0700404 std::shared_ptr<RpcCertificateVerifier> mCertVerifier;
Yifan Honge8212f22021-06-28 15:49:08 -0700405};
406
Yifan Hong9734cfc2021-09-13 16:14:09 -0700407std::vector<uint8_t> RpcTransportCtxTls::getCertificate(RpcCertificateFormat format) const {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700408 X509* x509 = SSL_CTX_get0_certificate(mCtx.get()); // does not own
409 return serializeCertificate(x509, format);
Yifan Hong588d59c2021-08-16 17:13:58 -0700410}
411
Yifan Hong180c2da2021-09-09 15:36:30 -0700412// Verify by comparing the leaf of peer certificate with every certificate in
413// mTrustedPeerCertificates. Does not support certificate chains.
414ssl_verify_result_t RpcTransportCtxTls::sslCustomVerify(SSL* ssl, uint8_t* outAlert) {
415 LOG_ALWAYS_FATAL_IF(outAlert == nullptr);
416 const char* logPrefix = SSL_is_server(ssl) ? "Server" : "Client";
417
Yifan Hong180c2da2021-09-09 15:36:30 -0700418 auto ctx = SSL_get_SSL_CTX(ssl); // Does not set error queue
419 LOG_ALWAYS_FATAL_IF(ctx == nullptr);
420 // void* -> RpcTransportCtxTls*
421 auto rpcTransportCtxTls = reinterpret_cast<RpcTransportCtxTls*>(SSL_CTX_get_app_data(ctx));
422 LOG_ALWAYS_FATAL_IF(rpcTransportCtxTls == nullptr);
423
Yifan Hongb160f8c2021-09-17 22:59:11 -0700424 status_t verifyStatus = rpcTransportCtxTls->mCertVerifier->verify(ssl, outAlert);
Yifan Hong180c2da2021-09-09 15:36:30 -0700425 if (verifyStatus == OK) {
426 return ssl_verify_ok;
427 }
428 LOG_TLS_DETAIL("%s: Failed to verify client: status = %s, alert = %s", logPrefix,
429 statusToString(verifyStatus).c_str(), SSL_alert_desc_string_long(*outAlert));
430 return ssl_verify_invalid;
431}
432
Yifan Hong1af48582021-08-16 17:13:30 -0700433// Common implementation for creating server and client contexts. The child class, |Impl|, is
434// provided as a template argument so that this function can initialize an |Impl| object.
435template <typename Impl, typename>
Yifan Hong180c2da2021-09-09 15:36:30 -0700436std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700437 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth) {
Yifan Honge8212f22021-06-28 15:49:08 -0700438 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
439 TEST_AND_RETURN(nullptr, ctx != nullptr);
440
Yifan Hongffdaf952021-09-17 18:08:38 -0700441 if (status_t authStatus = auth->configure(ctx.get()); authStatus != OK) {
442 ALOGE("%s: Failed to configure auth info: %s", __PRETTY_FUNCTION__,
443 statusToString(authStatus).c_str());
444 return nullptr;
445 };
Yifan Honge8212f22021-06-28 15:49:08 -0700446
Yifan Hong180c2da2021-09-09 15:36:30 -0700447 // Enable two-way authentication by setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT on server.
448 // Client ignores SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag.
449 SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
450 sslCustomVerify);
Yifan Honge8212f22021-06-28 15:49:08 -0700451
452 // Require at least TLS 1.3
453 TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
454
455 if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT
456 SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
457 }
458
Yifan Hong1af48582021-08-16 17:13:30 -0700459 auto ret = std::make_unique<Impl>();
Yifan Hong180c2da2021-09-09 15:36:30 -0700460 // RpcTransportCtxTls* -> void*
461 TEST_AND_RETURN(nullptr, SSL_CTX_set_app_data(ctx.get(), reinterpret_cast<void*>(ret.get())));
Yifan Hong1af48582021-08-16 17:13:30 -0700462 ret->mCtx = std::move(ctx);
Yifan Hong180c2da2021-09-09 15:36:30 -0700463 ret->mCertVerifier = std::move(verifier);
Yifan Hong1af48582021-08-16 17:13:30 -0700464 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700465}
466
Yifan Hong1af48582021-08-16 17:13:30 -0700467std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
468 FdTrigger* fdTrigger) const {
Yifan Honge8212f22021-06-28 15:49:08 -0700469 bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
470 TEST_AND_RETURN(nullptr, ssl != nullptr);
471 Ssl wrapped(std::move(ssl));
472
Yifan Hong1af48582021-08-16 17:13:30 -0700473 preHandshake(&wrapped);
474 TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
475 return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
Yifan Honge8212f22021-06-28 15:49:08 -0700476}
477
Yifan Hong1af48582021-08-16 17:13:30 -0700478class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
479protected:
480 void preHandshake(Ssl* ssl) const override {
481 ssl->call(SSL_set_accept_state).errorQueue.clear();
482 }
483};
484
485class RpcTransportCtxTlsClient : public RpcTransportCtxTls {
486protected:
487 void preHandshake(Ssl* ssl) const override {
488 ssl->call(SSL_set_connect_state).errorQueue.clear();
489 }
490};
491
Yifan Honge8212f22021-06-28 15:49:08 -0700492} // namespace
493
494std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700495 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>(mCertVerifier,
496 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700497}
498
499std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700500 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>(mCertVerifier,
501 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700502}
503
504const char* RpcTransportCtxFactoryTls::toCString() const {
505 return "tls";
506}
507
Yifan Hong13c90062021-09-09 14:59:53 -0700508std::unique_ptr<RpcTransportCtxFactory> RpcTransportCtxFactoryTls::make(
Yifan Hongffdaf952021-09-17 18:08:38 -0700509 std::shared_ptr<RpcCertificateVerifier> verifier, std::unique_ptr<RpcAuth> auth) {
Yifan Hong13c90062021-09-09 14:59:53 -0700510 if (verifier == nullptr) {
511 ALOGE("%s: Must provide a certificate verifier", __PRETTY_FUNCTION__);
512 return nullptr;
513 }
Yifan Hongffdaf952021-09-17 18:08:38 -0700514 if (auth == nullptr) {
515 ALOGE("%s: Must provide an auth provider", __PRETTY_FUNCTION__);
516 return nullptr;
517 }
Yifan Hong13c90062021-09-09 14:59:53 -0700518 return std::unique_ptr<RpcTransportCtxFactoryTls>(
Yifan Hongffdaf952021-09-17 18:08:38 -0700519 new RpcTransportCtxFactoryTls(std::move(verifier), std::move(auth)));
Yifan Honge8212f22021-06-28 15:49:08 -0700520}
521
522} // namespace android