-
Notifications
You must be signed in to change notification settings - Fork 16
/
dtls_record.c
1328 lines (1127 loc) · 41.4 KB
/
dtls_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 dtls_record.c
* @brief DTLS record protocol
*
* @section License
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* Copyright (C) 2010-2024 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.4.4
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL TLS_TRACE_LEVEL
//Dependencies
#include "tls.h"
#include "tls_common.h"
#include "tls_record.h"
#include "tls_record_encryption.h"
#include "tls_record_decryption.h"
#include "tls_misc.h"
#include "dtls_misc.h"
#include "dtls_record.h"
#include "debug.h"
//Check TLS library configuration
#if (TLS_SUPPORT == ENABLED && DTLS_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 dtlsWriteProtocolData(TlsContext *context,
const uint8_t *data, size_t length, TlsContentType contentType)
{
error_t error;
//Prepare DTLS record
error = dtlsWriteRecord(context, data, length, contentType);
//Check status code
if(!error)
{
//DTLS operates as a client or a server?
if(context->entity == TLS_CONNECTION_END_CLIENT)
{
//Client messages are grouped into a series of message flights
if(context->state == TLS_STATE_CLIENT_HELLO ||
context->state == TLS_STATE_CLIENT_FINISHED)
{
//Reset retransmission counter
context->retransmitCount = 0;
//Implementations should use an initial timer value of 1 second
context->retransmitTimeout = DTLS_INIT_TIMEOUT;
//Transmit the buffered flight of messages
error = dtlsSendFlight(context);
}
}
else
{
//Server messages are grouped into a series of message flights
if(context->state == TLS_STATE_SERVER_HELLO_DONE ||
context->state == TLS_STATE_SERVER_FINISHED)
{
//Reset retransmission counter
context->retransmitCount = 0;
//Implementations should use an initial timer value of 1 second
context->retransmitTimeout = DTLS_INIT_TIMEOUT;
//Transmit the buffered flight of messages
error = dtlsSendFlight(context);
}
else if(context->state == TLS_STATE_HELLO_VERIFY_REQUEST ||
context->state == TLS_STATE_HELLO_RETRY_REQUEST)
{
//Reset retransmission counter
context->retransmitCount = 0;
//Transmit the HelloVerifyRequest or HelloRetryRequest message
error = dtlsSendFlight(context);
//Timeout and retransmission do not apply to HelloVerifyRequest and
//HelloRetryRequest messages, because this would require creating
//state on the server
context->txBufferLen = 0;
}
}
}
//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 dtlsReadProtocolData(TlsContext *context,
uint8_t **data, size_t *length, TlsContentType *contentType)
{
error_t error;
//Initialize status code
error = NO_ERROR;
//Receive process
while(error == NO_ERROR)
{
if(context->rxBufferLen > 0)
{
//Pass the received data to the higher layer
break;
}
else if(context->rxRecordLen > 0)
{
//Process the incoming DTLS record
error = dtlsProcessRecord(context);
//Invalid record?
if(error)
{
//Debug message
TRACE_WARNING("Discarding DTLS record!\r\n");
//DTLS implementations should silently discard records with
//bad MACs and continue with the connection
error = NO_ERROR;
}
}
else if(context->rxDatagramLen > 0)
{
//Read a new DTLS record from the datagram
error = dtlsReadRecord(context);
//Malformed record?
if(error != NO_ERROR && error != ERROR_RECORD_OVERFLOW)
{
//Debug message
TRACE_WARNING("Discarding DTLS record!\r\n");
//The receiving implementation should discard the offending record
error = NO_ERROR;
}
}
else
{
//Read a new datagram
error = dtlsReadDatagram(context, context->rxBuffer + context->rxFragQueueLen,
context->rxBufferSize - context->rxFragQueueLen, &context->rxDatagramLen);
//Check whether a valid datagram has been received
if(!error)
{
//Make room for the fragment reassembly process
context->rxDatagramPos = context->rxBufferSize - context->rxDatagramLen;
//Copy the received datagram
osMemmove(context->rxBuffer + context->rxDatagramPos,
context->rxBuffer + context->rxFragQueueLen, context->rxDatagramLen);
}
}
}
//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
//Pointer to the received data
*data = context->rxBuffer + context->rxBufferPos;
//Length, in byte, of the data
*length = context->rxBufferLen;
//Protocol type
*contentType = context->rxBufferType;
}
//Return status code
return error;
}
/**
* @brief Send a DTLS 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 dtlsWriteRecord(TlsContext *context, const uint8_t *data,
size_t length, TlsContentType contentType)
{
error_t error;
size_t n;
DtlsRecord *record;
TlsEncryptionEngine *encryptionEngine;
//Calculate the length of the DTLS record
n = length + sizeof(DtlsRecord);
//Make sure the buffer is large enough to hold the DTLS record
if((context->txBufferLen + n) > context->txBufferSize)
return ERROR_BUFFER_OVERFLOW;
//Point to the encryption engine
encryptionEngine = &context->encryptionEngine;
//Point to the DTLS record header
record = (DtlsRecord *) (context->txBuffer + context->txBufferLen);
//Copy record data
osMemmove(record->data, data, length);
//Format DTLS record
record->type = contentType;
record->version = htons(dtlsTranslateVersion(encryptionEngine->version));
record->epoch = htons(encryptionEngine->epoch);
record->length = htons(length);
//Check record type
if(contentType == TLS_TYPE_HANDSHAKE ||
contentType == TLS_TYPE_CHANGE_CIPHER_SPEC)
{
//Sequence numbers are handled at record layer
osMemset(&record->seqNum, 0, sizeof(DtlsSequenceNumber));
//Adjust the length of the buffered flight of messages
context->txBufferLen += n;
}
else
{
//This record will have a new sequence number
record->seqNum = encryptionEngine->dtlsSeqNum;
//Take into account the overhead caused by encryption
n += tlsComputeEncryptionOverhead(encryptionEngine, n);
//Make sure the buffer is large enough to hold the encrypted record
if((context->txBufferLen + n) > context->txBufferSize)
return ERROR_BUFFER_OVERFLOW;
//Protect record payload?
if(encryptionEngine->cipherMode != CIPHER_MODE_NULL ||
encryptionEngine->hashAlgo != NULL)
{
//Encrypt DTLS record
error = tlsEncryptRecord(context, encryptionEngine, record);
//Any error to report?
if(error)
return error;
}
//Debug message
TRACE_DEBUG("Encrypted DTLS record (%" PRIuSIZE " bytes)...\r\n", ntohs(record->length));
TRACE_DEBUG_ARRAY(" ", record, ntohs(record->length) + sizeof(DtlsRecord));
//Increment sequence number
dtlsIncSequenceNumber(&encryptionEngine->dtlsSeqNum);
//Length of the resulting datagram, in bytes
n = ntohs(record->length) + sizeof(DtlsRecord);
//Debug message
TRACE_INFO("Sending UDP datagram (%" PRIuSIZE " bytes)...\r\n", n);
//Send datagram
error = context->socketSendCallback(context->socketHandle, record, n, &n, 0);
//Any error to report?
if(error)
return error;
}
//Successful processing
return NO_ERROR;
}
/**
* @brief Receive a DTLS record
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t dtlsReadRecord(TlsContext *context)
{
error_t error;
DtlsRecord *record;
size_t recordLen;
TlsEncryptionEngine *decryptionEngine;
//Point to the decryption engine
decryptionEngine = &context->decryptionEngine;
//Make sure the datagram is large enough to hold a DTLS record
if(context->rxDatagramLen < sizeof(DtlsRecord))
{
//Drop received datagram
context->rxDatagramLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
//Point to the DTLS record
record = (DtlsRecord *) (context->rxBuffer + context->rxDatagramPos);
//Retrieve the length of the record
recordLen = ntohs(record->length);
//Sanity check
if((recordLen + sizeof(DtlsRecord)) > context->rxDatagramLen)
{
//Drop received datagram
context->rxDatagramLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
//Debug message
TRACE_DEBUG("DTLS encrypted record received (%" PRIuSIZE " bytes)...\r\n", recordLen);
TRACE_DEBUG_ARRAY(" ", record, recordLen + sizeof(DtlsRecord));
//Point to the payload data
context->rxRecordPos = context->rxDatagramPos + sizeof(DtlsRecord);
//It is acceptable to pack multiple DTLS records in the same datagram
context->rxDatagramPos += recordLen + sizeof(DtlsRecord);
context->rxDatagramLen -= recordLen + sizeof(DtlsRecord);
//Compliant servers must accept any value {254,XX} as the record layer
//version number for ClientHello
if(LSB(record->version) != MSB(DTLS_VERSION_1_0))
return ERROR_VERSION_NOT_SUPPORTED;
//Discard packets from earlier epochs
if(ntohs(record->epoch) != context->decryptionEngine.epoch)
return ERROR_INVALID_EPOCH;
//Perform replay detection
error = dtlsCheckReplayWindow(context, &record->seqNum);
//Any error to report?
if(error)
return error;
//Check whether the record payload is protected
if(decryptionEngine->cipherMode != CIPHER_MODE_NULL ||
decryptionEngine->hashAlgo != NULL)
{
//Decrypt DTLS record
error = tlsDecryptRecord(context, decryptionEngine, record);
//If the MAC validation fails, the receiver must discard the record
if(error)
return error;
//The length of the plaintext record must not exceed 2^14 bytes
if(ntohs(record->length) > TLS_MAX_RECORD_LENGTH)
return ERROR_RECORD_OVERFLOW;
}
//The receive window is updated only if the MAC verification succeeds
dtlsUpdateReplayWindow(context, &record->seqNum);
//Retrieve the length of the record
recordLen = ntohs(record->length);
//Debug message
TRACE_DEBUG("DTLS decrypted record received (%" PRIuSIZE " bytes)...\r\n", recordLen);
TRACE_DEBUG_ARRAY(" ", record, recordLen + sizeof(DtlsRecord));
//Save record version
context->rxRecordVersion = ntohs(record->version);
//Save record type
context->rxBufferType = (TlsContentType) record->type;
//Save record length
context->rxRecordLen = recordLen;
//Successful processing
return NO_ERROR;
}
/**
* @brief Process incoming DTLS record
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t dtlsProcessRecord(TlsContext *context)
{
error_t error;
systime_t time;
//Handshake message received?
if(context->rxBufferType == TLS_TYPE_HANDSHAKE)
{
size_t fragLength;
DtlsHandshake *message;
//Make sure the DTLS record is large enough to hold a handshake message
if(context->rxRecordLen < sizeof(DtlsHandshake))
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
//Point to the handshake message
message = (DtlsHandshake *) (context->rxBuffer + context->rxRecordPos);
//Debug message
TRACE_DEBUG("Handshake message fragment received (%" PRIuSIZE " bytes)...\r\n",
LOAD24BE(message->fragLength));
TRACE_DEBUG(" msgType = %u\r\n", message->msgType);
TRACE_DEBUG(" msgSeq = %u\r\n", ntohs(message->msgSeq));
TRACE_DEBUG(" fragOffset = %u\r\n", LOAD24BE(message->fragOffset));
TRACE_DEBUG(" fragLength = %u\r\n", LOAD24BE(message->fragLength));
TRACE_DEBUG(" length = %u\r\n", LOAD24BE(message->length));
//Retrieve fragment length
fragLength = LOAD24BE(message->fragLength) + sizeof(DtlsHandshake);
//Sanity check
if(fragLength > context->rxRecordLen)
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
//It is acceptable to pack multiple handshake messages in the same record
context->rxRecordPos += fragLength;
context->rxRecordLen -= fragLength;
//Invalid fragment length?
if(LOAD24BE(message->fragLength) > LOAD24BE(message->length))
return ERROR_INVALID_LENGTH;
//Empty fragment?
if(LOAD24BE(message->fragLength) == 0 && LOAD24BE(message->length) != 0)
return ERROR_INVALID_LENGTH;
//Check whether TLS operates as a client or a server
if(context->entity == TLS_CONNECTION_END_CLIENT)
{
//HelloRequest message received?
if(message->msgType == TLS_TYPE_HELLO_REQUEST &&
context->state == TLS_STATE_APPLICATION_DATA)
{
//Re-initialize message sequence numbers
context->rxMsgSeq = ntohs(message->msgSeq);
context->txMsgSeq = 0;
}
}
else
{
//ClientHello message received?
if(message->msgType == TLS_TYPE_CLIENT_HELLO &&
context->state == TLS_STATE_CLIENT_HELLO)
{
//Initial handshake?
if(context->decryptionEngine.epoch == 0)
{
//The server must use the record sequence number in the ClientHello
//as the record sequence number in its response (HelloVerifyRequest
//or ServerHello)
context->encryptionEngine.dtlsSeqNum = context->decryptionEngine.dtlsSeqNum;
//Re-initialize message sequence numbers
context->rxMsgSeq = ntohs(message->msgSeq);
context->txMsgSeq = ntohs(message->msgSeq);
}
}
}
//When a peer receives a handshake message, it can quickly determine
//whether that message is the next message it expects
if(ntohs(message->msgSeq) < context->rxMsgSeq)
{
//Retransmitted flight from the peer?
if(message->msgType == TLS_TYPE_CLIENT_HELLO ||
message->msgType == TLS_TYPE_SERVER_HELLO_DONE ||
message->msgType == TLS_TYPE_FINISHED)
{
//First fragment of the handshake message?
if(LOAD24BE(message->fragOffset) == 0)
{
//Check whether a flight of messages is buffered
if(context->txBufferLen > 0)
{
//Get current time
time = osGetSystemTime();
//Send only one response in the case multiple retransmitted
//flights are received from the peer
if(timeCompare(time, context->retransmitTimestamp +
DTLS_MIN_TIMEOUT) >= 0)
{
//The implementation transitions to the SENDING state,
//where it retransmits the flight, resets the retransmit
//timer, and returns to the WAITING state
if(context->retransmitCount < DTLS_MAX_RETRIES)
{
dtlsSendFlight(context);
}
}
}
}
}
//If the sequence number of the received message is less than
//the expected value, the message must be discarded
return ERROR_INVALID_SEQUENCE_NUMBER;
}
else if(ntohs(message->msgSeq) > context->rxMsgSeq)
{
//If the sequence number of the received message is greater than
//the expected value, the implementation may discard it
return ERROR_INVALID_SEQUENCE_NUMBER;
}
else
{
//If the sequence number of the received message matches the
//expected value, the message is processed
}
//Check current state
if(context->state > TLS_STATE_SERVER_HELLO)
{
//Once the server has sent the ServerHello message, enforce the version
//of incoming records
if(context->rxRecordVersion != dtlsTranslateVersion(context->version))
return ERROR_VERSION_NOT_SUPPORTED;
}
//When a DTLS implementation receives a handshake message fragment,
//it must buffer it until it has the entire handshake message. DTLS
//implementations must be able to handle overlapping fragment ranges
error = dtlsReassembleHandshakeMessage(context, message);
//Unacceptable message received?
if(error)
{
//Flush the reassembly queue
context->rxFragQueueLen = 0;
//Report an error
return error;
}
//Point to the first fragment of the reassembly queue
message = (DtlsHandshake *) context->rxBuffer;
//An unfragmented message is a degenerate case with fragment_offset = 0
//and fragment_length = length
if(LOAD24BE(message->fragOffset) == 0 &&
LOAD24BE(message->fragLength) == LOAD24BE(message->length))
{
//The reassembly process is now complete
context->rxFragQueueLen = 0;
//Number of bytes available for reading
context->rxBufferLen = LOAD24BE(message->length) + sizeof(DtlsHandshake);
//Rewind to the beginning of the buffer
context->rxBufferPos = 0;
//The message sequence number is incremented by one
context->rxMsgSeq++;
//Check whether a complete flight of messages has been received
if(message->msgType == TLS_TYPE_CLIENT_HELLO ||
message->msgType == TLS_TYPE_HELLO_VERIFY_REQUEST ||
message->msgType == TLS_TYPE_SERVER_HELLO_DONE ||
message->msgType == TLS_TYPE_FINISHED)
{
//Exit from the WAITING state
context->txBufferLen = 0;
}
}
}
else
{
//ChangeCipherSpec message received?
if(context->rxBufferType == TLS_TYPE_CHANGE_CIPHER_SPEC)
{
//Sanity check
if(context->rxRecordLen < sizeof(TlsChangeCipherSpec))
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
//DTLS operates as a client or a server?
if(context->entity == TLS_CONNECTION_END_CLIENT)
{
//Check current state
if(context->state != TLS_STATE_SERVER_CHANGE_CIPHER_SPEC)
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_UNEXPECTED_MESSAGE;
}
}
else
{
//Check current state
if(context->state != TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC)
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_UNEXPECTED_MESSAGE;
}
}
//Enforce the version the received DTLS record
if(context->rxRecordVersion != dtlsTranslateVersion(context->version))
return ERROR_VERSION_NOT_SUPPORTED;
}
//Alert message received?
else if(context->rxBufferType == TLS_TYPE_ALERT)
{
//Sanity check
if(context->rxRecordLen < sizeof(TlsAlert))
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_INVALID_LENGTH;
}
}
//Application data received?
else if(context->rxBufferType == TLS_TYPE_APPLICATION_DATA)
{
//Check current state
if(context->state == TLS_STATE_APPLICATION_DATA)
{
//The last flight of messages has been received by the peer
context->txBufferLen = 0;
}
else
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_UNEXPECTED_MESSAGE;
}
//Enforce the version the received DTLS record
if(context->rxRecordVersion != dtlsTranslateVersion(context->version))
return ERROR_VERSION_NOT_SUPPORTED;
}
//Unknown content type?
else
{
//Drop the received DTLS record
context->rxRecordLen = 0;
//Report an error
return ERROR_UNEXPECTED_MESSAGE;
}
//Number of bytes available for reading
context->rxBufferLen = context->rxRecordLen;
//Rewind to the beginning of the buffer
context->rxBufferPos = 0;
//Copy application data
osMemcpy(context->rxBuffer, context->rxBuffer + context->rxRecordPos,
context->rxRecordLen);
//The DTLS record has been entirely processed
context->rxRecordLen = 0;
//Flush the reassembly queue
context->rxFragQueueLen = 0;
}
//Successful processing
return NO_ERROR;
}
/**
* @brief Send the buffered flight of messages
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t dtlsSendFlight(TlsContext *context)
{
error_t error;
size_t n;
size_t pmtu;
uint8_t *datagram;
DtlsRecord *record;
DtlsHandshake *message;
TlsEncryptionEngine *encryptionEngine;
//Determine the value of the PMTU
pmtu = MIN(context->pmtu, context->txBufferSize - context->txBufferLen);
//Make sure the PMTU value is acceptable
if(pmtu < DTLS_MIN_PMTU)
return ERROR_BUFFER_OVERFLOW;
//Point to the buffer where to format the datagram
datagram = context->txBuffer + context->txBufferLen;
//Length of the datagram, in bytes
context->txDatagramLen = 0;
//Point to the first message of the flight
context->txBufferPos = 0;
//In the SENDING state, the implementation transmits the buffered
//flight of messages
while(context->txBufferPos < context->txBufferLen)
{
//Point to the current DTLS record
record = (DtlsRecord *) (context->txBuffer + context->txBufferPos);
//Advance data pointer
context->txBufferPos += ntohs(record->length) + sizeof(DtlsRecord);
//Select the relevant encryption engine
if(ntohs(record->epoch) == context->encryptionEngine.epoch)
{
encryptionEngine = &context->encryptionEngine;
}
else
{
encryptionEngine = &context->prevEncryptionEngine;
}
//Handshake message?
if(record->type == TLS_TYPE_HANDSHAKE)
{
//Point to the handshake message header to be fragmented
message = (DtlsHandshake *) record->data;
//Fragment handshake message into smaller fragments
error = dtlsFragmentHandshakeMessage(context, ntohs(record->version),
encryptionEngine, message);
//Any error to report?
if(error)
return error;
}
else
{
//Any datagram pending to be sent?
if(context->txDatagramLen > 0)
{
//Estimate the length of the DTLS record
n = ntohs(record->length) + sizeof(DtlsRecord);
//Take into account the overhead caused by encryption
n += tlsComputeEncryptionOverhead(encryptionEngine, n);
//Records may not span datagrams
if((context->txDatagramLen + n) > pmtu)
{
//Debug message
TRACE_INFO("Sending UDP datagram (%" PRIuSIZE " bytes)...\r\n",
context->txDatagramLen);
//Send datagram
error = context->socketSendCallback(context->socketHandle,
datagram, context->txDatagramLen, &n, 0);
//Any error to report?
if(error)
return error;
//The datagram has been successfully transmitted
context->txDatagramLen = 0;
}
}
//Estimate the length of the DTLS record
n = ntohs(record->length) + sizeof(DtlsRecord);
//Take into account the overhead caused by encryption
n += tlsComputeEncryptionOverhead(encryptionEngine, n);
//Make sure the buffer is large enough to hold the DTLS record
if((context->txBufferLen + context->txDatagramLen + n) > context->txBufferSize)
return ERROR_BUFFER_OVERFLOW;
//Multiple DTLS records may be placed in a single datagram. They are
//simply encoded consecutively
osMemcpy(datagram + context->txDatagramLen, record,
ntohs(record->length) + sizeof(DtlsRecord));
//Point to the DTLS record header
record = (DtlsRecord *) (datagram + context->txDatagramLen);
//From the perspective of the DTLS record layer, the retransmission is
//a new record. This record will have a new sequence number
record->seqNum = encryptionEngine->dtlsSeqNum;
//Protect record payload?
if(encryptionEngine->cipherMode != CIPHER_MODE_NULL ||
encryptionEngine->hashAlgo != NULL)
{
//Encrypt DTLS record
error = tlsEncryptRecord(context, encryptionEngine, record);
//Any error to report?
if(error)
return error;
}
//Debug message
TRACE_DEBUG("Encrypted DTLS record (%" PRIuSIZE " bytes)...\r\n", ntohs(record->length));
TRACE_DEBUG_ARRAY(" ", record, ntohs(record->length) + sizeof(DtlsRecord));
//Increment sequence number
dtlsIncSequenceNumber(&encryptionEngine->dtlsSeqNum);
//Adjust the length of the datagram
context->txDatagramLen += ntohs(record->length) + sizeof(DtlsRecord);
}
}
//Any datagram pending to be sent?
if(context->txDatagramLen > 0)
{
//Debug message
TRACE_INFO("Sending UDP datagram (%" PRIuSIZE " bytes)...\r\n",
context->txDatagramLen);
//Send datagram
error = context->socketSendCallback(context->socketHandle, datagram,
context->txDatagramLen, &n, 0);
//Any error to report?
if(error)
return error;
//The datagram has been successfully transmitted
context->txDatagramLen = 0;
}
//Save the time at which the flight of messages was sent
context->retransmitTimestamp = osGetSystemTime();
//Increment retransmission counter
context->retransmitCount++;
//Successful processing
return NO_ERROR;
}
/**
* @brief Handshake message fragmentation
* @param[in] context Pointer to the TLS context
* @param[in] version DTLS version to be used
* @param[in] encryptionEngine Pointer to the encryption engine
* @param[in] message Pointer the handshake message to be fragmented
* @return Error code
**/
error_t dtlsFragmentHandshakeMessage(TlsContext *context, uint16_t version,
TlsEncryptionEngine *encryptionEngine, const DtlsHandshake *message)
{
error_t error;
size_t n;
size_t pmtu;
size_t totalLength;
size_t fragOffset;
size_t fragLength;
size_t maxFragSize;
uint8_t *datagram;
DtlsRecord *record;
DtlsHandshake *fragment;
//Determine the value of the PMTU
pmtu = MIN(context->pmtu, context->txBufferSize - context->txBufferLen);
//DTLS has 25 bytes overhead per packet
n = sizeof(DtlsRecord) + sizeof(DtlsHandshake);
//Take into account the overhead caused by encryption
n += tlsComputeEncryptionOverhead(encryptionEngine, 0);
//Make sure the PMTU value is acceptable
if(pmtu <= n || pmtu < DTLS_MIN_PMTU)
return ERROR_BUFFER_OVERFLOW;
//Determine the maximum payload size for fragmented messages
maxFragSize = pmtu - n;
//Point to the buffer where to format the datagram
datagram = context->txBuffer + context->txBufferLen;
//Get the length of the handshake message
totalLength = LOAD24BE(message->length);
//Prepare to send the first fragment
fragOffset = 0;
//Fragmentation process
do
{
//Calculate the length of the current fragment
fragLength = MIN(totalLength - fragOffset, maxFragSize);
//Any datagram pending to be sent?
if(context->txDatagramLen > 0)
{
//Estimate the length of the DTLS record
n = fragLength + sizeof(DtlsRecord) + sizeof(DtlsHandshake);
//Take into account the overhead caused by encryption
n += tlsComputeEncryptionOverhead(encryptionEngine, n);
//Records may not span datagrams
if((context->txDatagramLen + n) > pmtu)
{
//Debug message
TRACE_INFO("Sending UDP datagram (%" PRIuSIZE " bytes)...\r\n",
context->txDatagramLen);
//Send datagram
error = context->socketSendCallback(context->socketHandle,
datagram, context->txDatagramLen, &n, 0);
//Any error to report?
if(error)
return error;
//The datagram has been successfully transmitted
context->txDatagramLen = 0;
}
}
//Multiple DTLS records may be placed in a single datagram. They are
//simply encoded consecutively
record = (DtlsRecord *) (datagram + context->txDatagramLen);
//Format DTLS record
record->type = TLS_TYPE_HANDSHAKE;
record->version = htons(version);
record->epoch = htons(encryptionEngine->epoch);
record->seqNum = encryptionEngine->dtlsSeqNum;
record->length = htons(fragLength + sizeof(DtlsHandshake));
//Point to the handshake message header
fragment = (DtlsHandshake *) record->data;
//Handshake message type
fragment->msgType = message->msgType;
//Number of bytes in the message
STORE24BE(totalLength, fragment->length);
//Message sequence number
fragment->msgSeq = message->msgSeq;
//Fragment offset
STORE24BE(fragOffset, fragment->fragOffset);
//Fragment length
STORE24BE(fragLength, fragment->fragLength);
//Copy data
osMemcpy(fragment->data, message->data + fragOffset, fragLength);
//Debug message
TRACE_DEBUG("Sending handshake message fragment (%" PRIuSIZE " bytes)...\r\n",
LOAD24BE(fragment->fragLength));
TRACE_DEBUG(" msgType = %u\r\n", fragment->msgType);
TRACE_DEBUG(" msgSeq = %u\r\n", ntohs(fragment->msgSeq));
TRACE_DEBUG(" fragOffset = %u\r\n", LOAD24BE(fragment->fragOffset));
TRACE_DEBUG(" fragLength = %u\r\n", LOAD24BE(fragment->fragLength));
TRACE_DEBUG(" length = %u\r\n", LOAD24BE(fragment->length));
//Protect record payload?
if(encryptionEngine->cipherMode != CIPHER_MODE_NULL ||
encryptionEngine->hashAlgo != NULL)