forked from Oryx-Embedded/CycloneSSL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_record.c
1048 lines (921 loc) · 30.3 KB
/
tls_record.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_record.c
* @brief TLS record protocol
*
* @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_record.h"
#include "tls_record_encryption.h"
#include "tls_record_decryption.h"
#include "debug.h"
//Check TLS library configuration
#if (TLS_SUPPORT == ENABLED)
/**
* @brief Write protocol data
* @param[in] context Pointer to the TLS context
* @param[in] data Pointer to the data buffer
* @param[in] length Number of data bytes to be written
* @param[in] contentType Higher level protocol
* @return Error code
**/
error_t tlsWriteProtocolData(TlsContext *context,
const uint8_t *data, size_t length, TlsContentType contentType)
{
error_t error;
size_t n;
uint8_t *p;
//Initialize status code
error = NO_ERROR;
//Fragmentation process
while(!error)
{
if(context->txBufferLen == 0)
{
//Check the length of the data
if(length > context->txBufferMaxLen)
{
//Report an error
error = ERROR_MESSAGE_TOO_LONG;
}
else if(length > 0)
{
//Make room for the encryption overhead
osMemmove(context->txBuffer + context->txBufferSize - length, data,
length);
//Save record type
context->txBufferType = contentType;
//Set the length of the buffer
context->txBufferLen = length;
//Point to the beginning of the buffer
context->txBufferPos = 0;
}
else
{
//We are done
break;
}
}
else if(context->txBufferPos < context->txBufferLen)
{
//Number of bytes left to send
n = context->txBufferLen - context->txBufferPos;
//Point to the current fragment
p = context->txBuffer + context->txBufferSize - n;
//The record length must not exceed 16384 bytes
n = MIN(n, TLS_MAX_RECORD_LENGTH);
#if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
//Do not exceed the negotiated maximum fragment length
n = MIN(n, context->maxFragLen);
#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
if(context->encryptionEngine.cipherMode != CIPHER_MODE_NULL ||
context->encryptionEngine.hashAlgo != NULL)
{
//An endpoint must not generate a protected record with plaintext
//that is larger than the RecordSizeLimit value it receives from
//its peer (refer to RFC 8449, section 4)
n = MIN(n, context->encryptionEngine.recordSizeLimit);
}
#endif
//Send TLS record
error = tlsWriteRecord(context, p, n, context->txBufferType);
//Check status code
if(!error)
{
//Advance data pointer
context->txBufferPos += n;
}
}
else
{
//Prepare to send new protocol data
context->txBufferLen = 0;
context->txBufferPos = 0;
//We are done
break;
}
}
//Return status code
return error;
}
/**
* @brief Read protocol data
* @param[in] context Pointer to the TLS context
* @param[out] data Pointer to the received data
* @param[out] length Number of data bytes that were received
* @param[out] contentType Higher level protocol
* @return Error code
**/
error_t tlsReadProtocolData(TlsContext *context,
uint8_t **data, size_t *length, TlsContentType *contentType)
{
error_t error;
size_t n;
TlsContentType type;
TlsHandshake *message;
//Initialize status code
error = NO_ERROR;
//Fragment reassembly process
do
{
//Empty receive buffer?
if(context->rxBufferLen == 0)
{
//Read a TLS record
error = tlsReadRecord(context, context->rxBuffer,
context->rxBufferSize, &n, &type);
//Check status code
if(!error)
{
//Save record type
context->rxBufferType = type;
//Number of bytes available for reading
context->rxBufferLen = n;
//Rewind to the beginning of the buffer
context->rxBufferPos = 0;
}
}
//Imcomplete message received?
else if(error == ERROR_MORE_DATA_REQUIRED)
{
//Make room at the end of the buffer
if(context->rxBufferPos > 0)
{
//Move unread data to the beginning of the buffer
osMemmove(context->rxBuffer, context->rxBuffer +
context->rxBufferPos, context->rxBufferLen);
//Rewind to the beginning of the buffer
context->rxBufferPos = 0;
}
//Read a TLS record
error = tlsReadRecord(context, context->rxBuffer + context->rxBufferLen,
context->rxBufferSize - context->rxBufferLen, &n, &type);
//Check status code
if(!error)
{
//Fragmented records with mixed types cannot be interleaved
if(type != context->rxBufferType)
error = ERROR_UNEXPECTED_MESSAGE;
}
//Check status code
if(!error)
{
//Number of bytes available for reading
context->rxBufferLen += n;
}
}
//Check status code
if(!error)
{
//Handshake message received?
if(context->rxBufferType == TLS_TYPE_HANDSHAKE)
{
//A message may be fragmented across several records
if(context->rxBufferLen < sizeof(TlsHandshake))
{
//Read an additional record
error = ERROR_MORE_DATA_REQUIRED;
}
else
{
//Point to the handshake message
message = (TlsHandshake *) (context->rxBuffer + context->rxBufferPos);
//Retrieve the length of the handshake message
n = sizeof(TlsHandshake) + LOAD24BE(message->length);
//A message may be fragmented across several records
if(context->rxBufferLen < n)
{
//Read an additional record
error = ERROR_MORE_DATA_REQUIRED;
}
else
{
//Pass the handshake message to the higher layer
error = NO_ERROR;
}
}
}
//ChangeCipherSpec message received?
else if(context->rxBufferType == TLS_TYPE_CHANGE_CIPHER_SPEC)
{
//A message may be fragmented across several records
if(context->rxBufferLen < sizeof(TlsChangeCipherSpec))
{
//Read an additional record
error = ERROR_MORE_DATA_REQUIRED;
}
else
{
//Length of the ChangeCipherSpec message
n = sizeof(TlsChangeCipherSpec);
//Pass the ChangeCipherSpec message to the higher layer
error = NO_ERROR;
}
}
//Alert message received?
else if(context->rxBufferType == TLS_TYPE_ALERT)
{
//A message may be fragmented across several records
if(context->rxBufferLen < sizeof(TlsAlert))
{
//Read an additional record
error = ERROR_MORE_DATA_REQUIRED;
}
else
{
//Length of the Alert message
n = sizeof(TlsAlert);
//Pass the Alert message to the higher layer
error = NO_ERROR;
}
}
//Application data received?
else if(context->rxBufferType == TLS_TYPE_APPLICATION_DATA)
{
//Length of the application data
n = context->rxBufferLen;
//Pass the application data to the higher layer
error = NO_ERROR;
}
//Unknown content type?
else
{
//Report an error
error = ERROR_UNEXPECTED_MESSAGE;
}
}
//Read as many records as necessary to reassemble the data
} while(error == ERROR_MORE_DATA_REQUIRED);
//Successful processing?
if(!error)
{
#if (TLS_MAX_WARNING_ALERTS > 0)
//Reset the count of consecutive warning alerts
if(context->rxBufferType != TLS_TYPE_ALERT)
context->alertCount = 0;
#endif
#if (TLS_MAX_KEY_UPDATE_MESSAGES > 0)
//Reset the count of consecutive KeyUpdate messages
if(context->rxBufferType != TLS_TYPE_HANDSHAKE)
context->keyUpdateCount = 0;
#endif
//Pointer to the received data
*data = context->rxBuffer + context->rxBufferPos;
//Length, in byte, of the data
*length = n;
//Protocol type
*contentType = context->rxBufferType;
}
//Return status code
return error;
}
/**
* @brief Send a TLS record
* @param[in] context Pointer to the TLS context
* @param[in] data Pointer to the record data
* @param[in] length Length of the record data
* @param[in] contentType Record type
* @return Error code
**/
error_t tlsWriteRecord(TlsContext *context, const uint8_t *data,
size_t length, TlsContentType contentType)
{
error_t error;
size_t n;
uint16_t legacyVersion;
TlsRecord *record;
TlsEncryptionEngine *encryptionEngine;
//Point to the encryption engine
encryptionEngine = &context->encryptionEngine;
//Point to the TLS record
record = (TlsRecord *) context->txBuffer;
//Initialize status code
error = NO_ERROR;
//Send process
while(!error)
{
//Send as much data as possible
if(context->txRecordLen == 0)
{
//The record version must be set to 0x0303 for all records generated
//by a TLS 1.3 implementation other than an initial ClientHello
legacyVersion = MIN(context->version, TLS_VERSION_1_2);
//Format TLS record
record->type = contentType;
record->version = htons(legacyVersion);
record->length = htons(length);
//Copy record data
osMemmove(record->data, data, length);
//Debug message
TRACE_DEBUG("Sending TLS record (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_ARRAY(" ", record, length + sizeof(TlsRecord));
//Protect record payload?
if(encryptionEngine->cipherMode != CIPHER_MODE_NULL ||
encryptionEngine->hashAlgo != NULL)
{
//Encrypt TLS record
error = tlsEncryptRecord(context, encryptionEngine, record);
}
//Check status code
if(!error)
{
//Actual length of the record data
context->txRecordLen = sizeof(TlsRecord) + ntohs(record->length);
//Point to the beginning of the record
context->txRecordPos = 0;
}
}
else if(context->txRecordPos < context->txRecordLen)
{
//Total number of bytes that have been written
n = 0;
//Send more data
error = context->socketSendCallback(context->socketHandle,
context->txBuffer + context->txRecordPos,
context->txRecordLen - context->txRecordPos, &n, 0);
//Check status code
if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
{
//Advance data pointer
context->txRecordPos += n;
}
else
{
//The write operation has failed
error = ERROR_WRITE_FAILED;
}
}
else
{
//Prepare to send the next TLS record
context->txRecordLen = 0;
context->txRecordPos = 0;
//We are done
break;
}
}
//Return status code
return error;
}
/**
* @brief Receive a TLS record
* @param[in] context Pointer to the TLS context
* @param[out] data Buffer where to store the record data
* @param[in] size Maximum acceptable size for the incoming record
* @param[out] length Length of the record data
* @param[out] contentType Record type
* @return Error code
**/
error_t tlsReadRecord(TlsContext *context, uint8_t *data,
size_t size, size_t *length, TlsContentType *contentType)
{
error_t error;
size_t n;
TlsRecord *record;
//Initialize status code
error = NO_ERROR;
//Point to the buffer where to store the incoming TLS record
record = (TlsRecord *) data;
//Receive process
while(!error)
{
//Read as much data as possible
if(context->rxRecordPos < sizeof(TlsRecord))
{
//Make sure that the buffer is large enough to hold the record header
if(size >= sizeof(TlsRecord))
{
//Total number of bytes that have been received
n = 0;
//Read TLS record header
error = context->socketReceiveCallback(context->socketHandle,
data + context->rxRecordPos,
sizeof(TlsRecord) - context->rxRecordPos, &n, 0);
//Check status code
if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
{
//Advance data pointer
context->rxRecordPos += n;
//TLS record header successfully received?
if(context->rxRecordPos >= sizeof(TlsRecord))
{
//Debug message
TRACE_DEBUG("Record header received:\r\n");
TRACE_DEBUG_ARRAY(" ", record, sizeof(TlsRecord));
//Retrieve the length of the TLS record
context->rxRecordLen = sizeof(TlsRecord) + ntohs(record->length);
}
}
else
{
//The read operation has failed
error = ERROR_READ_FAILED;
}
}
else
{
//Report an error
error = ERROR_RECORD_OVERFLOW;
}
}
else if(context->rxRecordPos < context->rxRecordLen)
{
//Make sure that the buffer is large enough to hold the entire record
if(size >= context->rxRecordLen)
{
//Total number of bytes that have been received
n = 0;
//Read TLS record contents
error = context->socketReceiveCallback(context->socketHandle,
data + context->rxRecordPos,
context->rxRecordLen - context->rxRecordPos, &n, 0);
//Check status code
if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
{
//Advance data pointer
context->rxRecordPos += n;
}
else
{
//The read operation has failed
error = ERROR_READ_FAILED;
}
}
else
{
//Report an error
error = ERROR_RECORD_OVERFLOW;
}
}
else
{
//Process the incoming TLS record
error = tlsProcessRecord(context, record);
//Check status code
if(error == NO_ERROR)
{
//Actual length of the record data
*length = ntohs(record->length);
//Record type
*contentType = (TlsContentType) record->type;
//Debug message
TRACE_DEBUG("TLS record received (%" PRIuSIZE " bytes)...\r\n", *length);
TRACE_DEBUG_ARRAY(" ", record, *length + sizeof(TlsRecord));
//Discard record header
osMemmove(data, record->data, *length);
//Prepare to receive the next TLS record
context->rxRecordLen = 0;
context->rxRecordPos = 0;
//We are done
break;
}
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
else if(error == ERROR_BAD_RECORD_MAC)
{
//Check current state
if(context->version == TLS_VERSION_1_3 &&
context->entity == TLS_CONNECTION_END_SERVER &&
context->state == TLS_STATE_CLIENT_FINISHED &&
context->rxBufferLen == 0)
{
//Early data received?
if(!context->updatedClientHelloReceived &&
context->earlyDataExtReceived)
{
//Amount of 0-RTT data received by the server
context->earlyDataLen += ntohs(record->length);
//Discard records which fail deprotection (up to the configured
//max_early_data_size)
if(context->earlyDataLen <= context->maxEarlyDataSize)
{
//Debug message
TRACE_INFO("Discarding early data (%" PRIuSIZE " bytes)...\r\n",
ntohs(record->length));
//Prepare to receive the next TLS record
context->rxRecordLen = 0;
context->rxRecordPos = 0;
//Catch exception
error = NO_ERROR;
}
}
}
}
#endif
else
{
//Invalid record received
}
}
}
//Return status code
return error;
}
/**
* @brief Process incoming TLS record
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the received TLS record
* @return Error code
**/
error_t tlsProcessRecord(TlsContext *context, TlsRecord *record)
{
error_t error;
TlsEncryptionEngine *decryptionEngine;
//Point to the decryption engine
decryptionEngine = &context->decryptionEngine;
//Check current state
if(context->state > TLS_STATE_SERVER_HELLO)
{
//Once the server has sent the ServerHello message, enforce the version
//of incoming records. In TLS 1.3, this field is deprecated. It may be
//validated to match the fixed constant value 0x0303
if(ntohs(record->version) != MIN(context->version, TLS_VERSION_1_2))
return ERROR_VERSION_NOT_SUPPORTED;
}
else
{
//Compliant servers must accept any value {03,XX} as the record layer
//version number for ClientHello
if(LSB(record->version) != MSB(TLS_VERSION_1_0))
return ERROR_VERSION_NOT_SUPPORTED;
}
//Version of TLS prior to TLS 1.3?
if(context->version <= TLS_VERSION_1_2)
{
//Check whether the record payload is protected
if(decryptionEngine->cipherMode != CIPHER_MODE_NULL ||
decryptionEngine->hashAlgo != NULL)
{
//Decrypt TLS record
error = tlsDecryptRecord(context, decryptionEngine, record);
//Any error to report?
if(error)
return error;
}
}
else
{
//An implementation may receive an unencrypted ChangeCipherSpec at a point
//at the handshake where the implementation is expecting protected records
//and so it is necessary to detect this condition prior to attempting to
//deprotect the record
if(record->type != TLS_TYPE_CHANGE_CIPHER_SPEC)
{
#if (TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES > 0)
//Reset the count of consecutive ChangeCipherSpec messages
context->changeCipherSpecCount = 0;
#endif
//Check whether the record payload is protected
if(decryptionEngine->cipherMode != CIPHER_MODE_NULL ||
decryptionEngine->hashAlgo != NULL)
{
//Decrypt TLS record
error = tlsDecryptRecord(context, decryptionEngine, record);
//Any error to report?
if(error)
return error;
}
//Abort the handshake with an unexpected_message alert if a protected
//ChangeCipherSpec record was received
if(record->type == TLS_TYPE_CHANGE_CIPHER_SPEC)
return ERROR_UNEXPECTED_MESSAGE;
}
//Implementations must not send Handshake and Alert records that have a
//zero-length plaintext content (refer to RFC 8446, section 5.4)
if(record->type == TLS_TYPE_HANDSHAKE ||
record->type == TLS_TYPE_ALERT)
{
//If such a message is received, the receiving implementation must
//terminate the connection with an unexpected_message alert
if(ntohs(record->length) == 0)
return ERROR_UNEXPECTED_MESSAGE;
}
}
//The length of the plaintext record must not exceed 2^14 bytes
if(ntohs(record->length) > TLS_MAX_RECORD_LENGTH)
return ERROR_RECORD_OVERFLOW;
#if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
//Check whether the RecordSizeLimit extension has been negotiated
if(context->recordSizeLimitExtReceived)
{
//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
if(decryptionEngine->cipherMode != CIPHER_MODE_NULL ||
decryptionEngine->hashAlgo != NULL)
{
//A TLS endpoint that receives a record larger than its advertised
//limit must generate a fatal record_overflow alert
if(ntohs(record->length) > decryptionEngine->recordSizeLimit)
return ERROR_RECORD_OVERFLOW;
}
}
#endif
#if (TLS_MAX_EMPTY_RECORDS > 0)
//Empty record received?
if(ntohs(record->length) == 0)
{
//Increment the count of consecutive empty records
context->emptyRecordCount++;
//Do not allow too many consecutive empty records
if(context->emptyRecordCount > TLS_MAX_EMPTY_RECORDS)
return ERROR_UNEXPECTED_MESSAGE;
}
else
{
//Reset the count of consecutive empty records
context->emptyRecordCount = 0;
}
#endif
//Successful processing
return NO_ERROR;
}
/**
* @brief Set TLS record type
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the TLS record
* @param[in] type Record type
**/
void tlsSetRecordType(TlsContext *context, void *record, uint8_t type)
{
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Set the type of the DTLS record
((DtlsRecord *) record)->type = type;
}
else
#endif
//TLS protocol?
{
//Set the type of the DTLS record
((TlsRecord *) record)->type = type;
}
}
/**
* @brief Get TLS record type
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the TLS record
* @return Record type
**/
uint8_t tlsGetRecordType(TlsContext *context, void *record)
{
uint8_t type;
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Get the type of the DTLS record
type = ((DtlsRecord *) record)->type;
}
else
#endif
//TLS protocol?
{
//Get the type of the TLS record
type = ((TlsRecord *) record)->type;
}
//Return the content type of the record
return type;
}
/**
* @brief Set TLS record length
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the TLS record
* @param[in] length Record length
**/
void tlsSetRecordLength(TlsContext *context, void *record, size_t length)
{
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Set the length of the DTLS record
((DtlsRecord *) record)->length = htons(length);
}
else
#endif
//TLS protocol?
{
//Set the length of the DTLS record
((TlsRecord *) record)->length = htons(length);
}
}
/**
* @brief Get TLS record length
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the TLS record
* @return Record length
**/
size_t tlsGetRecordLength(TlsContext *context, void *record)
{
size_t length;
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Get the length of the DTLS record
length = ((DtlsRecord *) record)->length;
}
else
#endif
//TLS protocol?
{
//Get the length of the TLS record
length = ((TlsRecord *) record)->length;
}
//Convert the length field to host byte order
return htons(length);
}
/**
* @brief Get TLS record payload
* @param[in] context Pointer to the TLS context
* @param[in] record Pointer to the TLS record
* @return Pointer to the first byte of the payload
**/
uint8_t *tlsGetRecordData(TlsContext *context, void *record)
{
uint8_t *data;
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Point to the payload of the DTLS record
data = ((DtlsRecord *) record)->data;
}
else
#endif
//TLS protocol?
{
//Point to the payload of the TLS record
data = ((TlsRecord *) record)->data;
}
//Return a pointer to the first byte of the payload
return data;
}
/**
* @brief Format additional authenticated data (AAD)
* @param[in] context Pointer to the TLS context
* @param[in] encryptionEngine Pointer to the encryption engine
* @param[in] record Pointer to the TLS record
* @param[out] aad Pointer to the buffer where to store the resulting AAD
* @param[out] aadLen Length of the AAD, in bytes
**/
void tlsFormatAad(TlsContext *context, TlsEncryptionEngine *encryptionEngine,
const void *record, uint8_t *aad, size_t *aadLen)
{
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
const DtlsRecord *dtlsRecord;
//Point to the DTLS record
dtlsRecord = (DtlsRecord *) record;
//Additional data to be authenticated
osMemcpy(aad, (void *) &dtlsRecord->epoch, 2);
osMemcpy(aad + 2, &dtlsRecord->seqNum, 6);
osMemcpy(aad + 8, &dtlsRecord->type, 3);
osMemcpy(aad + 11, (void *) &dtlsRecord->length, 2);
//Length of the additional data, in bytes
*aadLen = 13;
}
else
#endif
//TLS protocol?
{
//Version of TLS prior to TLS 1.3?
if(context->version <= TLS_VERSION_1_2)
{
//Additional data to be authenticated
osMemcpy(aad, &encryptionEngine->seqNum, 8);
osMemcpy(aad + 8, record, 5);
//Length of the additional data, in bytes
*aadLen = 13;
}
else
{
//The additional data input is the record header (refer to RFC 8446,
//section 5.2)
osMemcpy(aad, record, 5);
//Length of the additional data, in bytes
*aadLen = 5;
}
}
}
/**
* @brief Format nonce
* @param[in] context Pointer to the TLS context
* @param[in] encryptionEngine Pointer to the encryption engine
* @param[in] record Pointer to the TLS record
* @param[in] recordIv Explicit part of the nonce
* @param[out] nonce Pointer to the buffer where to store the resulting nonce
* @param[out] nonceLen Length of the nonce, in bytes
**/
void tlsFormatNonce(TlsContext *context, TlsEncryptionEngine *encryptionEngine,
const void *record, const uint8_t *recordIv, uint8_t *nonce, size_t *nonceLen)
{
size_t i;
size_t n;
//Check the length of the nonce explicit part
if(encryptionEngine->recordIvLen != 0)
{
//Calculate the total length of the nonce
n = encryptionEngine->fixedIvLen + encryptionEngine->recordIvLen;
//The salt is the implicit part of the nonce and is not sent in the packet
osMemcpy(nonce, encryptionEngine->iv, encryptionEngine->fixedIvLen);
//The explicit part of the nonce is chosen by the sender
osMemcpy(nonce + encryptionEngine->fixedIvLen, recordIv,
encryptionEngine->recordIvLen);
}
else
{
//Calculate the total length of the nonce
n = encryptionEngine->fixedIvLen;
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
const DtlsRecord *dtlsRecord;
//Point to the DTLS record
dtlsRecord = (DtlsRecord *) record;
//The 64-bit record sequence number is serialized as an 8-byte,
//big-endian value
osMemcpy(nonce + n - 8, (void *) &dtlsRecord->epoch, 2);
osMemcpy(nonce + n - 6, &dtlsRecord->seqNum, 6);
}
else
#endif
//TLS protocol?
{
//The 64-bit record sequence number is serialized as an 8-byte,