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