3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/tsi/ssl_transport_security.h"
26 /* TODO(jboeuf): refactor inet_ntop into a portability header. */
27 /* Note: for whomever reads this and tries to refactor this, this
28 can't be in grpc, it has to be in gpr. */
32 #include <arpa/inet.h>
33 #include <sys/socket.h>
38 #include <grpc/grpc_security.h>
39 #include <grpc/support/alloc.h>
40 #include <grpc/support/log.h>
41 #include <grpc/support/string_util.h>
42 #include <grpc/support/sync.h>
43 #include <grpc/support/thd_id.h>
45 #include "absl/strings/match.h"
46 #include "absl/strings/string_view.h"
49 #include <openssl/bio.h>
50 #include <openssl/crypto.h> /* For OPENSSL_free */
51 #include <openssl/engine.h>
52 #include <openssl/err.h>
53 #include <openssl/ssl.h>
54 #include <openssl/tls1.h>
55 #include <openssl/x509.h>
56 #include <openssl/x509v3.h>
59 #include "src/core/lib/gpr/useful.h"
60 #include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
61 #include "src/core/tsi/ssl_types.h"
62 #include "src/core/tsi/transport_security.h"
64 /* --- Constants. ---*/
66 #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384
67 #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024
68 #define TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 1024
70 /* Putting a macro like this and littering the source file with #if is really
72 TODO(jboeuf): refactor all the #if / #endif in a separate module. */
73 #ifndef TSI_OPENSSL_ALPN_SUPPORT
74 #define TSI_OPENSSL_ALPN_SUPPORT 1
77 /* TODO(jboeuf): I have not found a way to get this number dynamically from the
78 SSL structure. This is what we would ultimately want though... */
79 #define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
81 /* --- Structure definitions. ---*/
83 struct tsi_ssl_root_certs_store {
87 struct tsi_ssl_handshaker_factory {
88 const tsi_ssl_handshaker_factory_vtable* vtable;
89 gpr_refcount refcount;
92 struct tsi_ssl_client_handshaker_factory {
93 tsi_ssl_handshaker_factory base;
95 unsigned char* alpn_protocol_list;
96 size_t alpn_protocol_list_length;
97 grpc_core::RefCountedPtr<tsi::SslSessionLRUCache> session_cache;
100 struct tsi_ssl_server_handshaker_factory {
101 /* Several contexts to support SNI.
102 The tsi_peer array contains the subject names of the server certificates
103 associated with the contexts at the same index. */
104 tsi_ssl_handshaker_factory base;
105 SSL_CTX** ssl_contexts;
106 tsi_peer* ssl_context_x509_subject_names;
107 size_t ssl_context_count;
108 unsigned char* alpn_protocol_list;
109 size_t alpn_protocol_list_length;
112 struct tsi_ssl_handshaker {
117 unsigned char* outgoing_bytes_buffer;
118 size_t outgoing_bytes_buffer_size;
119 tsi_ssl_handshaker_factory* factory_ref;
121 struct tsi_ssl_handshaker_result {
122 tsi_handshaker_result base;
125 unsigned char* unused_bytes;
126 size_t unused_bytes_size;
128 struct tsi_ssl_frame_protector {
129 tsi_frame_protector base;
132 unsigned char* buffer;
134 size_t buffer_offset;
136 /* --- Library Initialization. ---*/
138 static gpr_once g_init_openssl_once = GPR_ONCE_INIT;
139 static int g_ssl_ctx_ex_factory_index = -1;
140 static const unsigned char kSslSessionIdContext[] = {'g', 'r', 'p', 'c'};
141 #ifndef OPENSSL_IS_BORINGSSL
142 static const char kSslEnginePrefix[] = "engine:";
145 #if OPENSSL_VERSION_NUMBER < 0x10100000
146 static gpr_mu* g_openssl_mutexes = nullptr;
147 static void openssl_locking_cb(int mode, int type, const char* file,
148 int line) GRPC_UNUSED;
149 static unsigned long openssl_thread_id_cb(void) GRPC_UNUSED;
151 static void openssl_locking_cb(int mode, int type, const char* file, int line) {
152 if (mode & CRYPTO_LOCK) {
153 gpr_mu_lock(&g_openssl_mutexes[type]);
155 gpr_mu_unlock(&g_openssl_mutexes[type]);
159 static unsigned long openssl_thread_id_cb(void) {
160 return static_cast<unsigned long>(gpr_thd_currentid());
164 static void init_openssl(void) {
165 #if OPENSSL_VERSION_NUMBER >= 0x10100000
166 OPENSSL_init_ssl(0, nullptr);
169 SSL_load_error_strings();
170 OpenSSL_add_all_algorithms();
172 #if OPENSSL_VERSION_NUMBER < 0x10100000
173 if (!CRYPTO_get_locking_callback()) {
174 int num_locks = CRYPTO_num_locks();
175 GPR_ASSERT(num_locks > 0);
176 g_openssl_mutexes = static_cast<gpr_mu*>(
177 gpr_malloc(static_cast<size_t>(num_locks) * sizeof(gpr_mu)));
178 for (int i = 0; i < num_locks; i++) {
179 gpr_mu_init(&g_openssl_mutexes[i]);
181 CRYPTO_set_locking_callback(openssl_locking_cb);
182 CRYPTO_set_id_callback(openssl_thread_id_cb);
184 gpr_log(GPR_INFO, "OpenSSL callback has already been set.");
187 g_ssl_ctx_ex_factory_index =
188 SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
189 GPR_ASSERT(g_ssl_ctx_ex_factory_index != -1);
192 /* --- Ssl utils. ---*/
194 static const char* ssl_error_string(int error) {
197 return "SSL_ERROR_NONE";
198 case SSL_ERROR_ZERO_RETURN:
199 return "SSL_ERROR_ZERO_RETURN";
200 case SSL_ERROR_WANT_READ:
201 return "SSL_ERROR_WANT_READ";
202 case SSL_ERROR_WANT_WRITE:
203 return "SSL_ERROR_WANT_WRITE";
204 case SSL_ERROR_WANT_CONNECT:
205 return "SSL_ERROR_WANT_CONNECT";
206 case SSL_ERROR_WANT_ACCEPT:
207 return "SSL_ERROR_WANT_ACCEPT";
208 case SSL_ERROR_WANT_X509_LOOKUP:
209 return "SSL_ERROR_WANT_X509_LOOKUP";
210 case SSL_ERROR_SYSCALL:
211 return "SSL_ERROR_SYSCALL";
213 return "SSL_ERROR_SSL";
215 return "Unknown error";
219 /* TODO(jboeuf): Remove when we are past the debugging phase with this code. */
220 static void ssl_log_where_info(const SSL* ssl, int where, int flag,
222 if ((where & flag) && GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
223 gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
224 SSL_state_string_long(ssl), SSL_state_string(ssl));
228 /* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */
229 static void ssl_info_callback(const SSL* ssl, int where, int ret) {
231 gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n");
235 ssl_log_where_info(ssl, where, SSL_CB_LOOP, "LOOP");
236 ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START, "HANDSHAKE START");
237 ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE, "HANDSHAKE DONE");
240 /* Returns 1 if name looks like an IP address, 0 otherwise.
241 This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */
242 static int looks_like_ip_address(absl::string_view name) {
243 size_t dot_count = 0;
245 for (size_t i = 0; i < name.size(); ++i) {
246 if (name[i] == ':') {
247 /* IPv6 Address in hexadecimal form, : is not allowed in DNS names. */
250 if (name[i] >= '0' && name[i] <= '9') {
251 if (num_size > 3) return 0;
253 } else if (name[i] == '.') {
254 if (dot_count > 3 || num_size == 0) return 0;
261 if (dot_count < 3 || num_size == 0) return 0;
265 /* Gets the subject CN from an X509 cert. */
266 static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
268 int common_name_index = -1;
269 X509_NAME_ENTRY* common_name_entry = nullptr;
270 ASN1_STRING* common_name_asn1 = nullptr;
271 X509_NAME* subject_name = X509_get_subject_name(cert);
272 int utf8_returned_size = 0;
273 if (subject_name == nullptr) {
274 gpr_log(GPR_INFO, "Could not get subject name from certificate.");
275 return TSI_NOT_FOUND;
278 X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
279 if (common_name_index == -1) {
280 gpr_log(GPR_INFO, "Could not get common name of subject from certificate.");
281 return TSI_NOT_FOUND;
283 common_name_entry = X509_NAME_get_entry(subject_name, common_name_index);
284 if (common_name_entry == nullptr) {
285 gpr_log(GPR_ERROR, "Could not get common name entry from certificate.");
286 return TSI_INTERNAL_ERROR;
288 common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
289 if (common_name_asn1 == nullptr) {
291 "Could not get common name entry asn1 from certificate.");
292 return TSI_INTERNAL_ERROR;
294 utf8_returned_size = ASN1_STRING_to_UTF8(utf8, common_name_asn1);
295 if (utf8_returned_size < 0) {
296 gpr_log(GPR_ERROR, "Could not extract utf8 from asn1 string.");
297 return TSI_OUT_OF_RESOURCES;
299 *utf8_size = static_cast<size_t>(utf8_returned_size);
303 /* Gets the subject CN of an X509 cert as a tsi_peer_property. */
304 static tsi_result peer_property_from_x509_common_name(
305 X509* cert, tsi_peer_property* property) {
306 unsigned char* common_name;
307 size_t common_name_size;
309 ssl_get_x509_common_name(cert, &common_name, &common_name_size);
310 if (result != TSI_OK) {
311 if (result == TSI_NOT_FOUND) {
312 common_name = nullptr;
313 common_name_size = 0;
318 result = tsi_construct_string_peer_property(
319 TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY,
320 common_name == nullptr ? "" : reinterpret_cast<const char*>(common_name),
321 common_name_size, property);
322 OPENSSL_free(common_name);
326 /* Gets the X509 cert in PEM format as a tsi_peer_property. */
327 static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) {
328 BIO* bio = BIO_new(BIO_s_mem());
329 if (!PEM_write_bio_X509(bio, cert)) {
331 return TSI_INTERNAL_ERROR;
334 long len = BIO_get_mem_data(bio, &contents);
337 return TSI_INTERNAL_ERROR;
339 tsi_result result = tsi_construct_string_peer_property(
340 TSI_X509_PEM_CERT_PROPERTY, (const char*)contents,
341 static_cast<size_t>(len), property);
346 /* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
347 static tsi_result add_subject_alt_names_properties_to_peer(
348 tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
349 size_t subject_alt_name_count, int* current_insert_index) {
351 tsi_result result = TSI_OK;
353 for (i = 0; i < subject_alt_name_count; i++) {
354 GENERAL_NAME* subject_alt_name =
355 sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
356 if (subject_alt_name->type == GEN_DNS ||
357 subject_alt_name->type == GEN_EMAIL ||
358 subject_alt_name->type == GEN_URI) {
359 unsigned char* name = nullptr;
361 if (subject_alt_name->type == GEN_DNS) {
362 name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
363 } else if (subject_alt_name->type == GEN_EMAIL) {
364 name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.rfc822Name);
366 name_size = ASN1_STRING_to_UTF8(
367 &name, subject_alt_name->d.uniformResourceIdentifier);
370 gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
371 result = TSI_INTERNAL_ERROR;
374 result = tsi_construct_string_peer_property(
375 TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
376 reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
377 &peer->properties[(*current_insert_index)++]);
378 if (result != TSI_OK) {
382 if (subject_alt_name->type == GEN_URI) {
383 result = tsi_construct_string_peer_property(
384 TSI_X509_URI_PEER_PROPERTY, reinterpret_cast<const char*>(name),
385 static_cast<size_t>(name_size),
386 &peer->properties[(*current_insert_index)++]);
389 } else if (subject_alt_name->type == GEN_IPADD) {
390 char ntop_buf[INET6_ADDRSTRLEN];
393 if (subject_alt_name->d.iPAddress->length == 4) {
395 } else if (subject_alt_name->d.iPAddress->length == 16) {
398 gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
399 result = TSI_INTERNAL_ERROR;
402 const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
403 ntop_buf, INET6_ADDRSTRLEN);
404 if (name == nullptr) {
405 gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
406 result = TSI_INTERNAL_ERROR;
410 result = tsi_construct_string_peer_property_from_cstring(
411 TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
412 &peer->properties[(*current_insert_index)++]);
414 if (result != TSI_OK) break;
419 /* Gets information about the peer's X509 cert as a tsi_peer object. */
420 static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
422 /* TODO(jboeuf): Maybe add more properties. */
423 GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
424 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
425 int subject_alt_name_count =
426 (subject_alt_names != nullptr)
427 ? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
429 size_t property_count;
431 GPR_ASSERT(subject_alt_name_count >= 0);
432 property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
433 2 /* common name, certificate */ +
434 static_cast<size_t>(subject_alt_name_count);
435 for (int i = 0; i < subject_alt_name_count; i++) {
436 GENERAL_NAME* subject_alt_name =
437 sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
438 if (subject_alt_name->type == GEN_URI) {
442 result = tsi_construct_peer(property_count, peer);
443 if (result != TSI_OK) return result;
444 int current_insert_index = 0;
446 if (include_certificate_type) {
447 result = tsi_construct_string_peer_property_from_cstring(
448 TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
449 &peer->properties[current_insert_index++]);
450 if (result != TSI_OK) break;
452 result = peer_property_from_x509_common_name(
453 cert, &peer->properties[current_insert_index++]);
454 if (result != TSI_OK) break;
457 add_pem_certificate(cert, &peer->properties[current_insert_index++]);
458 if (result != TSI_OK) break;
460 if (subject_alt_name_count != 0) {
461 result = add_subject_alt_names_properties_to_peer(
462 peer, subject_alt_names, static_cast<size_t>(subject_alt_name_count),
463 ¤t_insert_index);
464 if (result != TSI_OK) break;
468 if (subject_alt_names != nullptr) {
469 sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
471 if (result != TSI_OK) tsi_peer_destruct(peer);
473 GPR_ASSERT((int)peer->property_count == current_insert_index);
477 /* Logs the SSL error stack. */
478 static void log_ssl_error_stack(void) {
480 while ((err = ERR_get_error()) != 0) {
482 ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
483 gpr_log(GPR_ERROR, "%s", details);
487 /* Performs an SSL_read and handle errors. */
488 static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
489 size_t* unprotected_bytes_size) {
491 GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
492 read_from_ssl = SSL_read(ssl, unprotected_bytes,
493 static_cast<int>(*unprotected_bytes_size));
494 if (read_from_ssl <= 0) {
495 read_from_ssl = SSL_get_error(ssl, read_from_ssl);
496 switch (read_from_ssl) {
497 case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
498 case SSL_ERROR_WANT_READ: /* We need more data to finish the frame. */
499 *unprotected_bytes_size = 0;
501 case SSL_ERROR_WANT_WRITE:
504 "Peer tried to renegotiate SSL connection. This is unsupported.");
505 return TSI_UNIMPLEMENTED;
507 gpr_log(GPR_ERROR, "Corruption detected.");
508 log_ssl_error_stack();
509 return TSI_DATA_CORRUPTED;
511 gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
512 ssl_error_string(read_from_ssl));
513 return TSI_PROTOCOL_FAILURE;
516 *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
520 /* Performs an SSL_write and handle errors. */
521 static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
522 size_t unprotected_bytes_size) {
523 int ssl_write_result;
524 GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
525 ssl_write_result = SSL_write(ssl, unprotected_bytes,
526 static_cast<int>(unprotected_bytes_size));
527 if (ssl_write_result < 0) {
528 ssl_write_result = SSL_get_error(ssl, ssl_write_result);
529 if (ssl_write_result == SSL_ERROR_WANT_READ) {
531 "Peer tried to renegotiate SSL connection. This is unsupported.");
532 return TSI_UNIMPLEMENTED;
534 gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
535 ssl_error_string(ssl_write_result));
536 return TSI_INTERNAL_ERROR;
542 /* Loads an in-memory PEM certificate chain into the SSL context. */
543 static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
544 const char* pem_cert_chain,
545 size_t pem_cert_chain_size) {
546 tsi_result result = TSI_OK;
547 X509* certificate = nullptr;
549 GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
550 pem = BIO_new_mem_buf((void*)pem_cert_chain,
551 static_cast<int>(pem_cert_chain_size));
552 if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
555 certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
556 if (certificate == nullptr) {
557 result = TSI_INVALID_ARGUMENT;
560 if (!SSL_CTX_use_certificate(context, certificate)) {
561 result = TSI_INVALID_ARGUMENT;
565 X509* certificate_authority =
566 PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
567 if (certificate_authority == nullptr) {
569 break; /* Done reading. */
571 if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
572 X509_free(certificate_authority);
573 result = TSI_INVALID_ARGUMENT;
576 /* We don't need to free certificate_authority as its ownership has been
577 transferred to the context. That is not the case for certificate
583 if (certificate != nullptr) X509_free(certificate);
588 #ifndef OPENSSL_IS_BORINGSSL
589 static tsi_result ssl_ctx_use_engine_private_key(SSL_CTX* context,
591 size_t pem_key_size) {
592 tsi_result result = TSI_OK;
593 EVP_PKEY* private_key = nullptr;
594 ENGINE* engine = nullptr;
595 char* engine_name = nullptr;
596 // Parse key which is in following format engine:<engine_id>:<key_id>
598 char* engine_start = (char*)pem_key + strlen(kSslEnginePrefix);
599 char* engine_end = (char*)strchr(engine_start, ':');
600 if (engine_end == nullptr) {
601 result = TSI_INVALID_ARGUMENT;
604 char* key_id = engine_end + 1;
605 int engine_name_length = engine_end - engine_start;
606 if (engine_name_length == 0) {
607 result = TSI_INVALID_ARGUMENT;
610 engine_name = static_cast<char*>(gpr_zalloc(engine_name_length + 1));
611 memcpy(engine_name, engine_start, engine_name_length);
612 gpr_log(GPR_DEBUG, "ENGINE key: %s", engine_name);
613 ENGINE_load_dynamic();
614 engine = ENGINE_by_id(engine_name);
615 if (engine == nullptr) {
616 // If not available at ENGINE_DIR, use dynamic to load from
617 // current working directory.
618 engine = ENGINE_by_id("dynamic");
619 if (engine == nullptr) {
620 gpr_log(GPR_ERROR, "Cannot load dynamic engine");
621 result = TSI_INVALID_ARGUMENT;
624 if (!ENGINE_ctrl_cmd_string(engine, "ID", engine_name, 0) ||
625 !ENGINE_ctrl_cmd_string(engine, "DIR_LOAD", "2", 0) ||
626 !ENGINE_ctrl_cmd_string(engine, "DIR_ADD", ".", 0) ||
627 !ENGINE_ctrl_cmd_string(engine, "LIST_ADD", "1", 0) ||
628 !ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0)) {
629 gpr_log(GPR_ERROR, "Cannot find engine");
630 result = TSI_INVALID_ARGUMENT;
634 if (!ENGINE_set_default(engine, ENGINE_METHOD_ALL)) {
635 gpr_log(GPR_ERROR, "ENGINE_set_default with ENGINE_METHOD_ALL failed");
636 result = TSI_INVALID_ARGUMENT;
639 if (!ENGINE_init(engine)) {
640 gpr_log(GPR_ERROR, "ENGINE_init failed");
641 result = TSI_INVALID_ARGUMENT;
644 private_key = ENGINE_load_private_key(engine, key_id, 0, 0);
645 if (private_key == nullptr) {
646 gpr_log(GPR_ERROR, "ENGINE_load_private_key failed");
647 result = TSI_INVALID_ARGUMENT;
650 if (!SSL_CTX_use_PrivateKey(context, private_key)) {
651 gpr_log(GPR_ERROR, "SSL_CTX_use_PrivateKey failed");
652 result = TSI_INVALID_ARGUMENT;
656 if (engine != nullptr) ENGINE_free(engine);
657 if (private_key != nullptr) EVP_PKEY_free(private_key);
658 if (engine_name != nullptr) gpr_free(engine_name);
661 #endif /* OPENSSL_IS_BORINGSSL */
663 static tsi_result ssl_ctx_use_pem_private_key(SSL_CTX* context,
665 size_t pem_key_size) {
666 tsi_result result = TSI_OK;
667 EVP_PKEY* private_key = nullptr;
669 GPR_ASSERT(pem_key_size <= INT_MAX);
670 pem = BIO_new_mem_buf((void*)pem_key, static_cast<int>(pem_key_size));
671 if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
673 private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
674 if (private_key == nullptr) {
675 result = TSI_INVALID_ARGUMENT;
678 if (!SSL_CTX_use_PrivateKey(context, private_key)) {
679 result = TSI_INVALID_ARGUMENT;
683 if (private_key != nullptr) EVP_PKEY_free(private_key);
688 /* Loads an in-memory PEM private key into the SSL context. */
689 static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
690 size_t pem_key_size) {
691 // BoringSSL does not have ENGINE support
692 #ifndef OPENSSL_IS_BORINGSSL
693 if (strncmp(pem_key, kSslEnginePrefix, strlen(kSslEnginePrefix)) == 0) {
694 return ssl_ctx_use_engine_private_key(context, pem_key, pem_key_size);
696 #endif /* OPENSSL_IS_BORINGSSL */
698 return ssl_ctx_use_pem_private_key(context, pem_key, pem_key_size);
702 /* Loads in-memory PEM verification certs into the SSL context and optionally
703 returns the verification cert names (root_names can be NULL). */
704 static tsi_result x509_store_load_certs(X509_STORE* cert_store,
705 const char* pem_roots,
706 size_t pem_roots_size,
707 STACK_OF(X509_NAME) * *root_names) {
708 tsi_result result = TSI_OK;
709 size_t num_roots = 0;
710 X509* root = nullptr;
711 X509_NAME* root_name = nullptr;
713 GPR_ASSERT(pem_roots_size <= INT_MAX);
714 pem = BIO_new_mem_buf((void*)pem_roots, static_cast<int>(pem_roots_size));
715 if (cert_store == nullptr) return TSI_INVALID_ARGUMENT;
716 if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
717 if (root_names != nullptr) {
718 *root_names = sk_X509_NAME_new_null();
719 if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
723 root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
724 if (root == nullptr) {
726 break; /* We're at the end of stream. */
728 if (root_names != nullptr) {
729 root_name = X509_get_subject_name(root);
730 if (root_name == nullptr) {
731 gpr_log(GPR_ERROR, "Could not get name from root certificate.");
732 result = TSI_INVALID_ARGUMENT;
735 root_name = X509_NAME_dup(root_name);
736 if (root_name == nullptr) {
737 result = TSI_OUT_OF_RESOURCES;
740 sk_X509_NAME_push(*root_names, root_name);
744 if (!X509_STORE_add_cert(cert_store, root)) {
745 unsigned long error = ERR_get_error();
746 if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
747 ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
748 gpr_log(GPR_ERROR, "Could not add root certificate to ssl context.");
749 result = TSI_INTERNAL_ERROR;
756 if (num_roots == 0) {
757 gpr_log(GPR_ERROR, "Could not load any root certificate.");
758 result = TSI_INVALID_ARGUMENT;
761 if (result != TSI_OK) {
762 if (root != nullptr) X509_free(root);
763 if (root_names != nullptr) {
764 sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
765 *root_names = nullptr;
766 if (root_name != nullptr) X509_NAME_free(root_name);
773 static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
774 const char* pem_roots,
775 size_t pem_roots_size,
776 STACK_OF(X509_NAME) *
778 X509_STORE* cert_store = SSL_CTX_get_cert_store(context);
779 X509_STORE_set_flags(cert_store,
780 X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST);
781 return x509_store_load_certs(cert_store, pem_roots, pem_roots_size,
785 /* Populates the SSL context with a private key and a cert chain, and sets the
786 cipher list and the ephemeral ECDH key. */
787 static tsi_result populate_ssl_context(
788 SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
789 const char* cipher_list) {
790 tsi_result result = TSI_OK;
791 if (key_cert_pair != nullptr) {
792 if (key_cert_pair->cert_chain != nullptr) {
793 result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
794 strlen(key_cert_pair->cert_chain));
795 if (result != TSI_OK) {
796 gpr_log(GPR_ERROR, "Invalid cert chain file.");
800 if (key_cert_pair->private_key != nullptr) {
801 result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
802 strlen(key_cert_pair->private_key));
803 if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
804 gpr_log(GPR_ERROR, "Invalid private key.");
805 return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
809 if ((cipher_list != nullptr) &&
810 !SSL_CTX_set_cipher_list(context, cipher_list)) {
811 gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
812 return TSI_INVALID_ARGUMENT;
815 EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
816 if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
817 gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
819 return TSI_INTERNAL_ERROR;
821 SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
827 /* Extracts the CN and the SANs from an X509 cert as a peer object. */
828 tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
829 const char* pem_cert, tsi_peer* peer) {
830 tsi_result result = TSI_OK;
831 X509* cert = nullptr;
833 pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
834 if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
836 cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
837 if (cert == nullptr) {
838 gpr_log(GPR_ERROR, "Invalid certificate");
839 result = TSI_INVALID_ARGUMENT;
841 result = peer_from_x509(cert, 0, peer);
843 if (cert != nullptr) X509_free(cert);
848 /* Builds the alpn protocol name list according to rfc 7301. */
849 static tsi_result build_alpn_protocol_name_list(
850 const char** alpn_protocols, uint16_t num_alpn_protocols,
851 unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
853 unsigned char* current;
854 *protocol_name_list = nullptr;
855 *protocol_name_list_length = 0;
856 if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
857 for (i = 0; i < num_alpn_protocols; i++) {
859 alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
860 if (length == 0 || length > 255) {
861 gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
862 static_cast<int>(length));
863 return TSI_INVALID_ARGUMENT;
865 *protocol_name_list_length += length + 1;
867 *protocol_name_list =
868 static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
869 if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
870 current = *protocol_name_list;
871 for (i = 0; i < num_alpn_protocols; i++) {
872 size_t length = strlen(alpn_protocols[i]);
873 *(current++) = static_cast<uint8_t>(length); /* max checked above. */
874 memcpy(current, alpn_protocols[i], length);
878 if ((current < *protocol_name_list) ||
879 (static_cast<uintptr_t>(current - *protocol_name_list) !=
880 *protocol_name_list_length)) {
881 return TSI_INTERNAL_ERROR;
886 // The verification callback is used for clients that don't really care about
887 // the server's certificate, but we need to pull it anyway, in case a higher
888 // layer wants to look at it. In this case the verification may fail, but
889 // we don't really care.
890 static int NullVerifyCallback(int /*preverify_ok*/, X509_STORE_CTX* /*ctx*/) {
894 // Sets the min and max TLS version of |ssl_context| to |min_tls_version| and
895 // |max_tls_version|, respectively. Calling this method is a no-op when using
896 // OpenSSL versions < 1.1.
897 static tsi_result tsi_set_min_and_max_tls_versions(
898 SSL_CTX* ssl_context, tsi_tls_version min_tls_version,
899 tsi_tls_version max_tls_version) {
900 if (ssl_context == nullptr) {
902 "Invalid nullptr argument to |tsi_set_min_and_max_tls_versions|.");
903 return TSI_INVALID_ARGUMENT;
905 #if OPENSSL_VERSION_NUMBER >= 0x10100000
906 // Set the min TLS version of the SSL context.
907 switch (min_tls_version) {
908 case tsi_tls_version::TSI_TLS1_2:
909 SSL_CTX_set_min_proto_version(ssl_context, TLS1_2_VERSION);
911 #if defined(TLS1_3_VERSION)
912 case tsi_tls_version::TSI_TLS1_3:
913 SSL_CTX_set_min_proto_version(ssl_context, TLS1_3_VERSION);
917 gpr_log(GPR_INFO, "TLS version is not supported.");
918 return TSI_FAILED_PRECONDITION;
920 // Set the max TLS version of the SSL context.
921 switch (max_tls_version) {
922 case tsi_tls_version::TSI_TLS1_2:
923 SSL_CTX_set_max_proto_version(ssl_context, TLS1_2_VERSION);
925 #if defined(TLS1_3_VERSION)
926 case tsi_tls_version::TSI_TLS1_3:
927 SSL_CTX_set_max_proto_version(ssl_context, TLS1_3_VERSION);
931 gpr_log(GPR_INFO, "TLS version is not supported.");
932 return TSI_FAILED_PRECONDITION;
938 /* --- tsi_ssl_root_certs_store methods implementation. ---*/
940 tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
941 const char* pem_roots) {
942 if (pem_roots == nullptr) {
943 gpr_log(GPR_ERROR, "The root certificates are empty.");
946 tsi_ssl_root_certs_store* root_store = static_cast<tsi_ssl_root_certs_store*>(
947 gpr_zalloc(sizeof(tsi_ssl_root_certs_store)));
948 if (root_store == nullptr) {
949 gpr_log(GPR_ERROR, "Could not allocate buffer for ssl_root_certs_store.");
952 root_store->store = X509_STORE_new();
953 if (root_store->store == nullptr) {
954 gpr_log(GPR_ERROR, "Could not allocate buffer for X509_STORE.");
955 gpr_free(root_store);
958 tsi_result result = x509_store_load_certs(root_store->store, pem_roots,
959 strlen(pem_roots), nullptr);
960 if (result != TSI_OK) {
961 gpr_log(GPR_ERROR, "Could not load root certificates.");
962 X509_STORE_free(root_store->store);
963 gpr_free(root_store);
969 void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self) {
970 if (self == nullptr) return;
971 X509_STORE_free(self->store);
975 /* --- tsi_ssl_session_cache methods implementation. ---*/
977 tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity) {
978 /* Pointer will be dereferenced by unref call. */
979 return reinterpret_cast<tsi_ssl_session_cache*>(
980 tsi::SslSessionLRUCache::Create(capacity).release());
983 void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache) {
984 /* Pointer will be dereferenced by unref call. */
985 reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Ref().release();
988 void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
989 reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
992 /* --- tsi_frame_protector methods implementation. ---*/
994 static tsi_result ssl_protector_protect(tsi_frame_protector* self,
995 const unsigned char* unprotected_bytes,
996 size_t* unprotected_bytes_size,
997 unsigned char* protected_output_frames,
998 size_t* protected_output_frames_size) {
999 tsi_ssl_frame_protector* impl =
1000 reinterpret_cast<tsi_ssl_frame_protector*>(self);
1003 tsi_result result = TSI_OK;
1005 /* First see if we have some pending data in the SSL BIO. */
1006 int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
1007 if (pending_in_ssl > 0) {
1008 *unprotected_bytes_size = 0;
1009 GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1010 read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1011 static_cast<int>(*protected_output_frames_size));
1012 if (read_from_ssl < 0) {
1014 "Could not read from BIO even though some data is pending");
1015 return TSI_INTERNAL_ERROR;
1017 *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1021 /* Now see if we can send a complete frame. */
1022 available = impl->buffer_size - impl->buffer_offset;
1023 if (available > *unprotected_bytes_size) {
1024 /* If we cannot, just copy the data in our internal buffer. */
1025 memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
1026 *unprotected_bytes_size);
1027 impl->buffer_offset += *unprotected_bytes_size;
1028 *protected_output_frames_size = 0;
1032 /* If we can, prepare the buffer, send it to SSL_write and read. */
1033 memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
1034 result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
1035 if (result != TSI_OK) return result;
1037 GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1038 read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1039 static_cast<int>(*protected_output_frames_size));
1040 if (read_from_ssl < 0) {
1041 gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
1042 return TSI_INTERNAL_ERROR;
1044 *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1045 *unprotected_bytes_size = available;
1046 impl->buffer_offset = 0;
1050 static tsi_result ssl_protector_protect_flush(
1051 tsi_frame_protector* self, unsigned char* protected_output_frames,
1052 size_t* protected_output_frames_size, size_t* still_pending_size) {
1053 tsi_result result = TSI_OK;
1054 tsi_ssl_frame_protector* impl =
1055 reinterpret_cast<tsi_ssl_frame_protector*>(self);
1056 int read_from_ssl = 0;
1059 if (impl->buffer_offset != 0) {
1060 result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
1061 if (result != TSI_OK) return result;
1062 impl->buffer_offset = 0;
1065 pending = static_cast<int>(BIO_pending(impl->network_io));
1066 GPR_ASSERT(pending >= 0);
1067 *still_pending_size = static_cast<size_t>(pending);
1068 if (*still_pending_size == 0) return TSI_OK;
1070 GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1071 read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1072 static_cast<int>(*protected_output_frames_size));
1073 if (read_from_ssl <= 0) {
1074 gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
1075 return TSI_INTERNAL_ERROR;
1077 *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1078 pending = static_cast<int>(BIO_pending(impl->network_io));
1079 GPR_ASSERT(pending >= 0);
1080 *still_pending_size = static_cast<size_t>(pending);
1084 static tsi_result ssl_protector_unprotect(
1085 tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
1086 size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
1087 size_t* unprotected_bytes_size) {
1088 tsi_result result = TSI_OK;
1089 int written_into_ssl = 0;
1090 size_t output_bytes_size = *unprotected_bytes_size;
1091 size_t output_bytes_offset = 0;
1092 tsi_ssl_frame_protector* impl =
1093 reinterpret_cast<tsi_ssl_frame_protector*>(self);
1095 /* First, try to read remaining data from ssl. */
1096 result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
1097 if (result != TSI_OK) return result;
1098 if (*unprotected_bytes_size == output_bytes_size) {
1099 /* We have read everything we could and cannot process any more input. */
1100 *protected_frames_bytes_size = 0;
1103 output_bytes_offset = *unprotected_bytes_size;
1104 unprotected_bytes += output_bytes_offset;
1105 *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
1107 /* Then, try to write some data to ssl. */
1108 GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
1109 written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
1110 static_cast<int>(*protected_frames_bytes_size));
1111 if (written_into_ssl < 0) {
1112 gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
1114 return TSI_INTERNAL_ERROR;
1116 *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
1118 /* Now try to read some data again. */
1119 result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
1120 if (result == TSI_OK) {
1121 /* Don't forget to output the total number of bytes read. */
1122 *unprotected_bytes_size += output_bytes_offset;
1127 static void ssl_protector_destroy(tsi_frame_protector* self) {
1128 tsi_ssl_frame_protector* impl =
1129 reinterpret_cast<tsi_ssl_frame_protector*>(self);
1130 if (impl->buffer != nullptr) gpr_free(impl->buffer);
1131 if (impl->ssl != nullptr) SSL_free(impl->ssl);
1132 if (impl->network_io != nullptr) BIO_free(impl->network_io);
1136 static const tsi_frame_protector_vtable frame_protector_vtable = {
1137 ssl_protector_protect,
1138 ssl_protector_protect_flush,
1139 ssl_protector_unprotect,
1140 ssl_protector_destroy,
1143 /* --- tsi_server_handshaker_factory methods implementation. --- */
1145 static void tsi_ssl_handshaker_factory_destroy(
1146 tsi_ssl_handshaker_factory* self) {
1147 if (self == nullptr) return;
1149 if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
1150 self->vtable->destroy(self);
1152 /* Note, we don't free(self) here because this object is always directly
1153 * embedded in another object. If tsi_ssl_handshaker_factory_init allocates
1154 * any memory, it should be free'd here. */
1157 static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
1158 tsi_ssl_handshaker_factory* self) {
1159 if (self == nullptr) return nullptr;
1160 gpr_refn(&self->refcount, 1);
1164 static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
1165 if (self == nullptr) return;
1167 if (gpr_unref(&self->refcount)) {
1168 tsi_ssl_handshaker_factory_destroy(self);
1172 static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
1174 /* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
1175 * allocating memory for the factory. */
1176 static void tsi_ssl_handshaker_factory_init(
1177 tsi_ssl_handshaker_factory* factory) {
1178 GPR_ASSERT(factory != nullptr);
1180 factory->vtable = &handshaker_factory_vtable;
1181 gpr_ref_init(&factory->refcount, 1);
1184 /* Gets the X509 cert chain in PEM format as a tsi_peer_property. */
1185 tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
1186 tsi_peer_property* property) {
1187 BIO* bio = BIO_new(BIO_s_mem());
1188 const auto peer_chain_len = sk_X509_num(peer_chain);
1189 for (auto i = decltype(peer_chain_len){0}; i < peer_chain_len; i++) {
1190 if (!PEM_write_bio_X509(bio, sk_X509_value(peer_chain, i))) {
1192 return TSI_INTERNAL_ERROR;
1196 long len = BIO_get_mem_data(bio, &contents);
1199 return TSI_INTERNAL_ERROR;
1201 tsi_result result = tsi_construct_string_peer_property(
1202 TSI_X509_PEM_CERT_CHAIN_PROPERTY, (const char*)contents,
1203 static_cast<size_t>(len), property);
1208 /* --- tsi_handshaker_result methods implementation. ---*/
1209 static tsi_result ssl_handshaker_result_extract_peer(
1210 const tsi_handshaker_result* self, tsi_peer* peer) {
1211 tsi_result result = TSI_OK;
1212 const unsigned char* alpn_selected = nullptr;
1213 unsigned int alpn_selected_len;
1214 const tsi_ssl_handshaker_result* impl =
1215 reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1216 X509* peer_cert = SSL_get_peer_certificate(impl->ssl);
1217 if (peer_cert != nullptr) {
1218 result = peer_from_x509(peer_cert, 1, peer);
1219 X509_free(peer_cert);
1220 if (result != TSI_OK) return result;
1222 #if TSI_OPENSSL_ALPN_SUPPORT
1223 SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
1224 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1225 if (alpn_selected == nullptr) {
1227 SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
1228 &alpn_selected_len);
1230 // When called on the client side, the stack also contains the
1231 // peer's certificate; When called on the server side,
1232 // the peer's certificate is not present in the stack
1233 STACK_OF(X509)* peer_chain = SSL_get_peer_cert_chain(impl->ssl);
1234 // 1 is for session reused property.
1235 size_t new_property_count = peer->property_count + 3;
1236 if (alpn_selected != nullptr) new_property_count++;
1237 if (peer_chain != nullptr) new_property_count++;
1238 tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
1239 gpr_zalloc(sizeof(*new_properties) * new_property_count));
1240 for (size_t i = 0; i < peer->property_count; i++) {
1241 new_properties[i] = peer->properties[i];
1243 if (peer->properties != nullptr) gpr_free(peer->properties);
1244 peer->properties = new_properties;
1245 // Add peer chain if available
1246 if (peer_chain != nullptr) {
1247 result = tsi_ssl_get_cert_chain_contents(
1248 peer_chain, &peer->properties[peer->property_count]);
1249 if (result == TSI_OK) peer->property_count++;
1251 if (alpn_selected != nullptr) {
1252 result = tsi_construct_string_peer_property(
1253 TSI_SSL_ALPN_SELECTED_PROTOCOL,
1254 reinterpret_cast<const char*>(alpn_selected), alpn_selected_len,
1255 &peer->properties[peer->property_count]);
1256 if (result != TSI_OK) return result;
1257 peer->property_count++;
1259 // Add security_level peer property.
1260 result = tsi_construct_string_peer_property_from_cstring(
1261 TSI_SECURITY_LEVEL_PEER_PROPERTY,
1262 tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY),
1263 &peer->properties[peer->property_count]);
1264 if (result != TSI_OK) return result;
1265 peer->property_count++;
1267 const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false";
1268 result = tsi_construct_string_peer_property_from_cstring(
1269 TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused,
1270 &peer->properties[peer->property_count]);
1271 if (result != TSI_OK) return result;
1272 peer->property_count++;
1276 static tsi_result ssl_handshaker_result_create_frame_protector(
1277 const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
1278 tsi_frame_protector** protector) {
1279 size_t actual_max_output_protected_frame_size =
1280 TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1281 tsi_ssl_handshaker_result* impl =
1282 reinterpret_cast<tsi_ssl_handshaker_result*>(
1283 const_cast<tsi_handshaker_result*>(self));
1284 tsi_ssl_frame_protector* protector_impl =
1285 static_cast<tsi_ssl_frame_protector*>(
1286 gpr_zalloc(sizeof(*protector_impl)));
1288 if (max_output_protected_frame_size != nullptr) {
1289 if (*max_output_protected_frame_size >
1290 TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) {
1291 *max_output_protected_frame_size =
1292 TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1293 } else if (*max_output_protected_frame_size <
1294 TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND) {
1295 *max_output_protected_frame_size =
1296 TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND;
1298 actual_max_output_protected_frame_size = *max_output_protected_frame_size;
1300 protector_impl->buffer_size =
1301 actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD;
1302 protector_impl->buffer =
1303 static_cast<unsigned char*>(gpr_malloc(protector_impl->buffer_size));
1304 if (protector_impl->buffer == nullptr) {
1306 "Could not allocated buffer for tsi_ssl_frame_protector.");
1307 gpr_free(protector_impl);
1308 return TSI_INTERNAL_ERROR;
1311 /* Transfer ownership of ssl and network_io to the frame protector. */
1312 protector_impl->ssl = impl->ssl;
1313 impl->ssl = nullptr;
1314 protector_impl->network_io = impl->network_io;
1315 impl->network_io = nullptr;
1316 protector_impl->base.vtable = &frame_protector_vtable;
1317 *protector = &protector_impl->base;
1321 static tsi_result ssl_handshaker_result_get_unused_bytes(
1322 const tsi_handshaker_result* self, const unsigned char** bytes,
1323 size_t* bytes_size) {
1324 const tsi_ssl_handshaker_result* impl =
1325 reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1326 *bytes_size = impl->unused_bytes_size;
1327 *bytes = impl->unused_bytes;
1331 static void ssl_handshaker_result_destroy(tsi_handshaker_result* self) {
1332 tsi_ssl_handshaker_result* impl =
1333 reinterpret_cast<tsi_ssl_handshaker_result*>(self);
1334 SSL_free(impl->ssl);
1335 BIO_free(impl->network_io);
1336 gpr_free(impl->unused_bytes);
1340 static const tsi_handshaker_result_vtable handshaker_result_vtable = {
1341 ssl_handshaker_result_extract_peer,
1342 nullptr, /* create_zero_copy_grpc_protector */
1343 ssl_handshaker_result_create_frame_protector,
1344 ssl_handshaker_result_get_unused_bytes,
1345 ssl_handshaker_result_destroy,
1348 static tsi_result ssl_handshaker_result_create(
1349 tsi_ssl_handshaker* handshaker, unsigned char* unused_bytes,
1350 size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) {
1351 if (handshaker == nullptr || handshaker_result == nullptr ||
1352 (unused_bytes_size > 0 && unused_bytes == nullptr)) {
1353 return TSI_INVALID_ARGUMENT;
1355 tsi_ssl_handshaker_result* result =
1356 static_cast<tsi_ssl_handshaker_result*>(gpr_zalloc(sizeof(*result)));
1357 result->base.vtable = &handshaker_result_vtable;
1358 /* Transfer ownership of ssl and network_io to the handshaker result. */
1359 result->ssl = handshaker->ssl;
1360 handshaker->ssl = nullptr;
1361 result->network_io = handshaker->network_io;
1362 handshaker->network_io = nullptr;
1363 /* Transfer ownership of |unused_bytes| to the handshaker result. */
1364 result->unused_bytes = unused_bytes;
1365 result->unused_bytes_size = unused_bytes_size;
1366 *handshaker_result = &result->base;
1370 /* --- tsi_handshaker methods implementation. ---*/
1372 static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(
1373 tsi_ssl_handshaker* impl, unsigned char* bytes, size_t* bytes_size) {
1374 int bytes_read_from_ssl = 0;
1375 if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 ||
1376 *bytes_size > INT_MAX) {
1377 return TSI_INVALID_ARGUMENT;
1379 GPR_ASSERT(*bytes_size <= INT_MAX);
1380 bytes_read_from_ssl =
1381 BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size));
1382 if (bytes_read_from_ssl < 0) {
1384 if (!BIO_should_retry(impl->network_io)) {
1385 impl->result = TSI_INTERNAL_ERROR;
1386 return impl->result;
1391 *bytes_size = static_cast<size_t>(bytes_read_from_ssl);
1392 return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
1395 static tsi_result ssl_handshaker_get_result(tsi_ssl_handshaker* impl) {
1396 if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) &&
1397 SSL_is_init_finished(impl->ssl)) {
1398 impl->result = TSI_OK;
1400 return impl->result;
1403 static tsi_result ssl_handshaker_process_bytes_from_peer(
1404 tsi_ssl_handshaker* impl, const unsigned char* bytes, size_t* bytes_size) {
1405 int bytes_written_into_ssl_size = 0;
1406 if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) {
1407 return TSI_INVALID_ARGUMENT;
1409 GPR_ASSERT(*bytes_size <= INT_MAX);
1410 bytes_written_into_ssl_size =
1411 BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size));
1412 if (bytes_written_into_ssl_size < 0) {
1413 gpr_log(GPR_ERROR, "Could not write to memory BIO.");
1414 impl->result = TSI_INTERNAL_ERROR;
1415 return impl->result;
1417 *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size);
1419 if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) {
1420 impl->result = TSI_OK;
1421 return impl->result;
1423 /* Get ready to get some bytes from SSL. */
1424 int ssl_result = SSL_do_handshake(impl->ssl);
1425 ssl_result = SSL_get_error(impl->ssl, ssl_result);
1426 switch (ssl_result) {
1427 case SSL_ERROR_WANT_READ:
1428 if (BIO_pending(impl->network_io) == 0) {
1429 /* We need more data. */
1430 return TSI_INCOMPLETE_DATA;
1434 case SSL_ERROR_NONE:
1438 ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1439 gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.",
1440 ssl_error_string(ssl_result), err_str);
1441 impl->result = TSI_PROTOCOL_FAILURE;
1442 return impl->result;
1448 static void ssl_handshaker_destroy(tsi_handshaker* self) {
1449 tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1450 SSL_free(impl->ssl);
1451 BIO_free(impl->network_io);
1452 gpr_free(impl->outgoing_bytes_buffer);
1453 tsi_ssl_handshaker_factory_unref(impl->factory_ref);
1457 // Removes the bytes remaining in |impl->SSL|'s read BIO and writes them to
1458 // |bytes_remaining|.
1459 static tsi_result ssl_bytes_remaining(tsi_ssl_handshaker* impl,
1460 unsigned char** bytes_remaining,
1461 size_t* bytes_remaining_size) {
1462 if (impl == nullptr || bytes_remaining == nullptr ||
1463 bytes_remaining_size == nullptr) {
1464 return TSI_INVALID_ARGUMENT;
1466 // Atempt to read all of the bytes in SSL's read BIO. These bytes should
1467 // contain application data records that were appended to a handshake record
1468 // containing the ClientFinished or ServerFinished message.
1469 size_t bytes_in_ssl = BIO_pending(SSL_get_rbio(impl->ssl));
1470 if (bytes_in_ssl == 0) return TSI_OK;
1471 *bytes_remaining = static_cast<uint8_t*>(gpr_malloc(bytes_in_ssl));
1472 int bytes_read = BIO_read(SSL_get_rbio(impl->ssl), *bytes_remaining,
1473 static_cast<int>(bytes_in_ssl));
1474 // If an unexpected number of bytes were read, return an error status and free
1475 // all of the bytes that were read.
1476 if (bytes_read < 0 || static_cast<size_t>(bytes_read) != bytes_in_ssl) {
1478 "Failed to read the expected number of bytes from SSL object.");
1479 gpr_free(*bytes_remaining);
1480 *bytes_remaining = nullptr;
1481 return TSI_INTERNAL_ERROR;
1483 *bytes_remaining_size = static_cast<size_t>(bytes_read);
1487 static tsi_result ssl_handshaker_next(
1488 tsi_handshaker* self, const unsigned char* received_bytes,
1489 size_t received_bytes_size, const unsigned char** bytes_to_send,
1490 size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
1491 tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
1492 /* Input sanity check. */
1493 if ((received_bytes_size > 0 && received_bytes == nullptr) ||
1494 bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
1495 handshaker_result == nullptr) {
1496 return TSI_INVALID_ARGUMENT;
1498 /* If there are received bytes, process them first. */
1499 tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1500 tsi_result status = TSI_OK;
1501 size_t bytes_consumed = received_bytes_size;
1502 if (received_bytes_size > 0) {
1503 status = ssl_handshaker_process_bytes_from_peer(impl, received_bytes,
1505 if (status != TSI_OK) return status;
1507 /* Get bytes to send to the peer, if available. */
1510 size_t to_send_size = impl->outgoing_bytes_buffer_size - offset;
1511 status = ssl_handshaker_get_bytes_to_send_to_peer(
1512 impl, impl->outgoing_bytes_buffer + offset, &to_send_size);
1513 offset += to_send_size;
1514 if (status == TSI_INCOMPLETE_DATA) {
1515 impl->outgoing_bytes_buffer_size *= 2;
1516 impl->outgoing_bytes_buffer = static_cast<unsigned char*>(gpr_realloc(
1517 impl->outgoing_bytes_buffer, impl->outgoing_bytes_buffer_size));
1519 } while (status == TSI_INCOMPLETE_DATA);
1520 if (status != TSI_OK) return status;
1521 *bytes_to_send = impl->outgoing_bytes_buffer;
1522 *bytes_to_send_size = offset;
1523 /* If handshake completes, create tsi_handshaker_result. */
1524 if (ssl_handshaker_get_result(impl) == TSI_HANDSHAKE_IN_PROGRESS) {
1525 *handshaker_result = nullptr;
1527 // Any bytes that remain in |impl->ssl|'s read BIO after the handshake is
1528 // complete must be extracted and set to the unused bytes of the handshaker
1529 // result. This indicates to the gRPC stack that there are bytes from the
1530 // peer that must be processed.
1531 unsigned char* unused_bytes = nullptr;
1532 size_t unused_bytes_size = 0;
1533 status = ssl_bytes_remaining(impl, &unused_bytes, &unused_bytes_size);
1534 if (status != TSI_OK) return status;
1535 if (unused_bytes_size > received_bytes_size) {
1536 gpr_log(GPR_ERROR, "More unused bytes than received bytes.");
1537 gpr_free(unused_bytes);
1538 return TSI_INTERNAL_ERROR;
1540 status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size,
1542 if (status == TSI_OK) {
1543 /* Indicates that the handshake has completed and that a handshaker_result
1544 * has been created. */
1545 self->handshaker_result_created = true;
1551 static const tsi_handshaker_vtable handshaker_vtable = {
1552 nullptr, /* get_bytes_to_send_to_peer -- deprecated */
1553 nullptr, /* process_bytes_from_peer -- deprecated */
1554 nullptr, /* get_result -- deprecated */
1555 nullptr, /* extract_peer -- deprecated */
1556 nullptr, /* create_frame_protector -- deprecated */
1557 ssl_handshaker_destroy,
1558 ssl_handshaker_next,
1559 nullptr, /* shutdown */
1562 /* --- tsi_ssl_handshaker_factory common methods. --- */
1564 static void tsi_ssl_handshaker_resume_session(
1565 SSL* ssl, tsi::SslSessionLRUCache* session_cache) {
1566 const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1567 if (server_name == nullptr) {
1570 tsi::SslSessionPtr session = session_cache->Get(server_name);
1571 if (session != nullptr) {
1572 // SSL_set_session internally increments reference counter.
1573 SSL_set_session(ssl, session.get());
1577 static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
1578 const char* server_name_indication,
1579 tsi_ssl_handshaker_factory* factory,
1580 tsi_handshaker** handshaker) {
1581 SSL* ssl = SSL_new(ctx);
1582 BIO* network_io = nullptr;
1583 BIO* ssl_io = nullptr;
1584 tsi_ssl_handshaker* impl = nullptr;
1585 *handshaker = nullptr;
1586 if (ctx == nullptr) {
1587 gpr_log(GPR_ERROR, "SSL Context is null. Should never happen.");
1588 return TSI_INTERNAL_ERROR;
1590 if (ssl == nullptr) {
1591 return TSI_OUT_OF_RESOURCES;
1593 SSL_set_info_callback(ssl, ssl_info_callback);
1595 if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
1596 gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
1598 return TSI_OUT_OF_RESOURCES;
1600 SSL_set_bio(ssl, ssl_io, ssl_io);
1603 SSL_set_connect_state(ssl);
1604 if (server_name_indication != nullptr) {
1605 if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) {
1606 gpr_log(GPR_ERROR, "Invalid server name indication %s.",
1607 server_name_indication);
1609 BIO_free(network_io);
1610 return TSI_INTERNAL_ERROR;
1613 tsi_ssl_client_handshaker_factory* client_factory =
1614 reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1615 if (client_factory->session_cache != nullptr) {
1616 tsi_ssl_handshaker_resume_session(ssl,
1617 client_factory->session_cache.get());
1619 ssl_result = SSL_do_handshake(ssl);
1620 ssl_result = SSL_get_error(ssl, ssl_result);
1621 if (ssl_result != SSL_ERROR_WANT_READ) {
1623 "Unexpected error received from first SSL_do_handshake call: %s",
1624 ssl_error_string(ssl_result));
1626 BIO_free(network_io);
1627 return TSI_INTERNAL_ERROR;
1630 SSL_set_accept_state(ssl);
1633 impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
1635 impl->network_io = network_io;
1636 impl->result = TSI_HANDSHAKE_IN_PROGRESS;
1637 impl->outgoing_bytes_buffer_size =
1638 TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
1639 impl->outgoing_bytes_buffer =
1640 static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size));
1641 impl->base.vtable = &handshaker_vtable;
1642 impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory);
1643 *handshaker = &impl->base;
1647 static int select_protocol_list(const unsigned char** out,
1648 unsigned char* outlen,
1649 const unsigned char* client_list,
1650 size_t client_list_len,
1651 const unsigned char* server_list,
1652 size_t server_list_len) {
1653 const unsigned char* client_current = client_list;
1654 while (static_cast<unsigned int>(client_current - client_list) <
1656 unsigned char client_current_len = *(client_current++);
1657 const unsigned char* server_current = server_list;
1658 while ((server_current >= server_list) &&
1659 static_cast<uintptr_t>(server_current - server_list) <
1661 unsigned char server_current_len = *(server_current++);
1662 if ((client_current_len == server_current_len) &&
1663 !memcmp(client_current, server_current, server_current_len)) {
1664 *out = server_current;
1665 *outlen = server_current_len;
1666 return SSL_TLSEXT_ERR_OK;
1668 server_current += server_current_len;
1670 client_current += client_current_len;
1672 return SSL_TLSEXT_ERR_NOACK;
1675 /* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
1677 tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
1678 tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
1679 tsi_handshaker** handshaker) {
1680 return create_tsi_ssl_handshaker(self->ssl_context, 1, server_name_indication,
1681 &self->base, handshaker);
1684 void tsi_ssl_client_handshaker_factory_unref(
1685 tsi_ssl_client_handshaker_factory* self) {
1686 if (self == nullptr) return;
1687 tsi_ssl_handshaker_factory_unref(&self->base);
1690 static void tsi_ssl_client_handshaker_factory_destroy(
1691 tsi_ssl_handshaker_factory* factory) {
1692 if (factory == nullptr) return;
1693 tsi_ssl_client_handshaker_factory* self =
1694 reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1695 if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context);
1696 if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1697 self->session_cache.reset();
1701 static int client_handshaker_factory_npn_callback(
1702 SSL* /*ssl*/, unsigned char** out, unsigned char* outlen,
1703 const unsigned char* in, unsigned int inlen, void* arg) {
1704 tsi_ssl_client_handshaker_factory* factory =
1705 static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1706 return select_protocol_list((const unsigned char**)out, outlen,
1707 factory->alpn_protocol_list,
1708 factory->alpn_protocol_list_length, in, inlen);
1711 /* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
1713 tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
1714 tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker) {
1715 if (self->ssl_context_count == 0) return TSI_INVALID_ARGUMENT;
1716 /* Create the handshaker with the first context. We will switch if needed
1717 because of SNI in ssl_server_handshaker_factory_servername_callback. */
1718 return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, nullptr,
1719 &self->base, handshaker);
1722 void tsi_ssl_server_handshaker_factory_unref(
1723 tsi_ssl_server_handshaker_factory* self) {
1724 if (self == nullptr) return;
1725 tsi_ssl_handshaker_factory_unref(&self->base);
1728 static void tsi_ssl_server_handshaker_factory_destroy(
1729 tsi_ssl_handshaker_factory* factory) {
1730 if (factory == nullptr) return;
1731 tsi_ssl_server_handshaker_factory* self =
1732 reinterpret_cast<tsi_ssl_server_handshaker_factory*>(factory);
1734 for (i = 0; i < self->ssl_context_count; i++) {
1735 if (self->ssl_contexts[i] != nullptr) {
1736 SSL_CTX_free(self->ssl_contexts[i]);
1737 tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]);
1740 if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts);
1741 if (self->ssl_context_x509_subject_names != nullptr) {
1742 gpr_free(self->ssl_context_x509_subject_names);
1744 if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1748 static int does_entry_match_name(absl::string_view entry,
1749 absl::string_view name) {
1750 if (entry.empty()) return 0;
1752 /* Take care of '.' terminations. */
1753 if (name.back() == '.') {
1754 name.remove_suffix(1);
1756 if (entry.back() == '.') {
1757 entry.remove_suffix(1);
1758 if (entry.empty()) return 0;
1761 if (absl::EqualsIgnoreCase(name, entry)) {
1762 return 1; /* Perfect match. */
1764 if (entry.front() != '*') return 0;
1766 /* Wildchar subdomain matching. */
1767 if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
1768 gpr_log(GPR_ERROR, "Invalid wildchar entry.");
1771 size_t name_subdomain_pos = name.find('.');
1772 if (name_subdomain_pos == absl::string_view::npos) return 0;
1773 if (name_subdomain_pos >= name.size() - 2) return 0;
1774 absl::string_view name_subdomain =
1775 name.substr(name_subdomain_pos + 1); /* Starts after the dot. */
1776 entry.remove_prefix(2); /* Remove *. */
1777 size_t dot = name_subdomain.find('.');
1778 if (dot == absl::string_view::npos || dot == name_subdomain.size() - 1) {
1779 gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
1780 std::string(name_subdomain).c_str());
1783 if (name_subdomain.back() == '.') {
1784 name_subdomain.remove_suffix(1);
1786 return !entry.empty() && absl::EqualsIgnoreCase(name_subdomain, entry);
1789 static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
1792 tsi_ssl_server_handshaker_factory* impl =
1793 static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1795 const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1796 if (servername == nullptr || strlen(servername) == 0) {
1797 return SSL_TLSEXT_ERR_NOACK;
1800 for (i = 0; i < impl->ssl_context_count; i++) {
1801 if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
1803 SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
1804 return SSL_TLSEXT_ERR_OK;
1807 gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
1808 return SSL_TLSEXT_ERR_NOACK;
1811 #if TSI_OPENSSL_ALPN_SUPPORT
1812 static int server_handshaker_factory_alpn_callback(
1813 SSL* /*ssl*/, const unsigned char** out, unsigned char* outlen,
1814 const unsigned char* in, unsigned int inlen, void* arg) {
1815 tsi_ssl_server_handshaker_factory* factory =
1816 static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1817 return select_protocol_list(out, outlen, in, inlen,
1818 factory->alpn_protocol_list,
1819 factory->alpn_protocol_list_length);
1821 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1823 static int server_handshaker_factory_npn_advertised_callback(
1824 SSL* /*ssl*/, const unsigned char** out, unsigned int* outlen, void* arg) {
1825 tsi_ssl_server_handshaker_factory* factory =
1826 static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1827 *out = factory->alpn_protocol_list;
1828 GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX);
1829 *outlen = static_cast<unsigned int>(factory->alpn_protocol_list_length);
1830 return SSL_TLSEXT_ERR_OK;
1833 /// This callback is called when new \a session is established and ready to
1834 /// be cached. This session can be reused for new connections to similar
1835 /// servers at later point of time.
1836 /// It's intended to be used with SSL_CTX_sess_set_new_cb function.
1838 /// It returns 1 if callback takes ownership over \a session and 0 otherwise.
1839 static int server_handshaker_factory_new_session_callback(
1840 SSL* ssl, SSL_SESSION* session) {
1841 SSL_CTX* ssl_context = SSL_get_SSL_CTX(ssl);
1842 if (ssl_context == nullptr) {
1845 void* arg = SSL_CTX_get_ex_data(ssl_context, g_ssl_ctx_ex_factory_index);
1846 tsi_ssl_client_handshaker_factory* factory =
1847 static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1848 const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1849 if (server_name == nullptr) {
1852 factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
1853 // Return 1 to indicate transferred ownership over the given session.
1857 /* --- tsi_ssl_handshaker_factory constructors. --- */
1859 static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
1860 tsi_ssl_client_handshaker_factory_destroy};
1862 tsi_result tsi_create_ssl_client_handshaker_factory(
1863 const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
1864 const char* pem_root_certs, const char* cipher_suites,
1865 const char** alpn_protocols, uint16_t num_alpn_protocols,
1866 tsi_ssl_client_handshaker_factory** factory) {
1867 tsi_ssl_client_handshaker_options options;
1868 options.pem_key_cert_pair = pem_key_cert_pair;
1869 options.pem_root_certs = pem_root_certs;
1870 options.cipher_suites = cipher_suites;
1871 options.alpn_protocols = alpn_protocols;
1872 options.num_alpn_protocols = num_alpn_protocols;
1873 return tsi_create_ssl_client_handshaker_factory_with_options(&options,
1877 tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
1878 const tsi_ssl_client_handshaker_options* options,
1879 tsi_ssl_client_handshaker_factory** factory) {
1880 SSL_CTX* ssl_context = nullptr;
1881 tsi_ssl_client_handshaker_factory* impl = nullptr;
1882 tsi_result result = TSI_OK;
1884 gpr_once_init(&g_init_openssl_once, init_openssl);
1886 if (factory == nullptr) return TSI_INVALID_ARGUMENT;
1888 if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
1889 return TSI_INVALID_ARGUMENT;
1892 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1893 ssl_context = SSL_CTX_new(TLS_method());
1895 ssl_context = SSL_CTX_new(TLSv1_2_method());
1897 result = tsi_set_min_and_max_tls_versions(
1898 ssl_context, options->min_tls_version, options->max_tls_version);
1899 if (result != TSI_OK) return result;
1900 if (ssl_context == nullptr) {
1901 gpr_log(GPR_ERROR, "Could not create ssl context.");
1902 return TSI_INVALID_ARGUMENT;
1905 impl = static_cast<tsi_ssl_client_handshaker_factory*>(
1906 gpr_zalloc(sizeof(*impl)));
1907 tsi_ssl_handshaker_factory_init(&impl->base);
1908 impl->base.vtable = &client_handshaker_factory_vtable;
1909 impl->ssl_context = ssl_context;
1910 if (options->session_cache != nullptr) {
1911 // Unref is called manually on factory destruction.
1912 impl->session_cache =
1913 reinterpret_cast<tsi::SslSessionLRUCache*>(options->session_cache)
1915 SSL_CTX_set_ex_data(ssl_context, g_ssl_ctx_ex_factory_index, impl);
1916 SSL_CTX_sess_set_new_cb(ssl_context,
1917 server_handshaker_factory_new_session_callback);
1918 SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_CLIENT);
1922 result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
1923 options->cipher_suites);
1924 if (result != TSI_OK) break;
1926 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1927 // X509_STORE_up_ref is only available since OpenSSL 1.1.
1928 if (options->root_store != nullptr) {
1929 X509_STORE_up_ref(options->root_store->store);
1930 SSL_CTX_set_cert_store(ssl_context, options->root_store->store);
1933 if (OPENSSL_VERSION_NUMBER < 0x10100000 || options->root_store == nullptr) {
1934 result = ssl_ctx_load_verification_certs(
1935 ssl_context, options->pem_root_certs, strlen(options->pem_root_certs),
1937 if (result != TSI_OK) {
1938 gpr_log(GPR_ERROR, "Cannot load server root certificates.");
1943 if (options->num_alpn_protocols != 0) {
1944 result = build_alpn_protocol_name_list(
1945 options->alpn_protocols, options->num_alpn_protocols,
1946 &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
1947 if (result != TSI_OK) {
1948 gpr_log(GPR_ERROR, "Building alpn list failed with error %s.",
1949 tsi_result_to_string(result));
1952 #if TSI_OPENSSL_ALPN_SUPPORT
1953 GPR_ASSERT(impl->alpn_protocol_list_length < UINT_MAX);
1954 if (SSL_CTX_set_alpn_protos(
1955 ssl_context, impl->alpn_protocol_list,
1956 static_cast<unsigned int>(impl->alpn_protocol_list_length))) {
1957 gpr_log(GPR_ERROR, "Could not set alpn protocol list to context.");
1958 result = TSI_INVALID_ARGUMENT;
1961 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1962 SSL_CTX_set_next_proto_select_cb(
1963 ssl_context, client_handshaker_factory_npn_callback, impl);
1966 if (result != TSI_OK) {
1967 tsi_ssl_handshaker_factory_unref(&impl->base);
1970 if (options->skip_server_certificate_verification) {
1971 SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NullVerifyCallback);
1973 SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr);
1975 /* TODO(jboeuf): Add revocation verification. */
1981 static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
1982 tsi_ssl_server_handshaker_factory_destroy};
1984 tsi_result tsi_create_ssl_server_handshaker_factory(
1985 const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
1986 size_t num_key_cert_pairs, const char* pem_client_root_certs,
1987 int force_client_auth, const char* cipher_suites,
1988 const char** alpn_protocols, uint16_t num_alpn_protocols,
1989 tsi_ssl_server_handshaker_factory** factory) {
1990 return tsi_create_ssl_server_handshaker_factory_ex(
1991 pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs,
1992 force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
1993 : TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
1994 cipher_suites, alpn_protocols, num_alpn_protocols, factory);
1997 tsi_result tsi_create_ssl_server_handshaker_factory_ex(
1998 const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
1999 size_t num_key_cert_pairs, const char* pem_client_root_certs,
2000 tsi_client_certificate_request_type client_certificate_request,
2001 const char* cipher_suites, const char** alpn_protocols,
2002 uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) {
2003 tsi_ssl_server_handshaker_options options;
2004 options.pem_key_cert_pairs = pem_key_cert_pairs;
2005 options.num_key_cert_pairs = num_key_cert_pairs;
2006 options.pem_client_root_certs = pem_client_root_certs;
2007 options.client_certificate_request = client_certificate_request;
2008 options.cipher_suites = cipher_suites;
2009 options.alpn_protocols = alpn_protocols;
2010 options.num_alpn_protocols = num_alpn_protocols;
2011 return tsi_create_ssl_server_handshaker_factory_with_options(&options,
2015 tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
2016 const tsi_ssl_server_handshaker_options* options,
2017 tsi_ssl_server_handshaker_factory** factory) {
2018 tsi_ssl_server_handshaker_factory* impl = nullptr;
2019 tsi_result result = TSI_OK;
2022 gpr_once_init(&g_init_openssl_once, init_openssl);
2024 if (factory == nullptr) return TSI_INVALID_ARGUMENT;
2026 if (options->num_key_cert_pairs == 0 ||
2027 options->pem_key_cert_pairs == nullptr) {
2028 return TSI_INVALID_ARGUMENT;
2031 impl = static_cast<tsi_ssl_server_handshaker_factory*>(
2032 gpr_zalloc(sizeof(*impl)));
2033 tsi_ssl_handshaker_factory_init(&impl->base);
2034 impl->base.vtable = &server_handshaker_factory_vtable;
2036 impl->ssl_contexts = static_cast<SSL_CTX**>(
2037 gpr_zalloc(options->num_key_cert_pairs * sizeof(SSL_CTX*)));
2038 impl->ssl_context_x509_subject_names = static_cast<tsi_peer*>(
2039 gpr_zalloc(options->num_key_cert_pairs * sizeof(tsi_peer)));
2040 if (impl->ssl_contexts == nullptr ||
2041 impl->ssl_context_x509_subject_names == nullptr) {
2042 tsi_ssl_handshaker_factory_unref(&impl->base);
2043 return TSI_OUT_OF_RESOURCES;
2045 impl->ssl_context_count = options->num_key_cert_pairs;
2047 if (options->num_alpn_protocols > 0) {
2048 result = build_alpn_protocol_name_list(
2049 options->alpn_protocols, options->num_alpn_protocols,
2050 &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
2051 if (result != TSI_OK) {
2052 tsi_ssl_handshaker_factory_unref(&impl->base);
2057 for (i = 0; i < options->num_key_cert_pairs; i++) {
2059 #if OPENSSL_VERSION_NUMBER >= 0x10100000
2060 impl->ssl_contexts[i] = SSL_CTX_new(TLS_method());
2062 impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
2064 result = tsi_set_min_and_max_tls_versions(impl->ssl_contexts[i],
2065 options->min_tls_version,
2066 options->max_tls_version);
2067 if (result != TSI_OK) return result;
2068 if (impl->ssl_contexts[i] == nullptr) {
2069 gpr_log(GPR_ERROR, "Could not create ssl context.");
2070 result = TSI_OUT_OF_RESOURCES;
2073 result = populate_ssl_context(impl->ssl_contexts[i],
2074 &options->pem_key_cert_pairs[i],
2075 options->cipher_suites);
2076 if (result != TSI_OK) break;
2078 // TODO(elessar): Provide ability to disable session ticket keys.
2080 // Allow client cache sessions (it's needed for OpenSSL only).
2081 int set_sid_ctx_result = SSL_CTX_set_session_id_context(
2082 impl->ssl_contexts[i], kSslSessionIdContext,
2083 GPR_ARRAY_SIZE(kSslSessionIdContext));
2084 if (set_sid_ctx_result == 0) {
2085 gpr_log(GPR_ERROR, "Failed to set session id context.");
2086 result = TSI_INTERNAL_ERROR;
2090 if (options->session_ticket_key != nullptr) {
2091 if (SSL_CTX_set_tlsext_ticket_keys(
2092 impl->ssl_contexts[i],
2093 const_cast<char*>(options->session_ticket_key),
2094 options->session_ticket_key_size) == 0) {
2095 gpr_log(GPR_ERROR, "Invalid STEK size.");
2096 result = TSI_INVALID_ARGUMENT;
2101 if (options->pem_client_root_certs != nullptr) {
2102 STACK_OF(X509_NAME)* root_names = nullptr;
2103 result = ssl_ctx_load_verification_certs(
2104 impl->ssl_contexts[i], options->pem_client_root_certs,
2105 strlen(options->pem_client_root_certs), &root_names);
2106 if (result != TSI_OK) {
2107 gpr_log(GPR_ERROR, "Invalid verification certs.");
2110 SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
2112 switch (options->client_certificate_request) {
2113 case TSI_DONT_REQUEST_CLIENT_CERTIFICATE:
2114 SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr);
2116 case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
2117 SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER,
2118 NullVerifyCallback);
2120 case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY:
2121 SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr);
2123 case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
2124 SSL_CTX_set_verify(impl->ssl_contexts[i],
2125 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2126 NullVerifyCallback);
2128 case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY:
2129 SSL_CTX_set_verify(impl->ssl_contexts[i],
2130 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2134 /* TODO(jboeuf): Add revocation verification. */
2136 result = tsi_ssl_extract_x509_subject_names_from_pem_cert(
2137 options->pem_key_cert_pairs[i].cert_chain,
2138 &impl->ssl_context_x509_subject_names[i]);
2139 if (result != TSI_OK) break;
2141 SSL_CTX_set_tlsext_servername_callback(
2142 impl->ssl_contexts[i],
2143 ssl_server_handshaker_factory_servername_callback);
2144 SSL_CTX_set_tlsext_servername_arg(impl->ssl_contexts[i], impl);
2145 #if TSI_OPENSSL_ALPN_SUPPORT
2146 SSL_CTX_set_alpn_select_cb(impl->ssl_contexts[i],
2147 server_handshaker_factory_alpn_callback, impl);
2148 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
2149 SSL_CTX_set_next_protos_advertised_cb(
2150 impl->ssl_contexts[i],
2151 server_handshaker_factory_npn_advertised_callback, impl);
2154 if (result != TSI_OK) {
2155 tsi_ssl_handshaker_factory_unref(&impl->base);
2164 /* --- tsi_ssl utils. --- */
2166 int tsi_ssl_peer_matches_name(const tsi_peer* peer, absl::string_view name) {
2168 size_t san_count = 0;
2169 const tsi_peer_property* cn_property = nullptr;
2170 int like_ip = looks_like_ip_address(name);
2172 /* Check the SAN first. */
2173 for (i = 0; i < peer->property_count; i++) {
2174 const tsi_peer_property* property = &peer->properties[i];
2175 if (property->name == nullptr) continue;
2176 if (strcmp(property->name,
2177 TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) {
2180 absl::string_view entry(property->value.data, property->value.length);
2181 if (!like_ip && does_entry_match_name(entry, name)) {
2183 } else if (like_ip && name == entry) {
2184 /* IP Addresses are exact matches only. */
2187 } else if (strcmp(property->name,
2188 TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
2189 cn_property = property;
2193 /* If there's no SAN, try the CN, but only if its not like an IP Address */
2194 if (san_count == 0 && cn_property != nullptr && !like_ip) {
2195 if (does_entry_match_name(absl::string_view(cn_property->value.data,
2196 cn_property->value.length),
2202 return 0; /* Not found. */
2205 /* --- Testing support. --- */
2206 const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
2207 tsi_ssl_handshaker_factory* factory,
2208 tsi_ssl_handshaker_factory_vtable* new_vtable) {
2209 GPR_ASSERT(factory != nullptr);
2210 GPR_ASSERT(factory->vtable != nullptr);
2212 const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
2213 factory->vtable = new_vtable;