Debian Codegraph @

src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/tlsio_mbedtls.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 <stdio.h>
6 #include <stdint.h>
7 #include <stdbool.h>
8 #include <string.h>
9
10 #include "mbedtls/debug.h"
11 #include "mbedtls/ssl.h"
12 #include "mbedtls/entropy.h"
13 #include "mbedtls/ctr_drbg.h"
14 #include "mbedtls/error.h"
15 #include "mbedtls/certs.h"
16 #include "mbedtls/entropy_poll.h"
17 #include "mbedtls/pk.h"
18
19 #include "azure_c_shared_utility/gballoc.h"
20 #include "azure_c_shared_utility/optimize_size.h"
21 #include "azure_c_shared_utility/tlsio.h"
22 #include "azure_c_shared_utility/tlsio_mbedtls.h"
23 #include "azure_c_shared_utility/socketio.h"
24 #include "azure_c_shared_utility/crt_abstractions.h"
25 #include "azure_c_shared_utility/shared_util_options.h"
26 #include "azure_c_shared_utility/threadapi.h"
27 #include "azure_c_shared_utility/safe_math.h"
28
29 static const char *const OPTION_UNDERLYING_IO_OPTIONS = "underlying_io_options";
30
31 #define HANDSHAKE_TIMEOUT_MS 5000
32 #define HANDSHAKE_WAIT_INTERVAL_MS 10
33
34 typedef enum TLSIO_STATE_ENUM_TAG
35 {
36 TLSIO_STATE_NOT_OPEN,
37 TLSIO_STATE_OPENING_UNDERLYING_IO,
38 TLSIO_STATE_IN_HANDSHAKE,
39 TLSIO_STATE_OPEN,
40 TLSIO_STATE_CLOSING,
41 TLSIO_STATE_ERROR
42 } TLSIO_STATE_ENUM;
43
44 typedef struct SEND_COMPLETE_INFO_TAG
45 {
46 bool is_fragmented_req;
47 IO_SEND_RESULT last_fragmented_req_status;
48 ON_SEND_COMPLETE on_send_complete;
49 void *on_send_complete_callback_context;
50 } SEND_COMPLETE_INFO;
51
52 typedef struct TLS_IO_INSTANCE_TAG
53 {
54 XIO_HANDLE socket_io;
55 ON_BYTES_RECEIVED on_bytes_received;
56 ON_IO_OPEN_COMPLETE on_io_open_complete;
57 ON_IO_CLOSE_COMPLETE on_io_close_complete;
58 ON_IO_ERROR on_io_error;
59 void *on_bytes_received_context;
60 void *on_io_open_complete_context;
61 void *on_io_close_complete_context;
62 void *on_io_error_context;
63 TLSIO_STATE_ENUM tlsio_state;
64 unsigned char *socket_io_read_bytes;
65 size_t socket_io_read_byte_count;
66 SEND_COMPLETE_INFO send_complete_info;
67
68 mbedtls_entropy_context entropy;
69 mbedtls_ctr_drbg_context ctr_drbg;
70 mbedtls_ssl_context ssl;
71 mbedtls_ssl_config config;
72 mbedtls_x509_crt trusted_certificates_parsed;
73 mbedtls_ssl_session ssn;
74 char *trusted_certificates;
75
76 bool invoke_on_send_complete_callback_for_fragments;
77 char *hostname;
78 mbedtls_x509_crt owncert;
79 mbedtls_pk_context pKey;
80
81 char* x509_certificate;
82 char* x509_private_key;
83
84 int tls_status;
85 } TLS_IO_INSTANCE;
86
87 typedef enum TLS_STATE_TAG
88 {
89 TLS_STATE_NOT_INITIALIZED,
90 TLS_STATE_INITIALIZED,
91 TLS_STATE_CLOSING,
92 } TLS_STATE;
93
94 static void indicate_error(TLS_IO_INSTANCE *tls_io_instance)
95 {
96 if ((tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN) && (tls_io_instance->tlsio_state != TLSIO_STATE_ERROR))
97 {
98 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
99 if (tls_io_instance->on_io_error != NULL)
100 {
101 tls_io_instance->on_io_error(tls_io_instance->on_io_error_context);
102 }
103 }
104 }
105
106 static void indicate_open_complete(TLS_IO_INSTANCE *tls_io_instance, IO_OPEN_RESULT open_result)
107 {
108 if (tls_io_instance->on_io_open_complete != NULL)
109 {
110 tls_io_instance->on_io_open_complete(tls_io_instance->on_io_open_complete_context, open_result);
111 }
112 }
113
114 static int decode_ssl_received_bytes(TLS_IO_INSTANCE *tls_io_instance)
115 {
116 int result = 0;
117 unsigned char buffer[64];
118 int rcv_bytes = 1;
119
120 while (rcv_bytes > 0)
121 {
122 rcv_bytes = mbedtls_ssl_read(&tls_io_instance->ssl, buffer, sizeof(buffer));
123 if (rcv_bytes > 0)
124 {
125 if (tls_io_instance->on_bytes_received != NULL)
126 {
127 tls_io_instance->on_bytes_received(tls_io_instance->on_bytes_received_context, buffer, rcv_bytes);
128 }
129 }
130 }
131
132 return result;
133 }
134
135 static bool is_fragmented_send_request(TLS_IO_INSTANCE *tls_io_instance, size_t send_size)
136 {
137 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
138 size_t max_len = mbedtls_ssl_get_max_frag_len(&tls_io_instance->ssl);
139 #else
140 size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
141 (void)tls_io_instance;
142 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
143 bool result;
144
145 if (send_size > max_len)
146 {
147 result = true;
148 }
149 else
150 {
151 result = false;
152 }
153
154 return result;
155 }
156
157 static void on_underlying_io_open_complete(void *context, IO_OPEN_RESULT open_result)
158 {
159 if (context == NULL)
160 {
161 LogError("Invalid context NULL value passed");
162 }
163 else
164 {
165 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
166 int result = 0;
167
168 if (open_result != IO_OPEN_OK)
169 {
170 xio_close(tls_io_instance->socket_io, NULL, NULL);
171 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
172 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
173 }
174 else
175 {
176 tls_io_instance->tlsio_state = TLSIO_STATE_IN_HANDSHAKE;
177
178 do
179 {
180 result = mbedtls_ssl_handshake(&tls_io_instance->ssl);
181 } while (result == MBEDTLS_ERR_SSL_WANT_READ || result == MBEDTLS_ERR_SSL_WANT_WRITE);
182
183 if (result == 0)
184 {
185 tls_io_instance->tlsio_state = TLSIO_STATE_OPEN;
186 indicate_open_complete(tls_io_instance, IO_OPEN_OK);
187 }
188 else
189 {
190 if (result == MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED)
191 {
192 LogError("Failure in ssl handshake has the server certificate been added?");
193 }
194 else
195 {
196 LogError("Failure ssl handshake %d", result);
197 }
198 xio_close(tls_io_instance->socket_io, NULL, NULL);
199 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
200 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
201 }
202 }
203 }
204 }
205
206 static void on_underlying_io_bytes_received(void *context, const unsigned char *buffer, size_t size)
207 {
208 if (context != NULL)
209 {
210 unsigned char* new_socket_io_read_bytes;
211 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
212
213 size_t realloc_size = safe_add_size_t(tls_io_instance->socket_io_read_byte_count, size);
214 if (realloc_size == SIZE_MAX)
215 {
216 LogError("Invalid realloc size");
217 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
218 indicate_error(tls_io_instance);
219 }
220 else if ((new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, realloc_size)) == NULL)
221 {
222 LogError("realloc failed");
223 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
224 indicate_error(tls_io_instance);
225 }
226 else
227 {
228 tls_io_instance->socket_io_read_bytes = new_socket_io_read_bytes;
229 (void)memcpy(tls_io_instance->socket_io_read_bytes + tls_io_instance->socket_io_read_byte_count, buffer, size);
230 tls_io_instance->socket_io_read_byte_count += size;
231 }
232 }
233 else
234 {
235 LogError("NULL value passed in context");
236 }
237 }
238
239 static void on_underlying_io_error(void *context)
240 {
241 if (context == NULL)
242 {
243 LogError("Invalid context NULL value passed");
244 }
245 else
246 {
247 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
248
249 switch (tls_io_instance->tlsio_state)
250 {
251 default:
252 case TLSIO_STATE_NOT_OPEN:
253 case TLSIO_STATE_ERROR:
254 break;
255
256 case TLSIO_STATE_OPENING_UNDERLYING_IO:
257 case TLSIO_STATE_IN_HANDSHAKE:
258 // Existing socket impls are all synchronous close, and this
259 // adapter does not yet support async close.
260 xio_close(tls_io_instance->socket_io, NULL, NULL);
261 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
262 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
263 break;
264
265 case TLSIO_STATE_OPEN:
266 indicate_error(tls_io_instance);
267 break;
268 }
269 }
270 }
271
272 static void on_underlying_io_close_complete_during_close(void *context)
273 {
274 if (context == NULL)
275 {
276 LogError("NULL value passed in context");
277 }
278 else
279 {
280 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
281
282 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
283
284 if (tls_io_instance->on_io_close_complete != NULL)
285 {
286 tls_io_instance->on_io_close_complete(tls_io_instance->on_io_close_complete_context);
287 }
288 }
289 }
290
291 static int on_io_recv(void *context, unsigned char *buf, size_t sz)
292 {
293 int result;
294 if (context == NULL)
295 {
296 LogError("Invalid context NULL value passed");
297 result = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
298 }
299 else
300 {
301 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
302 unsigned char *new_socket_io_read_bytes;
303 int pending = 0;
304
305 while (tls_io_instance->socket_io_read_byte_count == 0)
306 {
307 xio_dowork(tls_io_instance->socket_io);
308
309 if (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN)
310 {
311 break;
312 }
313 else if (tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN ||
314 tls_io_instance->tlsio_state == TLSIO_STATE_CLOSING ||
315 tls_io_instance->tlsio_state == TLSIO_STATE_ERROR)
316 {
317 // Underlying io error, exit.
318 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
319 }
320 else
321 {
322 // Handkshake
323 if (tls_io_instance->socket_io_read_byte_count == 0)
324 {
325 if (pending++ >= HANDSHAKE_TIMEOUT_MS / HANDSHAKE_WAIT_INTERVAL_MS)
326 {
327 // The connection is close from server side and no response.
328 LogError("Tlsio_Failure: encountered unknow connection issue, the connection will be restarted.");
329 indicate_error(tls_io_instance);
330 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
331 }
332 ThreadAPI_Sleep(HANDSHAKE_WAIT_INTERVAL_MS);
333 }
334 }
335 }
336
337 result = (int) tls_io_instance->socket_io_read_byte_count;
338 if (result > (int)sz)
339 {
340 result = (int)sz;
341 }
342
343 if (result > 0)
344 {
345 size_t read_byte_count = safe_subtract_size_t(tls_io_instance->socket_io_read_byte_count, (size_t)result);
346 if (read_byte_count != SIZE_MAX)
347 {
348 (void)memcpy((void*)buf, tls_io_instance->socket_io_read_bytes, result);
349 (void)memmove(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_bytes + result, read_byte_count);
350
351 tls_io_instance->socket_io_read_byte_count = read_byte_count;
352 if (tls_io_instance->socket_io_read_byte_count > 0)
353 {
354 new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_byte_count);
355 if (new_socket_io_read_bytes != NULL)
356 {
357 tls_io_instance->socket_io_read_bytes = new_socket_io_read_bytes;
358 }
359 }
360 else
361 {
362 free(tls_io_instance->socket_io_read_bytes);
363 tls_io_instance->socket_io_read_bytes = NULL;
364 }
365 }
366 else
367 {
368 LogError("Tlsio_Failure: memmove invalid size.");
369 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
370 }
371 }
372
373 if ((result == 0) && (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN))
374 {
375 result = MBEDTLS_ERR_SSL_WANT_READ;
376 }
377 }
378 return result;
379 }
380
381 static void on_send_complete(void* context, IO_SEND_RESULT send_result)
382 {
383 TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE *)context;
384 if (tls_io_instance != NULL)
385 {
386 // update fragment status
387 if (tls_io_instance->send_complete_info.is_fragmented_req)
388 {
389 tls_io_instance->send_complete_info.last_fragmented_req_status = send_result;
390 }
391
392 if (tls_io_instance->send_complete_info.on_send_complete != NULL &&
393 tls_io_instance->tlsio_state != TLSIO_STATE_CLOSING)
394 {
395 // trigger callback always on failure, otherwise call it on last fragment completion
396 // In case of http communication (ie blob upload), the callback is called with each fragment
397 if((tls_io_instance->invoke_on_send_complete_callback_for_fragments && tls_io_instance->send_complete_info.is_fragmented_req)||
398 (send_result != IO_SEND_OK || !tls_io_instance->send_complete_info.is_fragmented_req))
399 {
400 void *ctx = tls_io_instance->send_complete_info.on_send_complete_callback_context;
401 tls_io_instance->send_complete_info.on_send_complete(ctx, send_result);
402 }
403 }
404 }
405 else
406 {
407 LogError("Invalid context NULL value passed");
408 }
409 }
410
411 static int on_io_send(void *context, const unsigned char *buf, size_t sz)
412 {
413 int result;
414 if (context == NULL)
415 {
416 LogError("Invalid context NULL value passed");
417 result = 0;
418 }
419 else
420 {
421 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
422 ON_SEND_COMPLETE on_complete_callback = NULL;
423 context = NULL;
424
425 // Only allow Application data type message to send on_send_complete callback.
426 if (tls_io_instance->ssl.out_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA)
427 {
428 on_complete_callback = on_send_complete;
429 context = tls_io_instance;
430 }
431
432 if (xio_send(tls_io_instance->socket_io, buf, sz, on_complete_callback, context) != 0)
433 {
434 indicate_error(tls_io_instance);
435 result = 0;
436 }
437 else
438 {
439 result = (int)sz;
440 }
441 }
442 return result;
443 }
444
445 static int tlsio_entropy_poll(void *v, unsigned char *output, size_t len, size_t *olen)
446 {
447 (void)v;
448 int result = 0;
449 srand((unsigned int)time(NULL));
450 for (uint16_t i = 0; i < len; i++)
451 {
452 output[i] = rand() % 256;
453 }
454 *olen = len;
455 return result;
456 }
457
458 // Un-initialize mbedTLS
459 static void mbedtls_uninit(TLS_IO_INSTANCE *tls_io_instance)
460 {
461 if (tls_io_instance->tls_status != TLS_STATE_NOT_INITIALIZED)
462 {
463 // mbedTLS cleanup...
464 mbedtls_ssl_free(&tls_io_instance->ssl);
465 mbedtls_ssl_session_free(&tls_io_instance->ssn);
466 mbedtls_ssl_config_free(&tls_io_instance->config);
467 mbedtls_x509_crt_free(&tls_io_instance->trusted_certificates_parsed);
468 mbedtls_x509_crt_free(&tls_io_instance->owncert);
469 mbedtls_pk_free(&tls_io_instance->pKey);
470 mbedtls_ctr_drbg_free(&tls_io_instance->ctr_drbg);
471 mbedtls_entropy_free(&tls_io_instance->entropy);
472
473 tls_io_instance->tls_status = TLS_STATE_NOT_INITIALIZED;
474 }
475 else
476 {
477 LogError("Uninitialzing when not previously initialized");
478 }
479 }
480
481 static void mbedtls_init(TLS_IO_INSTANCE *tls_io_instance)
482 {
483 const char* pers = "azure_iot_client";
484 if (tls_io_instance->tls_status != TLS_STATE_INITIALIZED)
485 {
486 if (tls_io_instance->tls_status == TLS_STATE_CLOSING)
487 {
488 // The underlying connection has been closed, so here un-initialize first
489 mbedtls_uninit(tls_io_instance);
490 }
491 // mbedTLS initialize...
492 mbedtls_x509_crt_init(&tls_io_instance->trusted_certificates_parsed);
493 mbedtls_x509_crt_init(&tls_io_instance->owncert);
494 mbedtls_pk_init(&tls_io_instance->pKey);
495
496 mbedtls_entropy_init(&tls_io_instance->entropy);
497 // Add a weak entropy source here,avoid some platform doesn't have strong / hardware entropy
498 mbedtls_entropy_add_source(&tls_io_instance->entropy, tlsio_entropy_poll, NULL, MBEDTLS_ENTROPY_MAX_GATHER, MBEDTLS_ENTROPY_SOURCE_WEAK);
499
500 mbedtls_ctr_drbg_init(&tls_io_instance->ctr_drbg);
501 mbedtls_ctr_drbg_seed(&tls_io_instance->ctr_drbg, mbedtls_entropy_func, &tls_io_instance->entropy, (const unsigned char *)pers, strlen(pers));
502
503 mbedtls_ssl_config_init(&tls_io_instance->config);
504 mbedtls_ssl_config_defaults(&tls_io_instance->config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
505 mbedtls_ssl_conf_rng(&tls_io_instance->config, mbedtls_ctr_drbg_random, &tls_io_instance->ctr_drbg);
506 mbedtls_ssl_conf_authmode(&tls_io_instance->config, MBEDTLS_SSL_VERIFY_REQUIRED);
507 mbedtls_ssl_conf_min_version(&tls_io_instance->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); // v1.2
508
509 mbedtls_ssl_init(&tls_io_instance->ssl);
510 mbedtls_ssl_set_bio(&tls_io_instance->ssl, tls_io_instance, on_io_send, on_io_recv, NULL);
511 mbedtls_ssl_set_hostname(&tls_io_instance->ssl, tls_io_instance->hostname);
512
513 mbedtls_ssl_session_init(&tls_io_instance->ssn);
514
515 mbedtls_ssl_set_session(&tls_io_instance->ssl, &tls_io_instance->ssn);
516 mbedtls_ssl_setup(&tls_io_instance->ssl, &tls_io_instance->config);
517
518 tls_io_instance->tls_status = TLS_STATE_INITIALIZED;
519 }
520 }
521
522 CONCRETE_IO_HANDLE tlsio_mbedtls_create(void *io_create_parameters)
523 {
524 TLSIO_CONFIG *tls_io_config = (TLSIO_CONFIG *)io_create_parameters;
525 TLS_IO_INSTANCE *result;
526
527 if (tls_io_config == NULL)
528 {
529 LogError("NULL tls_io_config");
530 result = NULL;
531 }
532 else
533 {
534 // Codes_SRS_TLSIO_MBED_OS5_TLS_99_006: [ The tlsio_mbedtls_create shall return NULL if allocating memory for TLS_IO_INSTANCE failed. ]
535 result = calloc(1, sizeof(TLS_IO_INSTANCE));
536 if (result != NULL)
537 {
538 SOCKETIO_CONFIG socketio_config;
539 const IO_INTERFACE_DESCRIPTION *underlying_io_interface;
540 void *io_interface_parameters;
541
542 if (tls_io_config->underlying_io_interface != NULL)
543 {
544 underlying_io_interface = tls_io_config->underlying_io_interface;
545 io_interface_parameters = tls_io_config->underlying_io_parameters;
546 }
547 else
548 {
549 socketio_config.hostname = tls_io_config->hostname;
550 socketio_config.port = tls_io_config->port;
551 socketio_config.accepted_socket = NULL;
552 underlying_io_interface = socketio_get_interface_description();
553 io_interface_parameters = &socketio_config;
554 }
555
556 if (underlying_io_interface == NULL)
557 {
558 free(result);
559 result = NULL;
560 LogError("Failed getting socket IO interface description.");
561 }
562 else
563 {
564 if (mallocAndStrcpy_s((char **)&result->hostname, tls_io_config->hostname) != 0)
565 {
566 free(result);
567 result = NULL;
568 LogError("Failure allocating hostname.");
569 }
570 else if ((result->socket_io = xio_create(underlying_io_interface, io_interface_parameters)) == NULL)
571 {
572 LogError("socket xio create failed");
573 free(result->hostname);
574 free(result);
575 result = NULL;
576 }
577 else
578 {
579 result->tls_status = TLS_STATE_NOT_INITIALIZED;
580 mbedtls_init((void*)result);
581 result->tlsio_state = TLSIO_STATE_NOT_OPEN;
582 result->invoke_on_send_complete_callback_for_fragments = tls_io_config->invoke_on_send_complete_callback_for_fragments;
583 }
584 }
585 }
586 else
587 {
588 LogError("Failure allocating TLS object");
589 }
590 }
591 return result;
592 }
593
594 void tlsio_mbedtls_destroy(CONCRETE_IO_HANDLE tls_io)
595 {
596 if (tls_io != NULL)
597 {
598 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
599
600 mbedtls_uninit(tls_io_instance);
601
602 if (tls_io_instance->socket_io_read_bytes != NULL)
603 {
604 free(tls_io_instance->socket_io_read_bytes);
605 tls_io_instance->socket_io_read_bytes = NULL;
606 }
607 xio_destroy(tls_io_instance->socket_io);
608 if (tls_io_instance->hostname != NULL)
609 {
610 free(tls_io_instance->hostname);
611 tls_io_instance->hostname = NULL;
612 }
613 if (tls_io_instance->trusted_certificates != NULL)
614 {
615 free(tls_io_instance->trusted_certificates);
616 tls_io_instance->trusted_certificates = NULL;
617 }
618 if (tls_io_instance->x509_certificate != NULL)
619 {
620 free(tls_io_instance->x509_certificate);
621 tls_io_instance->x509_certificate = NULL;
622 }
623 if (tls_io_instance->x509_private_key != NULL)
624 {
625 free(tls_io_instance->x509_private_key);
626 tls_io_instance->x509_private_key = NULL;
627 }
628 free(tls_io);
629 }
630 }
631
632 int tlsio_mbedtls_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)
633 {
634 int result = 0;
635
636 if (tls_io == NULL)
637 {
638 LogError("Invalid parameter specified tls_io: NULL");
639 result = MU_FAILURE;
640 }
641 else
642 {
643 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
644
645 if (tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN)
646 {
647 LogError("IO should not be open: %d", tls_io_instance->tlsio_state);
648 result = MU_FAILURE;
649 }
650 else
651 {
652
653 tls_io_instance->on_bytes_received = on_bytes_received;
654 tls_io_instance->on_bytes_received_context = on_bytes_received_context;
655
656 tls_io_instance->on_io_open_complete = on_io_open_complete;
657 tls_io_instance->on_io_open_complete_context = on_io_open_complete_context;
658
659 tls_io_instance->on_io_error = on_io_error;
660 tls_io_instance->on_io_error_context = on_io_error_context;
661
662 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_UNDERLYING_IO;
663
664 mbedtls_ssl_session_reset(&tls_io_instance->ssl);
665
666 if (xio_open(tls_io_instance->socket_io, on_underlying_io_open_complete, tls_io_instance, on_underlying_io_bytes_received, tls_io_instance, on_underlying_io_error, tls_io_instance) != 0)
667 {
668
669 LogError("Underlying IO open failed");
670 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
671 result = MU_FAILURE;
672 }
673 }
674 }
675 return result;
676 }
677
678 int tlsio_mbedtls_close(CONCRETE_IO_HANDLE tls_io, ON_IO_CLOSE_COMPLETE on_io_close_complete, void *callback_context)
679 {
680 int result = 0;
681
682 if (tls_io == NULL)
683 {
684 LogError("Invalid parameter specified tls_io: NULL");
685 result = MU_FAILURE;
686 }
687 else
688 {
689 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
690
691 if ((tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN) ||
692 (tls_io_instance->tlsio_state == TLSIO_STATE_CLOSING))
693 {
694 LogError("IO should not be closed: %d", tls_io_instance->tlsio_state);
695 result = MU_FAILURE;
696 }
697 else
698 {
699 int is_error = tls_io_instance->tlsio_state == TLSIO_STATE_ERROR;
700 tls_io_instance->tlsio_state = TLSIO_STATE_CLOSING;
701
702 if (tls_io_instance->tls_status == TLS_STATE_INITIALIZED)
703 {
704 if (is_error)
705 {
706 // forced shutdown if tls is in ERROR state
707 mbedtls_ssl_session_reset(&tls_io_instance->ssl);
708 }
709 else
710 {
711 // Tell the peer that you're going to close
712 mbedtls_ssl_close_notify(&tls_io_instance->ssl);
713 }
714
715 tls_io_instance->tls_status = TLS_STATE_CLOSING;
716 }
717
718 tls_io_instance->on_io_close_complete = on_io_close_complete;
719 tls_io_instance->on_io_close_complete_context = callback_context;
720 if (xio_close(tls_io_instance->socket_io, on_underlying_io_close_complete_during_close, tls_io_instance) != 0)
721 {
722 LogError("xio_close failed");
723 result = MU_FAILURE;
724 }
725 else
726 {
727 result = 0;
728 }
729 }
730 }
731 return result;
732 }
733
734 int tlsio_mbedtls_send(CONCRETE_IO_HANDLE tls_io, const void *buffer, size_t size, ON_SEND_COMPLETE on_send_complete_callback, void *callback_context)
735 {
736 int result = 0;
737
738 if (tls_io == NULL || (buffer == NULL) || (size == 0))
739 {
740 LogError("Invalid parameter specified tls_io: %p, buffer: %p, size: %ul", tls_io, buffer, (unsigned int)size);
741 result = MU_FAILURE;
742 }
743 else
744 {
745 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
746 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN)
747 {
748 LogError("Invalid state specified %d", tls_io_instance->tlsio_state);
749 result = MU_FAILURE;
750 }
751 else
752 {
753 tls_io_instance->send_complete_info.on_send_complete = on_send_complete_callback;
754 tls_io_instance->send_complete_info.on_send_complete_callback_context = callback_context;
755 tls_io_instance->send_complete_info.last_fragmented_req_status = IO_SEND_OK;
756 int out_left = (int)size;
757 result = 0;
758
759 do
760 {
761 tls_io_instance->send_complete_info.is_fragmented_req = is_fragmented_send_request(tls_io_instance, out_left);
762 unsigned char *buf = (unsigned char *)buffer + size - out_left;
763 int ret = mbedtls_ssl_write(&tls_io_instance->ssl, buf, out_left);
764
765 if (ret < 0)
766 {
767 LogError("Unexpected data size returned from mbedtls_ssl_write %d/%d", ret, (int)size);
768 result = MU_FAILURE;
769 break;
770 }
771 else if (tls_io_instance->send_complete_info.last_fragmented_req_status != IO_SEND_OK)
772 {
773 LogError("Failed to send last fragment with error:0x%0x, aborting whole send",
774 tls_io_instance->send_complete_info.last_fragmented_req_status);
775 result = MU_FAILURE;
776 break;
777 }
778
779 out_left -= ret;
780 } while (out_left > 0);
781
782 // remove on send complete info
783 memset((void*)&tls_io_instance->send_complete_info, 0, sizeof(tls_io_instance->send_complete_info));
784 }
785 }
786
787 return result;
788 }
789
790 void tlsio_mbedtls_dowork(CONCRETE_IO_HANDLE tls_io)
791 {
792 if (tls_io != NULL)
793 {
794 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
795 if (tls_io_instance->tlsio_state == TLSIO_STATE_IN_HANDSHAKE || tls_io_instance->tlsio_state == TLSIO_STATE_OPEN)
796 {
797 decode_ssl_received_bytes(tls_io_instance);
798 }
799
800 xio_dowork(tls_io_instance->socket_io);
801 }
802 }
803
804 // this function will clone an option given by name and value
805 static void *tlsio_mbedtls_CloneOption(const char *name, const void *value)
806 {
807 void *result = NULL;
808 if (name == NULL || value == NULL)
809 {
810 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
811 result = NULL;
812 }
813 else
814 {
815 if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
816 {
817 result = (void*)OptionHandler_Clone((OPTIONHANDLER_HANDLE)value);
818 }
819 else if (strcmp(name, OPTION_TRUSTED_CERT) == 0)
820 {
821 if (mallocAndStrcpy_s((char **)&result, value) != 0)
822 {
823 LogError("unable to mallocAndStrcpy_s TrustedCerts value");
824 result = NULL;
825 }
826 else
827 {
828 /*return as is*/
829 }
830 }
831 else if (strcmp(name, SU_OPTION_X509_CERT) == 0)
832 {
833 if (mallocAndStrcpy_s((char**)&result, value) != 0)
834 {
835 LogError("unable to mallocAndStrcpy_s x509certificate value");
836 result = NULL;
837 }
838 else
839 {
840 /*return as is*/
841 }
842 }
843 else if (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0)
844 {
845 if (mallocAndStrcpy_s((char**)&result, value) != 0)
846 {
847 LogError("unable to mallocAndStrcpy_s x509privatekey value");
848 result = NULL;
849 }
850 else
851 {
852 /*return as is*/
853 }
854 }
855 else if (strcmp(name, OPTION_X509_ECC_CERT) == 0)
856 {
857 if (mallocAndStrcpy_s((char**)&result, value) != 0)
858 {
859 LogError("unable to mallocAndStrcpy_s x509EccCertificate value");
860 result = NULL;
861 }
862 else
863 {
864 /*return as is*/
865 }
866 }
867 else if (strcmp(name, OPTION_X509_ECC_KEY) == 0)
868 {
869 if (mallocAndStrcpy_s((char**)&result, value) != 0)
870 {
871 LogError("unable to mallocAndStrcpy_s x509EccKey value");
872 result = NULL;
873 }
874 else
875 {
876 /*return as is*/
877 }
878 }
879 else
880 {
881 LogError("not handled option : %s", name);
882 result = NULL;
883 }
884 }
885 return result;
886 }
887
888 // this function destroys an option previously created
889 static void tlsio_mbedtls_DestroyOption(const char *name, const void *value)
890 {
891 // since all options for this layer are actually string copies., disposing of one is just calling free
892 if (name == NULL || value == NULL)
893 {
894 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
895 }
896 else
897 {
898 if (
899 (strcmp(name, OPTION_TRUSTED_CERT) == 0) ||
900 (strcmp(name, SU_OPTION_X509_CERT) == 0) ||
901 (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0) ||
902 (strcmp(name, OPTION_X509_ECC_CERT) == 0) ||
903 (strcmp(name, OPTION_X509_ECC_KEY) == 0)
904 )
905 {
906 free((void*)value);
907 }
908 else if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
909 {
910 OptionHandler_Destroy((OPTIONHANDLER_HANDLE)value);
911 }
912 else
913 {
914 LogError("not handled option : %s", name);
915 }
916 }
917 }
918
919 int tlsio_mbedtls_setoption(CONCRETE_IO_HANDLE tls_io, const char *optionName, const void *value)
920 {
921 int result = 0;
922
923 if (tls_io == NULL || optionName == NULL)
924 {
925 result = MU_FAILURE;
926 }
927 else
928 {
929 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
930
931 if (strcmp(OPTION_TRUSTED_CERT, optionName) == 0)
932 {
933 if (tls_io_instance->trusted_certificates != NULL)
934 {
935 // Free the memory if it has been previously allocated
936 free(tls_io_instance->trusted_certificates);
937 tls_io_instance->trusted_certificates = NULL;
938 }
939 if (mallocAndStrcpy_s(&tls_io_instance->trusted_certificates, (const char *)value) != 0)
940 {
941 LogError("unable to mallocAndStrcpy_s");
942 result = MU_FAILURE;
943 }
944 else
945 {
946 int parse_result = mbedtls_x509_crt_parse(&tls_io_instance->trusted_certificates_parsed, (const unsigned char *)value, (int)(strlen(value) + 1));
947 if (parse_result != 0)
948 {
949 LogInfo("Malformed pem certificate");
950 free(tls_io_instance->trusted_certificates);
951 tls_io_instance->trusted_certificates = NULL;
952 result = MU_FAILURE;
953 }
954 else
955 {
956 mbedtls_ssl_conf_ca_chain(&tls_io_instance->config, &tls_io_instance->trusted_certificates_parsed, NULL);
957 }
958 }
959 }
960 else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0 || strcmp(OPTION_X509_ECC_CERT, optionName) == 0)
961 {
962 char* temp_cert;
963 if (mallocAndStrcpy_s(&temp_cert, (const char *)value) != 0)
964 {
965 LogError("unable to mallocAndStrcpy_s on certificate");
966 result = MU_FAILURE;
967 }
968 else if (mbedtls_x509_crt_parse(&tls_io_instance->owncert, (const unsigned char *)temp_cert, (int)(strlen(temp_cert) + 1)) != 0)
969 {
970 LogError("failure parsing certificate");
971 free(temp_cert);
972 result = MU_FAILURE;
973 }
974 else if (mbedtls_pk_get_type(&tls_io_instance->pKey) != MBEDTLS_PK_NONE &&
975 mbedtls_ssl_conf_own_cert(&tls_io_instance->config, &tls_io_instance->owncert, &tls_io_instance->pKey) != 0)
976 {
977 LogError("failure calling mbedtls_ssl_conf_own_cert");
978 free(temp_cert);
979 result = MU_FAILURE;
980 }
981 else
982 {
983 if (tls_io_instance->x509_certificate != NULL)
984 {
985 // Free the memory if it has been previously allocated
986 free(tls_io_instance->x509_certificate);
987 }
988 tls_io_instance->x509_certificate = temp_cert;
989 result = 0;
990 }
991 }
992 else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0 || strcmp(OPTION_X509_ECC_KEY, optionName) == 0)
993 {
994 char* temp_key;
995
996 if (mallocAndStrcpy_s(&temp_key, (const char *)value) != 0)
997 {
998 LogError("unable to mallocAndStrcpy_s on private key");
999 result = MU_FAILURE;
1000 }
1001 else if (mbedtls_pk_parse_key(&tls_io_instance->pKey, (const unsigned char *)temp_key, (int)(strlen(temp_key) + 1), NULL, 0) != 0)
1002 {
1003 LogError("failure calling mbedtls_pk_parse_key");
1004 free(temp_key);
1005 result = MU_FAILURE;
1006 }
1007 else if (tls_io_instance->owncert.version > 0 && mbedtls_ssl_conf_own_cert(&tls_io_instance->config, &tls_io_instance->owncert, &tls_io_instance->pKey))
1008 {
1009 LogError("failure calling mbedtls_ssl_conf_own_cert");
1010 free(temp_key);
1011 result = MU_FAILURE;
1012 }
1013 else
1014 {
1015 if (tls_io_instance->x509_private_key != NULL)
1016 {
1017 // Free the memory if it has been previously allocated
1018 free(tls_io_instance->x509_private_key);
1019 }
1020 tls_io_instance->x509_private_key = temp_key;
1021 result = 0;
1022 }
1023 }
1024 else if (strcmp(optionName, OPTION_UNDERLYING_IO_OPTIONS) == 0)
1025 {
1026 if (OptionHandler_FeedOptions((OPTIONHANDLER_HANDLE)value, (void*)tls_io_instance->socket_io) != OPTIONHANDLER_OK)
1027 {
1028 LogError("failed feeding options to underlying I/O instance");
1029 result = MU_FAILURE;
1030 }
1031 else
1032 {
1033 result = 0;
1034 }
1035 }
1036 else if (strcmp(optionName, OPTION_SET_TLS_RENEGOTIATION) == 0)
1037 {
1038 if (value == NULL)
1039 {
1040 LogError("Invalid value set for tls renegotiation");
1041 result = MU_FAILURE;
1042 }
1043 else
1044 {
1045 bool set_renegotiation = *((bool*)(value));
1046 mbedtls_ssl_conf_renegotiation(&tls_io_instance->config, set_renegotiation ? 1 : 0);
1047 result = 0;
1048 }
1049 }
1050 else
1051 {
1052 // tls_io_instance->socket_io is never NULL
1053 result = xio_setoption(tls_io_instance->socket_io, optionName, value);
1054 }
1055 }
1056 return result;
1057 }
1058
1059 OPTIONHANDLER_HANDLE tlsio_mbedtls_retrieveoptions(CONCRETE_IO_HANDLE handle)
1060 {
1061 OPTIONHANDLER_HANDLE result = NULL;
1062 if (handle == NULL)
1063 {
1064 LogError("invalid parameter detected: CONCRETE_IO_HANDLE handle=%p", handle);
1065 result = NULL;
1066 }
1067 else
1068 {
1069 result = OptionHandler_Create(tlsio_mbedtls_CloneOption, tlsio_mbedtls_DestroyOption, tlsio_mbedtls_setoption);
1070 if (result == NULL)
1071 {
1072 LogError("unable to OptionHandler_Create");
1073 // return as is
1074 }
1075 else
1076 {
1077 // this layer cares about the certificates
1078 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)handle;
1079 OPTIONHANDLER_HANDLE underlying_io_options;
1080
1081 if ((underlying_io_options = xio_retrieveoptions(tls_io_instance->socket_io)) == NULL)
1082 {
1083 LogError("unable to retrieve underlying_io options");
1084 OptionHandler_Destroy(result);
1085 result = NULL;
1086 }
1087 else
1088 {
1089 if (OptionHandler_AddOption(result, OPTION_UNDERLYING_IO_OPTIONS, underlying_io_options) != OPTIONHANDLER_OK)
1090 {
1091 LogError("unable to save underlying_io options");
1092 OptionHandler_Destroy(result);
1093 result = NULL;
1094 }
1095 else if (tls_io_instance->trusted_certificates != NULL &&
1096 OptionHandler_AddOption(result, OPTION_TRUSTED_CERT, tls_io_instance->trusted_certificates) != OPTIONHANDLER_OK)
1097 {
1098 LogError("unable to save TrustedCerts option");
1099 OptionHandler_Destroy(result);
1100 result = NULL;
1101 }
1102 else if (tls_io_instance->x509_certificate != NULL &&
1103 OptionHandler_AddOption(result, SU_OPTION_X509_CERT, tls_io_instance->x509_certificate) != OPTIONHANDLER_OK)
1104 {
1105 LogError("unable to save x509certificate option");
1106 OptionHandler_Destroy(result);
1107 result = NULL;
1108 }
1109 else if (tls_io_instance->x509_private_key != NULL &&
1110 OptionHandler_AddOption(result, SU_OPTION_X509_PRIVATE_KEY, tls_io_instance->x509_private_key) != OPTIONHANDLER_OK)
1111 {
1112 LogError("unable to save x509privatekey option");
1113 OptionHandler_Destroy(result);
1114 result = NULL;
1115 }
1116 else
1117 {
1118 // all is fine, all interesting options have been saved
1119 // return as is
1120 }
1121
1122 OptionHandler_Destroy(underlying_io_options);
1123 }
1124 }
1125 }
1126 return result;
1127 }
1128
1129 static const IO_INTERFACE_DESCRIPTION tlsio_mbedtls_interface_description =
1130 {
1131 tlsio_mbedtls_retrieveoptions,
1132 tlsio_mbedtls_create,
1133 tlsio_mbedtls_destroy,
1134 tlsio_mbedtls_open,
1135 tlsio_mbedtls_close,
1136 tlsio_mbedtls_send,
1137 tlsio_mbedtls_dowork,
1138 tlsio_mbedtls_setoption
1139 };
1140
1141 const IO_INTERFACE_DESCRIPTION *tlsio_mbedtls_get_interface_description(void)
1142 {
1143 return &tlsio_mbedtls_interface_description;
1144 }