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