Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / deps / grpc / 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/grpc_shadow_boringssl.h"
22
23 #include "src/core/tsi/ssl_transport_security.h"
24
25 #include <limits.h>
26 #include <string.h>
27
28 /* TODO(jboeuf): refactor inet_ntop into a portability header. */
29 /* Note: for whomever reads this and tries to refactor this, this
30    can't be in grpc, it has to be in gpr. */
31 #ifdef GPR_WINDOWS
32 #include <ws2tcpip.h>
33 #else
34 #include <arpa/inet.h>
35 #include <sys/socket.h>
36 #endif
37
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/log.h>
40 #include <grpc/support/string_util.h>
41 #include <grpc/support/sync.h>
42 #include <grpc/support/thd_id.h>
43
44 extern "C" {
45 #include <openssl/bio.h>
46 #include <openssl/crypto.h> /* For OPENSSL_free */
47 #include <openssl/err.h>
48 #include <openssl/ssl.h>
49 #include <openssl/x509.h>
50 #include <openssl/x509v3.h>
51 }
52
53 #include "src/core/lib/gpr/useful.h"
54 #include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
55 #include "src/core/tsi/ssl_types.h"
56 #include "src/core/tsi/transport_security.h"
57
58 /* --- Constants. ---*/
59
60 #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384
61 #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024
62 #define TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 1024
63
64 /* Putting a macro like this and littering the source file with #if is really
65    bad practice.
66    TODO(jboeuf): refactor all the #if / #endif in a separate module. */
67 #ifndef TSI_OPENSSL_ALPN_SUPPORT
68 #define TSI_OPENSSL_ALPN_SUPPORT 1
69 #endif
70
71 /* TODO(jboeuf): I have not found a way to get this number dynamically from the
72    SSL structure. This is what we would ultimately want though... */
73 #define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
74
75 /* --- Structure definitions. ---*/
76
77 struct tsi_ssl_root_certs_store {
78   X509_STORE* store;
79 };
80
81 struct tsi_ssl_handshaker_factory {
82   const tsi_ssl_handshaker_factory_vtable* vtable;
83   gpr_refcount refcount;
84 };
85
86 struct tsi_ssl_client_handshaker_factory {
87   tsi_ssl_handshaker_factory base;
88   SSL_CTX* ssl_context;
89   unsigned char* alpn_protocol_list;
90   size_t alpn_protocol_list_length;
91   grpc_core::RefCountedPtr<tsi::SslSessionLRUCache> session_cache;
92 };
93
94 struct tsi_ssl_server_handshaker_factory {
95   /* Several contexts to support SNI.
96      The tsi_peer array contains the subject names of the server certificates
97      associated with the contexts at the same index.  */
98   tsi_ssl_handshaker_factory base;
99   SSL_CTX** ssl_contexts;
100   tsi_peer* ssl_context_x509_subject_names;
101   size_t ssl_context_count;
102   unsigned char* alpn_protocol_list;
103   size_t alpn_protocol_list_length;
104 };
105
106 typedef struct {
107   tsi_handshaker base;
108   SSL* ssl;
109   BIO* network_io;
110   tsi_result result;
111   unsigned char* outgoing_bytes_buffer;
112   size_t outgoing_bytes_buffer_size;
113   tsi_ssl_handshaker_factory* factory_ref;
114 } tsi_ssl_handshaker;
115
116 typedef struct {
117   tsi_handshaker_result base;
118   SSL* ssl;
119   BIO* network_io;
120   unsigned char* unused_bytes;
121   size_t unused_bytes_size;
122 } tsi_ssl_handshaker_result;
123
124 typedef struct {
125   tsi_frame_protector base;
126   SSL* ssl;
127   BIO* network_io;
128   unsigned char* buffer;
129   size_t buffer_size;
130   size_t buffer_offset;
131 } tsi_ssl_frame_protector;
132
133 /* --- Library Initialization. ---*/
134
135 static gpr_once g_init_openssl_once = GPR_ONCE_INIT;
136 static int g_ssl_ctx_ex_factory_index = -1;
137 static const unsigned char kSslSessionIdContext[] = {'g', 'r', 'p', 'c'};
138
139 #if OPENSSL_VERSION_NUMBER < 0x10100000
140 static gpr_mu* g_openssl_mutexes = nullptr;
141 static void openssl_locking_cb(int mode, int type, const char* file,
142                                int line) GRPC_UNUSED;
143 static unsigned long openssl_thread_id_cb(void) GRPC_UNUSED;
144
145 static void openssl_locking_cb(int mode, int type, const char* file, int line) {
146   if (mode & CRYPTO_LOCK) {
147     gpr_mu_lock(&g_openssl_mutexes[type]);
148   } else {
149     gpr_mu_unlock(&g_openssl_mutexes[type]);
150   }
151 }
152
153 static unsigned long openssl_thread_id_cb(void) {
154   return static_cast<unsigned long>(gpr_thd_currentid());
155 }
156 #endif
157
158 static void init_openssl(void) {
159 #if OPENSSL_API_COMPAT >= 0x10100000L
160   OPENSSL_init_ssl(0, NULL);
161 #else
162   SSL_library_init();
163   SSL_load_error_strings();
164   OpenSSL_add_all_algorithms();
165 #endif
166 #if OPENSSL_VERSION_NUMBER < 0x10100000
167   if (!CRYPTO_get_locking_callback()) {
168     int num_locks = CRYPTO_num_locks();
169     GPR_ASSERT(num_locks > 0);
170     g_openssl_mutexes = static_cast<gpr_mu*>(
171         gpr_malloc(static_cast<size_t>(num_locks) * sizeof(gpr_mu)));
172     for (int i = 0; i < num_locks; i++) {
173       gpr_mu_init(&g_openssl_mutexes[i]);
174     }
175     CRYPTO_set_locking_callback(openssl_locking_cb);
176     CRYPTO_set_id_callback(openssl_thread_id_cb);
177   } else {
178     gpr_log(GPR_INFO, "OpenSSL callback has already been set.");
179   }
180 #endif
181   g_ssl_ctx_ex_factory_index =
182       SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
183   GPR_ASSERT(g_ssl_ctx_ex_factory_index != -1);
184 }
185
186 /* --- Ssl utils. ---*/
187
188 static const char* ssl_error_string(int error) {
189   switch (error) {
190     case SSL_ERROR_NONE:
191       return "SSL_ERROR_NONE";
192     case SSL_ERROR_ZERO_RETURN:
193       return "SSL_ERROR_ZERO_RETURN";
194     case SSL_ERROR_WANT_READ:
195       return "SSL_ERROR_WANT_READ";
196     case SSL_ERROR_WANT_WRITE:
197       return "SSL_ERROR_WANT_WRITE";
198     case SSL_ERROR_WANT_CONNECT:
199       return "SSL_ERROR_WANT_CONNECT";
200     case SSL_ERROR_WANT_ACCEPT:
201       return "SSL_ERROR_WANT_ACCEPT";
202     case SSL_ERROR_WANT_X509_LOOKUP:
203       return "SSL_ERROR_WANT_X509_LOOKUP";
204     case SSL_ERROR_SYSCALL:
205       return "SSL_ERROR_SYSCALL";
206     case SSL_ERROR_SSL:
207       return "SSL_ERROR_SSL";
208     default:
209       return "Unknown error";
210   }
211 }
212
213 /* TODO(jboeuf): Remove when we are past the debugging phase with this code. */
214 static void ssl_log_where_info(const SSL* ssl, int where, int flag,
215                                const char* msg) {
216   if ((where & flag) && GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
217     gpr_log(GPR_INFO, "%20.20s - %30.30s  - %5.10s", msg,
218             SSL_state_string_long(ssl), SSL_state_string(ssl));
219   }
220 }
221
222 /* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */
223 static void ssl_info_callback(const SSL* ssl, int where, int ret) {
224   if (ret == 0) {
225     gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n");
226     return;
227   }
228
229   ssl_log_where_info(ssl, where, SSL_CB_LOOP, "LOOP");
230   ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START, "HANDSHAKE START");
231   ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE, "HANDSHAKE DONE");
232 }
233
234 /* Returns 1 if name looks like an IP address, 0 otherwise.
235    This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */
236 static int looks_like_ip_address(grpc_core::StringView name) {
237   size_t dot_count = 0;
238   size_t num_size = 0;
239   for (size_t i = 0; i < name.size(); ++i) {
240     if (name[i] == ':') {
241       /* IPv6 Address in hexadecimal form, : is not allowed in DNS names. */
242       return 1;
243     }
244     if (name[i] >= '0' && name[i] <= '9') {
245       if (num_size > 3) return 0;
246       num_size++;
247     } else if (name[i] == '.') {
248       if (dot_count > 3 || num_size == 0) return 0;
249       dot_count++;
250       num_size = 0;
251     } else {
252       return 0;
253     }
254   }
255   if (dot_count < 3 || num_size == 0) return 0;
256   return 1;
257 }
258
259 /* Gets the subject CN from an X509 cert. */
260 static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
261                                            size_t* utf8_size) {
262   int common_name_index = -1;
263   X509_NAME_ENTRY* common_name_entry = nullptr;
264   ASN1_STRING* common_name_asn1 = nullptr;
265   X509_NAME* subject_name = X509_get_subject_name(cert);
266   int utf8_returned_size = 0;
267   if (subject_name == nullptr) {
268     gpr_log(GPR_INFO, "Could not get subject name from certificate.");
269     return TSI_NOT_FOUND;
270   }
271   common_name_index =
272       X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
273   if (common_name_index == -1) {
274     gpr_log(GPR_INFO, "Could not get common name of subject from certificate.");
275     return TSI_NOT_FOUND;
276   }
277   common_name_entry = X509_NAME_get_entry(subject_name, common_name_index);
278   if (common_name_entry == nullptr) {
279     gpr_log(GPR_ERROR, "Could not get common name entry from certificate.");
280     return TSI_INTERNAL_ERROR;
281   }
282   common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
283   if (common_name_asn1 == nullptr) {
284     gpr_log(GPR_ERROR,
285             "Could not get common name entry asn1 from certificate.");
286     return TSI_INTERNAL_ERROR;
287   }
288   utf8_returned_size = ASN1_STRING_to_UTF8(utf8, common_name_asn1);
289   if (utf8_returned_size < 0) {
290     gpr_log(GPR_ERROR, "Could not extract utf8 from asn1 string.");
291     return TSI_OUT_OF_RESOURCES;
292   }
293   *utf8_size = static_cast<size_t>(utf8_returned_size);
294   return TSI_OK;
295 }
296
297 /* Gets the subject CN of an X509 cert as a tsi_peer_property. */
298 static tsi_result peer_property_from_x509_common_name(
299     X509* cert, tsi_peer_property* property) {
300   unsigned char* common_name;
301   size_t common_name_size;
302   tsi_result result =
303       ssl_get_x509_common_name(cert, &common_name, &common_name_size);
304   if (result != TSI_OK) {
305     if (result == TSI_NOT_FOUND) {
306       common_name = nullptr;
307       common_name_size = 0;
308     } else {
309       return result;
310     }
311   }
312   result = tsi_construct_string_peer_property(
313       TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY,
314       common_name == nullptr ? "" : reinterpret_cast<const char*>(common_name),
315       common_name_size, property);
316   OPENSSL_free(common_name);
317   return result;
318 }
319
320 /* Gets the X509 cert in PEM format as a tsi_peer_property. */
321 static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) {
322   BIO* bio = BIO_new(BIO_s_mem());
323   if (!PEM_write_bio_X509(bio, cert)) {
324     BIO_free(bio);
325     return TSI_INTERNAL_ERROR;
326   }
327   char* contents;
328   long len = BIO_get_mem_data(bio, &contents);
329   if (len <= 0) {
330     BIO_free(bio);
331     return TSI_INTERNAL_ERROR;
332   }
333   tsi_result result = tsi_construct_string_peer_property(
334       TSI_X509_PEM_CERT_PROPERTY, (const char*)contents,
335       static_cast<size_t>(len), property);
336   BIO_free(bio);
337   return result;
338 }
339
340 /* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
341 static tsi_result add_subject_alt_names_properties_to_peer(
342     tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
343     size_t subject_alt_name_count) {
344   size_t i;
345   tsi_result result = TSI_OK;
346
347   /* Reset for DNS entries filtering. */
348   peer->property_count -= subject_alt_name_count;
349
350   for (i = 0; i < subject_alt_name_count; i++) {
351     GENERAL_NAME* subject_alt_name =
352         sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
353     if (subject_alt_name->type == GEN_DNS ||
354         subject_alt_name->type == GEN_EMAIL ||
355         subject_alt_name->type == GEN_URI) {
356       unsigned char* name = nullptr;
357       int name_size;
358       if (subject_alt_name->type == GEN_DNS) {
359         name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
360       } else if (subject_alt_name->type == GEN_EMAIL) {
361         name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.rfc822Name);
362       } else {
363         name_size = ASN1_STRING_to_UTF8(
364             &name, subject_alt_name->d.uniformResourceIdentifier);
365       }
366       if (name_size < 0) {
367         gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
368         result = TSI_INTERNAL_ERROR;
369         break;
370       }
371       result = tsi_construct_string_peer_property(
372           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
373           reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
374           &peer->properties[peer->property_count++]);
375       OPENSSL_free(name);
376     } else if (subject_alt_name->type == GEN_IPADD) {
377       char ntop_buf[INET6_ADDRSTRLEN];
378       int af;
379
380       if (subject_alt_name->d.iPAddress->length == 4) {
381         af = AF_INET;
382       } else if (subject_alt_name->d.iPAddress->length == 16) {
383         af = AF_INET6;
384       } else {
385         gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
386         result = TSI_INTERNAL_ERROR;
387         break;
388       }
389       const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
390                                    ntop_buf, INET6_ADDRSTRLEN);
391       if (name == nullptr) {
392         gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
393         result = TSI_INTERNAL_ERROR;
394         break;
395       }
396
397       result = tsi_construct_string_peer_property_from_cstring(
398           TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
399           &peer->properties[peer->property_count++]);
400     }
401     if (result != TSI_OK) break;
402   }
403   return result;
404 }
405
406 /* Gets information about the peer's X509 cert as a tsi_peer object. */
407 static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
408                                  tsi_peer* peer) {
409   /* TODO(jboeuf): Maybe add more properties. */
410   GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
411       X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
412   int subject_alt_name_count =
413       (subject_alt_names != nullptr)
414           ? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
415           : 0;
416   size_t property_count;
417   tsi_result result;
418   GPR_ASSERT(subject_alt_name_count >= 0);
419   property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
420                    2 /* common name, certificate */ +
421                    static_cast<size_t>(subject_alt_name_count);
422   result = tsi_construct_peer(property_count, peer);
423   if (result != TSI_OK) return result;
424   do {
425     if (include_certificate_type) {
426       result = tsi_construct_string_peer_property_from_cstring(
427           TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
428           &peer->properties[0]);
429       if (result != TSI_OK) break;
430     }
431     result = peer_property_from_x509_common_name(
432         cert, &peer->properties[include_certificate_type ? 1 : 0]);
433     if (result != TSI_OK) break;
434
435     result = add_pem_certificate(
436         cert, &peer->properties[include_certificate_type ? 2 : 1]);
437     if (result != TSI_OK) break;
438
439     if (subject_alt_name_count != 0) {
440       result = add_subject_alt_names_properties_to_peer(
441           peer, subject_alt_names, static_cast<size_t>(subject_alt_name_count));
442       if (result != TSI_OK) break;
443     }
444   } while (0);
445
446   if (subject_alt_names != nullptr) {
447     sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
448   }
449   if (result != TSI_OK) tsi_peer_destruct(peer);
450   return result;
451 }
452
453 /* Logs the SSL error stack. */
454 static void log_ssl_error_stack(void) {
455   unsigned long err;
456   while ((err = ERR_get_error()) != 0) {
457     char details[256];
458     ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
459     gpr_log(GPR_ERROR, "%s", details);
460   }
461 }
462
463 /* Performs an SSL_read and handle errors. */
464 static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
465                               size_t* unprotected_bytes_size) {
466   int read_from_ssl;
467   GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
468   read_from_ssl = SSL_read(ssl, unprotected_bytes,
469                            static_cast<int>(*unprotected_bytes_size));
470   if (read_from_ssl <= 0) {
471     read_from_ssl = SSL_get_error(ssl, read_from_ssl);
472     switch (read_from_ssl) {
473       case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
474       case SSL_ERROR_WANT_READ:   /* We need more data to finish the frame. */
475         *unprotected_bytes_size = 0;
476         return TSI_OK;
477       case SSL_ERROR_WANT_WRITE:
478         gpr_log(
479             GPR_ERROR,
480             "Peer tried to renegotiate SSL connection. This is unsupported.");
481         return TSI_UNIMPLEMENTED;
482       case SSL_ERROR_SSL:
483         gpr_log(GPR_ERROR, "Corruption detected.");
484         log_ssl_error_stack();
485         return TSI_DATA_CORRUPTED;
486       default:
487         gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
488                 ssl_error_string(read_from_ssl));
489         return TSI_PROTOCOL_FAILURE;
490     }
491   }
492   *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
493   return TSI_OK;
494 }
495
496 /* Performs an SSL_write and handle errors. */
497 static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
498                                size_t unprotected_bytes_size) {
499   int ssl_write_result;
500   GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
501   ssl_write_result = SSL_write(ssl, unprotected_bytes,
502                                static_cast<int>(unprotected_bytes_size));
503   if (ssl_write_result < 0) {
504     ssl_write_result = SSL_get_error(ssl, ssl_write_result);
505     if (ssl_write_result == SSL_ERROR_WANT_READ) {
506       gpr_log(GPR_ERROR,
507               "Peer tried to renegotiate SSL connection. This is unsupported.");
508       return TSI_UNIMPLEMENTED;
509     } else {
510       gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
511               ssl_error_string(ssl_write_result));
512       return TSI_INTERNAL_ERROR;
513     }
514   }
515   return TSI_OK;
516 }
517
518 /* Loads an in-memory PEM certificate chain into the SSL context. */
519 static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
520                                                 const char* pem_cert_chain,
521                                                 size_t pem_cert_chain_size) {
522   tsi_result result = TSI_OK;
523   X509* certificate = nullptr;
524   BIO* pem;
525   GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
526   pem = BIO_new_mem_buf((void*)pem_cert_chain,
527                         static_cast<int>(pem_cert_chain_size));
528   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
529
530   do {
531     certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
532     if (certificate == nullptr) {
533       result = TSI_INVALID_ARGUMENT;
534       break;
535     }
536     if (!SSL_CTX_use_certificate(context, certificate)) {
537       result = TSI_INVALID_ARGUMENT;
538       break;
539     }
540     while (1) {
541       X509* certificate_authority =
542           PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
543       if (certificate_authority == nullptr) {
544         ERR_clear_error();
545         break; /* Done reading. */
546       }
547       if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
548         X509_free(certificate_authority);
549         result = TSI_INVALID_ARGUMENT;
550         break;
551       }
552       /* We don't need to free certificate_authority as its ownership has been
553          transfered to the context. That is not the case for certificate though.
554        */
555     }
556   } while (0);
557
558   if (certificate != nullptr) X509_free(certificate);
559   BIO_free(pem);
560   return result;
561 }
562
563 /* Loads an in-memory PEM private key into the SSL context. */
564 static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
565                                           size_t pem_key_size) {
566   tsi_result result = TSI_OK;
567   EVP_PKEY* private_key = nullptr;
568   BIO* pem;
569   GPR_ASSERT(pem_key_size <= INT_MAX);
570   pem = BIO_new_mem_buf((void*)pem_key, static_cast<int>(pem_key_size));
571   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
572   do {
573     private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
574     if (private_key == nullptr) {
575       result = TSI_INVALID_ARGUMENT;
576       break;
577     }
578     if (!SSL_CTX_use_PrivateKey(context, private_key)) {
579       result = TSI_INVALID_ARGUMENT;
580       break;
581     }
582   } while (0);
583   if (private_key != nullptr) EVP_PKEY_free(private_key);
584   BIO_free(pem);
585   return result;
586 }
587
588 /* Loads in-memory PEM verification certs into the SSL context and optionally
589    returns the verification cert names (root_names can be NULL). */
590 static tsi_result x509_store_load_certs(X509_STORE* cert_store,
591                                         const char* pem_roots,
592                                         size_t pem_roots_size,
593                                         STACK_OF(X509_NAME) * *root_names) {
594   tsi_result result = TSI_OK;
595   size_t num_roots = 0;
596   X509* root = nullptr;
597   X509_NAME* root_name = nullptr;
598   BIO* pem;
599   GPR_ASSERT(pem_roots_size <= INT_MAX);
600   pem = BIO_new_mem_buf((void*)pem_roots, static_cast<int>(pem_roots_size));
601   if (cert_store == nullptr) return TSI_INVALID_ARGUMENT;
602   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
603   if (root_names != nullptr) {
604     *root_names = sk_X509_NAME_new_null();
605     if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
606   }
607
608   while (1) {
609     root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
610     if (root == nullptr) {
611       ERR_clear_error();
612       break; /* We're at the end of stream. */
613     }
614     if (root_names != nullptr) {
615       root_name = X509_get_subject_name(root);
616       if (root_name == nullptr) {
617         gpr_log(GPR_ERROR, "Could not get name from root certificate.");
618         result = TSI_INVALID_ARGUMENT;
619         break;
620       }
621       root_name = X509_NAME_dup(root_name);
622       if (root_name == nullptr) {
623         result = TSI_OUT_OF_RESOURCES;
624         break;
625       }
626       sk_X509_NAME_push(*root_names, root_name);
627       root_name = nullptr;
628     }
629     ERR_clear_error();
630     if (!X509_STORE_add_cert(cert_store, root)) {
631       unsigned long error = ERR_get_error();
632       if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
633           ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
634         gpr_log(GPR_ERROR, "Could not add root certificate to ssl context.");
635         result = TSI_INTERNAL_ERROR;
636         break;
637       }
638     }
639     X509_free(root);
640     num_roots++;
641   }
642   if (num_roots == 0) {
643     gpr_log(GPR_ERROR, "Could not load any root certificate.");
644     result = TSI_INVALID_ARGUMENT;
645   }
646
647   if (result != TSI_OK) {
648     if (root != nullptr) X509_free(root);
649     if (root_names != nullptr) {
650       sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
651       *root_names = nullptr;
652       if (root_name != nullptr) X509_NAME_free(root_name);
653     }
654   }
655   BIO_free(pem);
656   return result;
657 }
658
659 static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
660                                                   const char* pem_roots,
661                                                   size_t pem_roots_size,
662                                                   STACK_OF(X509_NAME) *
663                                                       *root_name) {
664   X509_STORE* cert_store = SSL_CTX_get_cert_store(context);
665   X509_STORE_set_flags(cert_store,
666                        X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST);
667   return x509_store_load_certs(cert_store, pem_roots, pem_roots_size,
668                                root_name);
669 }
670
671 /* Populates the SSL context with a private key and a cert chain, and sets the
672    cipher list and the ephemeral ECDH key. */
673 static tsi_result populate_ssl_context(
674     SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
675     const char* cipher_list) {
676   tsi_result result = TSI_OK;
677   if (key_cert_pair != nullptr) {
678     if (key_cert_pair->cert_chain != nullptr) {
679       result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
680                                              strlen(key_cert_pair->cert_chain));
681       if (result != TSI_OK) {
682         gpr_log(GPR_ERROR, "Invalid cert chain file.");
683         return result;
684       }
685     }
686     if (key_cert_pair->private_key != nullptr) {
687       result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
688                                        strlen(key_cert_pair->private_key));
689       if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
690         gpr_log(GPR_ERROR, "Invalid private key.");
691         return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
692       }
693     }
694   }
695   if ((cipher_list != nullptr) &&
696       !SSL_CTX_set_cipher_list(context, cipher_list)) {
697     gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
698     return TSI_INVALID_ARGUMENT;
699   }
700   {
701     EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
702     if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
703       gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
704       EC_KEY_free(ecdh);
705       return TSI_INTERNAL_ERROR;
706     }
707     SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
708     EC_KEY_free(ecdh);
709   }
710   return TSI_OK;
711 }
712
713 /* Extracts the CN and the SANs from an X509 cert as a peer object. */
714 tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
715     const char* pem_cert, tsi_peer* peer) {
716   tsi_result result = TSI_OK;
717   X509* cert = nullptr;
718   BIO* pem;
719   pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
720   if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
721
722   cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
723   if (cert == nullptr) {
724     gpr_log(GPR_ERROR, "Invalid certificate");
725     result = TSI_INVALID_ARGUMENT;
726   } else {
727     result = peer_from_x509(cert, 0, peer);
728   }
729   if (cert != nullptr) X509_free(cert);
730   BIO_free(pem);
731   return result;
732 }
733
734 /* Builds the alpn protocol name list according to rfc 7301. */
735 static tsi_result build_alpn_protocol_name_list(
736     const char** alpn_protocols, uint16_t num_alpn_protocols,
737     unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
738   uint16_t i;
739   unsigned char* current;
740   *protocol_name_list = nullptr;
741   *protocol_name_list_length = 0;
742   if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
743   for (i = 0; i < num_alpn_protocols; i++) {
744     size_t length =
745         alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
746     if (length == 0 || length > 255) {
747       gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
748               static_cast<int>(length));
749       return TSI_INVALID_ARGUMENT;
750     }
751     *protocol_name_list_length += length + 1;
752   }
753   *protocol_name_list =
754       static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
755   if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
756   current = *protocol_name_list;
757   for (i = 0; i < num_alpn_protocols; i++) {
758     size_t length = strlen(alpn_protocols[i]);
759     *(current++) = static_cast<uint8_t>(length); /* max checked above. */
760     memcpy(current, alpn_protocols[i], length);
761     current += length;
762   }
763   /* Safety check. */
764   if ((current < *protocol_name_list) ||
765       (static_cast<uintptr_t>(current - *protocol_name_list) !=
766        *protocol_name_list_length)) {
767     return TSI_INTERNAL_ERROR;
768   }
769   return TSI_OK;
770 }
771
772 // The verification callback is used for clients that don't really care about
773 // the server's certificate, but we need to pull it anyway, in case a higher
774 // layer wants to look at it. In this case the verification may fail, but
775 // we don't really care.
776 static int NullVerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
777   return 1;
778 }
779
780 /* --- tsi_ssl_root_certs_store methods implementation. ---*/
781
782 tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
783     const char* pem_roots) {
784   if (pem_roots == nullptr) {
785     gpr_log(GPR_ERROR, "The root certificates are empty.");
786     return nullptr;
787   }
788   tsi_ssl_root_certs_store* root_store = static_cast<tsi_ssl_root_certs_store*>(
789       gpr_zalloc(sizeof(tsi_ssl_root_certs_store)));
790   if (root_store == nullptr) {
791     gpr_log(GPR_ERROR, "Could not allocate buffer for ssl_root_certs_store.");
792     return nullptr;
793   }
794   root_store->store = X509_STORE_new();
795   if (root_store->store == nullptr) {
796     gpr_log(GPR_ERROR, "Could not allocate buffer for X509_STORE.");
797     gpr_free(root_store);
798     return nullptr;
799   }
800   tsi_result result = x509_store_load_certs(root_store->store, pem_roots,
801                                             strlen(pem_roots), nullptr);
802   if (result != TSI_OK) {
803     gpr_log(GPR_ERROR, "Could not load root certificates.");
804     X509_STORE_free(root_store->store);
805     gpr_free(root_store);
806     return nullptr;
807   }
808   return root_store;
809 }
810
811 void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self) {
812   if (self == nullptr) return;
813   X509_STORE_free(self->store);
814   gpr_free(self);
815 }
816
817 /* --- tsi_ssl_session_cache methods implementation. ---*/
818
819 tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity) {
820   /* Pointer will be dereferenced by unref call. */
821   return reinterpret_cast<tsi_ssl_session_cache*>(
822       tsi::SslSessionLRUCache::Create(capacity).release());
823 }
824
825 void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache) {
826   /* Pointer will be dereferenced by unref call. */
827   reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Ref().release();
828 }
829
830 void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
831   reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
832 }
833
834 /* --- tsi_frame_protector methods implementation. ---*/
835
836 static tsi_result ssl_protector_protect(tsi_frame_protector* self,
837                                         const unsigned char* unprotected_bytes,
838                                         size_t* unprotected_bytes_size,
839                                         unsigned char* protected_output_frames,
840                                         size_t* protected_output_frames_size) {
841   tsi_ssl_frame_protector* impl =
842       reinterpret_cast<tsi_ssl_frame_protector*>(self);
843   int read_from_ssl;
844   size_t available;
845   tsi_result result = TSI_OK;
846
847   /* First see if we have some pending data in the SSL BIO. */
848   int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
849   if (pending_in_ssl > 0) {
850     *unprotected_bytes_size = 0;
851     GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
852     read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
853                              static_cast<int>(*protected_output_frames_size));
854     if (read_from_ssl < 0) {
855       gpr_log(GPR_ERROR,
856               "Could not read from BIO even though some data is pending");
857       return TSI_INTERNAL_ERROR;
858     }
859     *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
860     return TSI_OK;
861   }
862
863   /* Now see if we can send a complete frame. */
864   available = impl->buffer_size - impl->buffer_offset;
865   if (available > *unprotected_bytes_size) {
866     /* If we cannot, just copy the data in our internal buffer. */
867     memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
868            *unprotected_bytes_size);
869     impl->buffer_offset += *unprotected_bytes_size;
870     *protected_output_frames_size = 0;
871     return TSI_OK;
872   }
873
874   /* If we can, prepare the buffer, send it to SSL_write and read. */
875   memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
876   result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
877   if (result != TSI_OK) return result;
878
879   GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
880   read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
881                            static_cast<int>(*protected_output_frames_size));
882   if (read_from_ssl < 0) {
883     gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
884     return TSI_INTERNAL_ERROR;
885   }
886   *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
887   *unprotected_bytes_size = available;
888   impl->buffer_offset = 0;
889   return TSI_OK;
890 }
891
892 static tsi_result ssl_protector_protect_flush(
893     tsi_frame_protector* self, unsigned char* protected_output_frames,
894     size_t* protected_output_frames_size, size_t* still_pending_size) {
895   tsi_result result = TSI_OK;
896   tsi_ssl_frame_protector* impl =
897       reinterpret_cast<tsi_ssl_frame_protector*>(self);
898   int read_from_ssl = 0;
899   int pending;
900
901   if (impl->buffer_offset != 0) {
902     result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
903     if (result != TSI_OK) return result;
904     impl->buffer_offset = 0;
905   }
906
907   pending = static_cast<int>(BIO_pending(impl->network_io));
908   GPR_ASSERT(pending >= 0);
909   *still_pending_size = static_cast<size_t>(pending);
910   if (*still_pending_size == 0) return TSI_OK;
911
912   GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
913   read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
914                            static_cast<int>(*protected_output_frames_size));
915   if (read_from_ssl <= 0) {
916     gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
917     return TSI_INTERNAL_ERROR;
918   }
919   *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
920   pending = static_cast<int>(BIO_pending(impl->network_io));
921   GPR_ASSERT(pending >= 0);
922   *still_pending_size = static_cast<size_t>(pending);
923   return TSI_OK;
924 }
925
926 static tsi_result ssl_protector_unprotect(
927     tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
928     size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
929     size_t* unprotected_bytes_size) {
930   tsi_result result = TSI_OK;
931   int written_into_ssl = 0;
932   size_t output_bytes_size = *unprotected_bytes_size;
933   size_t output_bytes_offset = 0;
934   tsi_ssl_frame_protector* impl =
935       reinterpret_cast<tsi_ssl_frame_protector*>(self);
936
937   /* First, try to read remaining data from ssl. */
938   result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
939   if (result != TSI_OK) return result;
940   if (*unprotected_bytes_size == output_bytes_size) {
941     /* We have read everything we could and cannot process any more input. */
942     *protected_frames_bytes_size = 0;
943     return TSI_OK;
944   }
945   output_bytes_offset = *unprotected_bytes_size;
946   unprotected_bytes += output_bytes_offset;
947   *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
948
949   /* Then, try to write some data to ssl. */
950   GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
951   written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
952                                static_cast<int>(*protected_frames_bytes_size));
953   if (written_into_ssl < 0) {
954     gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
955             written_into_ssl);
956     return TSI_INTERNAL_ERROR;
957   }
958   *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
959
960   /* Now try to read some data again. */
961   result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
962   if (result == TSI_OK) {
963     /* Don't forget to output the total number of bytes read. */
964     *unprotected_bytes_size += output_bytes_offset;
965   }
966   return result;
967 }
968
969 static void ssl_protector_destroy(tsi_frame_protector* self) {
970   tsi_ssl_frame_protector* impl =
971       reinterpret_cast<tsi_ssl_frame_protector*>(self);
972   if (impl->buffer != nullptr) gpr_free(impl->buffer);
973   if (impl->ssl != nullptr) SSL_free(impl->ssl);
974   if (impl->network_io != nullptr) BIO_free(impl->network_io);
975   gpr_free(self);
976 }
977
978 static const tsi_frame_protector_vtable frame_protector_vtable = {
979     ssl_protector_protect,
980     ssl_protector_protect_flush,
981     ssl_protector_unprotect,
982     ssl_protector_destroy,
983 };
984
985 /* --- tsi_server_handshaker_factory methods implementation. --- */
986
987 static void tsi_ssl_handshaker_factory_destroy(
988     tsi_ssl_handshaker_factory* self) {
989   if (self == nullptr) return;
990
991   if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
992     self->vtable->destroy(self);
993   }
994   /* Note, we don't free(self) here because this object is always directly
995    * embedded in another object. If tsi_ssl_handshaker_factory_init allocates
996    * any memory, it should be free'd here. */
997 }
998
999 static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
1000     tsi_ssl_handshaker_factory* self) {
1001   if (self == nullptr) return nullptr;
1002   gpr_refn(&self->refcount, 1);
1003   return self;
1004 }
1005
1006 static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
1007   if (self == nullptr) return;
1008
1009   if (gpr_unref(&self->refcount)) {
1010     tsi_ssl_handshaker_factory_destroy(self);
1011   }
1012 }
1013
1014 static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
1015
1016 /* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
1017  * allocating memory for the factory. */
1018 static void tsi_ssl_handshaker_factory_init(
1019     tsi_ssl_handshaker_factory* factory) {
1020   GPR_ASSERT(factory != nullptr);
1021
1022   factory->vtable = &handshaker_factory_vtable;
1023   gpr_ref_init(&factory->refcount, 1);
1024 }
1025
1026 /* --- tsi_handshaker_result methods implementation. ---*/
1027 static tsi_result ssl_handshaker_result_extract_peer(
1028     const tsi_handshaker_result* self, tsi_peer* peer) {
1029   tsi_result result = TSI_OK;
1030   const unsigned char* alpn_selected = nullptr;
1031   unsigned int alpn_selected_len;
1032   const tsi_ssl_handshaker_result* impl =
1033       reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1034   // TODO(yihuazhang): Return a full certificate chain as a peer property.
1035   X509* peer_cert = SSL_get_peer_certificate(impl->ssl);
1036   if (peer_cert != nullptr) {
1037     result = peer_from_x509(peer_cert, 1, peer);
1038     X509_free(peer_cert);
1039     if (result != TSI_OK) return result;
1040   }
1041 #if TSI_OPENSSL_ALPN_SUPPORT
1042   SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
1043 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1044   if (alpn_selected == nullptr) {
1045     /* Try npn. */
1046     SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
1047                                    &alpn_selected_len);
1048   }
1049
1050   // 1 is for session reused property.
1051   size_t new_property_count = peer->property_count + 1;
1052   if (alpn_selected != nullptr) new_property_count++;
1053   tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
1054       gpr_zalloc(sizeof(*new_properties) * new_property_count));
1055   for (size_t i = 0; i < peer->property_count; i++) {
1056     new_properties[i] = peer->properties[i];
1057   }
1058   if (peer->properties != nullptr) gpr_free(peer->properties);
1059   peer->properties = new_properties;
1060
1061   if (alpn_selected != nullptr) {
1062     result = tsi_construct_string_peer_property(
1063         TSI_SSL_ALPN_SELECTED_PROTOCOL,
1064         reinterpret_cast<const char*>(alpn_selected), alpn_selected_len,
1065         &peer->properties[peer->property_count]);
1066     if (result != TSI_OK) return result;
1067     peer->property_count++;
1068   }
1069
1070   const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false";
1071   result = tsi_construct_string_peer_property_from_cstring(
1072       TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused,
1073       &peer->properties[peer->property_count]);
1074   if (result != TSI_OK) return result;
1075   peer->property_count++;
1076   return result;
1077 }
1078
1079 static tsi_result ssl_handshaker_result_create_frame_protector(
1080     const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
1081     tsi_frame_protector** protector) {
1082   size_t actual_max_output_protected_frame_size =
1083       TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1084   tsi_ssl_handshaker_result* impl =
1085       reinterpret_cast<tsi_ssl_handshaker_result*>(
1086           const_cast<tsi_handshaker_result*>(self));
1087   tsi_ssl_frame_protector* protector_impl =
1088       static_cast<tsi_ssl_frame_protector*>(
1089           gpr_zalloc(sizeof(*protector_impl)));
1090
1091   if (max_output_protected_frame_size != nullptr) {
1092     if (*max_output_protected_frame_size >
1093         TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) {
1094       *max_output_protected_frame_size =
1095           TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
1096     } else if (*max_output_protected_frame_size <
1097                TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND) {
1098       *max_output_protected_frame_size =
1099           TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND;
1100     }
1101     actual_max_output_protected_frame_size = *max_output_protected_frame_size;
1102   }
1103   protector_impl->buffer_size =
1104       actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD;
1105   protector_impl->buffer =
1106       static_cast<unsigned char*>(gpr_malloc(protector_impl->buffer_size));
1107   if (protector_impl->buffer == nullptr) {
1108     gpr_log(GPR_ERROR,
1109             "Could not allocated buffer for tsi_ssl_frame_protector.");
1110     gpr_free(protector_impl);
1111     return TSI_INTERNAL_ERROR;
1112   }
1113
1114   /* Transfer ownership of ssl and network_io to the frame protector. */
1115   protector_impl->ssl = impl->ssl;
1116   impl->ssl = nullptr;
1117   protector_impl->network_io = impl->network_io;
1118   impl->network_io = nullptr;
1119   protector_impl->base.vtable = &frame_protector_vtable;
1120   *protector = &protector_impl->base;
1121   return TSI_OK;
1122 }
1123
1124 static tsi_result ssl_handshaker_result_get_unused_bytes(
1125     const tsi_handshaker_result* self, const unsigned char** bytes,
1126     size_t* bytes_size) {
1127   const tsi_ssl_handshaker_result* impl =
1128       reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
1129   *bytes_size = impl->unused_bytes_size;
1130   *bytes = impl->unused_bytes;
1131   return TSI_OK;
1132 }
1133
1134 static void ssl_handshaker_result_destroy(tsi_handshaker_result* self) {
1135   tsi_ssl_handshaker_result* impl =
1136       reinterpret_cast<tsi_ssl_handshaker_result*>(self);
1137   SSL_free(impl->ssl);
1138   BIO_free(impl->network_io);
1139   gpr_free(impl->unused_bytes);
1140   gpr_free(impl);
1141 }
1142
1143 static const tsi_handshaker_result_vtable handshaker_result_vtable = {
1144     ssl_handshaker_result_extract_peer,
1145     nullptr, /* create_zero_copy_grpc_protector */
1146     ssl_handshaker_result_create_frame_protector,
1147     ssl_handshaker_result_get_unused_bytes,
1148     ssl_handshaker_result_destroy,
1149 };
1150
1151 static tsi_result ssl_handshaker_result_create(
1152     tsi_ssl_handshaker* handshaker, const unsigned char* unused_bytes,
1153     size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) {
1154   if (handshaker == nullptr || handshaker_result == nullptr ||
1155       (unused_bytes_size > 0 && unused_bytes == nullptr)) {
1156     return TSI_INVALID_ARGUMENT;
1157   }
1158   tsi_ssl_handshaker_result* result =
1159       static_cast<tsi_ssl_handshaker_result*>(gpr_zalloc(sizeof(*result)));
1160   result->base.vtable = &handshaker_result_vtable;
1161   /* Transfer ownership of ssl and network_io to the handshaker result. */
1162   result->ssl = handshaker->ssl;
1163   handshaker->ssl = nullptr;
1164   result->network_io = handshaker->network_io;
1165   handshaker->network_io = nullptr;
1166   if (unused_bytes_size > 0) {
1167     result->unused_bytes =
1168         static_cast<unsigned char*>(gpr_malloc(unused_bytes_size));
1169     memcpy(result->unused_bytes, unused_bytes, unused_bytes_size);
1170   }
1171   result->unused_bytes_size = unused_bytes_size;
1172   *handshaker_result = &result->base;
1173   return TSI_OK;
1174 }
1175
1176 /* --- tsi_handshaker methods implementation. ---*/
1177
1178 static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(
1179     tsi_ssl_handshaker* impl, unsigned char* bytes, size_t* bytes_size) {
1180   int bytes_read_from_ssl = 0;
1181   if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 ||
1182       *bytes_size > INT_MAX) {
1183     return TSI_INVALID_ARGUMENT;
1184   }
1185   GPR_ASSERT(*bytes_size <= INT_MAX);
1186   bytes_read_from_ssl =
1187       BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size));
1188   if (bytes_read_from_ssl < 0) {
1189     *bytes_size = 0;
1190     if (!BIO_should_retry(impl->network_io)) {
1191       impl->result = TSI_INTERNAL_ERROR;
1192       return impl->result;
1193     } else {
1194       return TSI_OK;
1195     }
1196   }
1197   *bytes_size = static_cast<size_t>(bytes_read_from_ssl);
1198   return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
1199 }
1200
1201 static tsi_result ssl_handshaker_get_result(tsi_ssl_handshaker* impl) {
1202   if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) &&
1203       SSL_is_init_finished(impl->ssl)) {
1204     impl->result = TSI_OK;
1205   }
1206   return impl->result;
1207 }
1208
1209 static tsi_result ssl_handshaker_process_bytes_from_peer(
1210     tsi_ssl_handshaker* impl, const unsigned char* bytes, size_t* bytes_size) {
1211   int bytes_written_into_ssl_size = 0;
1212   if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) {
1213     return TSI_INVALID_ARGUMENT;
1214   }
1215   GPR_ASSERT(*bytes_size <= INT_MAX);
1216   bytes_written_into_ssl_size =
1217       BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size));
1218   if (bytes_written_into_ssl_size < 0) {
1219     gpr_log(GPR_ERROR, "Could not write to memory BIO.");
1220     impl->result = TSI_INTERNAL_ERROR;
1221     return impl->result;
1222   }
1223   *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size);
1224
1225   if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) {
1226     impl->result = TSI_OK;
1227     return impl->result;
1228   } else {
1229     /* Get ready to get some bytes from SSL. */
1230     int ssl_result = SSL_do_handshake(impl->ssl);
1231     ssl_result = SSL_get_error(impl->ssl, ssl_result);
1232     switch (ssl_result) {
1233       case SSL_ERROR_WANT_READ:
1234         if (BIO_pending(impl->network_io) == 0) {
1235           /* We need more data. */
1236           return TSI_INCOMPLETE_DATA;
1237         } else {
1238           return TSI_OK;
1239         }
1240       case SSL_ERROR_NONE:
1241         return TSI_OK;
1242       default: {
1243         char err_str[256];
1244         ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1245         gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.",
1246                 ssl_error_string(ssl_result), err_str);
1247         impl->result = TSI_PROTOCOL_FAILURE;
1248         return impl->result;
1249       }
1250     }
1251   }
1252 }
1253
1254 static void ssl_handshaker_destroy(tsi_handshaker* self) {
1255   tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1256   SSL_free(impl->ssl);
1257   BIO_free(impl->network_io);
1258   gpr_free(impl->outgoing_bytes_buffer);
1259   tsi_ssl_handshaker_factory_unref(impl->factory_ref);
1260   gpr_free(impl);
1261 }
1262
1263 static tsi_result ssl_handshaker_next(
1264     tsi_handshaker* self, const unsigned char* received_bytes,
1265     size_t received_bytes_size, const unsigned char** bytes_to_send,
1266     size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
1267     tsi_handshaker_on_next_done_cb cb, void* user_data) {
1268   /* Input sanity check.  */
1269   if ((received_bytes_size > 0 && received_bytes == nullptr) ||
1270       bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
1271       handshaker_result == nullptr) {
1272     return TSI_INVALID_ARGUMENT;
1273   }
1274   /* If there are received bytes, process them first.  */
1275   tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
1276   tsi_result status = TSI_OK;
1277   size_t bytes_consumed = received_bytes_size;
1278   if (received_bytes_size > 0) {
1279     status = ssl_handshaker_process_bytes_from_peer(impl, received_bytes,
1280                                                     &bytes_consumed);
1281     if (status != TSI_OK) return status;
1282   }
1283   /* Get bytes to send to the peer, if available.  */
1284   size_t offset = 0;
1285   do {
1286     size_t to_send_size = impl->outgoing_bytes_buffer_size - offset;
1287     status = ssl_handshaker_get_bytes_to_send_to_peer(
1288         impl, impl->outgoing_bytes_buffer + offset, &to_send_size);
1289     offset += to_send_size;
1290     if (status == TSI_INCOMPLETE_DATA) {
1291       impl->outgoing_bytes_buffer_size *= 2;
1292       impl->outgoing_bytes_buffer = static_cast<unsigned char*>(gpr_realloc(
1293           impl->outgoing_bytes_buffer, impl->outgoing_bytes_buffer_size));
1294     }
1295   } while (status == TSI_INCOMPLETE_DATA);
1296   if (status != TSI_OK) return status;
1297   *bytes_to_send = impl->outgoing_bytes_buffer;
1298   *bytes_to_send_size = offset;
1299   /* If handshake completes, create tsi_handshaker_result.  */
1300   if (ssl_handshaker_get_result(impl) == TSI_HANDSHAKE_IN_PROGRESS) {
1301     *handshaker_result = nullptr;
1302   } else {
1303     size_t unused_bytes_size = received_bytes_size - bytes_consumed;
1304     const unsigned char* unused_bytes =
1305         unused_bytes_size == 0 ? nullptr : received_bytes + bytes_consumed;
1306     status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size,
1307                                           handshaker_result);
1308     if (status == TSI_OK) {
1309       /* Indicates that the handshake has completed and that a handshaker_result
1310        * has been created. */
1311       self->handshaker_result_created = true;
1312     }
1313   }
1314   return status;
1315 }
1316
1317 static const tsi_handshaker_vtable handshaker_vtable = {
1318     nullptr, /* get_bytes_to_send_to_peer -- deprecated */
1319     nullptr, /* process_bytes_from_peer   -- deprecated */
1320     nullptr, /* get_result                -- deprecated */
1321     nullptr, /* extract_peer              -- deprecated */
1322     nullptr, /* create_frame_protector    -- deprecated */
1323     ssl_handshaker_destroy,
1324     ssl_handshaker_next,
1325     nullptr, /* shutdown */
1326 };
1327
1328 /* --- tsi_ssl_handshaker_factory common methods. --- */
1329
1330 static void tsi_ssl_handshaker_resume_session(
1331     SSL* ssl, tsi::SslSessionLRUCache* session_cache) {
1332   const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1333   if (server_name == nullptr) {
1334     return;
1335   }
1336   tsi::SslSessionPtr session = session_cache->Get(server_name);
1337   if (session != nullptr) {
1338     // SSL_set_session internally increments reference counter.
1339     SSL_set_session(ssl, session.get());
1340   }
1341 }
1342
1343 static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
1344                                             const char* server_name_indication,
1345                                             tsi_ssl_handshaker_factory* factory,
1346                                             tsi_handshaker** handshaker) {
1347   SSL* ssl = SSL_new(ctx);
1348   BIO* network_io = nullptr;
1349   BIO* ssl_io = nullptr;
1350   tsi_ssl_handshaker* impl = nullptr;
1351   *handshaker = nullptr;
1352   if (ctx == nullptr) {
1353     gpr_log(GPR_ERROR, "SSL Context is null. Should never happen.");
1354     return TSI_INTERNAL_ERROR;
1355   }
1356   if (ssl == nullptr) {
1357     return TSI_OUT_OF_RESOURCES;
1358   }
1359   SSL_set_info_callback(ssl, ssl_info_callback);
1360
1361   if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
1362     gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
1363     SSL_free(ssl);
1364     return TSI_OUT_OF_RESOURCES;
1365   }
1366   SSL_set_bio(ssl, ssl_io, ssl_io);
1367   if (is_client) {
1368     int ssl_result;
1369     SSL_set_connect_state(ssl);
1370     if (server_name_indication != nullptr) {
1371       if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) {
1372         gpr_log(GPR_ERROR, "Invalid server name indication %s.",
1373                 server_name_indication);
1374         SSL_free(ssl);
1375         BIO_free(network_io);
1376         return TSI_INTERNAL_ERROR;
1377       }
1378     }
1379     tsi_ssl_client_handshaker_factory* client_factory =
1380         reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1381     if (client_factory->session_cache != nullptr) {
1382       tsi_ssl_handshaker_resume_session(ssl,
1383                                         client_factory->session_cache.get());
1384     }
1385     ssl_result = SSL_do_handshake(ssl);
1386     ssl_result = SSL_get_error(ssl, ssl_result);
1387     if (ssl_result != SSL_ERROR_WANT_READ) {
1388       gpr_log(GPR_ERROR,
1389               "Unexpected error received from first SSL_do_handshake call: %s",
1390               ssl_error_string(ssl_result));
1391       SSL_free(ssl);
1392       BIO_free(network_io);
1393       return TSI_INTERNAL_ERROR;
1394     }
1395   } else {
1396     SSL_set_accept_state(ssl);
1397   }
1398
1399   impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
1400   impl->ssl = ssl;
1401   impl->network_io = network_io;
1402   impl->result = TSI_HANDSHAKE_IN_PROGRESS;
1403   impl->outgoing_bytes_buffer_size =
1404       TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
1405   impl->outgoing_bytes_buffer =
1406       static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size));
1407   impl->base.vtable = &handshaker_vtable;
1408   impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory);
1409   *handshaker = &impl->base;
1410   return TSI_OK;
1411 }
1412
1413 static int select_protocol_list(const unsigned char** out,
1414                                 unsigned char* outlen,
1415                                 const unsigned char* client_list,
1416                                 size_t client_list_len,
1417                                 const unsigned char* server_list,
1418                                 size_t server_list_len) {
1419   const unsigned char* client_current = client_list;
1420   while (static_cast<unsigned int>(client_current - client_list) <
1421          client_list_len) {
1422     unsigned char client_current_len = *(client_current++);
1423     const unsigned char* server_current = server_list;
1424     while ((server_current >= server_list) &&
1425            static_cast<uintptr_t>(server_current - server_list) <
1426                server_list_len) {
1427       unsigned char server_current_len = *(server_current++);
1428       if ((client_current_len == server_current_len) &&
1429           !memcmp(client_current, server_current, server_current_len)) {
1430         *out = server_current;
1431         *outlen = server_current_len;
1432         return SSL_TLSEXT_ERR_OK;
1433       }
1434       server_current += server_current_len;
1435     }
1436     client_current += client_current_len;
1437   }
1438   return SSL_TLSEXT_ERR_NOACK;
1439 }
1440
1441 /* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
1442
1443 tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
1444     tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
1445     tsi_handshaker** handshaker) {
1446   return create_tsi_ssl_handshaker(self->ssl_context, 1, server_name_indication,
1447                                    &self->base, handshaker);
1448 }
1449
1450 void tsi_ssl_client_handshaker_factory_unref(
1451     tsi_ssl_client_handshaker_factory* self) {
1452   if (self == nullptr) return;
1453   tsi_ssl_handshaker_factory_unref(&self->base);
1454 }
1455
1456 static void tsi_ssl_client_handshaker_factory_destroy(
1457     tsi_ssl_handshaker_factory* factory) {
1458   if (factory == nullptr) return;
1459   tsi_ssl_client_handshaker_factory* self =
1460       reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
1461   if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context);
1462   if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1463   self->session_cache.reset();
1464   gpr_free(self);
1465 }
1466
1467 static int client_handshaker_factory_npn_callback(SSL* ssl, unsigned char** out,
1468                                                   unsigned char* outlen,
1469                                                   const unsigned char* in,
1470                                                   unsigned int inlen,
1471                                                   void* arg) {
1472   tsi_ssl_client_handshaker_factory* factory =
1473       static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1474   return select_protocol_list((const unsigned char**)out, outlen,
1475                               factory->alpn_protocol_list,
1476                               factory->alpn_protocol_list_length, in, inlen);
1477 }
1478
1479 /* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
1480
1481 tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
1482     tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker) {
1483   if (self->ssl_context_count == 0) return TSI_INVALID_ARGUMENT;
1484   /* Create the handshaker with the first context. We will switch if needed
1485      because of SNI in ssl_server_handshaker_factory_servername_callback.  */
1486   return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, nullptr,
1487                                    &self->base, handshaker);
1488 }
1489
1490 void tsi_ssl_server_handshaker_factory_unref(
1491     tsi_ssl_server_handshaker_factory* self) {
1492   if (self == nullptr) return;
1493   tsi_ssl_handshaker_factory_unref(&self->base);
1494 }
1495
1496 static void tsi_ssl_server_handshaker_factory_destroy(
1497     tsi_ssl_handshaker_factory* factory) {
1498   if (factory == nullptr) return;
1499   tsi_ssl_server_handshaker_factory* self =
1500       reinterpret_cast<tsi_ssl_server_handshaker_factory*>(factory);
1501   size_t i;
1502   for (i = 0; i < self->ssl_context_count; i++) {
1503     if (self->ssl_contexts[i] != nullptr) {
1504       SSL_CTX_free(self->ssl_contexts[i]);
1505       tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]);
1506     }
1507   }
1508   if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts);
1509   if (self->ssl_context_x509_subject_names != nullptr) {
1510     gpr_free(self->ssl_context_x509_subject_names);
1511   }
1512   if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
1513   gpr_free(self);
1514 }
1515
1516 static int does_entry_match_name(grpc_core::StringView entry,
1517                                  grpc_core::StringView name) {
1518   if (entry.empty()) return 0;
1519
1520   /* Take care of '.' terminations. */
1521   if (name.back() == '.') {
1522     name.remove_suffix(1);
1523   }
1524   if (entry.back() == '.') {
1525     entry.remove_suffix(1);
1526     if (entry.empty()) return 0;
1527   }
1528
1529   if (name == entry) {
1530     return 1; /* Perfect match. */
1531   }
1532   if (entry.front() != '*') return 0;
1533
1534   /* Wildchar subdomain matching. */
1535   if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
1536     gpr_log(GPR_ERROR, "Invalid wildchar entry.");
1537     return 0;
1538   }
1539   size_t name_subdomain_pos = name.find('.');
1540   if (name_subdomain_pos == grpc_core::StringView::npos) return 0;
1541   if (name_subdomain_pos >= name.size() - 2) return 0;
1542   grpc_core::StringView name_subdomain =
1543       name.substr(name_subdomain_pos + 1); /* Starts after the dot. */
1544   entry.remove_prefix(2);                  /* Remove *. */
1545   size_t dot = name_subdomain.find('.');
1546   if (dot == grpc_core::StringView::npos || dot == name_subdomain.size() - 1) {
1547     grpc_core::UniquePtr<char> name_subdomain_cstr(name_subdomain.dup());
1548     gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
1549             name_subdomain_cstr.get());
1550     return 0;
1551   }
1552   if (name_subdomain.back() == '.') {
1553     name_subdomain.remove_suffix(1);
1554   }
1555   return !entry.empty() && name_subdomain == entry;
1556 }
1557
1558 static int ssl_server_handshaker_factory_servername_callback(SSL* ssl, int* ap,
1559                                                              void* arg) {
1560   tsi_ssl_server_handshaker_factory* impl =
1561       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1562   size_t i = 0;
1563   const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1564   if (servername == nullptr || strlen(servername) == 0) {
1565     return SSL_TLSEXT_ERR_NOACK;
1566   }
1567
1568   for (i = 0; i < impl->ssl_context_count; i++) {
1569     if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
1570                                   servername)) {
1571       SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
1572       return SSL_TLSEXT_ERR_OK;
1573     }
1574   }
1575   gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
1576   return SSL_TLSEXT_ERR_ALERT_WARNING;
1577 }
1578
1579 #if TSI_OPENSSL_ALPN_SUPPORT
1580 static int server_handshaker_factory_alpn_callback(
1581     SSL* ssl, const unsigned char** out, unsigned char* outlen,
1582     const unsigned char* in, unsigned int inlen, void* arg) {
1583   tsi_ssl_server_handshaker_factory* factory =
1584       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1585   return select_protocol_list(out, outlen, in, inlen,
1586                               factory->alpn_protocol_list,
1587                               factory->alpn_protocol_list_length);
1588 }
1589 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1590
1591 static int server_handshaker_factory_npn_advertised_callback(
1592     SSL* ssl, const unsigned char** out, unsigned int* outlen, void* arg) {
1593   tsi_ssl_server_handshaker_factory* factory =
1594       static_cast<tsi_ssl_server_handshaker_factory*>(arg);
1595   *out = factory->alpn_protocol_list;
1596   GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX);
1597   *outlen = static_cast<unsigned int>(factory->alpn_protocol_list_length);
1598   return SSL_TLSEXT_ERR_OK;
1599 }
1600
1601 /// This callback is called when new \a session is established and ready to
1602 /// be cached. This session can be reused for new connections to similar
1603 /// servers at later point of time.
1604 /// It's intended to be used with SSL_CTX_sess_set_new_cb function.
1605 ///
1606 /// It returns 1 if callback takes ownership over \a session and 0 otherwise.
1607 static int server_handshaker_factory_new_session_callback(
1608     SSL* ssl, SSL_SESSION* session) {
1609   SSL_CTX* ssl_context = SSL_get_SSL_CTX(ssl);
1610   if (ssl_context == nullptr) {
1611     return 0;
1612   }
1613   void* arg = SSL_CTX_get_ex_data(ssl_context, g_ssl_ctx_ex_factory_index);
1614   tsi_ssl_client_handshaker_factory* factory =
1615       static_cast<tsi_ssl_client_handshaker_factory*>(arg);
1616   const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1617   if (server_name == nullptr) {
1618     return 0;
1619   }
1620   factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
1621   // Return 1 to indicate transfered ownership over the given session.
1622   return 1;
1623 }
1624
1625 /* --- tsi_ssl_handshaker_factory constructors. --- */
1626
1627 static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
1628     tsi_ssl_client_handshaker_factory_destroy};
1629
1630 tsi_result tsi_create_ssl_client_handshaker_factory(
1631     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
1632     const char* pem_root_certs, const char* cipher_suites,
1633     const char** alpn_protocols, uint16_t num_alpn_protocols,
1634     tsi_ssl_client_handshaker_factory** factory) {
1635   tsi_ssl_client_handshaker_options options;
1636   options.pem_key_cert_pair = pem_key_cert_pair;
1637   options.pem_root_certs = pem_root_certs;
1638   options.cipher_suites = cipher_suites;
1639   options.alpn_protocols = alpn_protocols;
1640   options.num_alpn_protocols = num_alpn_protocols;
1641   return tsi_create_ssl_client_handshaker_factory_with_options(&options,
1642                                                                factory);
1643 }
1644
1645 tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
1646     const tsi_ssl_client_handshaker_options* options,
1647     tsi_ssl_client_handshaker_factory** factory) {
1648   SSL_CTX* ssl_context = nullptr;
1649   tsi_ssl_client_handshaker_factory* impl = nullptr;
1650   tsi_result result = TSI_OK;
1651
1652   gpr_once_init(&g_init_openssl_once, init_openssl);
1653
1654   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
1655   *factory = nullptr;
1656   if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
1657     return TSI_INVALID_ARGUMENT;
1658   }
1659
1660 #if defined(OPENSSL_NO_TLS1_2_METHOD) || OPENSSL_API_COMPAT >= 0x10100000L
1661   ssl_context = SSL_CTX_new(TLS_method());
1662 #else
1663   ssl_context = SSL_CTX_new(TLSv1_2_method());
1664 #endif
1665   if (ssl_context == nullptr) {
1666     gpr_log(GPR_ERROR, "Could not create ssl context.");
1667     return TSI_INVALID_ARGUMENT;
1668   }
1669
1670   impl = static_cast<tsi_ssl_client_handshaker_factory*>(
1671       gpr_zalloc(sizeof(*impl)));
1672   tsi_ssl_handshaker_factory_init(&impl->base);
1673   impl->base.vtable = &client_handshaker_factory_vtable;
1674   impl->ssl_context = ssl_context;
1675   if (options->session_cache != nullptr) {
1676     // Unref is called manually on factory destruction.
1677     impl->session_cache =
1678         reinterpret_cast<tsi::SslSessionLRUCache*>(options->session_cache)
1679             ->Ref();
1680     SSL_CTX_set_ex_data(ssl_context, g_ssl_ctx_ex_factory_index, impl);
1681     SSL_CTX_sess_set_new_cb(ssl_context,
1682                             server_handshaker_factory_new_session_callback);
1683     SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_CLIENT);
1684   }
1685
1686   do {
1687     result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
1688                                   options->cipher_suites);
1689     if (result != TSI_OK) break;
1690
1691 #if OPENSSL_VERSION_NUMBER >= 0x10100000
1692     // X509_STORE_up_ref is only available since OpenSSL 1.1.
1693     if (options->root_store != nullptr) {
1694       X509_STORE_up_ref(options->root_store->store);
1695       SSL_CTX_set_cert_store(ssl_context, options->root_store->store);
1696     }
1697 #endif
1698     if (OPENSSL_VERSION_NUMBER < 0x10100000 || options->root_store == nullptr) {
1699       result = ssl_ctx_load_verification_certs(
1700           ssl_context, options->pem_root_certs, strlen(options->pem_root_certs),
1701           nullptr);
1702       if (result != TSI_OK) {
1703         gpr_log(GPR_ERROR, "Cannot load server root certificates.");
1704         break;
1705       }
1706     }
1707
1708     if (options->num_alpn_protocols != 0) {
1709       result = build_alpn_protocol_name_list(
1710           options->alpn_protocols, options->num_alpn_protocols,
1711           &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
1712       if (result != TSI_OK) {
1713         gpr_log(GPR_ERROR, "Building alpn list failed with error %s.",
1714                 tsi_result_to_string(result));
1715         break;
1716       }
1717 #if TSI_OPENSSL_ALPN_SUPPORT
1718       GPR_ASSERT(impl->alpn_protocol_list_length < UINT_MAX);
1719       if (SSL_CTX_set_alpn_protos(
1720               ssl_context, impl->alpn_protocol_list,
1721               static_cast<unsigned int>(impl->alpn_protocol_list_length))) {
1722         gpr_log(GPR_ERROR, "Could not set alpn protocol list to context.");
1723         result = TSI_INVALID_ARGUMENT;
1724         break;
1725       }
1726 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1727       SSL_CTX_set_next_proto_select_cb(
1728           ssl_context, client_handshaker_factory_npn_callback, impl);
1729     }
1730   } while (0);
1731   if (result != TSI_OK) {
1732     tsi_ssl_handshaker_factory_unref(&impl->base);
1733     return result;
1734   }
1735   SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr);
1736   /* TODO(jboeuf): Add revocation verification. */
1737
1738   *factory = impl;
1739   return TSI_OK;
1740 }
1741
1742 static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
1743     tsi_ssl_server_handshaker_factory_destroy};
1744
1745 tsi_result tsi_create_ssl_server_handshaker_factory(
1746     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
1747     size_t num_key_cert_pairs, const char* pem_client_root_certs,
1748     int force_client_auth, const char* cipher_suites,
1749     const char** alpn_protocols, uint16_t num_alpn_protocols,
1750     tsi_ssl_server_handshaker_factory** factory) {
1751   return tsi_create_ssl_server_handshaker_factory_ex(
1752       pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs,
1753       force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
1754                         : TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
1755       cipher_suites, alpn_protocols, num_alpn_protocols, factory);
1756 }
1757
1758 tsi_result tsi_create_ssl_server_handshaker_factory_ex(
1759     const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
1760     size_t num_key_cert_pairs, const char* pem_client_root_certs,
1761     tsi_client_certificate_request_type client_certificate_request,
1762     const char* cipher_suites, const char** alpn_protocols,
1763     uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) {
1764   tsi_ssl_server_handshaker_options options;
1765   options.pem_key_cert_pairs = pem_key_cert_pairs;
1766   options.num_key_cert_pairs = num_key_cert_pairs;
1767   options.pem_client_root_certs = pem_client_root_certs;
1768   options.client_certificate_request = client_certificate_request;
1769   options.cipher_suites = cipher_suites;
1770   options.alpn_protocols = alpn_protocols;
1771   options.num_alpn_protocols = num_alpn_protocols;
1772   return tsi_create_ssl_server_handshaker_factory_with_options(&options,
1773                                                                factory);
1774 }
1775
1776 tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
1777     const tsi_ssl_server_handshaker_options* options,
1778     tsi_ssl_server_handshaker_factory** factory) {
1779   tsi_ssl_server_handshaker_factory* impl = nullptr;
1780   tsi_result result = TSI_OK;
1781   size_t i = 0;
1782
1783   gpr_once_init(&g_init_openssl_once, init_openssl);
1784
1785   if (factory == nullptr) return TSI_INVALID_ARGUMENT;
1786   *factory = nullptr;
1787   if (options->num_key_cert_pairs == 0 ||
1788       options->pem_key_cert_pairs == nullptr) {
1789     return TSI_INVALID_ARGUMENT;
1790   }
1791
1792   impl = static_cast<tsi_ssl_server_handshaker_factory*>(
1793       gpr_zalloc(sizeof(*impl)));
1794   tsi_ssl_handshaker_factory_init(&impl->base);
1795   impl->base.vtable = &server_handshaker_factory_vtable;
1796
1797   impl->ssl_contexts = static_cast<SSL_CTX**>(
1798       gpr_zalloc(options->num_key_cert_pairs * sizeof(SSL_CTX*)));
1799   impl->ssl_context_x509_subject_names = static_cast<tsi_peer*>(
1800       gpr_zalloc(options->num_key_cert_pairs * sizeof(tsi_peer)));
1801   if (impl->ssl_contexts == nullptr ||
1802       impl->ssl_context_x509_subject_names == nullptr) {
1803     tsi_ssl_handshaker_factory_unref(&impl->base);
1804     return TSI_OUT_OF_RESOURCES;
1805   }
1806   impl->ssl_context_count = options->num_key_cert_pairs;
1807
1808   if (options->num_alpn_protocols > 0) {
1809     result = build_alpn_protocol_name_list(
1810         options->alpn_protocols, options->num_alpn_protocols,
1811         &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
1812     if (result != TSI_OK) {
1813       tsi_ssl_handshaker_factory_unref(&impl->base);
1814       return result;
1815     }
1816   }
1817
1818   for (i = 0; i < options->num_key_cert_pairs; i++) {
1819     do {
1820 #if defined(OPENSSL_NO_TLS1_2_METHOD) || OPENSSL_API_COMPAT >= 0x10100000L
1821       impl->ssl_contexts[i] = SSL_CTX_new(TLS_method());
1822 #else
1823       impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
1824 #endif
1825       if (impl->ssl_contexts[i] == nullptr) {
1826         gpr_log(GPR_ERROR, "Could not create ssl context.");
1827         result = TSI_OUT_OF_RESOURCES;
1828         break;
1829       }
1830       result = populate_ssl_context(impl->ssl_contexts[i],
1831                                     &options->pem_key_cert_pairs[i],
1832                                     options->cipher_suites);
1833       if (result != TSI_OK) break;
1834
1835       // TODO(elessar): Provide ability to disable session ticket keys.
1836
1837       // Allow client cache sessions (it's needed for OpenSSL only).
1838       int set_sid_ctx_result = SSL_CTX_set_session_id_context(
1839           impl->ssl_contexts[i], kSslSessionIdContext,
1840           GPR_ARRAY_SIZE(kSslSessionIdContext));
1841       if (set_sid_ctx_result == 0) {
1842         gpr_log(GPR_ERROR, "Failed to set session id context.");
1843         result = TSI_INTERNAL_ERROR;
1844         break;
1845       }
1846
1847       if (options->session_ticket_key != nullptr) {
1848         if (SSL_CTX_set_tlsext_ticket_keys(
1849                 impl->ssl_contexts[i],
1850                 const_cast<char*>(options->session_ticket_key),
1851                 options->session_ticket_key_size) == 0) {
1852           gpr_log(GPR_ERROR, "Invalid STEK size.");
1853           result = TSI_INVALID_ARGUMENT;
1854           break;
1855         }
1856       }
1857
1858       if (options->pem_client_root_certs != nullptr) {
1859         STACK_OF(X509_NAME)* root_names = nullptr;
1860         result = ssl_ctx_load_verification_certs(
1861             impl->ssl_contexts[i], options->pem_client_root_certs,
1862             strlen(options->pem_client_root_certs), &root_names);
1863         if (result != TSI_OK) {
1864           gpr_log(GPR_ERROR, "Invalid verification certs.");
1865           break;
1866         }
1867         SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
1868       }
1869       switch (options->client_certificate_request) {
1870         case TSI_DONT_REQUEST_CLIENT_CERTIFICATE:
1871           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr);
1872           break;
1873         case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
1874           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER,
1875                              NullVerifyCallback);
1876           break;
1877         case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY:
1878           SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr);
1879           break;
1880         case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY:
1881           SSL_CTX_set_verify(impl->ssl_contexts[i],
1882                              SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1883                              NullVerifyCallback);
1884           break;
1885         case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY:
1886           SSL_CTX_set_verify(impl->ssl_contexts[i],
1887                              SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1888                              nullptr);
1889           break;
1890       }
1891       /* TODO(jboeuf): Add revocation verification. */
1892
1893       result = tsi_ssl_extract_x509_subject_names_from_pem_cert(
1894           options->pem_key_cert_pairs[i].cert_chain,
1895           &impl->ssl_context_x509_subject_names[i]);
1896       if (result != TSI_OK) break;
1897
1898       SSL_CTX_set_tlsext_servername_callback(
1899           impl->ssl_contexts[i],
1900           ssl_server_handshaker_factory_servername_callback);
1901       SSL_CTX_set_tlsext_servername_arg(impl->ssl_contexts[i], impl);
1902 #if TSI_OPENSSL_ALPN_SUPPORT
1903       SSL_CTX_set_alpn_select_cb(impl->ssl_contexts[i],
1904                                  server_handshaker_factory_alpn_callback, impl);
1905 #endif /* TSI_OPENSSL_ALPN_SUPPORT */
1906       SSL_CTX_set_next_protos_advertised_cb(
1907           impl->ssl_contexts[i],
1908           server_handshaker_factory_npn_advertised_callback, impl);
1909     } while (0);
1910
1911     if (result != TSI_OK) {
1912       tsi_ssl_handshaker_factory_unref(&impl->base);
1913       return result;
1914     }
1915   }
1916
1917   *factory = impl;
1918   return TSI_OK;
1919 }
1920
1921 /* --- tsi_ssl utils. --- */
1922
1923 int tsi_ssl_peer_matches_name(const tsi_peer* peer,
1924                               grpc_core::StringView name) {
1925   size_t i = 0;
1926   size_t san_count = 0;
1927   const tsi_peer_property* cn_property = nullptr;
1928   int like_ip = looks_like_ip_address(name);
1929
1930   /* Check the SAN first. */
1931   for (i = 0; i < peer->property_count; i++) {
1932     const tsi_peer_property* property = &peer->properties[i];
1933     if (property->name == nullptr) continue;
1934     if (strcmp(property->name,
1935                TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) {
1936       san_count++;
1937
1938       grpc_core::StringView entry(property->value.data, property->value.length);
1939       if (!like_ip && does_entry_match_name(entry, name)) {
1940         return 1;
1941       } else if (like_ip && name == entry) {
1942         /* IP Addresses are exact matches only. */
1943         return 1;
1944       }
1945     } else if (strcmp(property->name,
1946                       TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
1947       cn_property = property;
1948     }
1949   }
1950
1951   /* If there's no SAN, try the CN, but only if its not like an IP Address */
1952   if (san_count == 0 && cn_property != nullptr && !like_ip) {
1953     if (does_entry_match_name(grpc_core::StringView(cn_property->value.data,
1954                                                     cn_property->value.length),
1955                               name)) {
1956       return 1;
1957     }
1958   }
1959
1960   return 0; /* Not found. */
1961 }
1962
1963 /* --- Testing support. --- */
1964 const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
1965     tsi_ssl_handshaker_factory* factory,
1966     tsi_ssl_handshaker_factory_vtable* new_vtable) {
1967   GPR_ASSERT(factory != nullptr);
1968   GPR_ASSERT(factory->vtable != nullptr);
1969
1970   const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
1971   factory->vtable = new_vtable;
1972   return orig_vtable;
1973 }