Imported Upstream version 1.36.0
[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 #if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_NO_ENGINE)
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, contents, static_cast<size_t>(len), property);
341   BIO_free(bio);
342   return result;
343 }
344
345 /* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
346 static tsi_result add_subject_alt_names_properties_to_peer(
347     tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
348     size_t subject_alt_name_count, int* current_insert_index) {
349   size_t i;
350   tsi_result result = TSI_OK;
351
352   for (i = 0; i < subject_alt_name_count; i++) {
353     GENERAL_NAME* subject_alt_name =
354         sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
355     if (subject_alt_name->type == GEN_DNS ||
356         subject_alt_name->type == GEN_EMAIL ||
357         subject_alt_name->type == GEN_URI) {
358       unsigned char* name = nullptr;
359       int name_size;
360       if (subject_alt_name->type == GEN_DNS) {
361         name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
362       } else if (subject_alt_name->type == GEN_EMAIL) {
363         name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.rfc822Name);
364       } else {
365         name_size = ASN1_STRING_to_UTF8(
366             &name, subject_alt_name->d.uniformResourceIdentifier);
367       }
368       if (name_size < 0) {
369         gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
370         result = TSI_INTERNAL_ERROR;
371         break;
372       }
373       result = tsi_construct_string_peer_property(
374           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
375           reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
376           &peer->properties[(*current_insert_index)++]);
377       if (result != TSI_OK) {
378         OPENSSL_free(name);
379         break;
380       }
381       if (subject_alt_name->type == GEN_URI) {
382         result = tsi_construct_string_peer_property(
383             TSI_X509_URI_PEER_PROPERTY, reinterpret_cast<const char*>(name),
384             static_cast<size_t>(name_size),
385             &peer->properties[(*current_insert_index)++]);
386       }
387       OPENSSL_free(name);
388     } else if (subject_alt_name->type == GEN_IPADD) {
389       char ntop_buf[INET6_ADDRSTRLEN];
390       int af;
391
392       if (subject_alt_name->d.iPAddress->length == 4) {
393         af = AF_INET;
394       } else if (subject_alt_name->d.iPAddress->length == 16) {
395         af = AF_INET6;
396       } else {
397         gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
398         result = TSI_INTERNAL_ERROR;
399         break;
400       }
401       const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
402                                    ntop_buf, INET6_ADDRSTRLEN);
403       if (name == nullptr) {
404         gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
405         result = TSI_INTERNAL_ERROR;
406         break;
407       }
408
409       result = tsi_construct_string_peer_property_from_cstring(
410           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
411           &peer->properties[(*current_insert_index)++]);
412     } else {
413       result = tsi_construct_string_peer_property_from_cstring(
414           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, "other types of SAN",
415           &peer->properties[(*current_insert_index)++]);
416     }
417     if (result != TSI_OK) break;
418   }
419   return result;
420 }
421
422 /* Gets information about the peer's X509 cert as a tsi_peer object. */
423 static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
424                                  tsi_peer* peer) {
425   /* TODO(jboeuf): Maybe add more properties. */
426   GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
427       X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
428   int subject_alt_name_count =
429       (subject_alt_names != nullptr)
430           ? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
431           : 0;
432   size_t property_count;
433   tsi_result result;
434   GPR_ASSERT(subject_alt_name_count >= 0);
435   property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
436                    2 /* common name, certificate */ +
437                    static_cast<size_t>(subject_alt_name_count);
438   for (int i = 0; i < subject_alt_name_count; i++) {
439     GENERAL_NAME* subject_alt_name =
440         sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
441     if (subject_alt_name->type == GEN_URI) {
442       property_count += 1;
443     }
444   }
445   result = tsi_construct_peer(property_count, peer);
446   if (result != TSI_OK) return result;
447   int current_insert_index = 0;
448   do {
449     if (include_certificate_type) {
450       result = tsi_construct_string_peer_property_from_cstring(
451           TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
452           &peer->properties[current_insert_index++]);
453       if (result != TSI_OK) break;
454     }
455     result = peer_property_from_x509_common_name(
456         cert, &peer->properties[current_insert_index++]);
457     if (result != TSI_OK) break;
458
459     result =
460         add_pem_certificate(cert, &peer->properties[current_insert_index++]);
461     if (result != TSI_OK) break;
462
463     if (subject_alt_name_count != 0) {
464       result = add_subject_alt_names_properties_to_peer(
465           peer, subject_alt_names, static_cast<size_t>(subject_alt_name_count),
466           &current_insert_index);
467       if (result != TSI_OK) break;
468     }
469   } while (false);
470
471   if (subject_alt_names != nullptr) {
472     sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
473   }
474   if (result != TSI_OK) tsi_peer_destruct(peer);
475
476   GPR_ASSERT((int)peer->property_count == current_insert_index);
477   return result;
478 }
479
480 /* Logs the SSL error stack. */
481 static void log_ssl_error_stack(void) {
482   unsigned long err;
483   while ((err = ERR_get_error()) != 0) {
484     char details[256];
485     ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
486     gpr_log(GPR_ERROR, "%s", details);
487   }
488 }
489
490 /* Performs an SSL_read and handle errors. */
491 static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
492                               size_t* unprotected_bytes_size) {
493   int read_from_ssl;
494   GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
495   read_from_ssl = SSL_read(ssl, unprotected_bytes,
496                            static_cast<int>(*unprotected_bytes_size));
497   if (read_from_ssl <= 0) {
498     read_from_ssl = SSL_get_error(ssl, read_from_ssl);
499     switch (read_from_ssl) {
500       case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
501       case SSL_ERROR_WANT_READ:   /* We need more data to finish the frame. */
502         *unprotected_bytes_size = 0;
503         return TSI_OK;
504       case SSL_ERROR_WANT_WRITE:
505         gpr_log(
506             GPR_ERROR,
507             "Peer tried to renegotiate SSL connection. This is unsupported.");
508         return TSI_UNIMPLEMENTED;
509       case SSL_ERROR_SSL:
510         gpr_log(GPR_ERROR, "Corruption detected.");
511         log_ssl_error_stack();
512         return TSI_DATA_CORRUPTED;
513       default:
514         gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
515                 ssl_error_string(read_from_ssl));
516         return TSI_PROTOCOL_FAILURE;
517     }
518   }
519   *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
520   return TSI_OK;
521 }
522
523 /* Performs an SSL_write and handle errors. */
524 static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
525                                size_t unprotected_bytes_size) {
526   int ssl_write_result;
527   GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
528   ssl_write_result = SSL_write(ssl, unprotected_bytes,
529                                static_cast<int>(unprotected_bytes_size));
530   if (ssl_write_result < 0) {
531     ssl_write_result = SSL_get_error(ssl, ssl_write_result);
532     if (ssl_write_result == SSL_ERROR_WANT_READ) {
533       gpr_log(GPR_ERROR,
534               "Peer tried to renegotiate SSL connection. This is unsupported.");
535       return TSI_UNIMPLEMENTED;
536     } else {
537       gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
538               ssl_error_string(ssl_write_result));
539       return TSI_INTERNAL_ERROR;
540     }
541   }
542   return TSI_OK;
543 }
544
545 /* Loads an in-memory PEM certificate chain into the SSL context. */
546 static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
547                                                 const char* pem_cert_chain,
548                                                 size_t pem_cert_chain_size) {
549   tsi_result result = TSI_OK;
550   X509* certificate = nullptr;
551   BIO* pem;
552   GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
553   pem = BIO_new_mem_buf(pem_cert_chain, static_cast<int>(pem_cert_chain_size));
554   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
555
556   do {
557     certificate =
558         PEM_read_bio_X509_AUX(pem, nullptr, nullptr, const_cast<char*>(""));
559     if (certificate == nullptr) {
560       result = TSI_INVALID_ARGUMENT;
561       break;
562     }
563     if (!SSL_CTX_use_certificate(context, certificate)) {
564       result = TSI_INVALID_ARGUMENT;
565       break;
566     }
567     while (true) {
568       X509* certificate_authority =
569           PEM_read_bio_X509(pem, nullptr, nullptr, const_cast<char*>(""));
570       if (certificate_authority == nullptr) {
571         ERR_clear_error();
572         break; /* Done reading. */
573       }
574       if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
575         X509_free(certificate_authority);
576         result = TSI_INVALID_ARGUMENT;
577         break;
578       }
579       /* We don't need to free certificate_authority as its ownership has been
580          transferred to the context. That is not the case for certificate
581          though.
582        */
583     }
584   } while (false);
585
586   if (certificate != nullptr) X509_free(certificate);
587   BIO_free(pem);
588   return result;
589 }
590
591 #if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_NO_ENGINE)
592 static tsi_result ssl_ctx_use_engine_private_key(SSL_CTX* context,
593                                                  const char* pem_key,
594                                                  size_t pem_key_size) {
595   tsi_result result = TSI_OK;
596   EVP_PKEY* private_key = nullptr;
597   ENGINE* engine = nullptr;
598   char* engine_name = nullptr;
599   // Parse key which is in following format engine:<engine_id>:<key_id>
600   do {
601     char* engine_start = (char*)pem_key + strlen(kSslEnginePrefix);
602     char* engine_end = (char*)strchr(engine_start, ':');
603     if (engine_end == nullptr) {
604       result = TSI_INVALID_ARGUMENT;
605       break;
606     }
607     char* key_id = engine_end + 1;
608     int engine_name_length = engine_end - engine_start;
609     if (engine_name_length == 0) {
610       result = TSI_INVALID_ARGUMENT;
611       break;
612     }
613     engine_name = static_cast<char*>(gpr_zalloc(engine_name_length + 1));
614     memcpy(engine_name, engine_start, engine_name_length);
615     gpr_log(GPR_DEBUG, "ENGINE key: %s", engine_name);
616     ENGINE_load_dynamic();
617     engine = ENGINE_by_id(engine_name);
618     if (engine == nullptr) {
619       // If not available at ENGINE_DIR, use dynamic to load from
620       // current working directory.
621       engine = ENGINE_by_id("dynamic");
622       if (engine == nullptr) {
623         gpr_log(GPR_ERROR, "Cannot load dynamic engine");
624         result = TSI_INVALID_ARGUMENT;
625         break;
626       }
627       if (!ENGINE_ctrl_cmd_string(engine, "ID", engine_name, 0) ||
628           !ENGINE_ctrl_cmd_string(engine, "DIR_LOAD", "2", 0) ||
629           !ENGINE_ctrl_cmd_string(engine, "DIR_ADD", ".", 0) ||
630           !ENGINE_ctrl_cmd_string(engine, "LIST_ADD", "1", 0) ||
631           !ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0)) {
632         gpr_log(GPR_ERROR, "Cannot find engine");
633         result = TSI_INVALID_ARGUMENT;
634         break;
635       }
636     }
637     if (!ENGINE_set_default(engine, ENGINE_METHOD_ALL)) {
638       gpr_log(GPR_ERROR, "ENGINE_set_default with ENGINE_METHOD_ALL failed");
639       result = TSI_INVALID_ARGUMENT;
640       break;
641     }
642     if (!ENGINE_init(engine)) {
643       gpr_log(GPR_ERROR, "ENGINE_init failed");
644       result = TSI_INVALID_ARGUMENT;
645       break;
646     }
647     private_key = ENGINE_load_private_key(engine, key_id, 0, 0);
648     if (private_key == nullptr) {
649       gpr_log(GPR_ERROR, "ENGINE_load_private_key failed");
650       result = TSI_INVALID_ARGUMENT;
651       break;
652     }
653     if (!SSL_CTX_use_PrivateKey(context, private_key)) {
654       gpr_log(GPR_ERROR, "SSL_CTX_use_PrivateKey failed");
655       result = TSI_INVALID_ARGUMENT;
656       break;
657     }
658   } while (0);
659   if (engine != nullptr) ENGINE_free(engine);
660   if (private_key != nullptr) EVP_PKEY_free(private_key);
661   if (engine_name != nullptr) gpr_free(engine_name);
662   return result;
663 }
664 #endif /* !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_NO_ENGINE) */
665
666 static tsi_result ssl_ctx_use_pem_private_key(SSL_CTX* context,
667                                               const char* pem_key,
668                                               size_t pem_key_size) {
669   tsi_result result = TSI_OK;
670   EVP_PKEY* private_key = nullptr;
671   BIO* pem;
672   GPR_ASSERT(pem_key_size <= INT_MAX);
673   pem = BIO_new_mem_buf(pem_key, static_cast<int>(pem_key_size));
674   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
675   do {
676     private_key =
677         PEM_read_bio_PrivateKey(pem, nullptr, nullptr, const_cast<char*>(""));
678     if (private_key == nullptr) {
679       result = TSI_INVALID_ARGUMENT;
680       break;
681     }
682     if (!SSL_CTX_use_PrivateKey(context, private_key)) {
683       result = TSI_INVALID_ARGUMENT;
684       break;
685     }
686   } while (false);
687   if (private_key != nullptr) EVP_PKEY_free(private_key);
688   BIO_free(pem);
689   return result;
690 }
691
692 /* Loads an in-memory PEM private key into the SSL context. */
693 static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
694                                           size_t pem_key_size) {
695 // BoringSSL does not have ENGINE support
696 #if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_NO_ENGINE)
697   if (strncmp(pem_key, kSslEnginePrefix, strlen(kSslEnginePrefix)) == 0) {
698     return ssl_ctx_use_engine_private_key(context, pem_key, pem_key_size);
699   } else
700 #endif /* !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_NO_ENGINE) */
701   {
702     return ssl_ctx_use_pem_private_key(context, pem_key, pem_key_size);
703   }
704 }
705
706 /* Loads in-memory PEM verification certs into the SSL context and optionally
707    returns the verification cert names (root_names can be NULL). */
708 static tsi_result x509_store_load_certs(X509_STORE* cert_store,
709                                         const char* pem_roots,
710                                         size_t pem_roots_size,
711                                         STACK_OF(X509_NAME) * *root_names) {
712   tsi_result result = TSI_OK;
713   size_t num_roots = 0;
714   X509* root = nullptr;
715   X509_NAME* root_name = nullptr;
716   BIO* pem;
717   GPR_ASSERT(pem_roots_size <= INT_MAX);
718   pem = BIO_new_mem_buf(pem_roots, static_cast<int>(pem_roots_size));
719   if (cert_store == nullptr) return TSI_INVALID_ARGUMENT;
720   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
721   if (root_names != nullptr) {
722     *root_names = sk_X509_NAME_new_null();
723     if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
724   }
725
726   while (true) {
727     root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, const_cast<char*>(""));
728     if (root == nullptr) {
729       ERR_clear_error();
730       break; /* We're at the end of stream. */
731     }
732     if (root_names != nullptr) {
733       root_name = X509_get_subject_name(root);
734       if (root_name == nullptr) {
735         gpr_log(GPR_ERROR, "Could not get name from root certificate.");
736         result = TSI_INVALID_ARGUMENT;
737         break;
738       }
739       root_name = X509_NAME_dup(root_name);
740       if (root_name == nullptr) {
741         result = TSI_OUT_OF_RESOURCES;
742         break;
743       }
744       sk_X509_NAME_push(*root_names, root_name);
745       root_name = nullptr;
746     }
747     ERR_clear_error();
748     if (!X509_STORE_add_cert(cert_store, root)) {
749       unsigned long error = ERR_get_error();
750       if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
751           ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
752         gpr_log(GPR_ERROR, "Could not add root certificate to ssl context.");
753         result = TSI_INTERNAL_ERROR;
754         break;
755       }
756     }
757     X509_free(root);
758     num_roots++;
759   }
760   if (num_roots == 0) {
761     gpr_log(GPR_ERROR, "Could not load any root certificate.");
762     result = TSI_INVALID_ARGUMENT;
763   }
764
765   if (result != TSI_OK) {
766     if (root != nullptr) X509_free(root);
767     if (root_names != nullptr) {
768       sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
769       *root_names = nullptr;
770       if (root_name != nullptr) X509_NAME_free(root_name);
771     }
772   }
773   BIO_free(pem);
774   return result;
775 }
776
777 static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
778                                                   const char* pem_roots,
779                                                   size_t pem_roots_size,
780                                                   STACK_OF(X509_NAME) *
781                                                       *root_name) {
782   X509_STORE* cert_store = SSL_CTX_get_cert_store(context);
783   X509_STORE_set_flags(cert_store,
784                        X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST);
785   return x509_store_load_certs(cert_store, pem_roots, pem_roots_size,
786                                root_name);
787 }
788
789 /* Populates the SSL context with a private key and a cert chain, and sets the
790    cipher list and the ephemeral ECDH key. */
791 static tsi_result populate_ssl_context(
792     SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
793     const char* cipher_list) {
794   tsi_result result = TSI_OK;
795   if (key_cert_pair != nullptr) {
796     if (key_cert_pair->cert_chain != nullptr) {
797       result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
798                                              strlen(key_cert_pair->cert_chain));
799       if (result != TSI_OK) {
800         gpr_log(GPR_ERROR, "Invalid cert chain file.");
801         return result;
802       }
803     }
804     if (key_cert_pair->private_key != nullptr) {
805       result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
806                                        strlen(key_cert_pair->private_key));
807       if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
808         gpr_log(GPR_ERROR, "Invalid private key.");
809         return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
810       }
811     }
812   }
813   if ((cipher_list != nullptr) &&
814       !SSL_CTX_set_cipher_list(context, cipher_list)) {
815     gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
816     return TSI_INVALID_ARGUMENT;
817   }
818   {
819     EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
820     if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
821       gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
822       EC_KEY_free(ecdh);
823       return TSI_INTERNAL_ERROR;
824     }
825     SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
826     EC_KEY_free(ecdh);
827   }
828   return TSI_OK;
829 }
830
831 /* Extracts the CN and the SANs from an X509 cert as a peer object. */
832 tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
833     const char* pem_cert, tsi_peer* peer) {
834   tsi_result result = TSI_OK;
835   X509* cert = nullptr;
836   BIO* pem;
837   pem = BIO_new_mem_buf(pem_cert, static_cast<int>(strlen(pem_cert)));
838   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
839
840   cert = PEM_read_bio_X509(pem, nullptr, nullptr, const_cast<char*>(""));
841   if (cert == nullptr) {
842     gpr_log(GPR_ERROR, "Invalid certificate");
843     result = TSI_INVALID_ARGUMENT;
844   } else {
845     result = peer_from_x509(cert, 0, peer);
846   }
847   if (cert != nullptr) X509_free(cert);
848   BIO_free(pem);
849   return result;
850 }
851
852 /* Builds the alpn protocol name list according to rfc 7301. */
853 static tsi_result build_alpn_protocol_name_list(
854     const char** alpn_protocols, uint16_t num_alpn_protocols,
855     unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
856   uint16_t i;
857   unsigned char* current;
858   *protocol_name_list = nullptr;
859   *protocol_name_list_length = 0;
860   if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
861   for (i = 0; i < num_alpn_protocols; i++) {
862     size_t length =
863         alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
864     if (length == 0 || length > 255) {
865       gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
866               static_cast<int>(length));
867       return TSI_INVALID_ARGUMENT;
868     }
869     *protocol_name_list_length += length + 1;
870   }
871   *protocol_name_list =
872       static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
873   if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
874   current = *protocol_name_list;
875   for (i = 0; i < num_alpn_protocols; i++) {
876     size_t length = strlen(alpn_protocols[i]);
877     *(current++) = static_cast<uint8_t>(length); /* max checked above. */
878     memcpy(current, alpn_protocols[i], length);
879     current += length;
880   }
881   /* Safety check. */
882   if ((current < *protocol_name_list) ||
883       (static_cast<uintptr_t>(current - *protocol_name_list) !=
884        *protocol_name_list_length)) {
885     return TSI_INTERNAL_ERROR;
886   }
887   return TSI_OK;
888 }
889
890 // The verification callback is used for clients that don't really care about
891 // the server's certificate, but we need to pull it anyway, in case a higher
892 // layer wants to look at it. In this case the verification may fail, but
893 // we don't really care.
894 static int NullVerifyCallback(int /*preverify_ok*/, X509_STORE_CTX* /*ctx*/) {
895   return 1;
896 }
897
898 // Sets the min and max TLS version of |ssl_context| to |min_tls_version| and
899 // |max_tls_version|, respectively. Calling this method is a no-op when using
900 // OpenSSL versions < 1.1.
901 static tsi_result tsi_set_min_and_max_tls_versions(
902     SSL_CTX* ssl_context, tsi_tls_version min_tls_version,
903     tsi_tls_version max_tls_version) {
904   if (ssl_context == nullptr) {
905     gpr_log(GPR_INFO,
906             "Invalid nullptr argument to |tsi_set_min_and_max_tls_versions|.");
907     return TSI_INVALID_ARGUMENT;
908   }
909 #if OPENSSL_VERSION_NUMBER >= 0x10100000
910   // Set the min TLS version of the SSL context if using OpenSSL version
911   // >= 1.1.0. This OpenSSL version is required because the
912   // |SSL_CTX_set_min_proto_version| and |SSL_CTX_set_max_proto_version| APIs
913   // only exist in this version range.
914   switch (min_tls_version) {
915     case tsi_tls_version::TSI_TLS1_2:
916       SSL_CTX_set_min_proto_version(ssl_context, TLS1_2_VERSION);
917       break;
918 #if defined(TLS1_3_VERSION)
919     // If the library does not support TLS 1.3 and the caller requests a minimum
920     // of TLS 1.3, then return an error because the caller's request cannot be
921     // satisfied.
922     case tsi_tls_version::TSI_TLS1_3:
923       SSL_CTX_set_min_proto_version(ssl_context, TLS1_3_VERSION);
924       break;
925 #endif
926     default:
927       gpr_log(GPR_INFO, "TLS version is not supported.");
928       return TSI_FAILED_PRECONDITION;
929   }
930
931   // Set the max TLS version of the SSL context.
932   switch (max_tls_version) {
933     case tsi_tls_version::TSI_TLS1_2:
934       SSL_CTX_set_max_proto_version(ssl_context, TLS1_2_VERSION);
935       break;
936     case tsi_tls_version::TSI_TLS1_3:
937 #if defined(TLS1_3_VERSION)
938       SSL_CTX_set_max_proto_version(ssl_context, TLS1_3_VERSION);
939 #else
940       // If the library does not support TLS 1.3, then set the max TLS version
941       // to TLS 1.2 instead.
942       SSL_CTX_set_max_proto_version(ssl_context, TLS1_2_VERSION);
943 #endif
944       break;
945     default:
946       gpr_log(GPR_INFO, "TLS version is not supported.");
947       return TSI_FAILED_PRECONDITION;
948   }
949 #endif
950   return TSI_OK;
951 }
952
953 /* --- tsi_ssl_root_certs_store methods implementation. ---*/
954
955 tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
956     const char* pem_roots) {
957   if (pem_roots == nullptr) {
958     gpr_log(GPR_ERROR, "The root certificates are empty.");
959     return nullptr;
960   }
961   tsi_ssl_root_certs_store* root_store = static_cast<tsi_ssl_root_certs_store*>(
962       gpr_zalloc(sizeof(tsi_ssl_root_certs_store)));
963   if (root_store == nullptr) {
964     gpr_log(GPR_ERROR, "Could not allocate buffer for ssl_root_certs_store.");
965     return nullptr;
966   }
967   root_store->store = X509_STORE_new();
968   if (root_store->store == nullptr) {
969     gpr_log(GPR_ERROR, "Could not allocate buffer for X509_STORE.");
970     gpr_free(root_store);
971     return nullptr;
972   }
973   tsi_result result = x509_store_load_certs(root_store->store, pem_roots,
974                                             strlen(pem_roots), nullptr);
975   if (result != TSI_OK) {
976     gpr_log(GPR_ERROR, "Could not load root certificates.");
977     X509_STORE_free(root_store->store);
978     gpr_free(root_store);
979     return nullptr;
980   }
981   return root_store;
982 }
983
984 void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self) {
985   if (self == nullptr) return;
986   X509_STORE_free(self->store);
987   gpr_free(self);
988 }
989
990 /* --- tsi_ssl_session_cache methods implementation. ---*/
991
992 tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity) {
993   /* Pointer will be dereferenced by unref call. */
994   return reinterpret_cast<tsi_ssl_session_cache*>(
995       tsi::SslSessionLRUCache::Create(capacity).release());
996 }
997
998 void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache) {
999   /* Pointer will be dereferenced by unref call. */
1000   reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Ref().release();
1001 }
1002
1003 void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
1004   reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
1005 }
1006
1007 /* --- tsi_frame_protector methods implementation. ---*/
1008
1009 static tsi_result ssl_protector_protect(tsi_frame_protector* self,
1010                                         const unsigned char* unprotected_bytes,
1011                                         size_t* unprotected_bytes_size,
1012                                         unsigned char* protected_output_frames,
1013                                         size_t* protected_output_frames_size) {
1014   tsi_ssl_frame_protector* impl =
1015       reinterpret_cast<tsi_ssl_frame_protector*>(self);
1016   int read_from_ssl;
1017   size_t available;
1018   tsi_result result = TSI_OK;
1019
1020   /* First see if we have some pending data in the SSL BIO. */
1021   int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
1022   if (pending_in_ssl > 0) {
1023     *unprotected_bytes_size = 0;
1024     GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1025     read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1026                              static_cast<int>(*protected_output_frames_size));
1027     if (read_from_ssl < 0) {
1028       gpr_log(GPR_ERROR,
1029               "Could not read from BIO even though some data is pending");
1030       return TSI_INTERNAL_ERROR;
1031     }
1032     *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1033     return TSI_OK;
1034   }
1035
1036   /* Now see if we can send a complete frame. */
1037   available = impl->buffer_size - impl->buffer_offset;
1038   if (available > *unprotected_bytes_size) {
1039     /* If we cannot, just copy the data in our internal buffer. */
1040     memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
1041            *unprotected_bytes_size);
1042     impl->buffer_offset += *unprotected_bytes_size;
1043     *protected_output_frames_size = 0;
1044     return TSI_OK;
1045   }
1046
1047   /* If we can, prepare the buffer, send it to SSL_write and read. */
1048   memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
1049   result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
1050   if (result != TSI_OK) return result;
1051
1052   GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1053   read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1054                            static_cast<int>(*protected_output_frames_size));
1055   if (read_from_ssl < 0) {
1056     gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
1057     return TSI_INTERNAL_ERROR;
1058   }
1059   *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1060   *unprotected_bytes_size = available;
1061   impl->buffer_offset = 0;
1062   return TSI_OK;
1063 }
1064
1065 static tsi_result ssl_protector_protect_flush(
1066     tsi_frame_protector* self, unsigned char* protected_output_frames,
1067     size_t* protected_output_frames_size, size_t* still_pending_size) {
1068   tsi_result result = TSI_OK;
1069   tsi_ssl_frame_protector* impl =
1070       reinterpret_cast<tsi_ssl_frame_protector*>(self);
1071   int read_from_ssl = 0;
1072   int pending;
1073
1074   if (impl->buffer_offset != 0) {
1075     result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
1076     if (result != TSI_OK) return result;
1077     impl->buffer_offset = 0;
1078   }
1079
1080   pending = static_cast<int>(BIO_pending(impl->network_io));
1081   GPR_ASSERT(pending >= 0);
1082   *still_pending_size = static_cast<size_t>(pending);
1083   if (*still_pending_size == 0) return TSI_OK;
1084
1085   GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
1086   read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
1087                            static_cast<int>(*protected_output_frames_size));
1088   if (read_from_ssl <= 0) {
1089     gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
1090     return TSI_INTERNAL_ERROR;
1091   }
1092   *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
1093   pending = static_cast<int>(BIO_pending(impl->network_io));
1094   GPR_ASSERT(pending >= 0);
1095   *still_pending_size = static_cast<size_t>(pending);
1096   return TSI_OK;
1097 }
1098
1099 static tsi_result ssl_protector_unprotect(
1100     tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
1101     size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
1102     size_t* unprotected_bytes_size) {
1103   tsi_result result = TSI_OK;
1104   int written_into_ssl = 0;
1105   size_t output_bytes_size = *unprotected_bytes_size;
1106   size_t output_bytes_offset = 0;
1107   tsi_ssl_frame_protector* impl =
1108       reinterpret_cast<tsi_ssl_frame_protector*>(self);
1109
1110   /* First, try to read remaining data from ssl. */
1111   result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
1112   if (result != TSI_OK) return result;
1113   if (*unprotected_bytes_size == output_bytes_size) {
1114     /* We have read everything we could and cannot process any more input. */
1115     *protected_frames_bytes_size = 0;
1116     return TSI_OK;
1117   }
1118   output_bytes_offset = *unprotected_bytes_size;
1119   unprotected_bytes += output_bytes_offset;
1120   *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
1121
1122   /* Then, try to write some data to ssl. */
1123   GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
1124   written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
1125                                static_cast<int>(*protected_frames_bytes_size));
1126   if (written_into_ssl < 0) {
1127     gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
1128             written_into_ssl);
1129     return TSI_INTERNAL_ERROR;
1130   }
1131   *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
1132
1133   /* Now try to read some data again. */
1134   result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
1135   if (result == TSI_OK) {
1136     /* Don't forget to output the total number of bytes read. */
1137     *unprotected_bytes_size += output_bytes_offset;
1138   }
1139   return result;
1140 }
1141
1142 static void ssl_protector_destroy(tsi_frame_protector* self) {
1143   tsi_ssl_frame_protector* impl =
1144       reinterpret_cast<tsi_ssl_frame_protector*>(self);
1145   if (impl->buffer != nullptr) gpr_free(impl->buffer);
1146   if (impl->ssl != nullptr) SSL_free(impl->ssl);
1147   if (impl->network_io != nullptr) BIO_free(impl->network_io);
1148   gpr_free(self);
1149 }
1150
1151 static const tsi_frame_protector_vtable frame_protector_vtable = {
1152     ssl_protector_protect,
1153     ssl_protector_protect_flush,
1154     ssl_protector_unprotect,
1155     ssl_protector_destroy,
1156 };
1157
1158 /* --- tsi_server_handshaker_factory methods implementation. --- */
1159
1160 static void tsi_ssl_handshaker_factory_destroy(
1161     tsi_ssl_handshaker_factory* factory) {
1162   if (factory == nullptr) return;
1163
1164   if (factory->vtable != nullptr && factory->vtable->destroy != nullptr) {
1165     factory->vtable->destroy(factory);
1166   }
1167   /* Note, we don't free(self) here because this object is always directly
1168    * embedded in another object. If tsi_ssl_handshaker_factory_init allocates
1169    * any memory, it should be free'd here. */
1170 }
1171
1172 static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
1173     tsi_ssl_handshaker_factory* factory) {
1174   if (factory == nullptr) return nullptr;
1175   gpr_refn(&factory->refcount, 1);
1176   return factory;
1177 }
1178
1179 static void tsi_ssl_handshaker_factory_unref(
1180     tsi_ssl_handshaker_factory* factory) {
1181   if (factory == nullptr) return;
1182
1183   if (gpr_unref(&factory->refcount)) {
1184     tsi_ssl_handshaker_factory_destroy(factory);
1185   }
1186 }
1187
1188 static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
1189
1190 /* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
1191  * allocating memory for the factory. */
1192 static void tsi_ssl_handshaker_factory_init(
1193     tsi_ssl_handshaker_factory* factory) {
1194   GPR_ASSERT(factory != nullptr);
1195
1196   factory->vtable = &handshaker_factory_vtable;
1197   gpr_ref_init(&factory->refcount, 1);
1198 }
1199
1200 /* Gets the X509 cert chain in PEM format as a tsi_peer_property. */
1201 tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
1202                                            tsi_peer_property* property) {
1203   BIO* bio = BIO_new(BIO_s_mem());
1204   const auto peer_chain_len = sk_X509_num(peer_chain);
1205   for (auto i = decltype(peer_chain_len){0}; i < peer_chain_len; i++) {
1206     if (!PEM_write_bio_X509(bio, sk_X509_value(peer_chain, i))) {
1207       BIO_free(bio);
1208       return TSI_INTERNAL_ERROR;
1209     }
1210   }
1211   char* contents;
1212   long len = BIO_get_mem_data(bio, &contents);
1213   if (len <= 0) {
1214     BIO_free(bio);
1215     return TSI_INTERNAL_ERROR;
1216   }
1217   tsi_result result = tsi_construct_string_peer_property(
1218       TSI_X509_PEM_CERT_CHAIN_PROPERTY, contents, static_cast<size_t>(len),
1219       property);
1220   BIO_free(bio);
1221   return result;
1222 }
1223
1224 /* --- tsi_handshaker_result methods implementation. ---*/
1225 static tsi_result ssl_handshaker_result_extract_peer(
1226     const tsi_handshaker_result* self, tsi_peer* peer) {
1227   tsi_result result = TSI_OK;
1228   const unsigned char* alpn_selected = nullptr;
1229   unsigned int alpn_selected_len;
1230   const tsi_ssl_handshaker_result* impl =
1231       reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1232   X509* peer_cert = SSL_get_peer_certificate(impl->ssl);
1233   if (peer_cert != nullptr) {
1234     result = peer_from_x509(peer_cert, 1, peer);
1235     X509_free(peer_cert);
1236     if (result != TSI_OK) return result;
1237   }
1238 #if TSI_OPENSSL_ALPN_SUPPORT
1239   SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
1240 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1241   if (alpn_selected == nullptr) {
1242     /* Try npn. */
1243     SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
1244                                    &alpn_selected_len);
1245   }
1246   // When called on the client side, the stack also contains the
1247   // peer's certificate; When called on the server side,
1248   // the peer's certificate is not present in the stack
1249   STACK_OF(X509)* peer_chain = SSL_get_peer_cert_chain(impl->ssl);
1250   // 1 is for session reused property.
1251   size_t new_property_count = peer->property_count + 3;
1252   if (alpn_selected != nullptr) new_property_count++;
1253   if (peer_chain != nullptr) new_property_count++;
1254   tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
1255       gpr_zalloc(sizeof(*new_properties) * new_property_count));
1256   for (size_t i = 0; i < peer->property_count; i++) {
1257     new_properties[i] = peer->properties[i];
1258   }
1259   if (peer->properties != nullptr) gpr_free(peer->properties);
1260   peer->properties = new_properties;
1261   // Add peer chain if available
1262   if (peer_chain != nullptr) {
1263     result = tsi_ssl_get_cert_chain_contents(
1264         peer_chain, &peer->properties[peer->property_count]);
1265     if (result == TSI_OK) peer->property_count++;
1266   }
1267   if (alpn_selected != nullptr) {
1268     result = tsi_construct_string_peer_property(
1269         TSI_SSL_ALPN_SELECTED_PROTOCOL,
1270         reinterpret_cast<const char*>(alpn_selected), alpn_selected_len,
1271         &peer->properties[peer->property_count]);
1272     if (result != TSI_OK) return result;
1273     peer->property_count++;
1274   }
1275   // Add security_level peer property.
1276   result = tsi_construct_string_peer_property_from_cstring(
1277       TSI_SECURITY_LEVEL_PEER_PROPERTY,
1278       tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY),
1279       &peer->properties[peer->property_count]);
1280   if (result != TSI_OK) return result;
1281   peer->property_count++;
1282
1283   const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false";
1284   result = tsi_construct_string_peer_property_from_cstring(
1285       TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused,
1286       &peer->properties[peer->property_count]);
1287   if (result != TSI_OK) return result;
1288   peer->property_count++;
1289   return result;
1290 }
1291
1292 static tsi_result ssl_handshaker_result_create_frame_protector(
1293     const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
1294     tsi_frame_protector** protector) {
1295   size_t actual_max_output_protected_frame_size =
1296       TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1297   tsi_ssl_handshaker_result* impl =
1298       reinterpret_cast<tsi_ssl_handshaker_result*>(
1299           const_cast<tsi_handshaker_result*>(self));
1300   tsi_ssl_frame_protector* protector_impl =
1301       static_cast<tsi_ssl_frame_protector*>(
1302           gpr_zalloc(sizeof(*protector_impl)));
1303
1304   if (max_output_protected_frame_size != nullptr) {
1305     if (*max_output_protected_frame_size >
1306         TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) {
1307       *max_output_protected_frame_size =
1308           TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1309     } else if (*max_output_protected_frame_size <
1310                TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND) {
1311       *max_output_protected_frame_size =
1312           TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND;
1313     }
1314     actual_max_output_protected_frame_size = *max_output_protected_frame_size;
1315   }
1316   protector_impl->buffer_size =
1317       actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD;
1318   protector_impl->buffer =
1319       static_cast<unsigned char*>(gpr_malloc(protector_impl->buffer_size));
1320   if (protector_impl->buffer == nullptr) {
1321     gpr_log(GPR_ERROR,
1322             "Could not allocated buffer for tsi_ssl_frame_protector.");
1323     gpr_free(protector_impl);
1324     return TSI_INTERNAL_ERROR;
1325   }
1326
1327   /* Transfer ownership of ssl and network_io to the frame protector. */
1328   protector_impl->ssl = impl->ssl;
1329   impl->ssl = nullptr;
1330   protector_impl->network_io = impl->network_io;
1331   impl->network_io = nullptr;
1332   protector_impl->base.vtable = &frame_protector_vtable;
1333   *protector = &protector_impl->base;
1334   return TSI_OK;
1335 }
1336
1337 static tsi_result ssl_handshaker_result_get_unused_bytes(
1338     const tsi_handshaker_result* self, const unsigned char** bytes,
1339     size_t* bytes_size) {
1340   const tsi_ssl_handshaker_result* impl =
1341       reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1342   *bytes_size = impl->unused_bytes_size;
1343   *bytes = impl->unused_bytes;
1344   return TSI_OK;
1345 }
1346
1347 static void ssl_handshaker_result_destroy(tsi_handshaker_result* self) {
1348   tsi_ssl_handshaker_result* impl =
1349       reinterpret_cast<tsi_ssl_handshaker_result*>(self);
1350   SSL_free(impl->ssl);
1351   BIO_free(impl->network_io);
1352   gpr_free(impl->unused_bytes);
1353   gpr_free(impl);
1354 }
1355
1356 static const tsi_handshaker_result_vtable handshaker_result_vtable = {
1357     ssl_handshaker_result_extract_peer,
1358     nullptr, /* create_zero_copy_grpc_protector */
1359     ssl_handshaker_result_create_frame_protector,
1360     ssl_handshaker_result_get_unused_bytes,
1361     ssl_handshaker_result_destroy,
1362 };
1363
1364 static tsi_result ssl_handshaker_result_create(
1365     tsi_ssl_handshaker* handshaker, unsigned char* unused_bytes,
1366     size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) {
1367   if (handshaker == nullptr || handshaker_result == nullptr ||
1368       (unused_bytes_size > 0 && unused_bytes == nullptr)) {
1369     return TSI_INVALID_ARGUMENT;
1370   }
1371   tsi_ssl_handshaker_result* result =
1372       static_cast<tsi_ssl_handshaker_result*>(gpr_zalloc(sizeof(*result)));
1373   result->base.vtable = &handshaker_result_vtable;
1374   /* Transfer ownership of ssl and network_io to the handshaker result. */
1375   result->ssl = handshaker->ssl;
1376   handshaker->ssl = nullptr;
1377   result->network_io = handshaker->network_io;
1378   handshaker->network_io = nullptr;
1379   /* Transfer ownership of |unused_bytes| to the handshaker result. */
1380   result->unused_bytes = unused_bytes;
1381   result->unused_bytes_size = unused_bytes_size;
1382   *handshaker_result = &result->base;
1383   return TSI_OK;
1384 }
1385
1386 /* --- tsi_handshaker methods implementation. ---*/
1387
1388 static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(
1389     tsi_ssl_handshaker* impl, unsigned char* bytes, size_t* bytes_size) {
1390   int bytes_read_from_ssl = 0;
1391   if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 ||
1392       *bytes_size > INT_MAX) {
1393     return TSI_INVALID_ARGUMENT;
1394   }
1395   GPR_ASSERT(*bytes_size <= INT_MAX);
1396   bytes_read_from_ssl =
1397       BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size));
1398   if (bytes_read_from_ssl < 0) {
1399     *bytes_size = 0;
1400     if (!BIO_should_retry(impl->network_io)) {
1401       impl->result = TSI_INTERNAL_ERROR;
1402       return impl->result;
1403     } else {
1404       return TSI_OK;
1405     }
1406   }
1407   *bytes_size = static_cast<size_t>(bytes_read_from_ssl);
1408   return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
1409 }
1410
1411 static tsi_result ssl_handshaker_get_result(tsi_ssl_handshaker* impl) {
1412   if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) &&
1413       SSL_is_init_finished(impl->ssl)) {
1414     impl->result = TSI_OK;
1415   }
1416   return impl->result;
1417 }
1418
1419 static tsi_result ssl_handshaker_process_bytes_from_peer(
1420     tsi_ssl_handshaker* impl, const unsigned char* bytes, size_t* bytes_size) {
1421   int bytes_written_into_ssl_size = 0;
1422   if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) {
1423     return TSI_INVALID_ARGUMENT;
1424   }
1425   GPR_ASSERT(*bytes_size <= INT_MAX);
1426   bytes_written_into_ssl_size =
1427       BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size));
1428   if (bytes_written_into_ssl_size < 0) {
1429     gpr_log(GPR_ERROR, "Could not write to memory BIO.");
1430     impl->result = TSI_INTERNAL_ERROR;
1431     return impl->result;
1432   }
1433   *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size);
1434
1435   if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) {
1436     impl->result = TSI_OK;
1437     return impl->result;
1438   } else {
1439     /* Get ready to get some bytes from SSL. */
1440     int ssl_result = SSL_do_handshake(impl->ssl);
1441     ssl_result = SSL_get_error(impl->ssl, ssl_result);
1442     switch (ssl_result) {
1443       case SSL_ERROR_WANT_READ:
1444         if (BIO_pending(impl->network_io) == 0) {
1445           /* We need more data. */
1446           return TSI_INCOMPLETE_DATA;
1447         } else {
1448           return TSI_OK;
1449         }
1450       case SSL_ERROR_NONE:
1451         return TSI_OK;
1452       default: {
1453         char err_str[256];
1454         ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1455         gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.",
1456                 ssl_error_string(ssl_result), err_str);
1457         impl->result = TSI_PROTOCOL_FAILURE;
1458         return impl->result;
1459       }
1460     }
1461   }
1462 }
1463
1464 static void ssl_handshaker_destroy(tsi_handshaker* self) {
1465   tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1466   SSL_free(impl->ssl);
1467   BIO_free(impl->network_io);
1468   gpr_free(impl->outgoing_bytes_buffer);
1469   tsi_ssl_handshaker_factory_unref(impl->factory_ref);
1470   gpr_free(impl);
1471 }
1472
1473 // Removes the bytes remaining in |impl->SSL|'s read BIO and writes them to
1474 // |bytes_remaining|.
1475 static tsi_result ssl_bytes_remaining(tsi_ssl_handshaker* impl,
1476                                       unsigned char** bytes_remaining,
1477                                       size_t* bytes_remaining_size) {
1478   if (impl == nullptr || bytes_remaining == nullptr ||
1479       bytes_remaining_size == nullptr) {
1480     return TSI_INVALID_ARGUMENT;
1481   }
1482   // Atempt to read all of the bytes in SSL's read BIO. These bytes should
1483   // contain application data records that were appended to a handshake record
1484   // containing the ClientFinished or ServerFinished message.
1485   size_t bytes_in_ssl = BIO_pending(SSL_get_rbio(impl->ssl));
1486   if (bytes_in_ssl == 0) return TSI_OK;
1487   *bytes_remaining = static_cast<uint8_t*>(gpr_malloc(bytes_in_ssl));
1488   int bytes_read = BIO_read(SSL_get_rbio(impl->ssl), *bytes_remaining,
1489                             static_cast<int>(bytes_in_ssl));
1490   // If an unexpected number of bytes were read, return an error status and free
1491   // all of the bytes that were read.
1492   if (bytes_read < 0 || static_cast<size_t>(bytes_read) != bytes_in_ssl) {
1493     gpr_log(GPR_ERROR,
1494             "Failed to read the expected number of bytes from SSL object.");
1495     gpr_free(*bytes_remaining);
1496     *bytes_remaining = nullptr;
1497     return TSI_INTERNAL_ERROR;
1498   }
1499   *bytes_remaining_size = static_cast<size_t>(bytes_read);
1500   return TSI_OK;
1501 }
1502
1503 static tsi_result ssl_handshaker_next(
1504     tsi_handshaker* self, const unsigned char* received_bytes,
1505     size_t received_bytes_size, const unsigned char** bytes_to_send,
1506     size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
1507     tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
1508   /* Input sanity check.  */
1509   if ((received_bytes_size > 0 && received_bytes == nullptr) ||
1510       bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
1511       handshaker_result == nullptr) {
1512     return TSI_INVALID_ARGUMENT;
1513   }
1514   /* If there are received bytes, process them first.  */
1515   tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1516   tsi_result status = TSI_OK;
1517   size_t bytes_consumed = received_bytes_size;
1518   if (received_bytes_size > 0) {
1519     status = ssl_handshaker_process_bytes_from_peer(impl, received_bytes,
1520                                                     &bytes_consumed);
1521     if (status != TSI_OK) return status;
1522   }
1523   /* Get bytes to send to the peer, if available.  */
1524   size_t offset = 0;
1525   do {
1526     size_t to_send_size = impl->outgoing_bytes_buffer_size - offset;
1527     status = ssl_handshaker_get_bytes_to_send_to_peer(
1528         impl, impl->outgoing_bytes_buffer + offset, &to_send_size);
1529     offset += to_send_size;
1530     if (status == TSI_INCOMPLETE_DATA) {
1531       impl->outgoing_bytes_buffer_size *= 2;
1532       impl->outgoing_bytes_buffer = static_cast<unsigned char*>(gpr_realloc(
1533           impl->outgoing_bytes_buffer, impl->outgoing_bytes_buffer_size));
1534     }
1535   } while (status == TSI_INCOMPLETE_DATA);
1536   if (status != TSI_OK) return status;
1537   *bytes_to_send = impl->outgoing_bytes_buffer;
1538   *bytes_to_send_size = offset;
1539   /* If handshake completes, create tsi_handshaker_result.  */
1540   if (ssl_handshaker_get_result(impl) == TSI_HANDSHAKE_IN_PROGRESS) {
1541     *handshaker_result = nullptr;
1542   } else {
1543     // Any bytes that remain in |impl->ssl|'s read BIO after the handshake is
1544     // complete must be extracted and set to the unused bytes of the handshaker
1545     // result. This indicates to the gRPC stack that there are bytes from the
1546     // peer that must be processed.
1547     unsigned char* unused_bytes = nullptr;
1548     size_t unused_bytes_size = 0;
1549     status = ssl_bytes_remaining(impl, &unused_bytes, &unused_bytes_size);
1550     if (status != TSI_OK) return status;
1551     if (unused_bytes_size > received_bytes_size) {
1552       gpr_log(GPR_ERROR, "More unused bytes than received bytes.");
1553       gpr_free(unused_bytes);
1554       return TSI_INTERNAL_ERROR;
1555     }
1556     status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size,
1557                                           handshaker_result);
1558     if (status == TSI_OK) {
1559       /* Indicates that the handshake has completed and that a handshaker_result
1560        * has been created. */
1561       self->handshaker_result_created = true;
1562     }
1563   }
1564   return status;
1565 }
1566
1567 static const tsi_handshaker_vtable handshaker_vtable = {
1568     nullptr, /* get_bytes_to_send_to_peer -- deprecated */
1569     nullptr, /* process_bytes_from_peer   -- deprecated */
1570     nullptr, /* get_result                -- deprecated */
1571     nullptr, /* extract_peer              -- deprecated */
1572     nullptr, /* create_frame_protector    -- deprecated */
1573     ssl_handshaker_destroy,
1574     ssl_handshaker_next,
1575     nullptr, /* shutdown */
1576 };
1577
1578 /* --- tsi_ssl_handshaker_factory common methods. --- */
1579
1580 static void tsi_ssl_handshaker_resume_session(
1581     SSL* ssl, tsi::SslSessionLRUCache* session_cache) {
1582   const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1583   if (server_name == nullptr) {
1584     return;
1585   }
1586   tsi::SslSessionPtr session = session_cache->Get(server_name);
1587   if (session != nullptr) {
1588     // SSL_set_session internally increments reference counter.
1589     SSL_set_session(ssl, session.get());
1590   }
1591 }
1592
1593 static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
1594                                             const char* server_name_indication,
1595                                             tsi_ssl_handshaker_factory* factory,
1596                                             tsi_handshaker** handshaker) {
1597   SSL* ssl = SSL_new(ctx);
1598   BIO* network_io = nullptr;
1599   BIO* ssl_io = nullptr;
1600   tsi_ssl_handshaker* impl = nullptr;
1601   *handshaker = nullptr;
1602   if (ctx == nullptr) {
1603     gpr_log(GPR_ERROR, "SSL Context is null. Should never happen.");
1604     return TSI_INTERNAL_ERROR;
1605   }
1606   if (ssl == nullptr) {
1607     return TSI_OUT_OF_RESOURCES;
1608   }
1609   SSL_set_info_callback(ssl, ssl_info_callback);
1610
1611   if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
1612     gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
1613     SSL_free(ssl);
1614     return TSI_OUT_OF_RESOURCES;
1615   }
1616   SSL_set_bio(ssl, ssl_io, ssl_io);
1617   if (is_client) {
1618     int ssl_result;
1619     SSL_set_connect_state(ssl);
1620     if (server_name_indication != nullptr) {
1621       if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) {
1622         gpr_log(GPR_ERROR, "Invalid server name indication %s.",
1623                 server_name_indication);
1624         SSL_free(ssl);
1625         BIO_free(network_io);
1626         return TSI_INTERNAL_ERROR;
1627       }
1628     }
1629     tsi_ssl_client_handshaker_factory* client_factory =
1630         reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1631     if (client_factory->session_cache != nullptr) {
1632       tsi_ssl_handshaker_resume_session(ssl,
1633                                         client_factory->session_cache.get());
1634     }
1635     ssl_result = SSL_do_handshake(ssl);
1636     ssl_result = SSL_get_error(ssl, ssl_result);
1637     if (ssl_result != SSL_ERROR_WANT_READ) {
1638       gpr_log(GPR_ERROR,
1639               "Unexpected error received from first SSL_do_handshake call: %s",
1640               ssl_error_string(ssl_result));
1641       SSL_free(ssl);
1642       BIO_free(network_io);
1643       return TSI_INTERNAL_ERROR;
1644     }
1645   } else {
1646     SSL_set_accept_state(ssl);
1647   }
1648
1649   impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
1650   impl->ssl = ssl;
1651   impl->network_io = network_io;
1652   impl->result = TSI_HANDSHAKE_IN_PROGRESS;
1653   impl->outgoing_bytes_buffer_size =
1654       TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
1655   impl->outgoing_bytes_buffer =
1656       static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size));
1657   impl->base.vtable = &handshaker_vtable;
1658   impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory);
1659   *handshaker = &impl->base;
1660   return TSI_OK;
1661 }
1662
1663 static int select_protocol_list(const unsigned char** out,
1664                                 unsigned char* outlen,
1665                                 const unsigned char* client_list,
1666                                 size_t client_list_len,
1667                                 const unsigned char* server_list,
1668                                 size_t server_list_len) {
1669   const unsigned char* client_current = client_list;
1670   while (static_cast<unsigned int>(client_current - client_list) <
1671          client_list_len) {
1672     unsigned char client_current_len = *(client_current++);
1673     const unsigned char* server_current = server_list;
1674     while ((server_current >= server_list) &&
1675            static_cast<uintptr_t>(server_current - server_list) <
1676                server_list_len) {
1677       unsigned char server_current_len = *(server_current++);
1678       if ((client_current_len == server_current_len) &&
1679           !memcmp(client_current, server_current, server_current_len)) {
1680         *out = server_current;
1681         *outlen = server_current_len;
1682         return SSL_TLSEXT_ERR_OK;
1683       }
1684       server_current += server_current_len;
1685     }
1686     client_current += client_current_len;
1687   }
1688   return SSL_TLSEXT_ERR_NOACK;
1689 }
1690
1691 /* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
1692
1693 tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
1694     tsi_ssl_client_handshaker_factory* factory,
1695     const char* server_name_indication, tsi_handshaker** handshaker) {
1696   return create_tsi_ssl_handshaker(factory->ssl_context, 1,
1697                                    server_name_indication, &factory->base,
1698                                    handshaker);
1699 }
1700
1701 void tsi_ssl_client_handshaker_factory_unref(
1702     tsi_ssl_client_handshaker_factory* factory) {
1703   if (factory == nullptr) return;
1704   tsi_ssl_handshaker_factory_unref(&factory->base);
1705 }
1706
1707 static void tsi_ssl_client_handshaker_factory_destroy(
1708     tsi_ssl_handshaker_factory* factory) {
1709   if (factory == nullptr) return;
1710   tsi_ssl_client_handshaker_factory* self =
1711       reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1712   if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context);
1713   if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1714   self->session_cache.reset();
1715   gpr_free(self);
1716 }
1717
1718 static int client_handshaker_factory_npn_callback(
1719     SSL* /*ssl*/, unsigned char** out, unsigned char* outlen,
1720     const unsigned char* in, unsigned int inlen, void* arg) {
1721   tsi_ssl_client_handshaker_factory* factory =
1722       static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1723   return select_protocol_list(const_cast<const unsigned char**>(out), outlen,
1724                               factory->alpn_protocol_list,
1725                               factory->alpn_protocol_list_length, in, inlen);
1726 }
1727
1728 /* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
1729
1730 tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
1731     tsi_ssl_server_handshaker_factory* factory, tsi_handshaker** handshaker) {
1732   if (factory->ssl_context_count == 0) return TSI_INVALID_ARGUMENT;
1733   /* Create the handshaker with the first context. We will switch if needed
1734      because of SNI in ssl_server_handshaker_factory_servername_callback.  */
1735   return create_tsi_ssl_handshaker(factory->ssl_contexts[0], 0, nullptr,
1736                                    &factory->base, handshaker);
1737 }
1738
1739 void tsi_ssl_server_handshaker_factory_unref(
1740     tsi_ssl_server_handshaker_factory* factory) {
1741   if (factory == nullptr) return;
1742   tsi_ssl_handshaker_factory_unref(&factory->base);
1743 }
1744
1745 static void tsi_ssl_server_handshaker_factory_destroy(
1746     tsi_ssl_handshaker_factory* factory) {
1747   if (factory == nullptr) return;
1748   tsi_ssl_server_handshaker_factory* self =
1749       reinterpret_cast<tsi_ssl_server_handshaker_factory*>(factory);
1750   size_t i;
1751   for (i = 0; i < self->ssl_context_count; i++) {
1752     if (self->ssl_contexts[i] != nullptr) {
1753       SSL_CTX_free(self->ssl_contexts[i]);
1754       tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]);
1755     }
1756   }
1757   if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts);
1758   if (self->ssl_context_x509_subject_names != nullptr) {
1759     gpr_free(self->ssl_context_x509_subject_names);
1760   }
1761   if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1762   gpr_free(self);
1763 }
1764
1765 static int does_entry_match_name(absl::string_view entry,
1766                                  absl::string_view name) {
1767   if (entry.empty()) return 0;
1768
1769   /* Take care of '.' terminations. */
1770   if (name.back() == '.') {
1771     name.remove_suffix(1);
1772   }
1773   if (entry.back() == '.') {
1774     entry.remove_suffix(1);
1775     if (entry.empty()) return 0;
1776   }
1777
1778   if (absl::EqualsIgnoreCase(name, entry)) {
1779     return 1; /* Perfect match. */
1780   }
1781   if (entry.front() != '*') return 0;
1782
1783   /* Wildchar subdomain matching. */
1784   if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
1785     gpr_log(GPR_ERROR, "Invalid wildchar entry.");
1786     return 0;
1787   }
1788   size_t name_subdomain_pos = name.find('.');
1789   if (name_subdomain_pos == absl::string_view::npos) return 0;
1790   if (name_subdomain_pos >= name.size() - 2) return 0;
1791   absl::string_view name_subdomain =
1792       name.substr(name_subdomain_pos + 1); /* Starts after the dot. */
1793   entry.remove_prefix(2);                  /* Remove *. */
1794   size_t dot = name_subdomain.find('.');
1795   if (dot == absl::string_view::npos || dot == name_subdomain.size() - 1) {
1796     gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
1797             std::string(name_subdomain).c_str());
1798     return 0;
1799   }
1800   if (name_subdomain.back() == '.') {
1801     name_subdomain.remove_suffix(1);
1802   }
1803   return !entry.empty() && absl::EqualsIgnoreCase(name_subdomain, entry);
1804 }
1805
1806 static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
1807                                                              int* /*ap*/,
1808                                                              void* arg) {
1809   tsi_ssl_server_handshaker_factory* impl =
1810       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1811   size_t i = 0;
1812   const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1813   if (servername == nullptr || strlen(servername) == 0) {
1814     return SSL_TLSEXT_ERR_NOACK;
1815   }
1816
1817   for (i = 0; i < impl->ssl_context_count; i++) {
1818     if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
1819                                   servername)) {
1820       SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
1821       return SSL_TLSEXT_ERR_OK;
1822     }
1823   }
1824   gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
1825   return SSL_TLSEXT_ERR_NOACK;
1826 }
1827
1828 #if TSI_OPENSSL_ALPN_SUPPORT
1829 static int server_handshaker_factory_alpn_callback(
1830     SSL* /*ssl*/, const unsigned char** out, unsigned char* outlen,
1831     const unsigned char* in, unsigned int inlen, void* arg) {
1832   tsi_ssl_server_handshaker_factory* factory =
1833       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1834   return select_protocol_list(out, outlen, in, inlen,
1835                               factory->alpn_protocol_list,
1836                               factory->alpn_protocol_list_length);
1837 }
1838 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1839
1840 static int server_handshaker_factory_npn_advertised_callback(
1841     SSL* /*ssl*/, const unsigned char** out, unsigned int* outlen, void* arg) {
1842   tsi_ssl_server_handshaker_factory* factory =
1843       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1844   *out = factory->alpn_protocol_list;
1845   GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX);
1846   *outlen = static_cast<unsigned int>(factory->alpn_protocol_list_length);
1847   return SSL_TLSEXT_ERR_OK;
1848 }
1849
1850 /// This callback is called when new \a session is established and ready to
1851 /// be cached. This session can be reused for new connections to similar
1852 /// servers at later point of time.
1853 /// It's intended to be used with SSL_CTX_sess_set_new_cb function.
1854 ///
1855 /// It returns 1 if callback takes ownership over \a session and 0 otherwise.
1856 static int server_handshaker_factory_new_session_callback(
1857     SSL* ssl, SSL_SESSION* session) {
1858   SSL_CTX* ssl_context = SSL_get_SSL_CTX(ssl);
1859   if (ssl_context == nullptr) {
1860     return 0;
1861   }
1862   void* arg = SSL_CTX_get_ex_data(ssl_context, g_ssl_ctx_ex_factory_index);
1863   tsi_ssl_client_handshaker_factory* factory =
1864       static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1865   const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1866   if (server_name == nullptr) {
1867     return 0;
1868   }
1869   factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
1870   // Return 1 to indicate transferred ownership over the given session.
1871   return 1;
1872 }
1873
1874 /* --- tsi_ssl_handshaker_factory constructors. --- */
1875
1876 static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
1877     tsi_ssl_client_handshaker_factory_destroy};
1878
1879 tsi_result tsi_create_ssl_client_handshaker_factory(
1880     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
1881     const char* pem_root_certs, const char* cipher_suites,
1882     const char** alpn_protocols, uint16_t num_alpn_protocols,
1883     tsi_ssl_client_handshaker_factory** factory) {
1884   tsi_ssl_client_handshaker_options options;
1885   options.pem_key_cert_pair = pem_key_cert_pair;
1886   options.pem_root_certs = pem_root_certs;
1887   options.cipher_suites = cipher_suites;
1888   options.alpn_protocols = alpn_protocols;
1889   options.num_alpn_protocols = num_alpn_protocols;
1890   return tsi_create_ssl_client_handshaker_factory_with_options(&options,
1891                                                                factory);
1892 }
1893
1894 tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
1895     const tsi_ssl_client_handshaker_options* options,
1896     tsi_ssl_client_handshaker_factory** factory) {
1897   SSL_CTX* ssl_context = nullptr;
1898   tsi_ssl_client_handshaker_factory* impl = nullptr;
1899   tsi_result result = TSI_OK;
1900
1901   gpr_once_init(&g_init_openssl_once, init_openssl);
1902
1903   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
1904   *factory = nullptr;
1905   if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
1906     return TSI_INVALID_ARGUMENT;
1907   }
1908
1909 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1910   ssl_context = SSL_CTX_new(TLS_method());
1911 #else
1912   ssl_context = SSL_CTX_new(TLSv1_2_method());
1913 #endif
1914   result = tsi_set_min_and_max_tls_versions(
1915       ssl_context, options->min_tls_version, options->max_tls_version);
1916   if (result != TSI_OK) return result;
1917   if (ssl_context == nullptr) {
1918     gpr_log(GPR_ERROR, "Could not create ssl context.");
1919     return TSI_INVALID_ARGUMENT;
1920   }
1921
1922   impl = static_cast<tsi_ssl_client_handshaker_factory*>(
1923       gpr_zalloc(sizeof(*impl)));
1924   tsi_ssl_handshaker_factory_init(&impl->base);
1925   impl->base.vtable = &client_handshaker_factory_vtable;
1926   impl->ssl_context = ssl_context;
1927   if (options->session_cache != nullptr) {
1928     // Unref is called manually on factory destruction.
1929     impl->session_cache =
1930         reinterpret_cast<tsi::SslSessionLRUCache*>(options->session_cache)
1931             ->Ref();
1932     SSL_CTX_set_ex_data(ssl_context, g_ssl_ctx_ex_factory_index, impl);
1933     SSL_CTX_sess_set_new_cb(ssl_context,
1934                             server_handshaker_factory_new_session_callback);
1935     SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_CLIENT);
1936   }
1937
1938   do {
1939     result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
1940                                   options->cipher_suites);
1941     if (result != TSI_OK) break;
1942
1943 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1944     // X509_STORE_up_ref is only available since OpenSSL 1.1.
1945     if (options->root_store != nullptr) {
1946       X509_STORE_up_ref(options->root_store->store);
1947       SSL_CTX_set_cert_store(ssl_context, options->root_store->store);
1948     }
1949 #endif
1950     if (OPENSSL_VERSION_NUMBER < 0x10100000 || options->root_store == nullptr) {
1951       result = ssl_ctx_load_verification_certs(
1952           ssl_context, options->pem_root_certs, strlen(options->pem_root_certs),
1953           nullptr);
1954       if (result != TSI_OK) {
1955         gpr_log(GPR_ERROR, "Cannot load server root certificates.");
1956         break;
1957       }
1958     }
1959
1960     if (options->num_alpn_protocols != 0) {
1961       result = build_alpn_protocol_name_list(
1962           options->alpn_protocols, options->num_alpn_protocols,
1963           &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
1964       if (result != TSI_OK) {
1965         gpr_log(GPR_ERROR, "Building alpn list failed with error %s.",
1966                 tsi_result_to_string(result));
1967         break;
1968       }
1969 #if TSI_OPENSSL_ALPN_SUPPORT
1970       GPR_ASSERT(impl->alpn_protocol_list_length < UINT_MAX);
1971       if (SSL_CTX_set_alpn_protos(
1972               ssl_context, impl->alpn_protocol_list,
1973               static_cast<unsigned int>(impl->alpn_protocol_list_length))) {
1974         gpr_log(GPR_ERROR, "Could not set alpn protocol list to context.");
1975         result = TSI_INVALID_ARGUMENT;
1976         break;
1977       }
1978 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1979       SSL_CTX_set_next_proto_select_cb(
1980           ssl_context, client_handshaker_factory_npn_callback, impl);
1981     }
1982   } while (false);
1983   if (result != TSI_OK) {
1984     tsi_ssl_handshaker_factory_unref(&impl->base);
1985     return result;
1986   }
1987   if (options->skip_server_certificate_verification) {
1988     SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NullVerifyCallback);
1989   } else {
1990     SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr);
1991   }
1992   /* TODO(jboeuf): Add revocation verification. */
1993
1994   *factory = impl;
1995   return TSI_OK;
1996 }
1997
1998 static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
1999     tsi_ssl_server_handshaker_factory_destroy};
2000
2001 tsi_result tsi_create_ssl_server_handshaker_factory(
2002     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
2003     size_t num_key_cert_pairs, const char* pem_client_root_certs,
2004     int force_client_auth, const char* cipher_suites,
2005     const char** alpn_protocols, uint16_t num_alpn_protocols,
2006     tsi_ssl_server_handshaker_factory** factory) {
2007   return tsi_create_ssl_server_handshaker_factory_ex(
2008       pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs,
2009       force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
2010                         : TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
2011       cipher_suites, alpn_protocols, num_alpn_protocols, factory);
2012 }
2013
2014 tsi_result tsi_create_ssl_server_handshaker_factory_ex(
2015     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
2016     size_t num_key_cert_pairs, const char* pem_client_root_certs,
2017     tsi_client_certificate_request_type client_certificate_request,
2018     const char* cipher_suites, const char** alpn_protocols,
2019     uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) {
2020   tsi_ssl_server_handshaker_options options;
2021   options.pem_key_cert_pairs = pem_key_cert_pairs;
2022   options.num_key_cert_pairs = num_key_cert_pairs;
2023   options.pem_client_root_certs = pem_client_root_certs;
2024   options.client_certificate_request = client_certificate_request;
2025   options.cipher_suites = cipher_suites;
2026   options.alpn_protocols = alpn_protocols;
2027   options.num_alpn_protocols = num_alpn_protocols;
2028   return tsi_create_ssl_server_handshaker_factory_with_options(&options,
2029                                                                factory);
2030 }
2031
2032 tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
2033     const tsi_ssl_server_handshaker_options* options,
2034     tsi_ssl_server_handshaker_factory** factory) {
2035   tsi_ssl_server_handshaker_factory* impl = nullptr;
2036   tsi_result result = TSI_OK;
2037   size_t i = 0;
2038
2039   gpr_once_init(&g_init_openssl_once, init_openssl);
2040
2041   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
2042   *factory = nullptr;
2043   if (options->num_key_cert_pairs == 0 ||
2044       options->pem_key_cert_pairs == nullptr) {
2045     return TSI_INVALID_ARGUMENT;
2046   }
2047
2048   impl = static_cast<tsi_ssl_server_handshaker_factory*>(
2049       gpr_zalloc(sizeof(*impl)));
2050   tsi_ssl_handshaker_factory_init(&impl->base);
2051   impl->base.vtable = &server_handshaker_factory_vtable;
2052
2053   impl->ssl_contexts = static_cast<SSL_CTX**>(
2054       gpr_zalloc(options->num_key_cert_pairs * sizeof(SSL_CTX*)));
2055   impl->ssl_context_x509_subject_names = static_cast<tsi_peer*>(
2056       gpr_zalloc(options->num_key_cert_pairs * sizeof(tsi_peer)));
2057   if (impl->ssl_contexts == nullptr ||
2058       impl->ssl_context_x509_subject_names == nullptr) {
2059     tsi_ssl_handshaker_factory_unref(&impl->base);
2060     return TSI_OUT_OF_RESOURCES;
2061   }
2062   impl->ssl_context_count = options->num_key_cert_pairs;
2063
2064   if (options->num_alpn_protocols > 0) {
2065     result = build_alpn_protocol_name_list(
2066         options->alpn_protocols, options->num_alpn_protocols,
2067         &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
2068     if (result != TSI_OK) {
2069       tsi_ssl_handshaker_factory_unref(&impl->base);
2070       return result;
2071     }
2072   }
2073
2074   for (i = 0; i < options->num_key_cert_pairs; i++) {
2075     do {
2076 #if OPENSSL_VERSION_NUMBER >= 0x10100000
2077       impl->ssl_contexts[i] = SSL_CTX_new(TLS_method());
2078 #else
2079       impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
2080 #endif
2081       result = tsi_set_min_and_max_tls_versions(impl->ssl_contexts[i],
2082                                                 options->min_tls_version,
2083                                                 options->max_tls_version);
2084       if (result != TSI_OK) return result;
2085       if (impl->ssl_contexts[i] == nullptr) {
2086         gpr_log(GPR_ERROR, "Could not create ssl context.");
2087         result = TSI_OUT_OF_RESOURCES;
2088         break;
2089       }
2090       result = populate_ssl_context(impl->ssl_contexts[i],
2091                                     &options->pem_key_cert_pairs[i],
2092                                     options->cipher_suites);
2093       if (result != TSI_OK) break;
2094
2095       // TODO(elessar): Provide ability to disable session ticket keys.
2096
2097       // Allow client cache sessions (it's needed for OpenSSL only).
2098       int set_sid_ctx_result = SSL_CTX_set_session_id_context(
2099           impl->ssl_contexts[i], kSslSessionIdContext,
2100           GPR_ARRAY_SIZE(kSslSessionIdContext));
2101       if (set_sid_ctx_result == 0) {
2102         gpr_log(GPR_ERROR, "Failed to set session id context.");
2103         result = TSI_INTERNAL_ERROR;
2104         break;
2105       }
2106
2107       if (options->session_ticket_key != nullptr) {
2108         if (SSL_CTX_set_tlsext_ticket_keys(
2109                 impl->ssl_contexts[i],
2110                 const_cast<char*>(options->session_ticket_key),
2111                 options->session_ticket_key_size) == 0) {
2112           gpr_log(GPR_ERROR, "Invalid STEK size.");
2113           result = TSI_INVALID_ARGUMENT;
2114           break;
2115         }
2116       }
2117
2118       if (options->pem_client_root_certs != nullptr) {
2119         STACK_OF(X509_NAME)* root_names = nullptr;
2120         result = ssl_ctx_load_verification_certs(
2121             impl->ssl_contexts[i], options->pem_client_root_certs,
2122             strlen(options->pem_client_root_certs), &root_names);
2123         if (result != TSI_OK) {
2124           gpr_log(GPR_ERROR, "Invalid verification certs.");
2125           break;
2126         }
2127         SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
2128       }
2129       switch (options->client_certificate_request) {
2130         case TSI_DONT_REQUEST_CLIENT_CERTIFICATE:
2131           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr);
2132           break;
2133         case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
2134           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER,
2135                              NullVerifyCallback);
2136           break;
2137         case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY:
2138           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr);
2139           break;
2140         case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
2141           SSL_CTX_set_verify(impl->ssl_contexts[i],
2142                              SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2143                              NullVerifyCallback);
2144           break;
2145         case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY:
2146           SSL_CTX_set_verify(impl->ssl_contexts[i],
2147                              SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2148                              nullptr);
2149           break;
2150       }
2151       /* TODO(jboeuf): Add revocation verification. */
2152
2153       result = tsi_ssl_extract_x509_subject_names_from_pem_cert(
2154           options->pem_key_cert_pairs[i].cert_chain,
2155           &impl->ssl_context_x509_subject_names[i]);
2156       if (result != TSI_OK) break;
2157
2158       SSL_CTX_set_tlsext_servername_callback(
2159           impl->ssl_contexts[i],
2160           ssl_server_handshaker_factory_servername_callback);
2161       SSL_CTX_set_tlsext_servername_arg(impl->ssl_contexts[i], impl);
2162 #if TSI_OPENSSL_ALPN_SUPPORT
2163       SSL_CTX_set_alpn_select_cb(impl->ssl_contexts[i],
2164                                  server_handshaker_factory_alpn_callback, impl);
2165 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
2166       SSL_CTX_set_next_protos_advertised_cb(
2167           impl->ssl_contexts[i],
2168           server_handshaker_factory_npn_advertised_callback, impl);
2169     } while (false);
2170
2171     if (result != TSI_OK) {
2172       tsi_ssl_handshaker_factory_unref(&impl->base);
2173       return result;
2174     }
2175   }
2176
2177   *factory = impl;
2178   return TSI_OK;
2179 }
2180
2181 /* --- tsi_ssl utils. --- */
2182
2183 int tsi_ssl_peer_matches_name(const tsi_peer* peer, absl::string_view name) {
2184   size_t i = 0;
2185   size_t san_count = 0;
2186   const tsi_peer_property* cn_property = nullptr;
2187   int like_ip = looks_like_ip_address(name);
2188
2189   /* Check the SAN first. */
2190   for (i = 0; i < peer->property_count; i++) {
2191     const tsi_peer_property* property = &peer->properties[i];
2192     if (property->name == nullptr) continue;
2193     if (strcmp(property->name,
2194                TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) {
2195       san_count++;
2196
2197       absl::string_view entry(property->value.data, property->value.length);
2198       if (!like_ip && does_entry_match_name(entry, name)) {
2199         return 1;
2200       } else if (like_ip && name == entry) {
2201         /* IP Addresses are exact matches only. */
2202         return 1;
2203       }
2204     } else if (strcmp(property->name,
2205                       TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
2206       cn_property = property;
2207     }
2208   }
2209
2210   /* If there's no SAN, try the CN, but only if its not like an IP Address */
2211   if (san_count == 0 && cn_property != nullptr && !like_ip) {
2212     if (does_entry_match_name(absl::string_view(cn_property->value.data,
2213                                                 cn_property->value.length),
2214                               name)) {
2215       return 1;
2216     }
2217   }
2218
2219   return 0; /* Not found. */
2220 }
2221
2222 /* --- Testing support. --- */
2223 const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
2224     tsi_ssl_handshaker_factory* factory,
2225     tsi_ssl_handshaker_factory_vtable* new_vtable) {
2226   GPR_ASSERT(factory != nullptr);
2227   GPR_ASSERT(factory->vtable != nullptr);
2228
2229   const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
2230   factory->vtable = new_vtable;
2231   return orig_vtable;
2232 }