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