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