forked from Oryx-Embedded/CycloneSSL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_misc.c
1556 lines (1343 loc) · 43.7 KB
/
tls_misc.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file tls_misc.c
* @brief TLS helper functions
*
* @section License
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* Copyright (C) 2010-2022 Oryx Embedded SARL. All rights reserved.
*
* This file is part of CycloneSSL Open.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 2.1.4
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL TLS_TRACE_LEVEL
//Dependencies
#include <string.h>
#include "tls.h"
#include "tls_cipher_suites.h"
#include "tls_common.h"
#include "tls_ffdhe.h"
#include "tls_misc.h"
#include "tls13_key_material.h"
#include "encoding/oid.h"
#include "debug.h"
//Check TLS library configuration
#if (TLS_SUPPORT == ENABLED)
/**
* @brief Translate an error code to an alert message
* @param[in] context Pointer to the TLS context
* @param[in] errorCode Internal error code
**/
void tlsProcessError(TlsContext *context, error_t errorCode)
{
//Check current state
if(context->state != TLS_STATE_INIT &&
context->state != TLS_STATE_CLOSED)
{
//Check status code
switch(errorCode)
{
//The timeout interval has elapsed
case ERROR_TIMEOUT:
break;
//The read/write operation would have blocked
case ERROR_WOULD_BLOCK:
break;
//Failed to allocate memory
case ERROR_OUT_OF_MEMORY:
break;
//The read/write operation has failed
case ERROR_WRITE_FAILED:
case ERROR_READ_FAILED:
context->state = TLS_STATE_CLOSED;
break;
//An inappropriate message was received
case ERROR_UNEXPECTED_MESSAGE:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_UNEXPECTED_MESSAGE);
break;
//A record is received with an incorrect MAC
case ERROR_BAD_RECORD_MAC:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_BAD_RECORD_MAC);
break;
//Invalid record length
case ERROR_RECORD_OVERFLOW:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_RECORD_OVERFLOW);
break;
//Unable to negotiate an acceptable set of security parameters
case ERROR_HANDSHAKE_FAILED:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_HANDSHAKE_FAILURE);
break;
//A certificate was corrupt
case ERROR_BAD_CERTIFICATE:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_BAD_CERTIFICATE);
break;
//A certificate was of an unsupported type
case ERROR_UNSUPPORTED_CERTIFICATE:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_UNSUPPORTED_CERTIFICATE);
break;
//A certificate has expired or is not currently valid
case ERROR_CERTIFICATE_EXPIRED:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_CERTIFICATE_EXPIRED);
break;
//Some other issue arose in processing the certificate, rendering it unacceptable
case ERROR_UNKNOWN_CERTIFICATE:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_CERTIFICATE_UNKNOWN);
break;
//A field in the handshake was out of range or inconsistent with other fields
case ERROR_ILLEGAL_PARAMETER:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_ILLEGAL_PARAMETER);
break;
//The certificate could not be matched with a known, trusted CA
case ERROR_UNKNOWN_CA:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_UNKNOWN_CA);
break;
//A message could not be decoded because some field was incorrect
case ERROR_DECODING_FAILED:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECODE_ERROR);
break;
//A handshake cryptographic operation failed
case ERROR_DECRYPTION_FAILED:
case ERROR_INVALID_SIGNATURE:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_DECRYPT_ERROR);
break;
//The protocol version the client has attempted to negotiate is not supported
case ERROR_VERSION_NOT_SUPPORTED:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_PROTOCOL_VERSION);
break;
//Inappropriate fallback detected by the server
case ERROR_INAPPROPRIATE_FALLBACK:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_INAPPROPRIATE_FALLBACK);
break;
//Handshake message not containing an extension that is mandatory
case ERROR_MISSING_EXTENSION:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_MISSING_EXTENSION);
break;
//The ServerHello contains an extension not present in the ClientHello
case ERROR_UNSUPPORTED_EXTENSION:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_UNSUPPORTED_EXTENSION);
break;
//A client certificate is desired but none was provided by the client
case ERROR_CERTIFICATE_REQUIRED:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_CERTIFICATE_REQUIRED);
break;
//No application protocol supported by the server
case ERROR_NO_APPLICATION_PROTOCOL:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_NO_APPLICATION_PROTOCOL);
break;
//Internal error
default:
tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL, TLS_ALERT_INTERNAL_ERROR);
break;
}
}
}
/**
* @brief Generate client or server random value
* @param[in] context Pointer to the TLS context
* @param[out] random Pointer to the random value
* @return Error code
**/
error_t tlsGenerateRandomValue(TlsContext *context, uint8_t *random)
{
error_t error;
//Verify that the pseudorandom number generator is properly configured
if(context->prngAlgo != NULL && context->prngContext != NULL)
{
//Generate a 32-byte random value using a cryptographically-safe
//pseudorandom number generator
error = context->prngAlgo->read(context->prngContext, random, 32);
}
else
{
//Report an error
error = ERROR_NOT_CONFIGURED;
}
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
//Check status code
if(!error)
{
//TLS 1.3 has a downgrade protection mechanism embedded in the server's
//random value
if(context->entity == TLS_CONNECTION_END_SERVER)
{
//Check negotiated version
if(context->version <= TLS_VERSION_1_1 &&
context->versionMax >= TLS_VERSION_1_2)
{
//If negotiating TLS 1.1 or below, TLS 1.3 servers must, and TLS 1.2
//servers should, set the last eight bytes of their random value to
//the bytes 44 4F 57 4E 47 52 44 00
osMemcpy(random + 24, tls11DowngradeRandom, 8);
}
else if(context->version == TLS_VERSION_1_2 &&
context->versionMax >= TLS_VERSION_1_3)
{
//If negotiating TLS 1.2, TLS 1.3 servers must set the last eight
//bytes of their random value to the bytes 44 4F 57 4E 47 52 44 01
osMemcpy(random + 24, tls12DowngradeRandom, 8);
}
else
{
//No downgrade protection mechanism
}
}
}
#endif
//Return status code
return error;
}
/**
* @brief Generate a random session identifier
* @param[in] context Pointer to the TLS context
* @param[out] length Desired length of the session ID
* @return Error code
**/
error_t tlsGenerateSessionId(TlsContext *context, size_t length)
{
error_t error;
//Verify that the pseudorandom number generator is properly configured
if(context->prngAlgo != NULL && context->prngContext != NULL)
{
//Generate a random value using a cryptographically-safe pseudorandom
//number generator
error = context->prngAlgo->read(context->prngContext, context->sessionId,
length);
//Check status code
if(!error)
{
//Save the length of the session identifier
context->sessionIdLen = length;
}
}
else
{
//Report an error
error = ERROR_NOT_CONFIGURED;
}
//Return status code
return error;
}
/**
* @brief Set the TLS version to be used
* @param[in] context Pointer to the TLS context
* @param[in] version TLS version
* @return Error code
**/
error_t tlsSelectVersion(TlsContext *context, uint16_t version)
{
error_t error;
//Initialize status code
error = ERROR_VERSION_NOT_SUPPORTED;
//Check TLS version
if(version >= context->versionMin && version <= context->versionMax)
{
//Save the TLS protocol version to be used
context->version = version;
//The specified TLS version is acceptable
error = NO_ERROR;
}
//Return status code
return error;
}
/**
* @brief Set cipher suite
* @param[in] context Pointer to the TLS context
* @param[in] identifier Cipher suite identifier
* @return Error code
**/
error_t tlsSelectCipherSuite(TlsContext *context, uint16_t identifier)
{
error_t error;
uint_t i;
uint_t n;
const TlsCipherSuiteInfo *cipherSuite;
//Initialize status code
error = ERROR_HANDSHAKE_FAILED;
//Determine the number of supported cipher suites
n = tlsGetNumSupportedCipherSuites();
//Loop through the list of supported cipher suites
for(cipherSuite = NULL, i = 0; i < n; i++)
{
//Compare cipher suite identifiers
if(tlsSupportedCipherSuites[i].identifier == identifier)
{
//The cipher suite is supported
cipherSuite = &tlsSupportedCipherSuites[i];
break;
}
}
//Restrict the use of certain cipher suites
if(context->numCipherSuites > 0)
{
//Loop through the list of allowed cipher suites
for(i = 0; i < context->numCipherSuites; i++)
{
//Compare cipher suite identifiers
if(context->cipherSuites[i] == identifier)
break;
}
//Check whether the use of the cipher suite is restricted
if(i >= context->numCipherSuites)
cipherSuite = NULL;
}
//Acceptable cipher suite?
if(cipherSuite != NULL)
{
//Check whether the cipher suite can be negotiated with the negotiated
//protocol version
if(!tlsIsCipherSuiteAcceptable(cipherSuite, context->version,
context->version, context->transportProtocol))
{
cipherSuite = NULL;
}
}
//Ensure that the selected cipher suite matches all the criteria
if(cipherSuite != NULL)
{
//Save the negotiated cipher suite
context->cipherSuite = *cipherSuite;
//Set the key exchange method to be used
context->keyExchMethod = cipherSuite->keyExchMethod;
//PRF with the SHA-256 is used for all cipher suites published prior
//than TLS 1.2 when TLS 1.2 is negotiated
if(context->cipherSuite.prfHashAlgo == NULL)
{
context->cipherSuite.prfHashAlgo = SHA256_HASH_ALGO;
}
//The length of the verify data depends on the TLS version currently used
if(context->version <= TLS_VERSION_1_1)
{
//Verify data is always 12-byte long for TLS 1.0 and 1.1
context->cipherSuite.verifyDataLen = 12;
}
else
{
//The length of the verify data depends on the cipher suite for TLS 1.2
}
//The specified cipher suite is acceptable
error = NO_ERROR;
}
//Return status code
return error;
}
/**
* @brief Save session ID
* @param[in] context Pointer to the TLS context
* @param[out] session Pointer to the session state
* @return Error code
**/
error_t tlsSaveSessionId(const TlsContext *context,
TlsSessionState *session)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Check TLS version
if(context->version < TLS_VERSION_1_0 || context->version > TLS_VERSION_1_2)
return ERROR_INVALID_VERSION;
//Invalid session identifier?
if(context->sessionIdLen == 0)
return ERROR_INVALID_TICKET;
//Invalid session parameters?
if(context->cipherSuite.identifier == 0)
return ERROR_INVALID_SESSION;
//Save current time
session->timestamp = osGetSystemTime();
//Save session parameters
session->version = context->version;
session->cipherSuite = context->cipherSuite.identifier;
//Copy session identifier
osMemcpy(session->sessionId, context->sessionId, context->sessionIdLen);
session->sessionIdLen = context->sessionIdLen;
//Save master secret
osMemcpy(session->secret, context->masterSecret, TLS_MASTER_SECRET_SIZE);
#if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
//Extended master secret computation
session->extendedMasterSecret = context->emsExtReceived;
#endif
#if (TLS_SNI_SUPPORT == ENABLED)
//Any ServerName extension received by the server?
if(context->entity == TLS_CONNECTION_END_SERVER &&
context->serverName != NULL)
{
size_t n;
//Retrieve the length of the server name
n = osStrlen(context->serverName);
//Allocate a memory block to hold the server name
session->serverName = tlsAllocMem(n + 1);
//Failed to allocate memory?
if(session->serverName == NULL)
return ERROR_OUT_OF_MEMORY;
//Copy the server name
osStrcpy(session->serverName, context->serverName);
}
#endif
//Successful processing
return NO_ERROR;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Save session ticket
* @param[in] context Pointer to the TLS context
* @param[out] session Pointer to the session state
* @return Error code
**/
error_t tlsSaveSessionTicket(const TlsContext *context,
TlsSessionState *session)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Check TLS version
if(context->version < TLS_VERSION_1_0 || context->version > TLS_VERSION_1_2)
return ERROR_INVALID_VERSION;
//Invalid session ticket?
if(context->ticket == NULL || context->ticketLen == 0)
return ERROR_INVALID_TICKET;
//Invalid session parameters?
if(context->cipherSuite.identifier == 0)
return ERROR_INVALID_SESSION;
//Save session parameters
session->version = context->version;
session->cipherSuite = context->cipherSuite.identifier;
//Allocate a memory block to hold the ticket
session->ticket = tlsAllocMem(context->ticketLen);
//Failed to allocate memory?
if(session->ticket == NULL)
return ERROR_OUT_OF_MEMORY;
//Copy session ticket
osMemcpy(session->ticket, context->ticket, context->ticketLen);
session->ticketLen = context->ticketLen;
//Save master secret
osMemcpy(session->secret, context->masterSecret, TLS_MASTER_SECRET_SIZE);
#if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
//Extended master secret computation
session->extendedMasterSecret = context->emsExtReceived;
#endif
//Successful processing
return NO_ERROR;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Restore a TLS session using session ID
* @param[in] context Pointer to the TLS context
* @param[in] session Pointer to the session state
* @return Error code
**/
error_t tlsRestoreSessionId(TlsContext *context,
const TlsSessionState *session)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Check TLS version
if(session->version < TLS_VERSION_1_0 || session->version > TLS_VERSION_1_2)
return ERROR_INVALID_VERSION;
//Invalid session identifier?
if(session->sessionIdLen == 0)
return ERROR_INVALID_SESSION;
//Invalid session parameters?
if(session->cipherSuite == 0)
return ERROR_INVALID_SESSION;
//Restore session parameters
context->version = session->version;
context->cipherSuite.identifier = session->cipherSuite;
context->sessionIdLen = 0;
//Copy session identifier
osMemcpy(context->sessionId, session->sessionId, session->sessionIdLen);
context->sessionIdLen = session->sessionIdLen;
//Restore master secret
osMemcpy(context->masterSecret, session->secret, TLS_MASTER_SECRET_SIZE);
#if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
//Extended master secret computation
context->emsExtReceived = session->extendedMasterSecret;
#endif
//Successful processing
return NO_ERROR;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Restore a TLS session using session ticket
* @param[in] context Pointer to the TLS context
* @param[in] session Pointer to the session state
* @return Error code
**/
error_t tlsRestoreSessionTicket(TlsContext *context,
const TlsSessionState *session)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Check TLS version
if(session->version < TLS_VERSION_1_0 || session->version > TLS_VERSION_1_2)
return ERROR_INVALID_VERSION;
//Invalid session ticket?
if(session->ticket == NULL || session->ticketLen == 0)
return ERROR_INVALID_TICKET;
//Invalid session parameters?
if(session->cipherSuite == 0)
return ERROR_INVALID_SESSION;
//Restore session parameters
context->version = session->version;
context->cipherSuite.identifier = session->cipherSuite;
context->sessionIdLen = 0;
//Release existing session ticket, if any
if(context->ticket != NULL)
{
osMemset(context->ticket, 0, context->ticketLen);
tlsFreeMem(context->ticket);
context->ticket = NULL;
context->ticketLen = 0;
}
//Allocate a memory block to hold the ticket
context->ticket = tlsAllocMem(session->ticketLen);
//Failed to allocate memory?
if(context->ticket == NULL)
return ERROR_OUT_OF_MEMORY;
//Copy session ticket
osMemcpy(context->ticket, session->ticket, session->ticketLen);
context->ticketLen = session->ticketLen;
//Restore master secret
osMemcpy(context->masterSecret, session->secret, TLS_MASTER_SECRET_SIZE);
#if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
//Extended master secret computation
context->emsExtReceived = session->extendedMasterSecret;
#endif
//Successful processing
return NO_ERROR;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Initialize encryption engine
* @param[in] context Pointer to the TLS context
* @param[in] encryptionEngine Pointer to the encryption/decryption engine to
* be initialized
* @param[in] entity Specifies whether client or server write keys shall be used
* @param[in] secret Pointer to the secret value
* @return Error code
**/
error_t tlsInitEncryptionEngine(TlsContext *context,
TlsEncryptionEngine *encryptionEngine, TlsConnectionEnd entity,
const uint8_t *secret)
{
error_t error;
const CipherAlgo *cipherAlgo;
TlsCipherSuiteInfo *cipherSuite;
//Point to the negotiated cipher suite
cipherSuite = &context->cipherSuite;
//Point to the cipher algorithm
cipherAlgo = cipherSuite->cipherAlgo;
//Save the negotiated TLS version
encryptionEngine->version = context->version;
//The sequence number is set to zero at the beginning of a connection
//and whenever the key is changed
osMemset(&encryptionEngine->seqNum, 0, sizeof(TlsSequenceNumber));
#if (DTLS_SUPPORT == ENABLED)
//The epoch number is initially zero and is incremented each time a
//ChangeCipherSpec message is sent
encryptionEngine->epoch++;
//Sequence numbers are maintained separately for each epoch, with each
//sequence number initially being 0 for each epoch
osMemset(&encryptionEngine->dtlsSeqNum, 0, sizeof(DtlsSequenceNumber));
#endif
#if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
//The value of RecordSizeLimit is used to limit the size of records
//that are created when encoding application data and the protected
//handshake message into records (refer to RFC 8449, section 4)
if(entity == context->entity)
{
encryptionEngine->recordSizeLimit = context->recordSizeLimit;
}
else
{
encryptionEngine->recordSizeLimit = MIN(context->rxBufferMaxLen,
TLS_MAX_RECORD_LENGTH);
}
#endif
//Set appropriate length for MAC key, encryption key, authentication
//tag and IV
encryptionEngine->macKeyLen = cipherSuite->macKeyLen;
encryptionEngine->encKeyLen = cipherSuite->encKeyLen;
encryptionEngine->fixedIvLen = cipherSuite->fixedIvLen;
encryptionEngine->recordIvLen = cipherSuite->recordIvLen;
encryptionEngine->authTagLen = cipherSuite->authTagLen;
//Set cipher and hash algorithms
encryptionEngine->cipherAlgo = cipherSuite->cipherAlgo;
encryptionEngine->cipherMode = cipherSuite->cipherMode;
encryptionEngine->hashAlgo = cipherSuite->hashAlgo;
//Initialize cipher context
encryptionEngine->cipherContext = NULL;
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Initialize HMAC context
encryptionEngine->hmacContext = &context->hmacContext;
#endif
#if (TLS_GCM_CIPHER_SUPPORT == ENABLED)
//Initialize GCM context
encryptionEngine->gcmContext = NULL;
#endif
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
if(context->version <= TLS_VERSION_1_2)
{
const uint8_t *p;
//Check whether client or server write keys shall be used
if(entity == TLS_CONNECTION_END_CLIENT)
{
//Point to the key material
p = context->keyBlock;
//Save MAC key
osMemcpy(encryptionEngine->macKey, p, cipherSuite->macKeyLen);
//Advance current position in the key block
p += 2 * cipherSuite->macKeyLen;
//Save encryption key
osMemcpy(encryptionEngine->encKey, p, cipherSuite->encKeyLen);
//Advance current position in the key block
p += 2 * cipherSuite->encKeyLen;
//Save initialization vector
osMemcpy(encryptionEngine->iv, p, cipherSuite->fixedIvLen);
}
else
{
//Point to the key material
p = context->keyBlock + cipherSuite->macKeyLen;
//Save MAC key
osMemcpy(encryptionEngine->macKey, p, cipherSuite->macKeyLen);
//Advance current position in the key block
p += cipherSuite->macKeyLen + cipherSuite->encKeyLen;
//Save encryption key
osMemcpy(encryptionEngine->encKey, p, cipherSuite->encKeyLen);
//Advance current position in the key block
p += cipherSuite->encKeyLen + cipherSuite->fixedIvLen;
//Save initialization vector
osMemcpy(encryptionEngine->iv, p, cipherSuite->fixedIvLen);
}
//Successful processing
error = NO_ERROR;
}
else
#endif
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
//TLS 1.3 currently selected?
if(context->version == TLS_VERSION_1_3)
{
const HashAlgo *hashAlgo;
//The hash function used by HKDF is the cipher suite hash algorithm
hashAlgo = cipherSuite->prfHashAlgo;
//Make sure the hash algorithm is valid
if(hashAlgo != NULL)
{
//Calculate the write key
error = tls13HkdfExpandLabel(hashAlgo, secret, hashAlgo->digestSize,
"key", NULL, 0, encryptionEngine->encKey, cipherSuite->encKeyLen);
//Debug message
TRACE_DEBUG("Write Key:\r\n");
TRACE_DEBUG_ARRAY(" ", encryptionEngine->encKey, cipherSuite->encKeyLen);
//Check status code
if(!error)
{
//Calculate the write IV
error = tls13HkdfExpandLabel(hashAlgo, secret, hashAlgo->digestSize,
"iv", NULL, 0, encryptionEngine->iv, cipherSuite->fixedIvLen);
}
//Debug message
TRACE_DEBUG("Write IV:\r\n");
TRACE_DEBUG_ARRAY(" ", encryptionEngine->iv, cipherSuite->fixedIvLen);
}
else
{
//Invalid HKDF hash algorithm
error = ERROR_FAILURE;
}
}
else
#endif
//Invalid TLS version?
{
//Report an error
error = ERROR_INVALID_VERSION;
}
//Check status code
if(!error)
{
//Check cipher mode of operation
if(encryptionEngine->cipherMode == CIPHER_MODE_STREAM ||
encryptionEngine->cipherMode == CIPHER_MODE_CBC ||
encryptionEngine->cipherMode == CIPHER_MODE_CCM ||
encryptionEngine->cipherMode == CIPHER_MODE_GCM)
{
//Allocate encryption context
encryptionEngine->cipherContext = tlsAllocMem(cipherAlgo->contextSize);
//Successful memory allocation?
if(encryptionEngine->cipherContext != NULL)
{
//Configure the encryption engine with the write key
error = cipherAlgo->init(encryptionEngine->cipherContext,
encryptionEngine->encKey, cipherSuite->encKeyLen);
}
else
{
//Failed to allocate memory
error = ERROR_OUT_OF_MEMORY;
}
}
else if(encryptionEngine->cipherMode == CIPHER_MODE_NULL ||
encryptionEngine->cipherMode == CIPHER_MODE_CHACHA20_POLY1305)
{
//No need to allocate an encryption context
error = NO_ERROR;
}
else
{
//Unsupported mode of operation
error = ERROR_FAILURE;
}
}
#if (TLS_GCM_CIPHER_SUPPORT == ENABLED)
//Check status code
if(!error)
{
//GCM cipher mode?
if(encryptionEngine->cipherMode == CIPHER_MODE_GCM)
{
//Allocate a memory buffer to hold the GCM context
encryptionEngine->gcmContext = tlsAllocMem(sizeof(GcmContext));
//Successful memory allocation?
if(encryptionEngine->gcmContext != NULL)
{
//Initialize GCM context
error = gcmInit(encryptionEngine->gcmContext, cipherAlgo,
encryptionEngine->cipherContext);
}
else
{
//Failed to allocate memory
error = ERROR_OUT_OF_MEMORY;
}
}
}
#endif
//Return status code
return error;
}
/**
* @brief Release encryption engine
* @param[in] encryptionEngine Pointer to the encryption/decryption engine
**/
void tlsFreeEncryptionEngine(TlsEncryptionEngine *encryptionEngine)
{
//Valid cipher context?
if(encryptionEngine->cipherContext != NULL)
{
//Erase cipher context
osMemset(encryptionEngine->cipherContext, 0,
encryptionEngine->cipherAlgo->contextSize);
//Release memory
tlsFreeMem(encryptionEngine->cipherContext);
encryptionEngine->cipherContext = NULL;
}
#if (TLS_GCM_CIPHER_SUPPORT == ENABLED)
//Valid GCM context?
if(encryptionEngine->gcmContext != NULL)
{
//Erase GCM context
osMemset(encryptionEngine->gcmContext, 0, sizeof(GcmContext));
//Release memory
tlsFreeMem(encryptionEngine->gcmContext);
encryptionEngine->gcmContext = NULL;
}
#endif
//Reset encryption parameters
encryptionEngine->cipherAlgo = NULL;
encryptionEngine->cipherMode = CIPHER_MODE_NULL;
encryptionEngine->hashAlgo = NULL;
}
/**
* @brief Encode a multiple precision integer to an opaque vector
* @param[in] a Pointer to a multiple precision integer
* @param[out] data Buffer where to store the opaque vector
* @param[out] length Total number of bytes that have been written
* @return Error code
**/
error_t tlsWriteMpi(const Mpi *a, uint8_t *data, size_t *length)
{
error_t error;
size_t n;
//Retrieve the actual size of the integer
n = mpiGetByteLength(a);
//The data is preceded by a 2-byte length field
STORE16BE(n, data);
//Convert the integer to an octet string
error = mpiExport(a, data + 2, n, MPI_FORMAT_BIG_ENDIAN);
//Conversion failed?
if(error)
return error;
//Return the total number of bytes that have been written
*length = n + 2;
//Successful processing
return NO_ERROR;
}
/**
* @brief Read a multiple precision integer from an opaque vector
* @param[out] a Resulting multiple precision integer
* @param[in] data Buffer where to read the opaque vector
* @param[in] size Total number of bytes available in the buffer
* @param[out] length Total number of bytes that have been read
* @return Error code
**/
error_t tlsReadMpi(Mpi *a, const uint8_t *data, size_t size, size_t *length)
{
error_t error;
size_t n;
//Buffer underrun?
if(size < 2)
return ERROR_DECODING_FAILED;
//Decode the length field
n = LOAD16BE(data);
//Buffer underrun?
if(size < (n + 2))
return ERROR_DECODING_FAILED;
//Convert the octet string to a multiple precision integer
error = mpiImport(a, data + 2, n, MPI_FORMAT_BIG_ENDIAN);
//Any error to report?
if(error)
return error;
//Return the total number of bytes that have been read
*length = n + 2;
//Successful processing
return NO_ERROR;
}
/**
* @brief Encode an EC point to an opaque vector
* @param[in] params EC domain parameters
* @param[in] a Pointer to an EC point
* @param[out] data Buffer where to store the opaque vector
* @param[out] length Total number of bytes that have been written
* @return Error code
**/