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