Debian Codegraph @

src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/tlsio_openssl.c

raw
1 // Copyright (c) Microsoft. All rights reserved.
2 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4 #include <stdlib.h>
5 #include "openssl/ssl.h"
6 #include "openssl/err.h"
7 #include "openssl/crypto.h"
8 #include "openssl/opensslv.h"
9 #include "openssl/engine.h"
10 #include <stdio.h>
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include "azure_c_shared_utility/lock.h"
14 #include "azure_c_shared_utility/tlsio.h"
15 #include "azure_c_shared_utility/tlsio_openssl.h"
16 #include "azure_c_shared_utility/socketio.h"
17 #include "azure_c_shared_utility/optimize_size.h"
18 #include "azure_c_shared_utility/xlogging.h"
19 #include "azure_c_shared_utility/crt_abstractions.h"
20 #include "azure_c_shared_utility/x509_openssl.h"
21 #include "azure_c_shared_utility/shared_util_options.h"
22 #include "azure_c_shared_utility/gballoc.h"
23 #include "azure_c_shared_utility/const_defines.h"
24 #include "azure_c_shared_utility/safe_math.h"
25
26 typedef enum TLSIO_STATE_TAG
27 {
28 TLSIO_STATE_NOT_OPEN,
29 TLSIO_STATE_OPENING_UNDERLYING_IO,
30 TLSIO_STATE_IN_HANDSHAKE,
31 // TLSIO_STATE_HANDSHAKE_FAILED is an ephemeral state signalling successful socket
32 // operation but with rejected handshake. The tlsio will never be in this state
33 // at the start of any of the API calls.
34 TLSIO_STATE_HANDSHAKE_FAILED,
35 TLSIO_STATE_OPEN,
36 TLSIO_STATE_CLOSING,
37 TLSIO_STATE_ERROR
38 } TLSIO_STATE;
39
40 typedef enum TLSIO_VERSION_TAG
41 {
42 VERSION_1_0 = 10,
43 VERSION_1_1 = 11,
44 VERSION_1_2 = 12,
45 } TLSIO_VERSION;
46
47 static bool is_an_opening_state(TLSIO_STATE state)
48 {
49 // TLSIO_STATE_HANDSHAKE_FAILED is deliberately not one of these states.
50 return state == TLSIO_STATE_OPENING_UNDERLYING_IO ||
51 state == TLSIO_STATE_IN_HANDSHAKE;
52 }
53
54 typedef int(*TLS_CERTIFICATE_VALIDATION_CALLBACK)(X509_STORE_CTX*, void*);
55
56 typedef struct TLS_IO_INSTANCE_TAG
57 {
58 XIO_HANDLE underlying_io;
59 ON_BYTES_RECEIVED on_bytes_received;
60 ON_IO_OPEN_COMPLETE on_io_open_complete;
61 ON_IO_CLOSE_COMPLETE on_io_close_complete;
62 ON_IO_ERROR on_io_error;
63 void* on_bytes_received_context;
64 void* on_io_open_complete_context;
65 void* on_io_close_complete_context;
66 void* on_io_error_context;
67 SSL* ssl;
68 SSL_CTX* ssl_context;
69 BIO* in_bio;
70 BIO* out_bio;
71 TLSIO_STATE tlsio_state;
72 char* certificate;
73 char* cipher_list;
74 const char* x509_certificate;
75 const char* x509_private_key;
76 TLSIO_VERSION tls_version;
77 TLS_CERTIFICATE_VALIDATION_CALLBACK tls_validation_callback;
78 void* tls_validation_callback_data;
79 char* hostname;
80 char* engine_id;
81 bool ignore_host_name_check;
82 ENGINE* engine;
83 OPTION_OPENSSL_KEY_TYPE x509_private_key_type;
84 } TLS_IO_INSTANCE;
85
86 struct CRYPTO_dynlock_value
87 {
88 LOCK_HANDLE lock;
89 };
90
91 static const char* const OPTION_UNDERLYING_IO_OPTIONS = "underlying_io_options";
92 #define SSL_DO_HANDSHAKE_SUCCESS 1
93
94
95 /*this function will clone an option given by name and value*/
96 static void* tlsio_openssl_CloneOption(const char* name, const void* value)
97 {
98 void* result;
99 if (
100 (name == NULL) || (value == NULL)
101 )
102 {
103 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
104 result = NULL;
105 }
106 else
107 {
108 if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
109 {
110 result = (void*)OptionHandler_Clone((OPTIONHANDLER_HANDLE)value);
111 }
112 else if (strcmp(name, OPTION_TRUSTED_CERT) == 0)
113 {
114 if (mallocAndStrcpy_s((char**)&result, value) != 0)
115 {
116 LogError("unable to mallocAndStrcpy_s TrustedCerts value");
117 result = NULL;
118 }
119 else
120 {
121 /*return as is*/
122 }
123 }
124 else if (strcmp(name, OPTION_OPENSSL_CIPHER_SUITE) == 0)
125 {
126 if (mallocAndStrcpy_s((char**)&result, value) != 0)
127 {
128 LogError("unable to mallocAndStrcpy_s CipherSuite value");
129 result = NULL;
130 }
131 else
132 {
133 /*return as is*/
134 }
135 }
136 else if (strcmp(name, SU_OPTION_X509_CERT) == 0)
137 {
138 if (mallocAndStrcpy_s((char**)&result, value) != 0)
139 {
140 LogError("unable to mallocAndStrcpy_s x509certificate value");
141 result = NULL;
142 }
143 else
144 {
145 /*return as is*/
146 }
147 }
148 else if (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0)
149 {
150 if (mallocAndStrcpy_s((char**)&result, value) != 0)
151 {
152 LogError("unable to mallocAndStrcpy_s x509privatekey value");
153 result = NULL;
154 }
155 else
156 {
157 /*return as is*/
158 }
159 }
160 else if (strcmp(name, OPTION_X509_ECC_CERT) == 0)
161 {
162 if (mallocAndStrcpy_s((char**)&result, value) != 0)
163 {
164 LogError("unable to mallocAndStrcpy_s x509EccCertificate value");
165 result = NULL;
166 }
167 else
168 {
169 /*return as is*/
170 }
171 }
172 else if (strcmp(name, OPTION_X509_ECC_KEY) == 0)
173 {
174 if (mallocAndStrcpy_s((char**)&result, value) != 0)
175 {
176 LogError("unable to mallocAndStrcpy_s x509EccKey value");
177 result = NULL;
178 }
179 else
180 {
181 /*return as is*/
182 }
183 }
184 else if (strcmp(name, OPTION_TLS_VERSION) == 0)
185 {
186 int int_value;
187
188 if (*(TLSIO_VERSION*)value == VERSION_1_0)
189 {
190 int_value = 10;
191 }
192 else if (*(TLSIO_VERSION*)value == VERSION_1_1)
193 {
194 int_value = 11;
195 }
196 else if (*(TLSIO_VERSION*)value == VERSION_1_2)
197 {
198 int_value = 12;
199 }
200 else
201 {
202 LogError("Unexpected TLS version value (%d)", *(int*)value);
203 int_value = -1;
204 }
205
206 if (int_value < 0)
207 {
208 result = NULL;
209 }
210 else
211 {
212 int* value_clone;
213
214 if ((value_clone = (int*)malloc(sizeof(int))) == NULL)
215 {
216 LogError("Failed cloning tls_version option");
217 }
218 else
219 {
220 *value_clone = int_value;
221 }
222
223 result = value_clone;
224 }
225 }
226 else if (
227 (strcmp(name, "tls_validation_callback") == 0) ||
228 (strcmp(name, "tls_validation_callback_data") == 0)
229 )
230 {
231 result = (void*)value;
232 }
233 else if (strcmp(name, OPTION_OPENSSL_ENGINE) == 0)
234 {
235 if (mallocAndStrcpy_s((char**)&result, value) != 0)
236 {
237 LogError("unable to mallocAndStrcpy_s Engine value");
238 result = NULL;
239 }
240 else
241 {
242 /*return as is*/
243 }
244 }
245 else if (strcmp(name, OPTION_OPENSSL_PRIVATE_KEY_TYPE) == 0)
246 {
247 OPTION_OPENSSL_KEY_TYPE key_type_value = *((OPTION_OPENSSL_KEY_TYPE*)value);
248 OPTION_OPENSSL_KEY_TYPE* value_clone;
249
250 if ((value_clone = (OPTION_OPENSSL_KEY_TYPE*)malloc(sizeof(OPTION_OPENSSL_KEY_TYPE))) == NULL)
251 {
252 LogError("Failed cloning cert or private key option");
253 }
254 else
255 {
256 *value_clone = key_type_value;
257 }
258
259 result = value_clone;
260 }
261 else
262 {
263 LogError("not handled option : %s", name);
264 result = NULL;
265 }
266 }
267 return result;
268 }
269
270 /*this function destroys an option previously created*/
271 static void tlsio_openssl_DestroyOption(const char* name, const void* value)
272 {
273 /*since all options for this layer are actually string copies., disposing of one is just calling free*/
274 if (
275 (name == NULL) || (value == NULL)
276 )
277 {
278 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
279 }
280 else
281 {
282 if (
283 (strcmp(name, OPTION_TRUSTED_CERT) == 0) ||
284 (strcmp(name, OPTION_OPENSSL_CIPHER_SUITE) == 0) ||
285 (strcmp(name, SU_OPTION_X509_CERT) == 0) ||
286 (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0) ||
287 (strcmp(name, OPTION_X509_ECC_CERT) == 0) ||
288 (strcmp(name, OPTION_X509_ECC_KEY) == 0) ||
289 (strcmp(name, OPTION_TLS_VERSION) == 0) ||
290 (strcmp(name, OPTION_OPENSSL_ENGINE) == 0) ||
291 (strcmp(name, OPTION_OPENSSL_PRIVATE_KEY_TYPE) == 0)
292 )
293 {
294 free((void*)value);
295 }
296 else if (
297 (strcmp(name, "tls_validation_callback") == 0) ||
298 (strcmp(name, "tls_validation_callback_data") == 0)
299 )
300 {
301 // nothing to free.
302 }
303 else if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
304 {
305 OptionHandler_Destroy((OPTIONHANDLER_HANDLE)value);
306 }
307 else
308 {
309 LogError("not handled option : %s", name);
310 }
311 }
312 }
313
314 static OPTIONHANDLER_HANDLE tlsio_openssl_retrieveoptions(CONCRETE_IO_HANDLE handle)
315 {
316 OPTIONHANDLER_HANDLE result;
317 if (handle == NULL)
318 {
319 LogError("invalid parameter detected: CONCRETE_IO_HANDLE handle=%p", handle);
320 result = NULL;
321 }
322 else
323 {
324 result = OptionHandler_Create(tlsio_openssl_CloneOption, tlsio_openssl_DestroyOption, tlsio_openssl_setoption);
325 if (result == NULL)
326 {
327 LogError("unable to OptionHandler_Create");
328 /*return as is*/
329 }
330 else
331 {
332 /*this layer cares about the certificates and the x509 credentials*/
333 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)handle;
334 OPTIONHANDLER_HANDLE underlying_io_options;
335
336 if ((underlying_io_options = xio_retrieveoptions(tls_io_instance->underlying_io)) == NULL)
337 {
338 LogError("unable to retrieve underlying_io options");
339 OptionHandler_Destroy(result);
340 result = NULL;
341 }
342 else
343 {
344 if (OptionHandler_AddOption(result, OPTION_UNDERLYING_IO_OPTIONS, underlying_io_options) != OPTIONHANDLER_OK)
345 {
346 LogError("unable to save underlying_io options");
347 OptionHandler_Destroy(result);
348 result = NULL;
349 }
350 else if (
351 (tls_io_instance->certificate != NULL) &&
352 (OptionHandler_AddOption(result, OPTION_TRUSTED_CERT, tls_io_instance->certificate) != OPTIONHANDLER_OK)
353 )
354 {
355 LogError("unable to save TrustedCerts option");
356 OptionHandler_Destroy(result);
357 result = NULL;
358 }
359 else if (
360 (tls_io_instance->cipher_list != NULL) &&
361 (OptionHandler_AddOption(result, OPTION_OPENSSL_CIPHER_SUITE, tls_io_instance->cipher_list) != OPTIONHANDLER_OK)
362 )
363 {
364 LogError("unable to save CipherSuite option");
365 OptionHandler_Destroy(result);
366 result = NULL;
367 }
368 else if (tls_io_instance->x509_certificate != NULL && (OptionHandler_AddOption(result, SU_OPTION_X509_CERT, tls_io_instance->x509_certificate) != OPTIONHANDLER_OK) )
369 {
370 LogError("unable to save x509 certificate option");
371 OptionHandler_Destroy(result);
372 result = NULL;
373 }
374 else if (tls_io_instance->x509_private_key != NULL && (OptionHandler_AddOption(result, SU_OPTION_X509_PRIVATE_KEY, tls_io_instance->x509_private_key) != OPTIONHANDLER_OK) )
375 {
376 LogError("unable to save x509 privatekey option");
377 OptionHandler_Destroy(result);
378 result = NULL;
379 }
380 else if (tls_io_instance->tls_version != 0 && (OptionHandler_AddOption(result, OPTION_TLS_VERSION, &tls_io_instance->tls_version) != OPTIONHANDLER_OK) )
381 {
382 LogError("unable to save tls_version option");
383 OptionHandler_Destroy(result);
384 result = NULL;
385 }
386 else if (
387 (tls_io_instance->engine_id != NULL) &&
388 (OptionHandler_AddOption(result, OPTION_OPENSSL_ENGINE, tls_io_instance->engine_id) != OPTIONHANDLER_OK)
389 )
390 {
391 LogError("unable to save Engine option");
392 OptionHandler_Destroy(result);
393 result = NULL;
394 }
395 else if (
396 (tls_io_instance->x509_private_key_type != KEY_TYPE_DEFAULT) &&
397 (OptionHandler_AddOption(result, OPTION_OPENSSL_PRIVATE_KEY_TYPE, &tls_io_instance->x509_private_key_type))
398 )
399 {
400 LogError("unable to save x509PrivatekeyType option");
401 OptionHandler_Destroy(result);
402 result = NULL;
403 }
404 else if (tls_io_instance->tls_validation_callback != NULL)
405 {
406 #ifdef WIN32
407 #pragma warning(push)
408 #pragma warning(disable:4152)
409 #endif
410 void* ptr = tls_io_instance->tls_validation_callback;
411 #ifdef WIN32
412 #pragma warning(pop)
413 #endif
414 if (OptionHandler_AddOption(result, "tls_validation_callback", (const char*)ptr) != OPTIONHANDLER_OK)
415 {
416 LogError("unable to save tls_validation_callback option");
417 OptionHandler_Destroy(result);
418 result = NULL;
419 }
420
421 if (OptionHandler_AddOption(result, "tls_validation_callback_data", (const char*)tls_io_instance->tls_validation_callback_data) != OPTIONHANDLER_OK)
422 {
423 LogError("unable to save tls_validation_callback_data option");
424 OptionHandler_Destroy(result);
425 result = NULL;
426 }
427 }
428 else
429 {
430 /*all is fine, all interesting options have been saved*/
431 /*return as is*/
432 }
433
434 // Must destroy since OptionHandler_AddOption creates a copy of it.
435 OptionHandler_Destroy(underlying_io_options);
436 }
437 }
438 }
439 return result;
440 }
441
442 static const IO_INTERFACE_DESCRIPTION tlsio_openssl_interface_description =
443 {
444 tlsio_openssl_retrieveoptions,
445 tlsio_openssl_create,
446 tlsio_openssl_destroy,
447 tlsio_openssl_open,
448 tlsio_openssl_close,
449 tlsio_openssl_send,
450 tlsio_openssl_dowork,
451 tlsio_openssl_setoption
452 };
453
454 static LOCK_HANDLE * openssl_locks = NULL;
455
456
457 static void openssl_lock_unlock_helper(LOCK_HANDLE lock, int lock_mode, const char* file, int line)
458 {
459 #ifdef NO_LOGGING
460 // Avoid unused variable warning when logging not compiled in
461 (void)file;
462 (void)line;
463 #endif
464
465 if (lock_mode & CRYPTO_LOCK)
466 {
467 if (Lock(lock) != LOCK_OK)
468 {
469 LogError("Failed to lock openssl lock (%s:%d)", file, line);
470 }
471 }
472 else
473 {
474 if (Unlock(lock) != LOCK_OK)
475 {
476 LogError("Failed to unlock openssl lock (%s:%d)", file, line);
477 }
478 }
479 }
480
481 static void log_ERR_get_error(const char* message)
482 {
483 char buf[128];
484 AZURE_UNREFERENCED_PARAMETER(buf);
485 unsigned long error;
486 int i;
487
488 if (message != NULL)
489 {
490 LogError("%s", message);
491 }
492
493 error = ERR_get_error();
494
495 for (i = 0; 0 != error; i++)
496 {
497 LogError(" [%d] %s", i, ERR_error_string(error, buf));
498 error = ERR_get_error();
499 }
500 }
501
502 static STATIC_VAR_UNUSED struct CRYPTO_dynlock_value* openssl_dynamic_locks_create_cb(const char* file, int line)
503 {
504 #ifdef NO_LOGGING
505 // Avoid unused variable warning when logging not compiled in
506 (void)file;
507 (void)line;
508 #endif
509
510 struct CRYPTO_dynlock_value* result;
511
512 result = malloc(sizeof(struct CRYPTO_dynlock_value));
513
514 if (result == NULL)
515 {
516 LogError("Failed to allocate lock! Out of memory (%s:%d).", file, line);
517 }
518 else
519 {
520 result->lock = Lock_Init();
521 if (result->lock == NULL)
522 {
523 LogError("Failed to create lock for dynamic lock (%s:%d).", file, line);
524
525 free(result);
526 result = NULL;
527 }
528 }
529
530 return result;
531 }
532
533 static STATIC_VAR_UNUSED void openssl_dynamic_locks_lock_unlock_cb(int lock_mode, struct CRYPTO_dynlock_value* dynlock_value, const char* file, int line)
534 {
535 openssl_lock_unlock_helper(dynlock_value->lock, lock_mode, file, line);
536 }
537
538 static STATIC_VAR_UNUSED void openssl_dynamic_locks_destroy_cb(struct CRYPTO_dynlock_value* dynlock_value, const char* file, int line)
539 {
540 (void)file;
541 (void)line;
542 Lock_Deinit(dynlock_value->lock);
543 free(dynlock_value);
544 }
545
546 static void openssl_dynamic_locks_uninstall(void)
547 {
548 #if (OPENSSL_VERSION_NUMBER >= 0x00906000)
549 CRYPTO_set_dynlock_create_callback(NULL);
550 CRYPTO_set_dynlock_lock_callback(NULL);
551 CRYPTO_set_dynlock_destroy_callback(NULL);
552 #endif
553 }
554
555 static void openssl_dynamic_locks_install(void)
556 {
557 #if (OPENSSL_VERSION_NUMBER >= 0x00906000)
558 CRYPTO_set_dynlock_destroy_callback(openssl_dynamic_locks_destroy_cb);
559 CRYPTO_set_dynlock_lock_callback(openssl_dynamic_locks_lock_unlock_cb);
560 CRYPTO_set_dynlock_create_callback(openssl_dynamic_locks_create_cb);
561 #endif
562 }
563
564 static void STATIC_VAR_UNUSED openssl_static_locks_lock_unlock_cb(int lock_mode, int lock_index, const char * file, int line)
565 {
566 if (lock_index < 0 || lock_index >= CRYPTO_num_locks())
567 {
568 LogError("Bad lock index %d passed (%s:%d)", lock_index, file, line);
569 }
570 else
571 {
572 openssl_lock_unlock_helper(openssl_locks[lock_index], lock_mode, file, line);
573 }
574 }
575
576 static void openssl_static_locks_uninstall(void)
577 {
578 if (openssl_locks != NULL)
579 {
580 int i;
581 CRYPTO_set_locking_callback(NULL);
582
583 for (i = 0; i < CRYPTO_num_locks(); i++)
584 {
585 if (openssl_locks[i] != NULL)
586 {
587 Lock_Deinit(openssl_locks[i]);
588 }
589 }
590
591 free(openssl_locks);
592 openssl_locks = NULL;
593 }
594 else
595 {
596 LogError("Locks already uninstalled");
597 }
598 }
599
600 static int openssl_static_locks_install(void)
601 {
602 int result;
603
604 if (openssl_locks != NULL)
605 {
606 LogInfo("Locks already initialized");
607 result = MU_FAILURE;
608 }
609 else
610 {
611 size_t malloc_size = safe_multiply_size_t(CRYPTO_num_locks(), sizeof(LOCK_HANDLE));
612 if (malloc_size == SIZE_MAX ||
613 (openssl_locks = malloc(malloc_size)) == NULL)
614 {
615 LogError("Failed to allocate locks, size:%zu", malloc_size);
616 result = MU_FAILURE;
617 }
618 else
619 {
620 int i;
621 for (i = 0; i < CRYPTO_num_locks(); i++)
622 {
623 openssl_locks[i] = Lock_Init();
624 if (openssl_locks[i] == NULL)
625 {
626 LogError("Failed to allocate lock %d", i);
627 break;
628 }
629 }
630
631 if (i != CRYPTO_num_locks())
632 {
633 int j;
634 for (j = 0; j < i; j++)
635 {
636 Lock_Deinit(openssl_locks[j]);
637 }
638 result = MU_FAILURE;
639 }
640 else
641 {
642 CRYPTO_set_locking_callback(openssl_static_locks_lock_unlock_cb);
643
644 result = 0;
645 }
646 }
647 }
648 return result;
649 }
650
651 static void indicate_error(TLS_IO_INSTANCE* tls_io_instance)
652 {
653 if (tls_io_instance->on_io_error == NULL)
654 {
655 LogError("NULL on_io_error.");
656 }
657 else
658 {
659 tls_io_instance->on_io_error(tls_io_instance->on_io_error_context);
660 }
661 }
662
663 static void indicate_open_complete(TLS_IO_INSTANCE* tls_io_instance, IO_OPEN_RESULT open_result)
664 {
665 if (tls_io_instance->on_io_open_complete == NULL)
666 {
667 LogError("NULL on_io_open_complete.");
668 }
669 else
670 {
671 tls_io_instance->on_io_open_complete(tls_io_instance->on_io_open_complete_context, open_result);
672 }
673 }
674
675 static int write_outgoing_bytes(TLS_IO_INSTANCE* tls_io_instance, ON_SEND_COMPLETE on_send_complete, void* callback_context)
676 {
677 int result;
678
679 size_t pending = BIO_ctrl_pending(tls_io_instance->out_bio);
680
681 if (pending == 0)
682 {
683 result = 0;
684 }
685 else
686 {
687 unsigned char* bytes_to_send = malloc(pending);
688 if (bytes_to_send == NULL)
689 {
690 LogError("NULL bytes_to_send.");
691 result = MU_FAILURE;
692 }
693 else
694 {
695 if (BIO_read(tls_io_instance->out_bio, bytes_to_send, (int)pending) != (int)pending)
696 {
697 log_ERR_get_error("BIO_read not in pending state.");
698 result = MU_FAILURE;
699 }
700 else
701 {
702 if (xio_send(tls_io_instance->underlying_io, bytes_to_send, pending, on_send_complete, callback_context) != 0)
703 {
704 LogError("Error in xio_send.");
705 result = MU_FAILURE;
706 }
707 else
708 {
709 result = 0;
710 }
711 }
712
713 free(bytes_to_send);
714 }
715 }
716
717 return result;
718 }
719
720 // Non-NULL tls_io_instance is guaranteed by callers.
721 // We are in TLSIO_STATE_IN_HANDSHAKE when entering this method.
722 static void send_handshake_bytes(TLS_IO_INSTANCE* tls_io_instance)
723 {
724 int hsret;
725 // ERR_clear_error must be called before any call that might set an
726 // SSL_get_error result
727 ERR_clear_error();
728 hsret = SSL_do_handshake(tls_io_instance->ssl);
729 if (hsret != SSL_DO_HANDSHAKE_SUCCESS)
730 {
731 int ssl_err = SSL_get_error(tls_io_instance->ssl, hsret);
732 if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE)
733 {
734 if (ssl_err == SSL_ERROR_SSL)
735 {
736 LogError("%s", ERR_error_string(ERR_get_error(), NULL));
737 }
738 else
739 {
740 LogError("SSL handshake failed: %d", ssl_err);
741 }
742 tls_io_instance->tlsio_state = TLSIO_STATE_HANDSHAKE_FAILED;
743 }
744 else
745 {
746 if (write_outgoing_bytes(tls_io_instance, NULL, NULL) != 0)
747 {
748 LogError("Error in write_outgoing_bytes.");
749 tls_io_instance->tlsio_state = TLSIO_STATE_HANDSHAKE_FAILED;
750 }
751 }
752 }
753 else
754 {
755 tls_io_instance->tlsio_state = TLSIO_STATE_OPEN;
756 indicate_open_complete(tls_io_instance, IO_OPEN_OK);
757 }
758 }
759
760 void engine_destroy(TLS_IO_INSTANCE* tls)
761 {
762 if(tls->engine != NULL)
763 {
764 #ifndef OPENSSL_NO_ENGINE
765 ENGINE_free(tls->engine); // Release structural reference.
766 #endif // OPENSSL_NO_ENGINE
767 tls->engine = NULL;
768 }
769 }
770
771 #ifndef OPENSSL_NO_ENGINE
772 int engine_load(TLS_IO_INSTANCE* tls)
773 {
774 int result;
775
776 // TLSIO is only responsible for the Engine structural reference.
777 tls->engine = ENGINE_by_id(tls->engine_id);
778 if (tls->engine == NULL)
779 {
780 log_ERR_get_error("unable to load engine by ID.");
781 result = MU_FAILURE;
782 }
783 else
784 {
785 result = 0;
786 }
787
788 return result;
789 }
790 #endif // OPENSSL_NO_ENGINE
791
792 static void close_openssl_instance(TLS_IO_INSTANCE* tls_io_instance)
793 {
794 if (tls_io_instance->ssl != NULL)
795 {
796 SSL_free(tls_io_instance->ssl);
797 tls_io_instance->ssl = NULL;
798 }
799 if (tls_io_instance->ssl_context != NULL)
800 {
801 SSL_CTX_free(tls_io_instance->ssl_context);
802 tls_io_instance->ssl_context = NULL;
803 }
804 }
805
806 static void on_underlying_io_close_complete(void* context)
807 {
808 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)context;
809
810 switch (tls_io_instance->tlsio_state)
811 {
812 default:
813 case TLSIO_STATE_NOT_OPEN:
814 case TLSIO_STATE_OPEN:
815 case TLSIO_STATE_IN_HANDSHAKE:
816 case TLSIO_STATE_HANDSHAKE_FAILED:
817 case TLSIO_STATE_ERROR:
818 break;
819
820 case TLSIO_STATE_OPENING_UNDERLYING_IO:
821 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
822 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
823 break;
824
825 case TLSIO_STATE_CLOSING:
826 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
827
828 if (tls_io_instance->on_io_close_complete != NULL)
829 {
830 tls_io_instance->on_io_close_complete(tls_io_instance->on_io_close_complete_context);
831 }
832 break;
833 }
834
835 close_openssl_instance(tls_io_instance);
836 }
837
838 static void on_underlying_io_open_complete(void* context, IO_OPEN_RESULT open_result)
839 {
840 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)context;
841
842 if (tls_io_instance->tlsio_state == TLSIO_STATE_OPENING_UNDERLYING_IO)
843 {
844 if (open_result == IO_OPEN_OK)
845 {
846 tls_io_instance->tlsio_state = TLSIO_STATE_IN_HANDSHAKE;
847
848 // Begin the handshake process here. It continues in on_underlying_io_bytes_received
849 send_handshake_bytes(tls_io_instance);
850 }
851 else
852 {
853 LogError("Invalid open_result. Expected result is IO_OPEN_OK.");
854 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
855 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
856 }
857 }
858 else
859 {
860 LogError("Invalid tlsio_state. Expected state is TLSIO_STATE_OPENING_UNDERLYING_IO.");
861 }
862 }
863
864 static void on_underlying_io_error(void* context)
865 {
866 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)context;
867
868 switch (tls_io_instance->tlsio_state)
869 {
870 default:
871 break;
872
873 case TLSIO_STATE_OPENING_UNDERLYING_IO:
874 case TLSIO_STATE_IN_HANDSHAKE:
875 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
876 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
877 break;
878
879 case TLSIO_STATE_OPEN:
880 indicate_error(tls_io_instance);
881 break;
882 }
883 }
884
885 static int decode_ssl_received_bytes(TLS_IO_INSTANCE* tls_io_instance)
886 {
887 int result = 0;
888 unsigned char buffer[64];
889
890 int rcv_bytes = 1;
891
892 while (rcv_bytes > 0)
893 {
894 if (tls_io_instance->ssl == NULL)
895 {
896 LogError("SSL channel closed in decode_ssl_received_bytes.");
897 result = MU_FAILURE;
898 return result;
899 }
900
901 rcv_bytes = SSL_read(tls_io_instance->ssl, buffer, sizeof(buffer));
902 if (rcv_bytes > 0)
903 {
904 if (tls_io_instance->on_bytes_received == NULL)
905 {
906 LogError("NULL on_bytes_received.");
907 }
908 else
909 {
910 tls_io_instance->on_bytes_received(tls_io_instance->on_bytes_received_context, buffer, rcv_bytes);
911 }
912 }
913 }
914
915 return result;
916 }
917
918 static void on_underlying_io_bytes_received(void* context, const unsigned char* buffer, size_t size)
919 {
920 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)context;
921
922 int written = BIO_write(tls_io_instance->in_bio, buffer, (int)size);
923 if (written != (int)size)
924 {
925 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
926 indicate_error(tls_io_instance);
927 log_ERR_get_error("Error in BIO_write.");
928 }
929 else
930 {
931 switch (tls_io_instance->tlsio_state)
932 {
933 default:
934 break;
935
936 case TLSIO_STATE_IN_HANDSHAKE:
937 send_handshake_bytes(tls_io_instance);
938 break;
939
940 case TLSIO_STATE_OPEN:
941 if (decode_ssl_received_bytes(tls_io_instance) != 0)
942 {
943 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
944 indicate_error(tls_io_instance);
945 LogError("Error in decode_ssl_received_bytes.");
946 }
947 break;
948 }
949 }
950 }
951
952 static int add_certificate_to_store(TLS_IO_INSTANCE* tls_io_instance, const char* certValue)
953 {
954 int result = 0;
955
956 if (certValue != NULL)
957 {
958 X509_STORE* cert_store = SSL_CTX_get_cert_store(tls_io_instance->ssl_context);
959 if (cert_store == NULL)
960 {
961 log_ERR_get_error("failure in SSL_CTX_get_cert_store.");
962 result = MU_FAILURE;
963 }
964 else
965 {
966 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
967 const BIO_METHOD* bio_method;
968 #else
969 BIO_METHOD* bio_method;
970 #endif
971 bio_method = BIO_s_mem();
972 if (bio_method == NULL)
973 {
974 log_ERR_get_error("failure in BIO_s_mem");
975 result = MU_FAILURE;
976 }
977 else
978 {
979 BIO* cert_memory_bio = BIO_new(bio_method);
980
981 if (cert_memory_bio == NULL)
982 {
983 log_ERR_get_error("failure in BIO_new");
984 result = MU_FAILURE;
985 }
986 else
987 {
988 int puts_result = BIO_puts(cert_memory_bio, certValue);
989 if (puts_result < 0)
990 {
991 log_ERR_get_error("failure in BIO_puts");
992 result = MU_FAILURE;
993 }
994 else
995 {
996 if ((size_t)puts_result != strlen(certValue))
997 {
998 log_ERR_get_error("mismatching legths");
999 result = MU_FAILURE;
1000 }
1001 else
1002 {
1003 X509* certificate;
1004 while ((certificate = PEM_read_bio_X509(cert_memory_bio, NULL, NULL, NULL)) != NULL)
1005 {
1006 if (!X509_STORE_add_cert(cert_store, certificate))
1007 {
1008 X509_free(certificate);
1009 log_ERR_get_error("failure in X509_STORE_add_cert");
1010 break;
1011 }
1012 X509_free(certificate);
1013 }
1014 if (certificate == NULL)
1015 {
1016 result = 0;/*all is fine*/
1017 }
1018 else
1019 {
1020 /*previous while loop terminated unfortunately*/
1021 result = MU_FAILURE;
1022 }
1023 }
1024 }
1025 BIO_free(cert_memory_bio);
1026 }
1027 }
1028 }
1029 }
1030 return result;
1031 }
1032
1033 static int enable_domain_check(TLS_IO_INSTANCE* tlsInstance)
1034 {
1035 int result = 0;
1036
1037 if (!tlsInstance->ignore_host_name_check)
1038 {
1039 #if (OPENSSL_VERSION_NUMBER < 0x10002000L)
1040 #error "OpenSSL v1.0.2 or above required. See https://wiki.openssl.org/index.php/Hostname_validation for details."
1041 #endif
1042 X509_VERIFY_PARAM *param = SSL_get0_param(tlsInstance->ssl);
1043
1044 X509_VERIFY_PARAM_set_hostflags(param, 0);
1045 if (!(X509_VERIFY_PARAM_set1_ip_asc(param, tlsInstance->hostname) ||
1046 X509_VERIFY_PARAM_set1_host(param, tlsInstance->hostname, strlen(tlsInstance->hostname))))
1047 {
1048 result = MU_FAILURE;
1049 }
1050 else
1051 {
1052 SSL_set_verify(tlsInstance->ssl, SSL_VERIFY_PEER, NULL);
1053 }
1054 }
1055
1056 return result;
1057 }
1058
1059 static int create_openssl_instance(TLS_IO_INSTANCE* tlsInstance)
1060 {
1061 int result;
1062
1063 const SSL_METHOD* method = NULL;
1064
1065 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
1066 if (tlsInstance->tls_version == VERSION_1_2)
1067 {
1068 method = TLSv1_2_method();
1069 }
1070 else if (tlsInstance->tls_version == VERSION_1_1)
1071 {
1072 method = TLSv1_1_method();
1073 }
1074 else
1075 {
1076 method = TLSv1_method();
1077 }
1078 #else
1079 {
1080 method = TLS_method();
1081 }
1082 #endif
1083
1084 tlsInstance->ssl_context = SSL_CTX_new(method);
1085 if (tlsInstance->ssl_context == NULL)
1086 {
1087 log_ERR_get_error("Failed allocating OpenSSL context.");
1088 result = MU_FAILURE;
1089 }
1090 #ifndef OPENSSL_NO_ENGINE
1091 else if ((tlsInstance->engine_id != NULL) &&
1092 (engine_load(tlsInstance) != 0))
1093 {
1094 SSL_CTX_free(tlsInstance->ssl_context);
1095 tlsInstance->ssl_context = NULL;
1096 result = MU_FAILURE;
1097 }
1098 #endif // OPENSSL_NO_ENGINE
1099 else if ((tlsInstance->cipher_list != NULL) &&
1100 (SSL_CTX_set_cipher_list(tlsInstance->ssl_context, tlsInstance->cipher_list)) != 1)
1101 {
1102 engine_destroy(tlsInstance);
1103 SSL_CTX_free(tlsInstance->ssl_context);
1104 tlsInstance->ssl_context = NULL;
1105 log_ERR_get_error("unable to set cipher list.");
1106 result = MU_FAILURE;
1107 }
1108 else if (add_certificate_to_store(tlsInstance, tlsInstance->certificate) != 0)
1109 {
1110 engine_destroy(tlsInstance);
1111 SSL_CTX_free(tlsInstance->ssl_context);
1112 tlsInstance->ssl_context = NULL;
1113 log_ERR_get_error("unable to add_certificate_to_store.");
1114 result = MU_FAILURE;
1115 }
1116 /*x509 authentication can only be build before underlying connection is realized*/
1117 else if (
1118 (tlsInstance->x509_certificate != NULL) &&
1119 (tlsInstance->x509_private_key != NULL) &&
1120 (x509_openssl_add_credentials(
1121 tlsInstance->ssl_context,
1122 tlsInstance->x509_certificate,
1123 tlsInstance->x509_private_key,
1124 #ifndef OPENSSL_NO_ENGINE
1125 tlsInstance->x509_private_key_type,
1126 tlsInstance->engine) != 0)
1127 #else // OPENSSL_NO_ENGINE
1128 tlsInstance->x509_private_key_type) != 0)
1129 #endif // OPENSSL_NO_ENGINE
1130 )
1131 {
1132 engine_destroy(tlsInstance);
1133 SSL_CTX_free(tlsInstance->ssl_context);
1134 tlsInstance->ssl_context = NULL;
1135 log_ERR_get_error("unable to use x509 authentication");
1136 result = MU_FAILURE;
1137 }
1138 else
1139 {
1140 SSL_CTX_set_cert_verify_callback(tlsInstance->ssl_context, tlsInstance->tls_validation_callback, tlsInstance->tls_validation_callback_data);
1141
1142 tlsInstance->in_bio = BIO_new(BIO_s_mem());
1143 if (tlsInstance->in_bio == NULL)
1144 {
1145 engine_destroy(tlsInstance);
1146 SSL_CTX_free(tlsInstance->ssl_context);
1147 tlsInstance->ssl_context = NULL;
1148 log_ERR_get_error("Failed BIO_new for in BIO.");
1149 result = MU_FAILURE;
1150 }
1151 else
1152 {
1153 tlsInstance->out_bio = BIO_new(BIO_s_mem());
1154 if (tlsInstance->out_bio == NULL)
1155 {
1156 (void)BIO_free(tlsInstance->in_bio);
1157 engine_destroy(tlsInstance);
1158 SSL_CTX_free(tlsInstance->ssl_context);
1159 tlsInstance->ssl_context = NULL;
1160 log_ERR_get_error("Failed BIO_new for out BIO.");
1161 result = MU_FAILURE;
1162 }
1163 else
1164 {
1165 if ((BIO_set_mem_eof_return(tlsInstance->in_bio, -1) <= 0) ||
1166 (BIO_set_mem_eof_return(tlsInstance->out_bio, -1) <= 0))
1167 {
1168 (void)BIO_free(tlsInstance->in_bio);
1169 (void)BIO_free(tlsInstance->out_bio);
1170 engine_destroy(tlsInstance);
1171 SSL_CTX_free(tlsInstance->ssl_context);
1172 tlsInstance->ssl_context = NULL;
1173 LogError("Failed BIO_set_mem_eof_return.");
1174 result = MU_FAILURE;
1175 }
1176 else
1177 {
1178 SSL_CTX_set_verify(tlsInstance->ssl_context, SSL_VERIFY_PEER, NULL);
1179
1180 // Specifies that the default locations for which CA certificates are loaded should be used.
1181 if (SSL_CTX_set_default_verify_paths(tlsInstance->ssl_context) != 1)
1182 {
1183 // This is only a warning to the user. They can still specify the certificate via SetOption.
1184 LogInfo("WARNING: Unable to specify the default location for CA certificates on this platform.");
1185 }
1186
1187 tlsInstance->ssl = SSL_new(tlsInstance->ssl_context);
1188
1189 if (tlsInstance->ssl == NULL)
1190 {
1191 (void)BIO_free(tlsInstance->in_bio);
1192 (void)BIO_free(tlsInstance->out_bio);
1193 engine_destroy(tlsInstance);
1194 SSL_CTX_free(tlsInstance->ssl_context);
1195 tlsInstance->ssl_context = NULL;
1196 log_ERR_get_error("Failed creating OpenSSL instance.");
1197 result = MU_FAILURE;
1198 }
1199 else if (SSL_set_tlsext_host_name(tlsInstance->ssl, tlsInstance->hostname) != 1)
1200 {
1201 SSL_free(tlsInstance->ssl);
1202 tlsInstance->ssl = NULL;
1203 (void)BIO_free(tlsInstance->in_bio);
1204 (void)BIO_free(tlsInstance->out_bio);
1205 engine_destroy(tlsInstance);
1206 SSL_CTX_free(tlsInstance->ssl_context);
1207 tlsInstance->ssl_context = NULL;
1208 log_ERR_get_error("Failed setting SNI hostname hint.");
1209 result = MU_FAILURE;
1210 }
1211 else if (enable_domain_check(tlsInstance))
1212 {
1213 SSL_free(tlsInstance->ssl);
1214 tlsInstance->ssl = NULL;
1215 (void)BIO_free(tlsInstance->in_bio);
1216 (void)BIO_free(tlsInstance->out_bio);
1217 SSL_CTX_free(tlsInstance->ssl_context);
1218 tlsInstance->ssl_context = NULL;
1219 log_ERR_get_error("Failed to configure domain name verification.");
1220 result = MU_FAILURE;
1221 }
1222 else
1223 {
1224 SSL_set_bio(tlsInstance->ssl, tlsInstance->in_bio, tlsInstance->out_bio);
1225 SSL_set_connect_state(tlsInstance->ssl);
1226 result = 0;
1227 }
1228 }
1229 }
1230 }
1231 }
1232 return result;
1233 }
1234
1235 int tlsio_openssl_init(void)
1236 {
1237 (void)SSL_library_init();
1238
1239 SSL_load_error_strings();
1240 ERR_load_BIO_strings();
1241 OpenSSL_add_all_algorithms();
1242
1243 if (openssl_static_locks_install() != 0)
1244 {
1245 LogInfo("Failed to install static locks in OpenSSL!");
1246 return MU_FAILURE;
1247 }
1248
1249 openssl_dynamic_locks_install();
1250 return 0;
1251 }
1252
1253 void tlsio_openssl_deinit(void)
1254 {
1255 openssl_dynamic_locks_uninstall();
1256 openssl_static_locks_uninstall();
1257 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L) && (FIPS_mode_set)
1258 FIPS_mode_set(0);
1259 #endif
1260 CRYPTO_set_locking_callback(NULL);
1261 CRYPTO_set_id_callback(NULL);
1262 ERR_free_strings();
1263 EVP_cleanup();
1264
1265 #if (OPENSSL_VERSION_NUMBER < 0x10000000L)
1266 ERR_remove_state(0);
1267 #elif (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
1268 ERR_remove_thread_state(NULL);
1269 #endif
1270 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && (OPENSSL_VERSION_NUMBER < 0x10010000L) && (SSL_COMP_free_compression_methods)
1271 SSL_COMP_free_compression_methods();
1272 #endif
1273 CRYPTO_cleanup_all_ex_data();
1274 }
1275
1276 CONCRETE_IO_HANDLE tlsio_openssl_create(void* io_create_parameters)
1277 {
1278 TLSIO_CONFIG* tls_io_config = io_create_parameters;
1279 TLS_IO_INSTANCE* result;
1280
1281 if (tls_io_config == NULL)
1282 {
1283 result = NULL;
1284 LogError("NULL tls_io_config.");
1285 }
1286 else
1287 {
1288 result = malloc(sizeof(TLS_IO_INSTANCE));
1289 if (result == NULL)
1290 {
1291 LogError("Failed allocating TLSIO instance.");
1292 }
1293 else if (mallocAndStrcpy_s(&result->hostname, tls_io_config->hostname) != 0)
1294 {
1295 LogError("Failed copying the target hostname.");
1296 free(result);
1297 result = NULL;
1298 }
1299 else
1300 {
1301 SOCKETIO_CONFIG socketio_config;
1302 const IO_INTERFACE_DESCRIPTION* underlying_io_interface;
1303 void* io_interface_parameters;
1304
1305 if (tls_io_config->underlying_io_interface != NULL)
1306 {
1307 underlying_io_interface = tls_io_config->underlying_io_interface;
1308 io_interface_parameters = tls_io_config->underlying_io_parameters;
1309 }
1310 else
1311 {
1312 socketio_config.hostname = tls_io_config->hostname;
1313 socketio_config.port = tls_io_config->port;
1314 socketio_config.accepted_socket = NULL;
1315
1316 underlying_io_interface = socketio_get_interface_description();
1317 io_interface_parameters = &socketio_config;
1318 }
1319
1320 if (underlying_io_interface == NULL)
1321 {
1322 free(result->hostname);
1323 free(result);
1324 result = NULL;
1325 LogError("Failed getting socket IO interface description.");
1326 }
1327 else
1328 {
1329 result->certificate = NULL;
1330 result->cipher_list = NULL;
1331 result->in_bio = NULL;
1332 result->out_bio = NULL;
1333 result->on_bytes_received = NULL;
1334 result->on_bytes_received_context = NULL;
1335 result->on_io_open_complete = NULL;
1336 result->on_io_open_complete_context = NULL;
1337 result->on_io_close_complete = NULL;
1338 result->on_io_close_complete_context = NULL;
1339 result->on_io_error = NULL;
1340 result->on_io_error_context = NULL;
1341 result->ssl = NULL;
1342 result->ssl_context = NULL;
1343 result->tls_validation_callback = NULL;
1344 result->tls_validation_callback_data = NULL;
1345 result->x509_certificate = NULL;
1346 result->x509_private_key = NULL;
1347 result->ignore_host_name_check = false;
1348 result->engine_id = NULL;
1349 result->engine = NULL;
1350 result->x509_private_key_type = KEY_TYPE_DEFAULT;
1351
1352 result->tls_version = VERSION_1_2;
1353
1354 result->underlying_io = xio_create(underlying_io_interface, io_interface_parameters);
1355 if (result->underlying_io == NULL)
1356 {
1357 free(result->hostname);
1358 free(result);
1359 result = NULL;
1360 LogError("Failed xio_create.");
1361 }
1362 else
1363 {
1364 result->tlsio_state = TLSIO_STATE_NOT_OPEN;
1365 }
1366 }
1367 }
1368 }
1369
1370 return result;
1371 }
1372
1373 void tlsio_openssl_destroy(CONCRETE_IO_HANDLE tls_io)
1374 {
1375 if (tls_io == NULL)
1376 {
1377 LogError("NULL tls_io.");
1378 }
1379 else
1380 {
1381 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1382 engine_destroy(tls_io_instance);
1383
1384 if (tls_io_instance->certificate != NULL)
1385 {
1386 free(tls_io_instance->certificate);
1387 tls_io_instance->certificate = NULL;
1388 }
1389 if (tls_io_instance->cipher_list != NULL)
1390 {
1391 free(tls_io_instance->cipher_list);
1392 tls_io_instance->cipher_list = NULL;
1393 }
1394 free((void*)tls_io_instance->x509_certificate);
1395 tls_io_instance->x509_certificate = NULL;
1396 free((void*)tls_io_instance->x509_private_key);
1397 tls_io_instance->x509_private_key = NULL;
1398 close_openssl_instance(tls_io_instance);
1399 if (tls_io_instance->underlying_io != NULL)
1400 {
1401 xio_destroy(tls_io_instance->underlying_io);
1402 tls_io_instance->underlying_io = NULL;
1403 }
1404 free(tls_io_instance->hostname);
1405 tls_io_instance->hostname = NULL;
1406 if (tls_io_instance->engine_id != NULL)
1407 {
1408 free(tls_io_instance->engine_id);
1409 tls_io_instance->engine_id = NULL;
1410 }
1411
1412 free(tls_io);
1413 }
1414 }
1415
1416 int tlsio_openssl_open(CONCRETE_IO_HANDLE tls_io, ON_IO_OPEN_COMPLETE on_io_open_complete, void* on_io_open_complete_context, ON_BYTES_RECEIVED on_bytes_received, void* on_bytes_received_context, ON_IO_ERROR on_io_error, void* on_io_error_context)
1417 {
1418 int result;
1419
1420 if (tls_io == NULL)
1421 {
1422 result = MU_FAILURE;
1423 LogError("NULL tls_io.");
1424 }
1425 else
1426 {
1427 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1428
1429 if (tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN)
1430 {
1431 LogError("Invalid tlsio_state. Expected state is TLSIO_STATE_NOT_OPEN.");
1432 result = MU_FAILURE;
1433 }
1434 else
1435 {
1436 tls_io_instance->on_io_open_complete = on_io_open_complete;
1437 tls_io_instance->on_io_open_complete_context = on_io_open_complete_context;
1438
1439 tls_io_instance->on_bytes_received = on_bytes_received;
1440 tls_io_instance->on_bytes_received_context = on_bytes_received_context;
1441
1442 tls_io_instance->on_io_error = on_io_error;
1443 tls_io_instance->on_io_error_context = on_io_error_context;
1444
1445 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_UNDERLYING_IO;
1446
1447 if (create_openssl_instance(tls_io_instance) != 0)
1448 {
1449 LogError("Failed creating the OpenSSL instance.");
1450 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1451 result = MU_FAILURE;
1452 }
1453 else if (xio_open(tls_io_instance->underlying_io, on_underlying_io_open_complete, tls_io_instance,
1454 on_underlying_io_bytes_received, tls_io_instance, on_underlying_io_error, tls_io_instance) != 0)
1455 {
1456 LogError("Failed opening the underlying I/O.");
1457 close_openssl_instance(tls_io_instance);
1458 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1459 result = MU_FAILURE;
1460 }
1461 else
1462 {
1463 result = 0;
1464 }
1465 }
1466 }
1467
1468 return result;
1469 }
1470
1471 /* Codes_SRS_TLSIO_30_009: [ The phrase "enter TLSIO_STATE_EXT_CLOSING" means the adapter shall iterate through any unsent messages in the queue and shall delete each message after calling its on_send_complete with the associated callback_context and IO_SEND_CANCELLED. ]*/
1472 /* Codes_SRS_TLSIO_30_006: [ The phrase "enter TLSIO_STATE_EXT_CLOSED" means the adapter shall forcibly close any existing connections then call the on_io_close_complete function and pass the on_io_close_complete_context that was supplied in tlsio_close_async. ]*/
1473 /* Codes_SRS_TLSIO_30_051: [ On success, if the underlying TLS does not support asynchronous closing, then the adapter shall enter TLSIO_STATE_EXT_CLOSED immediately after entering TLSIO_STATE_EX_CLOSING. ]*/
1474 int tlsio_openssl_close(CONCRETE_IO_HANDLE tls_io, ON_IO_CLOSE_COMPLETE on_io_close_complete, void* callback_context)
1475 {
1476 int result;
1477
1478 /* Codes_SRS_TLSIO_30_050: [ If the tlsio_handle parameter is NULL, tlsio_close_async shall log an error and return _FAILURE_. ]*/
1479 if (tls_io == NULL)
1480 {
1481 LogError("NULL tls_io.");
1482 result = MU_FAILURE;
1483 }
1484 else
1485 {
1486 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1487
1488 if (tls_io_instance->tlsio_state != TLSIO_STATE_ERROR && tls_io_instance->tlsio_state != TLSIO_STATE_OPEN)
1489 {
1490 /* Codes_RS_TLSIO_30_053: [ If the adapter is in any state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR then tlsio_close_async shall log that tlsio_close_async has been called and then continue normally. ]*/
1491 // LogInfo rather than LogError because this is an unusual but not erroneous situation
1492 LogInfo("Closing tlsio from a state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR");
1493 }
1494
1495 if (is_an_opening_state(tls_io_instance->tlsio_state))
1496 {
1497 /* Codes_SRS_TLSIO_30_057: [ On success, if the adapter is in TLSIO_STATE_EXT_OPENING, it shall call on_io_open_complete with the on_io_open_complete_context supplied in tlsio_open_async and IO_OPEN_CANCELLED. This callback shall be made before changing the internal state of the adapter. ]*/
1498 tls_io_instance->on_io_open_complete(tls_io_instance->on_io_open_complete_context, IO_OPEN_CANCELLED);
1499 }
1500
1501 if (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN)
1502 {
1503 // Attempt a graceful shutdown
1504 /* Codes_SRS_TLSIO_30_056: [ On success the adapter shall enter TLSIO_STATE_EX_CLOSING. ]*/
1505 tls_io_instance->tlsio_state = TLSIO_STATE_CLOSING;
1506 tls_io_instance->on_io_close_complete = on_io_close_complete;
1507 tls_io_instance->on_io_close_complete_context = callback_context;
1508 // xio_close is guaranteed to succeed from the open state, and the callback completes the
1509 // transition into TLSIO_STATE_NOT_OPEN
1510 if (xio_close(tls_io_instance->underlying_io, on_underlying_io_close_complete, tls_io_instance) != 0)
1511 {
1512 close_openssl_instance(tls_io_instance);
1513 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1514 }
1515 }
1516 else
1517 {
1518 // Just force the shutdown
1519 /* Codes_SRS_TLSIO_30_056: [ On success the adapter shall enter TLSIO_STATE_EX_CLOSING. ]*/
1520 /* Codes_SRS_TLSIO_30_051: [ On success, if the underlying TLS does not support asynchronous closing or if the adapter is not in TLSIO_STATE_EXT_OPEN, then the adapter shall enter TLSIO_STATE_EXT_CLOSED immediately after entering TLSIO_STATE_EXT_CLOSING. ]*/
1521 // Current implementations of xio_close will fail if not in the open state, but we don't care
1522 (void)xio_close(tls_io_instance->underlying_io, NULL, NULL);
1523 close_openssl_instance(tls_io_instance);
1524 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1525 }
1526
1527 result = 0;
1528 }
1529 /* Codes_SRS_TLSIO_30_054: [ On failure, the adapter shall not call on_io_close_complete. ]*/
1530
1531 return result;
1532 }
1533
1534 int tlsio_openssl_send(CONCRETE_IO_HANDLE tls_io, const void* buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void* callback_context)
1535 {
1536 int result;
1537
1538 if (tls_io == NULL)
1539 {
1540 LogError("NULL tls_io.");
1541 result = MU_FAILURE;
1542 }
1543 else
1544 {
1545 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1546
1547 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN)
1548 {
1549 LogError("Invalid tlsio_state. Expected state is TLSIO_STATE_OPEN.");
1550 result = MU_FAILURE;
1551 }
1552 else
1553 {
1554 int res;
1555 if (tls_io_instance->ssl == NULL)
1556 {
1557 LogError("SSL channel closed in tlsio_openssl_send.");
1558 result = MU_FAILURE;
1559 return result;
1560 }
1561
1562 res = SSL_write(tls_io_instance->ssl, buffer, (int)size);
1563 if (res != (int)size)
1564 {
1565 log_ERR_get_error("SSL_write error.");
1566 result = MU_FAILURE;
1567 }
1568 else
1569 {
1570 if (write_outgoing_bytes(tls_io_instance, on_send_complete, callback_context) != 0)
1571 {
1572 LogError("Error in write_outgoing_bytes.");
1573 result = MU_FAILURE;
1574 }
1575 else
1576 {
1577 result = 0;
1578 }
1579 }
1580 }
1581 }
1582
1583 return result;
1584 }
1585
1586 void tlsio_openssl_dowork(CONCRETE_IO_HANDLE tls_io)
1587 {
1588 if (tls_io == NULL)
1589 {
1590 LogError("NULL tls_io.");
1591 }
1592 else
1593 {
1594 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1595
1596 switch (tls_io_instance->tlsio_state)
1597 {
1598 case TLSIO_STATE_OPENING_UNDERLYING_IO:
1599 case TLSIO_STATE_IN_HANDSHAKE:
1600 case TLSIO_STATE_OPEN:
1601 /* this is needed in order to pump out bytes produces by OpenSSL for things like renegotiation */
1602 write_outgoing_bytes(tls_io_instance, NULL, NULL);
1603 break;
1604 case TLSIO_STATE_NOT_OPEN:
1605 case TLSIO_STATE_HANDSHAKE_FAILED:
1606 case TLSIO_STATE_CLOSING:
1607 case TLSIO_STATE_ERROR:
1608 default:
1609 break;
1610 }
1611
1612 if (tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN)
1613 {
1614 /* Same behavior as schannel */
1615 xio_dowork(tls_io_instance->underlying_io);
1616
1617 if (tls_io_instance->tlsio_state == TLSIO_STATE_HANDSHAKE_FAILED)
1618 {
1619 // The handshake failed so we need to close. The tlsio becomes aware of the
1620 // handshake failure during an on_bytes_received while the underlying
1621 // xio_dowork is pumping data out of the socket in a while loop. The tlsio can't
1622 // close down during the callback because that would mean the xio_dowork would
1623 // be trying to read from a closed socket. So instead, the tlsio sets its state
1624 // to TLSIO_STATE_HANDSHAKE_FAILED during the on_bytes_received callback,
1625 // can then gracefully shut things down here.
1626 //
1627 // Set the state to TLSIO_STATE_ERROR so close won't gripe about the state
1628 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
1629 tlsio_openssl_close(tls_io_instance, NULL, NULL);
1630 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
1631 }
1632 }
1633 }
1634 }
1635
1636 int tlsio_openssl_setoption(CONCRETE_IO_HANDLE tls_io, const char* optionName, const void* value)
1637 {
1638 int result;
1639
1640 if (tls_io == NULL || optionName == NULL)
1641 {
1642 result = MU_FAILURE;
1643 }
1644 else
1645 {
1646 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io;
1647
1648 if (strcmp(OPTION_TRUSTED_CERT, optionName) == 0)
1649 {
1650 const char* cert = (const char*)value;
1651 size_t len;
1652
1653 if (tls_io_instance->certificate != NULL)
1654 {
1655 // Free the memory if it has been previously allocated
1656 free(tls_io_instance->certificate);
1657 tls_io_instance->certificate = NULL;
1658 }
1659
1660 // Store the certificate
1661 len = strlen(cert);
1662 size_t malloc_size = safe_add_size_t(len, 1);
1663 if (malloc_size == SIZE_MAX ||
1664 (tls_io_instance->certificate = malloc(malloc_size)) == NULL)
1665 {
1666 LogError("malloc failure, size:%zu", malloc_size);
1667 result = MU_FAILURE;
1668 }
1669 else
1670 {
1671 strcpy(tls_io_instance->certificate, cert);
1672 result = 0;
1673 }
1674
1675 // If we're previously connected then add the cert to the context
1676 if (tls_io_instance->ssl_context != NULL)
1677 {
1678 result = add_certificate_to_store(tls_io_instance, cert);
1679 }
1680 }
1681 else if (strcmp(OPTION_OPENSSL_CIPHER_SUITE, optionName) == 0)
1682 {
1683 if (tls_io_instance->cipher_list != NULL)
1684 {
1685 // Free the memory if it has been previously allocated
1686 free(tls_io_instance->cipher_list);
1687 tls_io_instance->cipher_list = NULL;
1688 }
1689
1690 // Store the cipher suites
1691 if (mallocAndStrcpy_s((char**)&tls_io_instance->cipher_list, value) != 0)
1692 {
1693 LogError("unable to mallocAndStrcpy_s %s", optionName);
1694 result = MU_FAILURE;
1695 }
1696 else
1697 {
1698 result = 0;
1699 }
1700 }
1701 else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0 || strcmp(OPTION_X509_ECC_CERT, optionName) == 0)
1702 {
1703 if (tls_io_instance->x509_certificate != NULL)
1704 {
1705 LogError("unable to set x509 options more than once");
1706 result = MU_FAILURE;
1707 }
1708 else
1709 {
1710 /*let's make a copy of this option*/
1711 if (mallocAndStrcpy_s((char**)&tls_io_instance->x509_certificate, value) != 0)
1712 {
1713 LogError("unable to mallocAndStrcpy_s %s", optionName);
1714 result = MU_FAILURE;
1715 }
1716 else
1717 {
1718 result = 0;
1719 }
1720 }
1721 }
1722 else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0 || strcmp(OPTION_X509_ECC_KEY, optionName) == 0)
1723 {
1724 if (tls_io_instance->x509_private_key != NULL)
1725 {
1726 LogError("unable to set more than once x509 options");
1727 result = MU_FAILURE;
1728 }
1729 else
1730 {
1731 /*let's make a copy of this option*/
1732 if (mallocAndStrcpy_s((char**)&tls_io_instance->x509_private_key, value) != 0)
1733 {
1734 LogError("unable to mallocAndStrcpy_s %s", optionName);
1735 result = MU_FAILURE;
1736 }
1737 else
1738 {
1739 result = 0;
1740 }
1741 }
1742 }
1743 #ifndef OPENSSL_NO_ENGINE
1744 else if (strcmp(OPTION_OPENSSL_ENGINE, optionName) == 0)
1745 {
1746 ENGINE_load_builtin_engines();
1747
1748 if (mallocAndStrcpy_s((char**)&tls_io_instance->engine_id, value) != 0)
1749 {
1750 LogError("unable to mallocAndStrcpy_s %s", optionName);
1751 result = MU_FAILURE;
1752 }
1753 else
1754 {
1755 result = 0;
1756 }
1757 }
1758 #endif // OPENSSL_NO_ENGINE
1759 else if (strcmp(OPTION_OPENSSL_PRIVATE_KEY_TYPE, optionName) == 0)
1760 {
1761 const OPTION_OPENSSL_KEY_TYPE type = *(const OPTION_OPENSSL_KEY_TYPE*)value;
1762 switch (type)
1763 {
1764 case KEY_TYPE_DEFAULT:
1765 case KEY_TYPE_ENGINE:
1766 tls_io_instance->x509_private_key_type = type;
1767 result = 0;
1768 break;
1769
1770 default:
1771 LogError("Unknown x509PrivatekeyType type %d", type);
1772 result = MU_FAILURE;
1773 }
1774 }
1775 else if (strcmp("tls_validation_callback", optionName) == 0)
1776 {
1777 #ifdef WIN32
1778 #pragma warning(push)
1779 #pragma warning(disable:4055)
1780 #endif // WIN32
1781 tls_io_instance->tls_validation_callback = (TLS_CERTIFICATE_VALIDATION_CALLBACK)value;
1782 #ifdef WIN32
1783 #pragma warning(pop)
1784 #endif // WIN32
1785
1786 if (tls_io_instance->ssl_context != NULL)
1787 {
1788 SSL_CTX_set_cert_verify_callback(tls_io_instance->ssl_context, tls_io_instance->tls_validation_callback, tls_io_instance->tls_validation_callback_data);
1789 }
1790
1791 result = 0;
1792 }
1793 else if (strcmp("tls_validation_callback_data", optionName) == 0)
1794 {
1795 tls_io_instance->tls_validation_callback_data = (void*)value;
1796
1797 if (tls_io_instance->ssl_context != NULL)
1798 {
1799 SSL_CTX_set_cert_verify_callback(tls_io_instance->ssl_context, tls_io_instance->tls_validation_callback, tls_io_instance->tls_validation_callback_data);
1800 }
1801
1802 result = 0;
1803 }
1804 else if (strcmp(OPTION_TLS_VERSION, optionName) == 0)
1805 {
1806 if (tls_io_instance->ssl_context != NULL)
1807 {
1808 LogError("Unable to set the tls version after the tls connection is established");
1809 result = MU_FAILURE;
1810 }
1811 else
1812 {
1813 const int version_option = *(const int*)value;
1814 if (version_option == 0 || version_option == 10)
1815 {
1816 tls_io_instance->tls_version = VERSION_1_0;
1817 }
1818 else if (version_option == 11)
1819 {
1820 tls_io_instance->tls_version = VERSION_1_1;
1821 }
1822 else if (version_option == 12)
1823 {
1824 tls_io_instance->tls_version = VERSION_1_2;
1825 }
1826 else
1827 {
1828 LogInfo("Value of TLS version option %d is not found shall default to version 1.2", version_option);
1829 tls_io_instance->tls_version = VERSION_1_2;
1830 }
1831 result = 0;
1832 }
1833 }
1834 else if (strcmp(optionName, OPTION_UNDERLYING_IO_OPTIONS) == 0)
1835 {
1836 if (OptionHandler_FeedOptions((OPTIONHANDLER_HANDLE)value, (void*)tls_io_instance->underlying_io) != OPTIONHANDLER_OK)
1837 {
1838 LogError("failed feeding options to underlying I/O instance");
1839 result = MU_FAILURE;
1840 }
1841 else
1842 {
1843 result = 0;
1844 }
1845 }
1846 else if (strcmp(optionName, OPTION_SET_TLS_RENEGOTIATION) == 0)
1847 {
1848 // No need to do anything for Openssl
1849 result = 0;
1850 }
1851 else if (strcmp("ignore_host_name_check", optionName) == 0)
1852 {
1853 bool* server_name_check = (bool*)value;
1854 tls_io_instance->ignore_host_name_check = *server_name_check;
1855 result = 0;
1856 }
1857 else
1858 {
1859 if (tls_io_instance->underlying_io == NULL)
1860 {
1861 result = MU_FAILURE;
1862 }
1863 else
1864 {
1865 result = xio_setoption(tls_io_instance->underlying_io, optionName, value);
1866 }
1867 }
1868 }
1869
1870 return result;
1871 }
1872
1873 const IO_INTERFACE_DESCRIPTION* tlsio_openssl_get_interface_description(void)
1874 {
1875 return &tlsio_openssl_interface_description;
1876 }