-
Notifications
You must be signed in to change notification settings - Fork 14
/
using_mbedtls.c
804 lines (691 loc) · 30 KB
/
using_mbedtls.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
/*
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file tls_freertos.c
* @brief TLS transport interface implementations. This implementation uses
* mbedTLS.
*/
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* TLS transport header. */
#include "using_mbedtls.h"
/* mbedTLS util includes. */
#include "mbedtls_error.h"
/*-----------------------------------------------------------*/
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a high-level code.
*/
static const char * pNoHighLevelMbedTlsCodeStr = "<No-High-Level-Code>";
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a low-level code.
*/
static const char * pNoLowLevelMbedTlsCodeStr = "<No-Low-Level-Code>";
/**
* @brief Utility for converting the high-level code in an mbedTLS error to string,
* if the code-contains a high-level code; otherwise, using a default string.
*/
#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \
( mbedtls_strerror_highlevel( mbedTlsCode ) != NULL ) ? \
mbedtls_strerror_highlevel( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr
/**
* @brief Utility for converting the level-level code in an mbedTLS error to string,
* if the code-contains a level-level code; otherwise, using a default string.
*/
#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \
( mbedtls_strerror_lowlevel( mbedTlsCode ) != NULL ) ? \
mbedtls_strerror_lowlevel( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr
/*-----------------------------------------------------------*/
/**
* @brief Initialize the mbed TLS structures in a network connection.
*
* @param[in] pSslContext The SSL context to initialize.
*/
static void sslContextInit( SSLContext_t * pSslContext );
/**
* @brief Free the mbed TLS structures in a network connection.
*
* @param[in] pSslContext The SSL context to free.
*/
static void sslContextFree( SSLContext_t * pSslContext );
/**
* @brief Add X509 certificate to the trusted list of root certificates.
*
* OpenSSL does not provide a single function for reading and loading certificates
* from files into stores, so the file API must be called. Start with the
* root certificate.
*
* @param[out] pSslContext SSL context to which the trusted server root CA is to be added.
* @param[in] pRootCa PEM-encoded string of the trusted server root CA.
* @param[in] rootCaSize Size of the trusted server root CA.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setRootCa( SSLContext_t * pSslContext,
const uint8_t * pRootCa,
size_t rootCaSize );
/**
* @brief Set X509 certificate as client certificate for the server to authenticate.
*
* @param[out] pSslContext SSL context to which the client certificate is to be set.
* @param[in] pClientCert PEM-encoded string of the client certificate.
* @param[in] clientCertSize Size of the client certificate.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setClientCertificate( SSLContext_t * pSslContext,
const uint8_t * pClientCert,
size_t clientCertSize );
/**
* @brief Set private key for the client's certificate.
*
* @param[out] pSslContext SSL context to which the private key is to be set.
* @param[in] pPrivateKey PEM-encoded string of the client private key.
* @param[in] privateKeySize Size of the client private key.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setPrivateKey( SSLContext_t * pSslContext,
const uint8_t * pPrivateKey,
size_t privateKeySize );
/**
* @brief Passes TLS credentials to the OpenSSL library.
*
* Provides the root CA certificate, client certificate, and private key to the
* OpenSSL library. If the client certificate or private key is not NULL, mutual
* authentication is used when performing the TLS handshake.
*
* @param[out] pSslContext SSL context to which the credentials are to be imported.
* @param[in] pNetworkCredentials TLS credentials to be imported.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setCredentials( SSLContext_t * pSslContext,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Set optional configurations for the TLS connection.
*
* This function is used to set SNI and ALPN protocols.
*
* @param[in] pSslContext SSL context to which the optional configurations are to be set.
* @param[in] pHostName Remote host name, used for server name indication.
* @param[in] pNetworkCredentials TLS setup parameters.
*/
static void setOptionalConfigurations( SSLContext_t * pSslContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Setup TLS by initializing contexts and setting configurations.
*
* @param[in] pNetworkContext Network context.
* @param[in] pHostName Remote host name, used for server name indication.
* @param[in] pNetworkCredentials TLS setup parameters.
*
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS,
* or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Perform the TLS handshake on a TCP connection.
*
* @param[in] pNetworkContext Network context.
* @param[in] pNetworkCredentials TLS setup parameters.
*
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Initialize mbedTLS.
*
* @param[out] entropyContext mbed TLS entropy context for generation of random numbers.
* @param[out] ctrDrgbContext mbed TLS CTR DRBG context for generation of random numbers.
*
* @return #TLS_TRANSPORT_SUCCESS, or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
mbedtls_ctr_drbg_context * pCtrDrgbContext );
/*-----------------------------------------------------------*/
static void sslContextInit( SSLContext_t * pSslContext )
{
configASSERT( pSslContext != NULL );
mbedtls_ssl_config_init( &( pSslContext->config ) );
mbedtls_x509_crt_init( &( pSslContext->rootCa ) );
mbedtls_pk_init( &( pSslContext->privKey ) );
mbedtls_x509_crt_init( &( pSslContext->clientCert ) );
mbedtls_ssl_init( &( pSslContext->context ) );
}
/*-----------------------------------------------------------*/
static void sslContextFree( SSLContext_t * pSslContext )
{
configASSERT( pSslContext != NULL );
mbedtls_ssl_free( &( pSslContext->context ) );
mbedtls_x509_crt_free( &( pSslContext->rootCa ) );
mbedtls_x509_crt_free( &( pSslContext->clientCert ) );
mbedtls_pk_free( &( pSslContext->privKey ) );
mbedtls_entropy_free( &( pSslContext->entropyContext ) );
mbedtls_ctr_drbg_free( &( pSslContext->ctrDrgbContext ) );
mbedtls_ssl_config_free( &( pSslContext->config ) );
}
/*-----------------------------------------------------------*/
static int32_t setRootCa( SSLContext_t * pSslContext,
const uint8_t * pRootCa,
size_t rootCaSize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pRootCa != NULL );
/* Parse the server root CA certificate into the SSL context. */
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->rootCa ),
pRootCa,
rootCaSize );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
else
{
mbedtls_ssl_conf_ca_chain( &( pSslContext->config ),
&( pSslContext->rootCa ),
NULL );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setClientCertificate( SSLContext_t * pSslContext,
const uint8_t * pClientCert,
size_t clientCertSize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pClientCert != NULL );
/* Setup the client certificate. */
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->clientCert ),
pClientCert,
clientCertSize );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse the client certificate: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setPrivateKey( SSLContext_t * pSslContext,
const uint8_t * pPrivateKeyPath,
size_t privateKeySize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pPrivateKeyPath != NULL );
/* Setup the client private key. */
mbedtlsError = mbedtls_pk_parse_key( &( pSslContext->privKey ),
pPrivateKeyPath,
privateKeySize,
NULL,
0 );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse the client key: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setCredentials( SSLContext_t * pSslContext,
const NetworkCredentials_t * pNetworkCredentials )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pNetworkCredentials != NULL );
/* Set up the certificate security profile, starting from the default value. */
pSslContext->certProfile = mbedtls_x509_crt_profile_default;
/* Set SSL authmode and the RNG context. */
mbedtls_ssl_conf_authmode( &( pSslContext->config ),
MBEDTLS_SSL_VERIFY_REQUIRED );
mbedtls_ssl_conf_rng( &( pSslContext->config ),
mbedtls_ctr_drbg_random,
&( pSslContext->ctrDrgbContext ) );
mbedtls_ssl_conf_cert_profile( &( pSslContext->config ),
&( pSslContext->certProfile ) );
mbedtlsError = setRootCa( pSslContext,
pNetworkCredentials->pRootCa,
pNetworkCredentials->rootCaSize );
if( ( pNetworkCredentials->pClientCert != NULL ) &&
( pNetworkCredentials->pPrivateKey != NULL ) )
{
if( mbedtlsError == 0 )
{
mbedtlsError = setClientCertificate( pSslContext,
pNetworkCredentials->pClientCert,
pNetworkCredentials->clientCertSize );
}
if( mbedtlsError == 0 )
{
mbedtlsError = setPrivateKey( pSslContext,
pNetworkCredentials->pPrivateKey,
pNetworkCredentials->privateKeySize );
}
if( mbedtlsError == 0 )
{
mbedtlsError = mbedtls_ssl_conf_own_cert( &( pSslContext->config ),
&( pSslContext->clientCert ),
&( pSslContext->privKey ) );
}
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static void setOptionalConfigurations( SSLContext_t * pSslContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pHostName != NULL );
configASSERT( pNetworkCredentials != NULL );
if( pNetworkCredentials->pAlpnProtos != NULL )
{
/* Include an application protocol list in the TLS ClientHello
* message. */
mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pSslContext->config ),
pNetworkCredentials->pAlpnProtos );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
}
/* Enable SNI if requested. */
if( pNetworkCredentials->disableSni == pdFALSE )
{
mbedtlsError = mbedtls_ssl_set_hostname( &( pSslContext->context ),
pHostName );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to set server name: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
}
/* Set Maximum Fragment Length if enabled. */
#ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
/* Enable the max fragment extension. 4096 bytes is currently the largest fragment size permitted.
* See RFC 8449 https://tools.ietf.org/html/rfc8449 for more information.
*
* Smaller values can be found in "mbedtls/include/ssl.h".
*/
mbedtlsError = mbedtls_ssl_conf_max_frag_len( &( pSslContext->config ), MBEDTLS_SSL_MAX_FRAG_LEN_4096 );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to maximum fragment length extension: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
#endif /* ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t mbedtlsError = 0;
configASSERT( pNetworkContext != NULL );
configASSERT( pHostName != NULL );
configASSERT( pNetworkCredentials != NULL );
configASSERT( pNetworkCredentials->pRootCa != NULL );
/* Initialize the mbed TLS context structures. */
sslContextInit( &( pNetworkContext->sslContext ) );
mbedtlsError = mbedtls_ssl_config_defaults( &( pNetworkContext->sslContext.config ),
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to set default SSL configuration: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
/* Per mbed TLS docs, mbedtls_ssl_config_defaults only fails on memory allocation. */
returnStatus = TLS_TRANSPORT_INSUFFICIENT_MEMORY;
}
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
mbedtlsError = setCredentials( &( pNetworkContext->sslContext ),
pNetworkCredentials );
if( mbedtlsError != 0 )
{
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
else
{
/* Optionally set SNI and ALPN protocols. */
setOptionalConfigurations( &( pNetworkContext->sslContext ),
pHostName,
pNetworkCredentials );
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
const NetworkCredentials_t * pNetworkCredentials )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t mbedtlsError = 0;
configASSERT( pNetworkContext != NULL );
configASSERT( pNetworkCredentials != NULL );
/* Initialize the mbed TLS secured connection context. */
mbedtlsError = mbedtls_ssl_setup( &( pNetworkContext->sslContext.context ),
&( pNetworkContext->sslContext.config ) );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to set up mbed TLS SSL context: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
}
else
{
/* Set the underlying IO for the TLS connection. */
/* MISRA Rule 11.2 flags the following line for casting the second
* parameter to void *. This rule is suppressed because
* #mbedtls_ssl_set_bio requires the second parameter as void *.
*/
/* coverity[misra_c_2012_rule_11_2_violation] */
mbedtls_ssl_set_bio( &( pNetworkContext->sslContext.context ),
( void * ) pNetworkContext->tcpSocket,
mbedtls_platform_send,
mbedtls_platform_recv,
NULL );
}
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
/* Perform the TLS handshake. */
do
{
mbedtlsError = mbedtls_ssl_handshake( &( pNetworkContext->sslContext.context ) );
} while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) ||
( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED;
}
else
{
LogInfo( ( "(Network connection %p) TLS handshake successful.",
pNetworkContext ) );
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
mbedtls_ctr_drbg_context * pCtrDrgbContext )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t mbedtlsError = 0;
/* Set the mutex functions for mbed TLS thread safety. */
mbedtls_threading_set_alt( mbedtls_platform_mutex_init,
mbedtls_platform_mutex_free,
mbedtls_platform_mutex_lock,
mbedtls_platform_mutex_unlock );
/* Initialize contexts for random number generation. */
mbedtls_entropy_init( pEntropyContext );
mbedtls_ctr_drbg_init( pCtrDrgbContext );
/* Add a strong entropy source. At least one is required. */
mbedtlsError = mbedtls_entropy_add_source( pEntropyContext,
mbedtls_platform_entropy_poll,
NULL,
32,
MBEDTLS_ENTROPY_SOURCE_STRONG );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to add entropy source: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
}
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
/* Seed the random number generator. */
mbedtlsError = mbedtls_ctr_drbg_seed( pCtrDrgbContext,
mbedtls_entropy_func,
pEntropyContext,
NULL,
0 );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to seed PRNG: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
}
}
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
LogDebug( ( "Successfully initialized mbedTLS." ) );
}
return returnStatus;
}
/*-----------------------------------------------------------*/
TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
const char * pHostName,
uint16_t port,
const NetworkCredentials_t * pNetworkCredentials,
uint32_t receiveTimeoutMs,
uint32_t sendTimeoutMs )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
BaseType_t socketStatus = 0;
if( ( pNetworkContext == NULL ) ||
( pHostName == NULL ) ||
( pNetworkCredentials == NULL ) )
{
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
"pHostName=%p, pNetworkCredentials=%p.",
pNetworkContext,
pHostName,
pNetworkCredentials ) );
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
}
else if( ( pNetworkCredentials->pRootCa == NULL ) )
{
LogError( ( "pRootCa cannot be NULL." ) );
returnStatus = TLS_TRANSPORT_INVALID_PARAMETER;
}
else
{
/* Empty else for MISRA 15.7 compliance. */
}
/* Establish a TCP connection with the server. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
socketStatus = Sockets_Connect( &( pNetworkContext->tcpSocket ),
pHostName,
port,
receiveTimeoutMs,
sendTimeoutMs );
if( socketStatus != 0 )
{
LogError( ( "Failed to connect to %s with error %d.",
pHostName,
socketStatus ) );
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
}
}
/* Initialize mbedtls. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = initMbedtls( &( pNetworkContext->sslContext.entropyContext ),
&( pNetworkContext->sslContext.ctrDrgbContext ) );
}
/* Initialize TLS contexts and set credentials. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials );
}
/* Perform TLS handshake. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = tlsHandshake( pNetworkContext, pNetworkCredentials );
}
/* Clean up on failure. */
if( returnStatus != TLS_TRANSPORT_SUCCESS )
{
if( pNetworkContext != NULL )
{
sslContextFree( &( pNetworkContext->sslContext ) );
if( pNetworkContext->tcpSocket != NULL )
{
( void ) Sockets_Disconnect( pNetworkContext->tcpSocket );
}
}
}
else
{
LogInfo( ( "(Network connection %p) Connection to %s established.",
pNetworkContext,
pHostName ) );
}
return returnStatus;
}
/*-----------------------------------------------------------*/
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
{
BaseType_t tlsStatus = 0;
if( pNetworkContext != NULL )
{
/* Attempting to terminate TLS connection. */
tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pNetworkContext->sslContext.context ) );
/* Ignore the WANT_READ and WANT_WRITE return values. */
if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) &&
( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) )
{
if( tlsStatus == 0 )
{
LogInfo( ( "(Network connection %p) TLS close-notify sent.",
pNetworkContext ) );
}
else
{
LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.",
pNetworkContext,
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
}
}
else
{
/* WANT_READ and WANT_WRITE can be ignored. Logging for debugging purposes. */
LogInfo( ( "(Network connection %p) TLS close-notify sent; ",
"received %s as the TLS status can be ignored for close-notify."
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ? "WANT_READ" : "WANT_WRITE",
pNetworkContext ) );
}
/* Call socket shutdown function to close connection. */
Sockets_Disconnect( pNetworkContext->tcpSocket );
/* Free mbed TLS contexts. */
sslContextFree( &( pNetworkContext->sslContext ) );
}
/* Clear the mutex functions for mbed TLS thread safety. */
mbedtls_threading_free_alt();
}
/*-----------------------------------------------------------*/
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
void * pBuffer,
size_t bytesToRecv )
{
int32_t tlsStatus = 0;
tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pNetworkContext->sslContext.context ),
pBuffer,
bytesToRecv );
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
{
LogDebug( ( "Failed to read data. However, a read can be retried on this error. "
"mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
/* Mark these set of errors as a timeout. The libraries may retry read
* on these errors. */
tlsStatus = 0;
}
else if( tlsStatus < 0 )
{
LogError( ( "Failed to read data: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
}
else
{
/* Empty else marker. */
}
return tlsStatus;
}
/*-----------------------------------------------------------*/
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
const void * pBuffer,
size_t bytesToSend )
{
int32_t tlsStatus = 0;
tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pNetworkContext->sslContext.context ),
pBuffer,
bytesToSend );
if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) ||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ||
( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) )
{
LogDebug( ( "Failed to send data. However, send can be retried on this error. "
"mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
/* Mark these set of errors as a timeout. The libraries may retry send
* on these errors. */
tlsStatus = 0;
}
else if( tlsStatus < 0 )
{
LogError( ( "Failed to send data: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( tlsStatus ),
mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
}
else
{
/* Empty else marker. */
}
return tlsStatus;
}
/*-----------------------------------------------------------*/