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