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