blob: 85c7655727f2a7fbcd4bc03ea10f57108602d480 [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 -070040namespace android {
41namespace {
42
Yifan Hongd17353c2021-06-24 21:56:38 -070043// Implement BIO for socket that ignores SIGPIPE.
44int socketNew(BIO* bio) {
45 BIO_set_data(bio, reinterpret_cast<void*>(-1));
46 BIO_set_init(bio, 0);
47 return 1;
48}
49int socketFree(BIO* bio) {
50 LOG_ALWAYS_FATAL_IF(bio == nullptr);
51 return 1;
52}
53int 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
63int 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
73long 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
Yifan Honge8212f22021-06-28 15:49:08 -070080bssl::UniquePtr<BIO> newSocketBio(android::base::borrowed_fd fd) {
Yifan Hongd17353c2021-06-24 21:56:38 -070081 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;
Yifan Honge8212f22021-06-28 15:49:08 -070095}
96
Yifan Honge8212f22021-06-28 15:49:08 -070097[[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
Yifan Hong87a379c2021-08-12 18:53:24 -0700114// Helper class to ErrorQueue::toString
115class ErrorQueueString {
116public:
117 static std::string toString() {
118 ErrorQueueString thiz;
119 ERR_print_errors_cb(staticCallback, &thiz);
120 return thiz.mSs.str();
121 }
122
123private:
124 static int staticCallback(const char* str, size_t len, void* ctx) {
125 return reinterpret_cast<ErrorQueueString*>(ctx)->callback(str, len);
126 }
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
Yifan Honge8212f22021-06-28 15:49:08 -0700142// 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.
146class ErrorQueue {
147public:
148 ~ErrorQueue() { LOG_ALWAYS_FATAL_IF(!mHandled); }
149
150 // Clear the error queue.
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.
157 std::string toString() {
Yifan Hong87a379c2021-08-12 18:53:24 -0700158 auto ret = ErrorQueueString::toString();
Yifan Honge8212f22021-06-28 15:49:08 -0700159 // Though ERR_print_errors_cb should have cleared it, it is okay to clear again.
160 clear();
Yifan Hong87a379c2021-08-12 18:53:24 -0700161 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700162 }
163
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000164 status_t toStatus(int sslError, const char* fnString) {
Yifan Honge8212f22021-06-28 15:49:08 -0700165 switch (sslError) {
Yifan Honge8212f22021-06-28 15:49:08 -0700166 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
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000181 // |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().
184 status_t pollForSslError(android::base::borrowed_fd fd, int sslError, FdTrigger* fdTrigger,
185 const char* fnString, int additionalEvent,
186 const std::function<status_t()>& altPoll) {
187 switch (sslError) {
188 case SSL_ERROR_WANT_READ:
189 return handlePoll(POLLIN | additionalEvent, fd, fdTrigger, fnString, altPoll);
190 case SSL_ERROR_WANT_WRITE:
191 return handlePoll(POLLOUT | additionalEvent, fd, fdTrigger, fnString, altPoll);
192 default:
193 return toStatus(sslError, fnString);
194 }
195 }
196
Yifan Honge8212f22021-06-28 15:49:08 -0700197private:
198 bool mHandled = false;
199
200 status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger,
Steven Moreland43921d52021-09-27 17:15:56 -0700201 const char* fnString, const std::function<status_t()>& altPoll) {
202 status_t ret;
203 if (altPoll) {
204 ret = altPoll();
205 if (fdTrigger->isTriggered()) ret = DEAD_OBJECT;
206 } else {
207 ret = fdTrigger->triggerablePoll(fd, event);
208 }
209
Steven Morelandc591b472021-09-16 13:56:11 -0700210 if (ret != OK && ret != DEAD_OBJECT) {
Steven Moreland43921d52021-09-27 17:15:56 -0700211 ALOGE("poll error while after %s(): %s", fnString, statusToString(ret).c_str());
Yifan Honge8212f22021-06-28 15:49:08 -0700212 }
213 clear();
214 return ret;
215 }
216};
217
218// Helper to call a function, with its return value instantiable.
219template <typename Fn, typename... Args>
220struct FuncCaller {
221 struct Monostate {};
222 static constexpr bool sIsVoid = std::is_void_v<std::invoke_result_t<Fn, Args...>>;
223 using Result = std::conditional_t<sIsVoid, Monostate, std::invoke_result_t<Fn, Args...>>;
224 static inline Result call(Fn fn, Args&&... args) {
225 if constexpr (std::is_void_v<std::invoke_result_t<Fn, Args...>>) {
226 std::invoke(fn, std::forward<Args>(args)...);
227 return {};
228 } else {
229 return std::invoke(fn, std::forward<Args>(args)...);
230 }
231 }
232};
233
234// Helper to Ssl::call(). Returns the result to the SSL_* function as well as an ErrorQueue object.
235template <typename Fn, typename... Args>
236struct SslCaller {
237 using RawCaller = FuncCaller<Fn, SSL*, Args...>;
238 struct ResultAndErrorQueue {
239 typename RawCaller::Result result;
240 ErrorQueue errorQueue;
241 };
242 static inline ResultAndErrorQueue call(Fn fn, SSL* ssl, Args&&... args) {
243 LOG_ALWAYS_FATAL_IF(ssl == nullptr);
244 auto result = RawCaller::call(fn, std::forward<SSL*>(ssl), std::forward<Args>(args)...);
245 return ResultAndErrorQueue{std::move(result), ErrorQueue()};
246 }
247};
248
249// A wrapper over bssl::UniquePtr<SSL>. This class ensures that all SSL_* functions are called
250// through call(), which returns an ErrorQueue object that requires the caller to either handle
251// or clear it.
252// Example:
253// auto [ret, errorQueue] = ssl.call(SSL_read, buf, size);
254// if (ret >= 0) errorQueue.clear();
255// else ALOGE("%s", errorQueue.toString().c_str());
256class Ssl {
257public:
258 explicit Ssl(bssl::UniquePtr<SSL> ssl) : mSsl(std::move(ssl)) {
259 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
260 }
261
262 template <typename Fn, typename... Args>
263 inline typename SslCaller<Fn, Args...>::ResultAndErrorQueue call(Fn fn, Args&&... args) {
264 return SslCaller<Fn, Args...>::call(fn, mSsl.get(), std::forward<Args>(args)...);
265 }
266
267 int getError(int ret) {
268 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
269 return SSL_get_error(mSsl.get(), ret);
270 }
271
272private:
273 bssl::UniquePtr<SSL> mSsl;
274};
275
276class RpcTransportTls : public RpcTransport {
277public:
278 RpcTransportTls(android::base::unique_fd socket, Ssl ssl)
279 : mSocket(std::move(socket)), mSsl(std::move(ssl)) {}
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000280 status_t pollRead(void) override;
Colin Cross9adfeaf2022-01-21 17:22:09 -0800281 status_t interruptableWriteFully(FdTrigger* fdTrigger, iovec* iovs, int niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700282 const std::function<status_t()>& altPoll) override;
Colin Cross9adfeaf2022-01-21 17:22:09 -0800283 status_t interruptableReadFully(FdTrigger* fdTrigger, iovec* iovs, int niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700284 const std::function<status_t()>& altPoll) override;
Yifan Honge8212f22021-06-28 15:49:08 -0700285
286private:
287 android::base::unique_fd mSocket;
288 Ssl mSsl;
289};
290
291// Error code is errno.
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000292status_t RpcTransportTls::pollRead(void) {
293 uint8_t buf;
294 auto [ret, errorQueue] = mSsl.call(SSL_peek, &buf, sizeof(buf));
Yifan Honge8212f22021-06-28 15:49:08 -0700295 if (ret < 0) {
296 int err = mSsl.getError(ret);
297 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
298 // Seen EAGAIN / EWOULDBLOCK on recv(2) / send(2).
299 // Like RpcTransportRaw::peek(), don't handle it here.
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000300 errorQueue.clear();
301 return WOULD_BLOCK;
Yifan Honge8212f22021-06-28 15:49:08 -0700302 }
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000303 return errorQueue.toStatus(err, "SSL_peek");
Yifan Honge8212f22021-06-28 15:49:08 -0700304 }
305 errorQueue.clear();
306 LOG_TLS_DETAIL("TLS: Peeked %d bytes!", ret);
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000307 return OK;
Yifan Honge8212f22021-06-28 15:49:08 -0700308}
309
Colin Cross9adfeaf2022-01-21 17:22:09 -0800310status_t RpcTransportTls::interruptableWriteFully(FdTrigger* fdTrigger, iovec* iovs, int niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700311 const std::function<status_t()>& altPoll) {
Yifan Honge8212f22021-06-28 15:49:08 -0700312 MAYBE_WAIT_IN_FLAKE_MODE;
313
Colin Cross9adfeaf2022-01-21 17:22:09 -0800314 if (niovs < 0) return BAD_VALUE;
315
Yifan Hong15fff8c2021-08-10 15:07:56 -0700316 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
317 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700318 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700319
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000320 size_t size = 0;
Colin Cross9adfeaf2022-01-21 17:22:09 -0800321 for (int i = 0; i < niovs; i++) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000322 const iovec& iov = iovs[i];
323 if (iov.iov_len == 0) {
Yifan Honge8212f22021-06-28 15:49:08 -0700324 continue;
325 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000326 size += iov.iov_len;
327
328 auto buffer = reinterpret_cast<const uint8_t*>(iov.iov_base);
329 const uint8_t* end = buffer + iov.iov_len;
330 while (buffer < end) {
331 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
332 auto [writeSize, errorQueue] = mSsl.call(SSL_write, buffer, todo);
333 if (writeSize > 0) {
334 buffer += writeSize;
335 errorQueue.clear();
336 continue;
337 }
338 // SSL_write() should never return 0 unless BIO_write were to return 0.
339 int sslError = mSsl.getError(writeSize);
340 // TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be
341 // triggerablePoll()-ed. Then additionalEvent is no longer necessary.
342 status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
343 "SSL_write", POLLIN, altPoll);
344 if (pollStatus != OK) return pollStatus;
345 // Do not advance buffer. Try SSL_write() again.
346 }
Yifan Honge8212f22021-06-28 15:49:08 -0700347 }
348 LOG_TLS_DETAIL("TLS: Sent %zu bytes!", size);
349 return OK;
350}
351
Colin Cross9adfeaf2022-01-21 17:22:09 -0800352status_t RpcTransportTls::interruptableReadFully(FdTrigger* fdTrigger, iovec* iovs, int niovs,
Steven Moreland43921d52021-09-27 17:15:56 -0700353 const std::function<status_t()>& altPoll) {
Yifan Honge8212f22021-06-28 15:49:08 -0700354 MAYBE_WAIT_IN_FLAKE_MODE;
355
Colin Cross9adfeaf2022-01-21 17:22:09 -0800356 if (niovs < 0) return BAD_VALUE;
357
Yifan Hong15fff8c2021-08-10 15:07:56 -0700358 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
359 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700360 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700361
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000362 size_t size = 0;
Colin Cross9adfeaf2022-01-21 17:22:09 -0800363 for (int i = 0; i < niovs; i++) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000364 const iovec& iov = iovs[i];
365 if (iov.iov_len == 0) {
Yifan Honge8212f22021-06-28 15:49:08 -0700366 continue;
367 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000368 size += iov.iov_len;
369
370 auto buffer = reinterpret_cast<uint8_t*>(iov.iov_base);
371 const uint8_t* end = buffer + iov.iov_len;
372 while (buffer < end) {
373 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
374 auto [readSize, errorQueue] = mSsl.call(SSL_read, buffer, todo);
375 if (readSize > 0) {
376 buffer += readSize;
377 errorQueue.clear();
378 continue;
379 }
380 if (readSize == 0) {
381 // SSL_read() only returns 0 on EOF.
382 errorQueue.clear();
383 return DEAD_OBJECT;
384 }
385 int sslError = mSsl.getError(readSize);
386 status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
387 "SSL_read", 0, altPoll);
388 if (pollStatus != OK) return pollStatus;
389 // Do not advance buffer. Try SSL_read() again.
Yifan Honge8212f22021-06-28 15:49:08 -0700390 }
Yifan Honge8212f22021-06-28 15:49:08 -0700391 }
392 LOG_TLS_DETAIL("TLS: Received %zu bytes!", size);
393 return OK;
394}
395
396// For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|.
397bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) {
398 bssl::UniquePtr<BIO> bio = newSocketBio(fd);
399 TEST_AND_RETURN(false, bio != nullptr);
400 auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get());
401 (void)bio.release(); // SSL_set_bio takes ownership.
402 errorQueue.clear();
403
404 MAYBE_WAIT_IN_FLAKE_MODE;
405
406 while (true) {
407 auto [ret, errorQueue] = ssl->call(SSL_do_handshake);
408 if (ret > 0) {
409 errorQueue.clear();
410 return true;
411 }
412 if (ret == 0) {
413 // SSL_do_handshake() only returns 0 on EOF.
414 ALOGE("SSL_do_handshake(): EOF: %s", errorQueue.toString().c_str());
415 return false;
416 }
417 int sslError = ssl->getError(ret);
418 status_t pollStatus =
Steven Moreland43921d52021-09-27 17:15:56 -0700419 errorQueue.pollForSslError(fd, sslError, fdTrigger, "SSL_do_handshake", 0, {});
Yifan Honge8212f22021-06-28 15:49:08 -0700420 if (pollStatus != OK) return false;
421 }
422}
423
Yifan Hong1af48582021-08-16 17:13:30 -0700424class RpcTransportCtxTls : public RpcTransportCtx {
Yifan Honge8212f22021-06-28 15:49:08 -0700425public:
Yifan Hong1af48582021-08-16 17:13:30 -0700426 template <typename Impl,
427 typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
Yifan Hong180c2da2021-09-09 15:36:30 -0700428 static std::unique_ptr<RpcTransportCtxTls> create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700429 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth);
Yifan Hong1af48582021-08-16 17:13:30 -0700430 std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
Yifan Honge8212f22021-06-28 15:49:08 -0700431 FdTrigger* fdTrigger) const override;
Yifan Hong9734cfc2021-09-13 16:14:09 -0700432 std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override;
Yifan Honge8212f22021-06-28 15:49:08 -0700433
Yifan Hong1af48582021-08-16 17:13:30 -0700434protected:
Yifan Hong180c2da2021-09-09 15:36:30 -0700435 static ssl_verify_result_t sslCustomVerify(SSL* ssl, uint8_t* outAlert);
Yifan Hong1af48582021-08-16 17:13:30 -0700436 virtual void preHandshake(Ssl* ssl) const = 0;
Yifan Honge8212f22021-06-28 15:49:08 -0700437 bssl::UniquePtr<SSL_CTX> mCtx;
Yifan Hong180c2da2021-09-09 15:36:30 -0700438 std::shared_ptr<RpcCertificateVerifier> mCertVerifier;
Yifan Honge8212f22021-06-28 15:49:08 -0700439};
440
Yifan Hong9734cfc2021-09-13 16:14:09 -0700441std::vector<uint8_t> RpcTransportCtxTls::getCertificate(RpcCertificateFormat format) const {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700442 X509* x509 = SSL_CTX_get0_certificate(mCtx.get()); // does not own
443 return serializeCertificate(x509, format);
Yifan Hong588d59c2021-08-16 17:13:58 -0700444}
445
Yifan Hong180c2da2021-09-09 15:36:30 -0700446// Verify by comparing the leaf of peer certificate with every certificate in
447// mTrustedPeerCertificates. Does not support certificate chains.
448ssl_verify_result_t RpcTransportCtxTls::sslCustomVerify(SSL* ssl, uint8_t* outAlert) {
449 LOG_ALWAYS_FATAL_IF(outAlert == nullptr);
450 const char* logPrefix = SSL_is_server(ssl) ? "Server" : "Client";
451
Yifan Hong180c2da2021-09-09 15:36:30 -0700452 auto ctx = SSL_get_SSL_CTX(ssl); // Does not set error queue
453 LOG_ALWAYS_FATAL_IF(ctx == nullptr);
454 // void* -> RpcTransportCtxTls*
455 auto rpcTransportCtxTls = reinterpret_cast<RpcTransportCtxTls*>(SSL_CTX_get_app_data(ctx));
456 LOG_ALWAYS_FATAL_IF(rpcTransportCtxTls == nullptr);
457
Yifan Hongb160f8c2021-09-17 22:59:11 -0700458 status_t verifyStatus = rpcTransportCtxTls->mCertVerifier->verify(ssl, outAlert);
Yifan Hong180c2da2021-09-09 15:36:30 -0700459 if (verifyStatus == OK) {
460 return ssl_verify_ok;
461 }
462 LOG_TLS_DETAIL("%s: Failed to verify client: status = %s, alert = %s", logPrefix,
463 statusToString(verifyStatus).c_str(), SSL_alert_desc_string_long(*outAlert));
464 return ssl_verify_invalid;
465}
466
Yifan Hong1af48582021-08-16 17:13:30 -0700467// Common implementation for creating server and client contexts. The child class, |Impl|, is
468// provided as a template argument so that this function can initialize an |Impl| object.
469template <typename Impl, typename>
Yifan Hong180c2da2021-09-09 15:36:30 -0700470std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create(
Yifan Hongffdaf952021-09-17 18:08:38 -0700471 std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth) {
Yifan Honge8212f22021-06-28 15:49:08 -0700472 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
473 TEST_AND_RETURN(nullptr, ctx != nullptr);
474
Yifan Hongffdaf952021-09-17 18:08:38 -0700475 if (status_t authStatus = auth->configure(ctx.get()); authStatus != OK) {
476 ALOGE("%s: Failed to configure auth info: %s", __PRETTY_FUNCTION__,
477 statusToString(authStatus).c_str());
478 return nullptr;
479 };
Yifan Honge8212f22021-06-28 15:49:08 -0700480
Yifan Hong180c2da2021-09-09 15:36:30 -0700481 // Enable two-way authentication by setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT on server.
482 // Client ignores SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag.
483 SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
484 sslCustomVerify);
Yifan Honge8212f22021-06-28 15:49:08 -0700485
486 // Require at least TLS 1.3
487 TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
488
489 if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT
490 SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
491 }
492
Yifan Hong1af48582021-08-16 17:13:30 -0700493 auto ret = std::make_unique<Impl>();
Yifan Hong180c2da2021-09-09 15:36:30 -0700494 // RpcTransportCtxTls* -> void*
495 TEST_AND_RETURN(nullptr, SSL_CTX_set_app_data(ctx.get(), reinterpret_cast<void*>(ret.get())));
Yifan Hong1af48582021-08-16 17:13:30 -0700496 ret->mCtx = std::move(ctx);
Yifan Hong180c2da2021-09-09 15:36:30 -0700497 ret->mCertVerifier = std::move(verifier);
Yifan Hong1af48582021-08-16 17:13:30 -0700498 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700499}
500
Yifan Hong1af48582021-08-16 17:13:30 -0700501std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
502 FdTrigger* fdTrigger) const {
Yifan Honge8212f22021-06-28 15:49:08 -0700503 bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
504 TEST_AND_RETURN(nullptr, ssl != nullptr);
505 Ssl wrapped(std::move(ssl));
506
Yifan Hong1af48582021-08-16 17:13:30 -0700507 preHandshake(&wrapped);
508 TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
509 return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
Yifan Honge8212f22021-06-28 15:49:08 -0700510}
511
Yifan Hong1af48582021-08-16 17:13:30 -0700512class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
513protected:
514 void preHandshake(Ssl* ssl) const override {
515 ssl->call(SSL_set_accept_state).errorQueue.clear();
516 }
517};
518
519class RpcTransportCtxTlsClient : public RpcTransportCtxTls {
520protected:
521 void preHandshake(Ssl* ssl) const override {
522 ssl->call(SSL_set_connect_state).errorQueue.clear();
523 }
524};
525
Yifan Honge8212f22021-06-28 15:49:08 -0700526} // namespace
527
528std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700529 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>(mCertVerifier,
530 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700531}
532
533std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const {
Yifan Hongffdaf952021-09-17 18:08:38 -0700534 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>(mCertVerifier,
535 mAuth.get());
Yifan Honge8212f22021-06-28 15:49:08 -0700536}
537
538const char* RpcTransportCtxFactoryTls::toCString() const {
539 return "tls";
540}
541
Yifan Hong13c90062021-09-09 14:59:53 -0700542std::unique_ptr<RpcTransportCtxFactory> RpcTransportCtxFactoryTls::make(
Yifan Hongffdaf952021-09-17 18:08:38 -0700543 std::shared_ptr<RpcCertificateVerifier> verifier, std::unique_ptr<RpcAuth> auth) {
Yifan Hong13c90062021-09-09 14:59:53 -0700544 if (verifier == nullptr) {
545 ALOGE("%s: Must provide a certificate verifier", __PRETTY_FUNCTION__);
546 return nullptr;
547 }
Yifan Hongffdaf952021-09-17 18:08:38 -0700548 if (auth == nullptr) {
549 ALOGE("%s: Must provide an auth provider", __PRETTY_FUNCTION__);
550 return nullptr;
551 }
Yifan Hong13c90062021-09-09 14:59:53 -0700552 return std::unique_ptr<RpcTransportCtxFactoryTls>(
Yifan Hongffdaf952021-09-17 18:08:38 -0700553 new RpcTransportCtxFactoryTls(std::move(verifier), std::move(auth)));
Yifan Honge8212f22021-06-28 15:49:08 -0700554}
555
556} // namespace android