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