blob: 8c066ee6b27335e311bbe4f0fdaf80aae487df99 [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
47constexpr const int kCertValidDays = 30;
48
Yifan Hongd17353c2021-06-24 21:56:38 -070049// Implement BIO for socket that ignores SIGPIPE.
50int socketNew(BIO* bio) {
51 BIO_set_data(bio, reinterpret_cast<void*>(-1));
52 BIO_set_init(bio, 0);
53 return 1;
54}
55int socketFree(BIO* bio) {
56 LOG_ALWAYS_FATAL_IF(bio == nullptr);
57 return 1;
58}
59int socketRead(BIO* bio, char* buf, int size) {
60 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
61 int ret = TEMP_FAILURE_RETRY(::recv(fd.get(), buf, size, MSG_NOSIGNAL));
62 BIO_clear_retry_flags(bio);
63 if (errno == EAGAIN || errno == EWOULDBLOCK) {
64 BIO_set_retry_read(bio);
65 }
66 return ret;
67}
68
69int socketWrite(BIO* bio, const char* buf, int size) {
70 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
71 int ret = TEMP_FAILURE_RETRY(::send(fd.get(), buf, size, MSG_NOSIGNAL));
72 BIO_clear_retry_flags(bio);
73 if (errno == EAGAIN || errno == EWOULDBLOCK) {
74 BIO_set_retry_write(bio);
75 }
76 return ret;
77}
78
79long socketCtrl(BIO* bio, int cmd, long num, void*) { // NOLINT
80 android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
81 if (cmd == BIO_CTRL_FLUSH) return 1;
82 LOG_ALWAYS_FATAL("sockCtrl(fd=%d, %d, %ld)", fd.get(), cmd, num);
83 return 0;
84}
85
Yifan Honge8212f22021-06-28 15:49:08 -070086bssl::UniquePtr<BIO> newSocketBio(android::base::borrowed_fd fd) {
Yifan Hongd17353c2021-06-24 21:56:38 -070087 static const BIO_METHOD* gMethods = ([] {
88 auto methods = BIO_meth_new(BIO_get_new_index(), "socket_no_signal");
89 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_write(methods, socketWrite), "BIO_meth_set_write");
90 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_read(methods, socketRead), "BIO_meth_set_read");
91 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_ctrl(methods, socketCtrl), "BIO_meth_set_ctrl");
92 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_create(methods, socketNew), "BIO_meth_set_create");
93 LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_destroy(methods, socketFree), "BIO_meth_set_destroy");
94 return methods;
95 })();
96 bssl::UniquePtr<BIO> ret(BIO_new(gMethods));
97 if (ret == nullptr) return nullptr;
98 BIO_set_data(ret.get(), reinterpret_cast<void*>(fd.get()));
99 BIO_set_init(ret.get(), 1);
100 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700101}
102
103bssl::UniquePtr<EVP_PKEY> makeKeyPairForSelfSignedCert() {
104 bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
105 if (ec_key == nullptr || !EC_KEY_generate_key(ec_key.get())) {
106 ALOGE("Failed to generate key pair.");
107 return nullptr;
108 }
109 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
110 // Use set1 instead of assign to avoid leaking ec_key when assign fails. set1 increments
111 // the refcount of the ec_key, so it is okay to release it at the end of this function.
112 if (evp_pkey == nullptr || !EVP_PKEY_set1_EC_KEY(evp_pkey.get(), ec_key.get())) {
113 ALOGE("Failed to assign key pair.");
114 return nullptr;
115 }
116 return evp_pkey;
117}
118
119bssl::UniquePtr<X509> makeSelfSignedCert(EVP_PKEY* evp_pkey, const int valid_days) {
120 bssl::UniquePtr<X509> x509(X509_new());
121 bssl::UniquePtr<BIGNUM> serial(BN_new());
122 bssl::UniquePtr<BIGNUM> serialLimit(BN_new());
123 TEST_AND_RETURN(nullptr, BN_lshift(serialLimit.get(), BN_value_one(), 128));
124 TEST_AND_RETURN(nullptr, BN_rand_range(serial.get(), serialLimit.get()));
125 TEST_AND_RETURN(nullptr, BN_to_ASN1_INTEGER(serial.get(), X509_get_serialNumber(x509.get())));
126 TEST_AND_RETURN(nullptr, X509_gmtime_adj(X509_getm_notBefore(x509.get()), 0));
127 TEST_AND_RETURN(nullptr,
128 X509_gmtime_adj(X509_getm_notAfter(x509.get()), 60 * 60 * 24 * valid_days));
129
130 X509_NAME* subject = X509_get_subject_name(x509.get());
131 TEST_AND_RETURN(nullptr,
132 X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
133 reinterpret_cast<const uint8_t*>("Android"), -1, -1,
134 0));
135 TEST_AND_RETURN(nullptr,
136 X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC,
137 reinterpret_cast<const uint8_t*>("BinderRPC"), -1,
138 -1, 0));
139 TEST_AND_RETURN(nullptr, X509_set_issuer_name(x509.get(), subject));
140
141 TEST_AND_RETURN(nullptr, X509_set_pubkey(x509.get(), evp_pkey));
142 TEST_AND_RETURN(nullptr, X509_sign(x509.get(), evp_pkey, EVP_sha256()));
143 return x509;
144}
145
146[[maybe_unused]] void sslDebugLog(const SSL* ssl, int type, int value) {
147 switch (type) {
148 case SSL_CB_HANDSHAKE_START:
149 LOG_TLS_DETAIL("Handshake started.");
150 break;
151 case SSL_CB_HANDSHAKE_DONE:
152 LOG_TLS_DETAIL("Handshake done.");
153 break;
154 case SSL_CB_ACCEPT_LOOP:
155 LOG_TLS_DETAIL("Handshake progress: %s", SSL_state_string_long(ssl));
156 break;
157 default:
158 LOG_TLS_DETAIL("SSL Debug Log: type = %d, value = %d", type, value);
159 break;
160 }
161}
162
Yifan Hong87a379c2021-08-12 18:53:24 -0700163// Helper class to ErrorQueue::toString
164class ErrorQueueString {
165public:
166 static std::string toString() {
167 ErrorQueueString thiz;
168 ERR_print_errors_cb(staticCallback, &thiz);
169 return thiz.mSs.str();
170 }
171
172private:
173 static int staticCallback(const char* str, size_t len, void* ctx) {
174 return reinterpret_cast<ErrorQueueString*>(ctx)->callback(str, len);
175 }
176 int callback(const char* str, size_t len) {
177 if (len == 0) return 1; // continue
178 // ERR_print_errors_cb place a new line at the end, but it doesn't say so in the API.
179 if (str[len - 1] == '\n') len -= 1;
180 if (!mIsFirst) {
181 mSs << '\n';
182 }
183 mSs << std::string_view(str, len);
184 mIsFirst = false;
185 return 1; // continue
186 }
187 std::stringstream mSs;
188 bool mIsFirst = true;
189};
190
Yifan Honge8212f22021-06-28 15:49:08 -0700191// Handles libssl's error queue.
192//
193// Call into any of its member functions to ensure the error queue is properly handled or cleared.
194// If the error queue is not handled or cleared, the destructor will abort.
195class ErrorQueue {
196public:
197 ~ErrorQueue() { LOG_ALWAYS_FATAL_IF(!mHandled); }
198
199 // Clear the error queue.
200 void clear() {
201 ERR_clear_error();
202 mHandled = true;
203 }
204
205 // Stores the error queue in |ssl| into a string, then clears the error queue.
206 std::string toString() {
Yifan Hong87a379c2021-08-12 18:53:24 -0700207 auto ret = ErrorQueueString::toString();
Yifan Honge8212f22021-06-28 15:49:08 -0700208 // Though ERR_print_errors_cb should have cleared it, it is okay to clear again.
209 clear();
Yifan Hong87a379c2021-08-12 18:53:24 -0700210 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700211 }
212
213 // |sslError| should be from Ssl::getError().
214 // If |sslError| is WANT_READ / WANT_WRITE, poll for POLLIN / POLLOUT respectively. Otherwise
215 // return error. Also return error if |fdTrigger| is triggered before or during poll().
216 status_t pollForSslError(android::base::borrowed_fd fd, int sslError, FdTrigger* fdTrigger,
217 const char* fnString, int additionalEvent = 0) {
218 switch (sslError) {
219 case SSL_ERROR_WANT_READ:
220 return handlePoll(POLLIN | additionalEvent, fd, fdTrigger, fnString);
221 case SSL_ERROR_WANT_WRITE:
222 return handlePoll(POLLOUT | additionalEvent, fd, fdTrigger, fnString);
223 case SSL_ERROR_SYSCALL: {
224 auto queue = toString();
225 LOG_TLS_DETAIL("%s(): %s. Treating as DEAD_OBJECT. Error queue: %s", fnString,
226 SSL_error_description(sslError), queue.c_str());
227 return DEAD_OBJECT;
228 }
229 default: {
230 auto queue = toString();
231 ALOGE("%s(): %s. Error queue: %s", fnString, SSL_error_description(sslError),
232 queue.c_str());
233 return UNKNOWN_ERROR;
234 }
235 }
236 }
237
238private:
239 bool mHandled = false;
240
241 status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger,
242 const char* fnString) {
243 status_t ret = fdTrigger->triggerablePoll(fd, event);
Steven Morelandc591b472021-09-16 13:56:11 -0700244 if (ret != OK && ret != DEAD_OBJECT) {
Yifan Honge8212f22021-06-28 15:49:08 -0700245 ALOGE("triggerablePoll error while poll()-ing after %s(): %s", fnString,
246 statusToString(ret).c_str());
247 }
248 clear();
249 return ret;
250 }
251};
252
253// Helper to call a function, with its return value instantiable.
254template <typename Fn, typename... Args>
255struct FuncCaller {
256 struct Monostate {};
257 static constexpr bool sIsVoid = std::is_void_v<std::invoke_result_t<Fn, Args...>>;
258 using Result = std::conditional_t<sIsVoid, Monostate, std::invoke_result_t<Fn, Args...>>;
259 static inline Result call(Fn fn, Args&&... args) {
260 if constexpr (std::is_void_v<std::invoke_result_t<Fn, Args...>>) {
261 std::invoke(fn, std::forward<Args>(args)...);
262 return {};
263 } else {
264 return std::invoke(fn, std::forward<Args>(args)...);
265 }
266 }
267};
268
269// Helper to Ssl::call(). Returns the result to the SSL_* function as well as an ErrorQueue object.
270template <typename Fn, typename... Args>
271struct SslCaller {
272 using RawCaller = FuncCaller<Fn, SSL*, Args...>;
273 struct ResultAndErrorQueue {
274 typename RawCaller::Result result;
275 ErrorQueue errorQueue;
276 };
277 static inline ResultAndErrorQueue call(Fn fn, SSL* ssl, Args&&... args) {
278 LOG_ALWAYS_FATAL_IF(ssl == nullptr);
279 auto result = RawCaller::call(fn, std::forward<SSL*>(ssl), std::forward<Args>(args)...);
280 return ResultAndErrorQueue{std::move(result), ErrorQueue()};
281 }
282};
283
284// A wrapper over bssl::UniquePtr<SSL>. This class ensures that all SSL_* functions are called
285// through call(), which returns an ErrorQueue object that requires the caller to either handle
286// or clear it.
287// Example:
288// auto [ret, errorQueue] = ssl.call(SSL_read, buf, size);
289// if (ret >= 0) errorQueue.clear();
290// else ALOGE("%s", errorQueue.toString().c_str());
291class Ssl {
292public:
293 explicit Ssl(bssl::UniquePtr<SSL> ssl) : mSsl(std::move(ssl)) {
294 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
295 }
296
297 template <typename Fn, typename... Args>
298 inline typename SslCaller<Fn, Args...>::ResultAndErrorQueue call(Fn fn, Args&&... args) {
299 return SslCaller<Fn, Args...>::call(fn, mSsl.get(), std::forward<Args>(args)...);
300 }
301
302 int getError(int ret) {
303 LOG_ALWAYS_FATAL_IF(mSsl == nullptr);
304 return SSL_get_error(mSsl.get(), ret);
305 }
306
307private:
308 bssl::UniquePtr<SSL> mSsl;
309};
310
311class RpcTransportTls : public RpcTransport {
312public:
313 RpcTransportTls(android::base::unique_fd socket, Ssl ssl)
314 : mSocket(std::move(socket)), mSsl(std::move(ssl)) {}
315 Result<size_t> peek(void* buf, size_t size) override;
316 status_t interruptableWriteFully(FdTrigger* fdTrigger, const void* data, size_t size) override;
317 status_t interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) override;
318
319private:
320 android::base::unique_fd mSocket;
321 Ssl mSsl;
322};
323
324// Error code is errno.
325Result<size_t> RpcTransportTls::peek(void* buf, size_t size) {
326 size_t todo = std::min<size_t>(size, std::numeric_limits<int>::max());
327 auto [ret, errorQueue] = mSsl.call(SSL_peek, buf, static_cast<int>(todo));
328 if (ret < 0) {
329 int err = mSsl.getError(ret);
330 if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
331 // Seen EAGAIN / EWOULDBLOCK on recv(2) / send(2).
332 // Like RpcTransportRaw::peek(), don't handle it here.
333 return Error(EWOULDBLOCK) << "SSL_peek(): " << errorQueue.toString();
334 }
335 return Error() << "SSL_peek(): " << errorQueue.toString();
336 }
337 errorQueue.clear();
338 LOG_TLS_DETAIL("TLS: Peeked %d bytes!", ret);
339 return ret;
340}
341
342status_t RpcTransportTls::interruptableWriteFully(FdTrigger* fdTrigger, const void* data,
343 size_t size) {
344 auto buffer = reinterpret_cast<const uint8_t*>(data);
345 const uint8_t* end = buffer + size;
346
347 MAYBE_WAIT_IN_FLAKE_MODE;
348
Yifan Hong15fff8c2021-08-10 15:07:56 -0700349 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
350 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700351 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700352
Yifan Honge8212f22021-06-28 15:49:08 -0700353 while (buffer < end) {
354 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
355 auto [writeSize, errorQueue] = mSsl.call(SSL_write, buffer, todo);
356 if (writeSize > 0) {
357 buffer += writeSize;
358 errorQueue.clear();
359 continue;
360 }
361 // SSL_write() should never return 0 unless BIO_write were to return 0.
362 int sslError = mSsl.getError(writeSize);
363 // TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be
364 // triggerablePoll()-ed. Then additionalEvent is no longer necessary.
365 status_t pollStatus =
366 errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_write", POLLIN);
367 if (pollStatus != OK) return pollStatus;
368 // Do not advance buffer. Try SSL_write() again.
369 }
370 LOG_TLS_DETAIL("TLS: Sent %zu bytes!", size);
371 return OK;
372}
373
374status_t RpcTransportTls::interruptableReadFully(FdTrigger* fdTrigger, void* data, size_t size) {
375 auto buffer = reinterpret_cast<uint8_t*>(data);
376 uint8_t* end = buffer + size;
377
378 MAYBE_WAIT_IN_FLAKE_MODE;
379
Yifan Hong15fff8c2021-08-10 15:07:56 -0700380 // Before doing any I/O, check trigger once. This ensures the trigger is checked at least
381 // once. The trigger is also checked via triggerablePoll() after every SSL_write().
Steven Morelandc591b472021-09-16 13:56:11 -0700382 if (fdTrigger->isTriggered()) return DEAD_OBJECT;
Yifan Hong15fff8c2021-08-10 15:07:56 -0700383
Yifan Honge8212f22021-06-28 15:49:08 -0700384 while (buffer < end) {
385 size_t todo = std::min<size_t>(end - buffer, std::numeric_limits<int>::max());
386 auto [readSize, errorQueue] = mSsl.call(SSL_read, buffer, todo);
387 if (readSize > 0) {
388 buffer += readSize;
389 errorQueue.clear();
390 continue;
391 }
392 if (readSize == 0) {
393 // SSL_read() only returns 0 on EOF.
394 errorQueue.clear();
395 return DEAD_OBJECT;
396 }
397 int sslError = mSsl.getError(readSize);
398 status_t pollStatus =
399 errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger, "SSL_read");
400 if (pollStatus != OK) return pollStatus;
401 // Do not advance buffer. Try SSL_read() again.
402 }
403 LOG_TLS_DETAIL("TLS: Received %zu bytes!", size);
404 return OK;
405}
406
407// For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|.
408bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) {
409 bssl::UniquePtr<BIO> bio = newSocketBio(fd);
410 TEST_AND_RETURN(false, bio != nullptr);
411 auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get());
412 (void)bio.release(); // SSL_set_bio takes ownership.
413 errorQueue.clear();
414
415 MAYBE_WAIT_IN_FLAKE_MODE;
416
417 while (true) {
418 auto [ret, errorQueue] = ssl->call(SSL_do_handshake);
419 if (ret > 0) {
420 errorQueue.clear();
421 return true;
422 }
423 if (ret == 0) {
424 // SSL_do_handshake() only returns 0 on EOF.
425 ALOGE("SSL_do_handshake(): EOF: %s", errorQueue.toString().c_str());
426 return false;
427 }
428 int sslError = ssl->getError(ret);
429 status_t pollStatus =
430 errorQueue.pollForSslError(fd, sslError, fdTrigger, "SSL_do_handshake");
431 if (pollStatus != OK) return false;
432 }
433}
434
Yifan Hong1af48582021-08-16 17:13:30 -0700435class RpcTransportCtxTls : public RpcTransportCtx {
Yifan Honge8212f22021-06-28 15:49:08 -0700436public:
Yifan Hong1af48582021-08-16 17:13:30 -0700437 template <typename Impl,
438 typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
Yifan Hong180c2da2021-09-09 15:36:30 -0700439 static std::unique_ptr<RpcTransportCtxTls> create(
440 std::shared_ptr<RpcCertificateVerifier> verifier);
Yifan Hong1af48582021-08-16 17:13:30 -0700441 std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
Yifan Honge8212f22021-06-28 15:49:08 -0700442 FdTrigger* fdTrigger) const override;
Yifan Hong9734cfc2021-09-13 16:14:09 -0700443 std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override;
Yifan Honge8212f22021-06-28 15:49:08 -0700444
Yifan Hong1af48582021-08-16 17:13:30 -0700445protected:
Yifan Hong180c2da2021-09-09 15:36:30 -0700446 static ssl_verify_result_t sslCustomVerify(SSL* ssl, uint8_t* outAlert);
Yifan Hong1af48582021-08-16 17:13:30 -0700447 virtual void preHandshake(Ssl* ssl) const = 0;
Yifan Honge8212f22021-06-28 15:49:08 -0700448 bssl::UniquePtr<SSL_CTX> mCtx;
Yifan Hong180c2da2021-09-09 15:36:30 -0700449 std::shared_ptr<RpcCertificateVerifier> mCertVerifier;
Yifan Honge8212f22021-06-28 15:49:08 -0700450};
451
Yifan Hong9734cfc2021-09-13 16:14:09 -0700452std::vector<uint8_t> RpcTransportCtxTls::getCertificate(RpcCertificateFormat format) const {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700453 X509* x509 = SSL_CTX_get0_certificate(mCtx.get()); // does not own
454 return serializeCertificate(x509, format);
Yifan Hong588d59c2021-08-16 17:13:58 -0700455}
456
Yifan Hong180c2da2021-09-09 15:36:30 -0700457// Verify by comparing the leaf of peer certificate with every certificate in
458// mTrustedPeerCertificates. Does not support certificate chains.
459ssl_verify_result_t RpcTransportCtxTls::sslCustomVerify(SSL* ssl, uint8_t* outAlert) {
460 LOG_ALWAYS_FATAL_IF(outAlert == nullptr);
461 const char* logPrefix = SSL_is_server(ssl) ? "Server" : "Client";
462
Yifan Hong180c2da2021-09-09 15:36:30 -0700463 auto ctx = SSL_get_SSL_CTX(ssl); // Does not set error queue
464 LOG_ALWAYS_FATAL_IF(ctx == nullptr);
465 // void* -> RpcTransportCtxTls*
466 auto rpcTransportCtxTls = reinterpret_cast<RpcTransportCtxTls*>(SSL_CTX_get_app_data(ctx));
467 LOG_ALWAYS_FATAL_IF(rpcTransportCtxTls == nullptr);
468
Yifan Hongb160f8c2021-09-17 22:59:11 -0700469 status_t verifyStatus = rpcTransportCtxTls->mCertVerifier->verify(ssl, outAlert);
Yifan Hong180c2da2021-09-09 15:36:30 -0700470 if (verifyStatus == OK) {
471 return ssl_verify_ok;
472 }
473 LOG_TLS_DETAIL("%s: Failed to verify client: status = %s, alert = %s", logPrefix,
474 statusToString(verifyStatus).c_str(), SSL_alert_desc_string_long(*outAlert));
475 return ssl_verify_invalid;
476}
477
Yifan Hong1af48582021-08-16 17:13:30 -0700478// Common implementation for creating server and client contexts. The child class, |Impl|, is
479// provided as a template argument so that this function can initialize an |Impl| object.
480template <typename Impl, typename>
Yifan Hong180c2da2021-09-09 15:36:30 -0700481std::unique_ptr<RpcTransportCtxTls> RpcTransportCtxTls::create(
482 std::shared_ptr<RpcCertificateVerifier> verifier) {
Yifan Honge8212f22021-06-28 15:49:08 -0700483 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
484 TEST_AND_RETURN(nullptr, ctx != nullptr);
485
Yifan Honge8212f22021-06-28 15:49:08 -0700486 auto evp_pkey = makeKeyPairForSelfSignedCert();
487 TEST_AND_RETURN(nullptr, evp_pkey != nullptr);
488 auto cert = makeSelfSignedCert(evp_pkey.get(), kCertValidDays);
489 TEST_AND_RETURN(nullptr, cert != nullptr);
490 TEST_AND_RETURN(nullptr, SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get()));
491 TEST_AND_RETURN(nullptr, SSL_CTX_use_certificate(ctx.get(), cert.get()));
Yifan Honge8212f22021-06-28 15:49:08 -0700492
Yifan Hong180c2da2021-09-09 15:36:30 -0700493 // Enable two-way authentication by setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT on server.
494 // Client ignores SSL_VERIFY_FAIL_IF_NO_PEER_CERT flag.
495 SSL_CTX_set_custom_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
496 sslCustomVerify);
Yifan Honge8212f22021-06-28 15:49:08 -0700497
498 // Require at least TLS 1.3
499 TEST_AND_RETURN(nullptr, SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
500
501 if constexpr (SHOULD_LOG_TLS_DETAIL) { // NOLINT
502 SSL_CTX_set_info_callback(ctx.get(), sslDebugLog);
503 }
504
Yifan Hong1af48582021-08-16 17:13:30 -0700505 auto ret = std::make_unique<Impl>();
Yifan Hong180c2da2021-09-09 15:36:30 -0700506 // RpcTransportCtxTls* -> void*
507 TEST_AND_RETURN(nullptr, SSL_CTX_set_app_data(ctx.get(), reinterpret_cast<void*>(ret.get())));
Yifan Hong1af48582021-08-16 17:13:30 -0700508 ret->mCtx = std::move(ctx);
Yifan Hong180c2da2021-09-09 15:36:30 -0700509 ret->mCertVerifier = std::move(verifier);
Yifan Hong1af48582021-08-16 17:13:30 -0700510 return ret;
Yifan Honge8212f22021-06-28 15:49:08 -0700511}
512
Yifan Hong1af48582021-08-16 17:13:30 -0700513std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
514 FdTrigger* fdTrigger) const {
Yifan Honge8212f22021-06-28 15:49:08 -0700515 bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
516 TEST_AND_RETURN(nullptr, ssl != nullptr);
517 Ssl wrapped(std::move(ssl));
518
Yifan Hong1af48582021-08-16 17:13:30 -0700519 preHandshake(&wrapped);
520 TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
521 return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
Yifan Honge8212f22021-06-28 15:49:08 -0700522}
523
Yifan Hong1af48582021-08-16 17:13:30 -0700524class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
525protected:
526 void preHandshake(Ssl* ssl) const override {
527 ssl->call(SSL_set_accept_state).errorQueue.clear();
528 }
529};
530
531class RpcTransportCtxTlsClient : public RpcTransportCtxTls {
532protected:
533 void preHandshake(Ssl* ssl) const override {
534 ssl->call(SSL_set_connect_state).errorQueue.clear();
535 }
536};
537
Yifan Honge8212f22021-06-28 15:49:08 -0700538} // namespace
539
540std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newServerCtx() const {
Yifan Hong180c2da2021-09-09 15:36:30 -0700541 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsServer>(mCertVerifier);
Yifan Honge8212f22021-06-28 15:49:08 -0700542}
543
544std::unique_ptr<RpcTransportCtx> RpcTransportCtxFactoryTls::newClientCtx() const {
Yifan Hong180c2da2021-09-09 15:36:30 -0700545 return android::RpcTransportCtxTls::create<RpcTransportCtxTlsClient>(mCertVerifier);
Yifan Honge8212f22021-06-28 15:49:08 -0700546}
547
548const char* RpcTransportCtxFactoryTls::toCString() const {
549 return "tls";
550}
551
Yifan Hong13c90062021-09-09 14:59:53 -0700552std::unique_ptr<RpcTransportCtxFactory> RpcTransportCtxFactoryTls::make(
553 std::shared_ptr<RpcCertificateVerifier> verifier) {
554 if (verifier == nullptr) {
555 ALOGE("%s: Must provide a certificate verifier", __PRETTY_FUNCTION__);
556 return nullptr;
557 }
558 return std::unique_ptr<RpcTransportCtxFactoryTls>(
559 new RpcTransportCtxFactoryTls(std::move(verifier)));
Yifan Honge8212f22021-06-28 15:49:08 -0700560}
561
562} // namespace android