Imported Upstream version 1.33.1
[platform/upstream/grpc.git] / src / core / tsi / ssl_transport_security.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/tsi/ssl_transport_security.h"
22
23 #include <limits.h>
24 #include <string.h>
25
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. */
29 #ifdef GPR_WINDOWS
30 #include <ws2tcpip.h>
31 #else
32 #include <arpa/inet.h>
33 #include <sys/socket.h>
34 #endif
35
36 #include <string>
37
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>
44
45 #include "absl/strings/match.h"
46 #include "absl/strings/string_view.h"
47
48 extern "C" {
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>
57 }
58
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"
63
64 /* --- Constants. ---*/
65
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
69
70 /* Putting a macro like this and littering the source file with #if is really
71    bad practice.
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
75 #endif
76
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
80
81 /* --- Structure definitions. ---*/
82
83 struct tsi_ssl_root_certs_store {
84   X509_STORE* store;
85 };
86
87 struct tsi_ssl_handshaker_factory {
88   const tsi_ssl_handshaker_factory_vtable* vtable;
89   gpr_refcount refcount;
90 };
91
92 struct tsi_ssl_client_handshaker_factory {
93   tsi_ssl_handshaker_factory base;
94   SSL_CTX* ssl_context;
95   unsigned char* alpn_protocol_list;
96   size_t alpn_protocol_list_length;
97   grpc_core::RefCountedPtr<tsi::SslSessionLRUCache> session_cache;
98 };
99
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;
110 };
111
112 struct tsi_ssl_handshaker {
113   tsi_handshaker base;
114   SSL* ssl;
115   BIO* network_io;
116   tsi_result result;
117   unsigned char* outgoing_bytes_buffer;
118   size_t outgoing_bytes_buffer_size;
119   tsi_ssl_handshaker_factory* factory_ref;
120 };
121 struct tsi_ssl_handshaker_result {
122   tsi_handshaker_result base;
123   SSL* ssl;
124   BIO* network_io;
125   unsigned char* unused_bytes;
126   size_t unused_bytes_size;
127 };
128 struct tsi_ssl_frame_protector {
129   tsi_frame_protector base;
130   SSL* ssl;
131   BIO* network_io;
132   unsigned char* buffer;
133   size_t buffer_size;
134   size_t buffer_offset;
135 };
136 /* --- Library Initialization. ---*/
137
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:";
143 #endif
144
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;
150
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]);
154   } else {
155     gpr_mu_unlock(&g_openssl_mutexes[type]);
156   }
157 }
158
159 static unsigned long openssl_thread_id_cb(void) {
160   return static_cast<unsigned long>(gpr_thd_currentid());
161 }
162 #endif
163
164 static void init_openssl(void) {
165 #if OPENSSL_VERSION_NUMBER >= 0x10100000
166   OPENSSL_init_ssl(0, nullptr);
167 #else
168   SSL_library_init();
169   SSL_load_error_strings();
170   OpenSSL_add_all_algorithms();
171 #endif
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]);
180     }
181     CRYPTO_set_locking_callback(openssl_locking_cb);
182     CRYPTO_set_id_callback(openssl_thread_id_cb);
183   } else {
184     gpr_log(GPR_INFO, "OpenSSL callback has already been set.");
185   }
186 #endif
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);
190 }
191
192 /* --- Ssl utils. ---*/
193
194 static const char* ssl_error_string(int error) {
195   switch (error) {
196     case SSL_ERROR_NONE:
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";
212     case SSL_ERROR_SSL:
213       return "SSL_ERROR_SSL";
214     default:
215       return "Unknown error";
216   }
217 }
218
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,
221                                const char* msg) {
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));
225   }
226 }
227
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) {
230   if (ret == 0) {
231     gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n");
232     return;
233   }
234
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");
238 }
239
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;
244   size_t num_size = 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. */
248       return 1;
249     }
250     if (name[i] >= '0' && name[i] <= '9') {
251       if (num_size > 3) return 0;
252       num_size++;
253     } else if (name[i] == '.') {
254       if (dot_count > 3 || num_size == 0) return 0;
255       dot_count++;
256       num_size = 0;
257     } else {
258       return 0;
259     }
260   }
261   if (dot_count < 3 || num_size == 0) return 0;
262   return 1;
263 }
264
265 /* Gets the subject CN from an X509 cert. */
266 static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
267                                            size_t* utf8_size) {
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;
276   }
277   common_name_index =
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;
282   }
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;
287   }
288   common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
289   if (common_name_asn1 == nullptr) {
290     gpr_log(GPR_ERROR,
291             "Could not get common name entry asn1 from certificate.");
292     return TSI_INTERNAL_ERROR;
293   }
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;
298   }
299   *utf8_size = static_cast<size_t>(utf8_returned_size);
300   return TSI_OK;
301 }
302
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;
308   tsi_result result =
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;
314     } else {
315       return result;
316     }
317   }
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);
323   return result;
324 }
325
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)) {
330     BIO_free(bio);
331     return TSI_INTERNAL_ERROR;
332   }
333   char* contents;
334   long len = BIO_get_mem_data(bio, &contents);
335   if (len <= 0) {
336     BIO_free(bio);
337     return TSI_INTERNAL_ERROR;
338   }
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);
342   BIO_free(bio);
343   return result;
344 }
345
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) {
350   size_t i;
351   tsi_result result = TSI_OK;
352
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;
360       int name_size;
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);
365       } else {
366         name_size = ASN1_STRING_to_UTF8(
367             &name, subject_alt_name->d.uniformResourceIdentifier);
368       }
369       if (name_size < 0) {
370         gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
371         result = TSI_INTERNAL_ERROR;
372         break;
373       }
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) {
379         OPENSSL_free(name);
380         break;
381       }
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)++]);
387       }
388       OPENSSL_free(name);
389     } else if (subject_alt_name->type == GEN_IPADD) {
390       char ntop_buf[INET6_ADDRSTRLEN];
391       int af;
392
393       if (subject_alt_name->d.iPAddress->length == 4) {
394         af = AF_INET;
395       } else if (subject_alt_name->d.iPAddress->length == 16) {
396         af = AF_INET6;
397       } else {
398         gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
399         result = TSI_INTERNAL_ERROR;
400         break;
401       }
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;
407         break;
408       }
409
410       result = tsi_construct_string_peer_property_from_cstring(
411           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
412           &peer->properties[(*current_insert_index)++]);
413     }
414     if (result != TSI_OK) break;
415   }
416   return result;
417 }
418
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,
421                                  tsi_peer* peer) {
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))
428           : 0;
429   size_t property_count;
430   tsi_result result;
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) {
439       property_count += 1;
440     }
441   }
442   result = tsi_construct_peer(property_count, peer);
443   if (result != TSI_OK) return result;
444   int current_insert_index = 0;
445   do {
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;
451     }
452     result = peer_property_from_x509_common_name(
453         cert, &peer->properties[current_insert_index++]);
454     if (result != TSI_OK) break;
455
456     result =
457         add_pem_certificate(cert, &peer->properties[current_insert_index++]);
458     if (result != TSI_OK) break;
459
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           &current_insert_index);
464       if (result != TSI_OK) break;
465     }
466   } while (0);
467
468   if (subject_alt_names != nullptr) {
469     sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
470   }
471   if (result != TSI_OK) tsi_peer_destruct(peer);
472
473   GPR_ASSERT((int)peer->property_count == current_insert_index);
474   return result;
475 }
476
477 /* Logs the SSL error stack. */
478 static void log_ssl_error_stack(void) {
479   unsigned long err;
480   while ((err = ERR_get_error()) != 0) {
481     char details[256];
482     ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
483     gpr_log(GPR_ERROR, "%s", details);
484   }
485 }
486
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) {
490   int read_from_ssl;
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;
500         return TSI_OK;
501       case SSL_ERROR_WANT_WRITE:
502         gpr_log(
503             GPR_ERROR,
504             "Peer tried to renegotiate SSL connection. This is unsupported.");
505         return TSI_UNIMPLEMENTED;
506       case SSL_ERROR_SSL:
507         gpr_log(GPR_ERROR, "Corruption detected.");
508         log_ssl_error_stack();
509         return TSI_DATA_CORRUPTED;
510       default:
511         gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
512                 ssl_error_string(read_from_ssl));
513         return TSI_PROTOCOL_FAILURE;
514     }
515   }
516   *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
517   return TSI_OK;
518 }
519
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) {
530       gpr_log(GPR_ERROR,
531               "Peer tried to renegotiate SSL connection. This is unsupported.");
532       return TSI_UNIMPLEMENTED;
533     } else {
534       gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
535               ssl_error_string(ssl_write_result));
536       return TSI_INTERNAL_ERROR;
537     }
538   }
539   return TSI_OK;
540 }
541
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;
548   BIO* pem;
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;
553
554   do {
555     certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
556     if (certificate == nullptr) {
557       result = TSI_INVALID_ARGUMENT;
558       break;
559     }
560     if (!SSL_CTX_use_certificate(context, certificate)) {
561       result = TSI_INVALID_ARGUMENT;
562       break;
563     }
564     while (1) {
565       X509* certificate_authority =
566           PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
567       if (certificate_authority == nullptr) {
568         ERR_clear_error();
569         break; /* Done reading. */
570       }
571       if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
572         X509_free(certificate_authority);
573         result = TSI_INVALID_ARGUMENT;
574         break;
575       }
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
578          though.
579        */
580     }
581   } while (0);
582
583   if (certificate != nullptr) X509_free(certificate);
584   BIO_free(pem);
585   return result;
586 }
587
588 #ifndef OPENSSL_IS_BORINGSSL
589 static tsi_result ssl_ctx_use_engine_private_key(SSL_CTX* context,
590                                                  const char* pem_key,
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>
597   do {
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;
602       break;
603     }
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;
608       break;
609     }
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;
622         break;
623       }
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;
631         break;
632       }
633     }
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;
637       break;
638     }
639     if (!ENGINE_init(engine)) {
640       gpr_log(GPR_ERROR, "ENGINE_init failed");
641       result = TSI_INVALID_ARGUMENT;
642       break;
643     }
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;
648       break;
649     }
650     if (!SSL_CTX_use_PrivateKey(context, private_key)) {
651       gpr_log(GPR_ERROR, "SSL_CTX_use_PrivateKey failed");
652       result = TSI_INVALID_ARGUMENT;
653       break;
654     }
655   } while (0);
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);
659   return result;
660 }
661 #endif /* OPENSSL_IS_BORINGSSL */
662
663 static tsi_result ssl_ctx_use_pem_private_key(SSL_CTX* context,
664                                               const char* pem_key,
665                                               size_t pem_key_size) {
666   tsi_result result = TSI_OK;
667   EVP_PKEY* private_key = nullptr;
668   BIO* pem;
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;
672   do {
673     private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
674     if (private_key == nullptr) {
675       result = TSI_INVALID_ARGUMENT;
676       break;
677     }
678     if (!SSL_CTX_use_PrivateKey(context, private_key)) {
679       result = TSI_INVALID_ARGUMENT;
680       break;
681     }
682   } while (0);
683   if (private_key != nullptr) EVP_PKEY_free(private_key);
684   BIO_free(pem);
685   return result;
686 }
687
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);
695   } else
696 #endif /* OPENSSL_IS_BORINGSSL */
697   {
698     return ssl_ctx_use_pem_private_key(context, pem_key, pem_key_size);
699   }
700 }
701
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;
712   BIO* pem;
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;
720   }
721
722   while (1) {
723     root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
724     if (root == nullptr) {
725       ERR_clear_error();
726       break; /* We're at the end of stream. */
727     }
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;
733         break;
734       }
735       root_name = X509_NAME_dup(root_name);
736       if (root_name == nullptr) {
737         result = TSI_OUT_OF_RESOURCES;
738         break;
739       }
740       sk_X509_NAME_push(*root_names, root_name);
741       root_name = nullptr;
742     }
743     ERR_clear_error();
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;
750         break;
751       }
752     }
753     X509_free(root);
754     num_roots++;
755   }
756   if (num_roots == 0) {
757     gpr_log(GPR_ERROR, "Could not load any root certificate.");
758     result = TSI_INVALID_ARGUMENT;
759   }
760
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);
767     }
768   }
769   BIO_free(pem);
770   return result;
771 }
772
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) *
777                                                       *root_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,
782                                root_name);
783 }
784
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.");
797         return result;
798       }
799     }
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;
806       }
807     }
808   }
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;
813   }
814   {
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.");
818       EC_KEY_free(ecdh);
819       return TSI_INTERNAL_ERROR;
820     }
821     SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
822     EC_KEY_free(ecdh);
823   }
824   return TSI_OK;
825 }
826
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;
832   BIO* pem;
833   pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
834   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
835
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;
840   } else {
841     result = peer_from_x509(cert, 0, peer);
842   }
843   if (cert != nullptr) X509_free(cert);
844   BIO_free(pem);
845   return result;
846 }
847
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) {
852   uint16_t i;
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++) {
858     size_t length =
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;
864     }
865     *protocol_name_list_length += length + 1;
866   }
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);
875     current += length;
876   }
877   /* Safety check. */
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;
882   }
883   return TSI_OK;
884 }
885
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*/) {
891   return 1;
892 }
893
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) {
901     gpr_log(GPR_INFO,
902             "Invalid nullptr argument to |tsi_set_min_and_max_tls_versions|.");
903     return TSI_INVALID_ARGUMENT;
904   }
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);
910       break;
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);
914       break;
915 #endif
916     default:
917       gpr_log(GPR_INFO, "TLS version is not supported.");
918       return TSI_FAILED_PRECONDITION;
919   }
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);
924       break;
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);
928       break;
929 #endif
930     default:
931       gpr_log(GPR_INFO, "TLS version is not supported.");
932       return TSI_FAILED_PRECONDITION;
933   }
934 #endif
935   return TSI_OK;
936 }
937
938 /* --- tsi_ssl_root_certs_store methods implementation. ---*/
939
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.");
944     return nullptr;
945   }
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.");
950     return nullptr;
951   }
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);
956     return nullptr;
957   }
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);
964     return nullptr;
965   }
966   return root_store;
967 }
968
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);
972   gpr_free(self);
973 }
974
975 /* --- tsi_ssl_session_cache methods implementation. ---*/
976
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());
981 }
982
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();
986 }
987
988 void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
989   reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
990 }
991
992 /* --- tsi_frame_protector methods implementation. ---*/
993
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);
1001   int read_from_ssl;
1002   size_t available;
1003   tsi_result result = TSI_OK;
1004
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) {
1013       gpr_log(GPR_ERROR,
1014               "Could not read from BIO even though some data is pending");
1015       return TSI_INTERNAL_ERROR;
1016     }
1017     *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1018     return TSI_OK;
1019   }
1020
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;
1029     return TSI_OK;
1030   }
1031
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;
1036
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;
1043   }
1044   *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1045   *unprotected_bytes_size = available;
1046   impl->buffer_offset = 0;
1047   return TSI_OK;
1048 }
1049
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;
1057   int pending;
1058
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;
1063   }
1064
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;
1069
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;
1076   }
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);
1081   return TSI_OK;
1082 }
1083
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);
1094
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;
1101     return TSI_OK;
1102   }
1103   output_bytes_offset = *unprotected_bytes_size;
1104   unprotected_bytes += output_bytes_offset;
1105   *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
1106
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",
1113             written_into_ssl);
1114     return TSI_INTERNAL_ERROR;
1115   }
1116   *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
1117
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;
1123   }
1124   return result;
1125 }
1126
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);
1133   gpr_free(self);
1134 }
1135
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,
1141 };
1142
1143 /* --- tsi_server_handshaker_factory methods implementation. --- */
1144
1145 static void tsi_ssl_handshaker_factory_destroy(
1146     tsi_ssl_handshaker_factory* self) {
1147   if (self == nullptr) return;
1148
1149   if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
1150     self->vtable->destroy(self);
1151   }
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. */
1155 }
1156
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);
1161   return self;
1162 }
1163
1164 static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
1165   if (self == nullptr) return;
1166
1167   if (gpr_unref(&self->refcount)) {
1168     tsi_ssl_handshaker_factory_destroy(self);
1169   }
1170 }
1171
1172 static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
1173
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);
1179
1180   factory->vtable = &handshaker_factory_vtable;
1181   gpr_ref_init(&factory->refcount, 1);
1182 }
1183
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))) {
1191       BIO_free(bio);
1192       return TSI_INTERNAL_ERROR;
1193     }
1194   }
1195   char* contents;
1196   long len = BIO_get_mem_data(bio, &contents);
1197   if (len <= 0) {
1198     BIO_free(bio);
1199     return TSI_INTERNAL_ERROR;
1200   }
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);
1204   BIO_free(bio);
1205   return result;
1206 }
1207
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;
1221   }
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) {
1226     /* Try npn. */
1227     SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
1228                                    &alpn_selected_len);
1229   }
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];
1242   }
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++;
1250   }
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++;
1258   }
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++;
1266
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++;
1273   return result;
1274 }
1275
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)));
1287
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;
1297     }
1298     actual_max_output_protected_frame_size = *max_output_protected_frame_size;
1299   }
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) {
1305     gpr_log(GPR_ERROR,
1306             "Could not allocated buffer for tsi_ssl_frame_protector.");
1307     gpr_free(protector_impl);
1308     return TSI_INTERNAL_ERROR;
1309   }
1310
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;
1318   return TSI_OK;
1319 }
1320
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;
1328   return TSI_OK;
1329 }
1330
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);
1337   gpr_free(impl);
1338 }
1339
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,
1346 };
1347
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;
1354   }
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;
1367   return TSI_OK;
1368 }
1369
1370 /* --- tsi_handshaker methods implementation. ---*/
1371
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;
1378   }
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) {
1383     *bytes_size = 0;
1384     if (!BIO_should_retry(impl->network_io)) {
1385       impl->result = TSI_INTERNAL_ERROR;
1386       return impl->result;
1387     } else {
1388       return TSI_OK;
1389     }
1390   }
1391   *bytes_size = static_cast<size_t>(bytes_read_from_ssl);
1392   return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
1393 }
1394
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;
1399   }
1400   return impl->result;
1401 }
1402
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;
1408   }
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;
1416   }
1417   *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size);
1418
1419   if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) {
1420     impl->result = TSI_OK;
1421     return impl->result;
1422   } else {
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;
1431         } else {
1432           return TSI_OK;
1433         }
1434       case SSL_ERROR_NONE:
1435         return TSI_OK;
1436       default: {
1437         char err_str[256];
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;
1443       }
1444     }
1445   }
1446 }
1447
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);
1454   gpr_free(impl);
1455 }
1456
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;
1465   }
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) {
1477     gpr_log(GPR_ERROR,
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;
1482   }
1483   *bytes_remaining_size = static_cast<size_t>(bytes_read);
1484   return TSI_OK;
1485 }
1486
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;
1497   }
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,
1504                                                     &bytes_consumed);
1505     if (status != TSI_OK) return status;
1506   }
1507   /* Get bytes to send to the peer, if available.  */
1508   size_t offset = 0;
1509   do {
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));
1518     }
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;
1526   } else {
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;
1539     }
1540     status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size,
1541                                           handshaker_result);
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;
1546     }
1547   }
1548   return status;
1549 }
1550
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 */
1560 };
1561
1562 /* --- tsi_ssl_handshaker_factory common methods. --- */
1563
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) {
1568     return;
1569   }
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());
1574   }
1575 }
1576
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;
1589   }
1590   if (ssl == nullptr) {
1591     return TSI_OUT_OF_RESOURCES;
1592   }
1593   SSL_set_info_callback(ssl, ssl_info_callback);
1594
1595   if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
1596     gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
1597     SSL_free(ssl);
1598     return TSI_OUT_OF_RESOURCES;
1599   }
1600   SSL_set_bio(ssl, ssl_io, ssl_io);
1601   if (is_client) {
1602     int ssl_result;
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);
1608         SSL_free(ssl);
1609         BIO_free(network_io);
1610         return TSI_INTERNAL_ERROR;
1611       }
1612     }
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());
1618     }
1619     ssl_result = SSL_do_handshake(ssl);
1620     ssl_result = SSL_get_error(ssl, ssl_result);
1621     if (ssl_result != SSL_ERROR_WANT_READ) {
1622       gpr_log(GPR_ERROR,
1623               "Unexpected error received from first SSL_do_handshake call: %s",
1624               ssl_error_string(ssl_result));
1625       SSL_free(ssl);
1626       BIO_free(network_io);
1627       return TSI_INTERNAL_ERROR;
1628     }
1629   } else {
1630     SSL_set_accept_state(ssl);
1631   }
1632
1633   impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
1634   impl->ssl = ssl;
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;
1644   return TSI_OK;
1645 }
1646
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) <
1655          client_list_len) {
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) <
1660                server_list_len) {
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;
1667       }
1668       server_current += server_current_len;
1669     }
1670     client_current += client_current_len;
1671   }
1672   return SSL_TLSEXT_ERR_NOACK;
1673 }
1674
1675 /* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
1676
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);
1682 }
1683
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);
1688 }
1689
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();
1698   gpr_free(self);
1699 }
1700
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);
1709 }
1710
1711 /* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
1712
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);
1720 }
1721
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);
1726 }
1727
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);
1733   size_t i;
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]);
1738     }
1739   }
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);
1743   }
1744   if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1745   gpr_free(self);
1746 }
1747
1748 static int does_entry_match_name(absl::string_view entry,
1749                                  absl::string_view name) {
1750   if (entry.empty()) return 0;
1751
1752   /* Take care of '.' terminations. */
1753   if (name.back() == '.') {
1754     name.remove_suffix(1);
1755   }
1756   if (entry.back() == '.') {
1757     entry.remove_suffix(1);
1758     if (entry.empty()) return 0;
1759   }
1760
1761   if (absl::EqualsIgnoreCase(name, entry)) {
1762     return 1; /* Perfect match. */
1763   }
1764   if (entry.front() != '*') return 0;
1765
1766   /* Wildchar subdomain matching. */
1767   if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
1768     gpr_log(GPR_ERROR, "Invalid wildchar entry.");
1769     return 0;
1770   }
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());
1781     return 0;
1782   }
1783   if (name_subdomain.back() == '.') {
1784     name_subdomain.remove_suffix(1);
1785   }
1786   return !entry.empty() && absl::EqualsIgnoreCase(name_subdomain, entry);
1787 }
1788
1789 static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
1790                                                              int* /*ap*/,
1791                                                              void* arg) {
1792   tsi_ssl_server_handshaker_factory* impl =
1793       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1794   size_t i = 0;
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;
1798   }
1799
1800   for (i = 0; i < impl->ssl_context_count; i++) {
1801     if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
1802                                   servername)) {
1803       SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
1804       return SSL_TLSEXT_ERR_OK;
1805     }
1806   }
1807   gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
1808   return SSL_TLSEXT_ERR_NOACK;
1809 }
1810
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);
1820 }
1821 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1822
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;
1831 }
1832
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.
1837 ///
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) {
1843     return 0;
1844   }
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) {
1850     return 0;
1851   }
1852   factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
1853   // Return 1 to indicate transferred ownership over the given session.
1854   return 1;
1855 }
1856
1857 /* --- tsi_ssl_handshaker_factory constructors. --- */
1858
1859 static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
1860     tsi_ssl_client_handshaker_factory_destroy};
1861
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,
1874                                                                factory);
1875 }
1876
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;
1883
1884   gpr_once_init(&g_init_openssl_once, init_openssl);
1885
1886   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
1887   *factory = nullptr;
1888   if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
1889     return TSI_INVALID_ARGUMENT;
1890   }
1891
1892 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1893   ssl_context = SSL_CTX_new(TLS_method());
1894 #else
1895   ssl_context = SSL_CTX_new(TLSv1_2_method());
1896 #endif
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;
1903   }
1904
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)
1914             ->Ref();
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);
1919   }
1920
1921   do {
1922     result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
1923                                   options->cipher_suites);
1924     if (result != TSI_OK) break;
1925
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);
1931     }
1932 #endif
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),
1936           nullptr);
1937       if (result != TSI_OK) {
1938         gpr_log(GPR_ERROR, "Cannot load server root certificates.");
1939         break;
1940       }
1941     }
1942
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));
1950         break;
1951       }
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;
1959         break;
1960       }
1961 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1962       SSL_CTX_set_next_proto_select_cb(
1963           ssl_context, client_handshaker_factory_npn_callback, impl);
1964     }
1965   } while (0);
1966   if (result != TSI_OK) {
1967     tsi_ssl_handshaker_factory_unref(&impl->base);
1968     return result;
1969   }
1970   if (options->skip_server_certificate_verification) {
1971     SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NullVerifyCallback);
1972   } else {
1973     SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr);
1974   }
1975   /* TODO(jboeuf): Add revocation verification. */
1976
1977   *factory = impl;
1978   return TSI_OK;
1979 }
1980
1981 static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
1982     tsi_ssl_server_handshaker_factory_destroy};
1983
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);
1995 }
1996
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,
2012                                                                factory);
2013 }
2014
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;
2020   size_t i = 0;
2021
2022   gpr_once_init(&g_init_openssl_once, init_openssl);
2023
2024   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
2025   *factory = nullptr;
2026   if (options->num_key_cert_pairs == 0 ||
2027       options->pem_key_cert_pairs == nullptr) {
2028     return TSI_INVALID_ARGUMENT;
2029   }
2030
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;
2035
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;
2044   }
2045   impl->ssl_context_count = options->num_key_cert_pairs;
2046
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);
2053       return result;
2054     }
2055   }
2056
2057   for (i = 0; i < options->num_key_cert_pairs; i++) {
2058     do {
2059 #if OPENSSL_VERSION_NUMBER >= 0x10100000
2060       impl->ssl_contexts[i] = SSL_CTX_new(TLS_method());
2061 #else
2062       impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
2063 #endif
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;
2071         break;
2072       }
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;
2077
2078       // TODO(elessar): Provide ability to disable session ticket keys.
2079
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;
2087         break;
2088       }
2089
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;
2097           break;
2098         }
2099       }
2100
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.");
2108           break;
2109         }
2110         SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
2111       }
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);
2115           break;
2116         case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
2117           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER,
2118                              NullVerifyCallback);
2119           break;
2120         case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY:
2121           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr);
2122           break;
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);
2127           break;
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,
2131                              nullptr);
2132           break;
2133       }
2134       /* TODO(jboeuf): Add revocation verification. */
2135
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;
2140
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);
2152     } while (0);
2153
2154     if (result != TSI_OK) {
2155       tsi_ssl_handshaker_factory_unref(&impl->base);
2156       return result;
2157     }
2158   }
2159
2160   *factory = impl;
2161   return TSI_OK;
2162 }
2163
2164 /* --- tsi_ssl utils. --- */
2165
2166 int tsi_ssl_peer_matches_name(const tsi_peer* peer, absl::string_view name) {
2167   size_t i = 0;
2168   size_t san_count = 0;
2169   const tsi_peer_property* cn_property = nullptr;
2170   int like_ip = looks_like_ip_address(name);
2171
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) {
2178       san_count++;
2179
2180       absl::string_view entry(property->value.data, property->value.length);
2181       if (!like_ip && does_entry_match_name(entry, name)) {
2182         return 1;
2183       } else if (like_ip && name == entry) {
2184         /* IP Addresses are exact matches only. */
2185         return 1;
2186       }
2187     } else if (strcmp(property->name,
2188                       TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
2189       cn_property = property;
2190     }
2191   }
2192
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),
2197                               name)) {
2198       return 1;
2199     }
2200   }
2201
2202   return 0; /* Not found. */
2203 }
2204
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);
2211
2212   const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
2213   factory->vtable = new_vtable;
2214   return orig_vtable;
2215 }