-
Notifications
You must be signed in to change notification settings - Fork 969
Expand file tree
/
Copy pathdtls13.c
More file actions
3184 lines (2646 loc) · 91.2 KB
/
dtls13.c
File metadata and controls
3184 lines (2646 loc) · 91.2 KB
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
/* dtls13.c
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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 3 of the License, or
* (at your option) any later version.
*
* wolfSSL 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-1335, USA
*/
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
#ifdef WOLFSSL_DTLS13
#include <wolfssl/error-ssl.h>
#include <wolfssl/internal.h>
#include <wolfssl/ssl.h>
#include <wolfssl/wolfcrypt/aes.h>
#include <wolfssl/wolfcrypt/kdf.h>
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
/**
* enum rnDirection - distinguish between RecordNumber Enc/Dec
* PROTECT: encrypt the Record Number
* DEPROTECT: decrypt the Record Number
*/
enum rnDirection {
PROTECT = 0,
DEPROTECT,
};
/**
* struct Dtls13HandshakeHeader: represent DTLS Handshake header
* @msg_type: type of message (client_hello,server_hello,etc)
* @length: length of the message
* @messageSeq: message sequence number (used for reordering and retransmission)
* @fragmentOffset: this is the offset of the data in the complete message. For
* an unfragmented message this is always zero
* @fragmentLength: length of this fragment (if not fragmented @fragmentLength
* is always equal to @length)
*/
typedef struct Dtls13HandshakeHeader {
byte msg_type;
byte length[3];
byte messageSeq[2];
byte fragmentOffset[3];
byte fragmentLength[3];
} Dtls13HandshakeHeader;
wc_static_assert(sizeof(Dtls13HandshakeHeader) == DTLS13_HANDSHAKE_HEADER_SZ);
/**
* struct Dtls13Recordplaintextheader: represent header of unprotected DTLSv1.3
* record
* @contentType: content type of the record (handshake, applicationData, etc)
* @legacyversionrecord: legacy version field
* @epoch: epoch number (lower 16 bits)
* @sequenceNumber: sequence number (lower 16 bits)
* @length: length of the record
*/
typedef struct Dtls13RecordPlaintextHeader {
byte contentType;
ProtocolVersion legacyVersionRecord;
byte epoch[2];
byte sequenceNumber[6];
byte length[2];
} Dtls13RecordPlaintextHeader;
/* size of the len field in the unified header */
#define DTLS13_LEN_SIZE 2
/* size of the flags in the unified header */
#define DTLS13_HDR_FLAGS_SIZE 1
/* size of the sequence number where SEQ_LEN_BIT is present */
#define DTLS13_SEQ_16_LEN 2
/* size of the sequence number where SEQ_LEN_BIT is not present */
#define DTLS13_SEQ_8_LEN 1
/* fixed bits mask to detect unified header */
#define DTLS13_FIXED_BITS_MASK (0x7 << 5)
/* fixed bits value to detect unified header */
#define DTLS13_FIXED_BITS (0x1 << 5)
/* ConnectionID present bit in the unified header flags */
#define DTLS13_CID_BIT (0x1 << 4)
/* Sequence number is 16 bits if this bit is into unified header flags */
#define DTLS13_SEQ_LEN_BIT (0x1 << 3)
/* Length field is present if this bit is into unified header flags */
#define DTLS13_LEN_BIT (0x1 << 2)
/* For now, the size of the outgoing DTLSv1.3 record header is fixed to 5 bytes
(8 bit header flags + 16bit record number + 16 bit length). In the future, we
can dynamically choose to remove the length from the header to save
space. Also it will need to account for client connection ID when
supported. */
#define DTLS13_UNIFIED_HEADER_SIZE 5
#define DTLS13_MIN_CIPHERTEXT 16
#ifndef DTLS13_MIN_RTX_INTERVAL
#define DTLS13_MIN_RTX_INTERVAL (DTLS_TIMEOUT_INIT * 1000)
#endif
#ifndef NO_WOLFSSL_CLIENT
WOLFSSL_METHOD* wolfDTLSv1_3_client_method_ex(void* heap)
{
WOLFSSL_METHOD* method;
WOLFSSL_ENTER("DTLSv1_3_client_method_ex");
(void)heap;
method = (WOLFSSL_METHOD*)XMALLOC(sizeof(WOLFSSL_METHOD), heap,
DYNAMIC_TYPE_METHOD);
if (method)
InitSSL_Method(method, MakeDTLSv1_3());
return method;
}
WOLFSSL_METHOD* wolfDTLSv1_3_client_method(void)
{
return wolfDTLSv1_3_client_method_ex(NULL);
}
#endif /* !NO_WOLFSSL_CLIENT */
#ifndef NO_WOLFSSL_SERVER
WOLFSSL_METHOD* wolfDTLSv1_3_server_method_ex(void* heap)
{
WOLFSSL_METHOD* method;
WOLFSSL_ENTER("DTLSv1_3_server_method_ex");
(void)heap;
method = (WOLFSSL_METHOD*)XMALLOC(sizeof(WOLFSSL_METHOD), heap,
DYNAMIC_TYPE_METHOD);
if (method) {
InitSSL_Method(method, MakeDTLSv1_3());
method->side = WOLFSSL_SERVER_END;
}
return method;
}
WOLFSSL_METHOD* wolfDTLSv1_3_server_method(void)
{
return wolfDTLSv1_3_server_method_ex(NULL);
}
#endif /* !NO_WOLFSSL_SERVER */
int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out,
enum ContentType content_type, word16 length)
{
Dtls13RecordPlaintextHeader* hdr;
word32 seq[2];
int ret;
hdr = (Dtls13RecordPlaintextHeader*)out;
hdr->contentType = content_type;
hdr->legacyVersionRecord.major = DTLS_MAJOR;
hdr->legacyVersionRecord.minor = DTLSv1_2_MINOR;
ret = Dtls13GetSeq(ssl, CUR_ORDER, seq, 1);
if (ret != 0)
return ret;
/* seq[0] combines the epoch and 16 MSB of sequence number. We write on the
epoch field and will overflow to the first two bytes of the sequence
number */
c16toa((word16)(seq[0] >> 16), hdr->epoch);
c16toa((word16)seq[0], hdr->sequenceNumber);
c32toa(seq[1], &hdr->sequenceNumber[2]);
c16toa(length, hdr->length);
return 0;
}
static int Dtls13HandshakeAddHeaderFrag(WOLFSSL* ssl, byte* output,
enum HandShakeType msg_type, word32 frag_offset, word32 frag_length,
word32 msg_length)
{
Dtls13HandshakeHeader* hdr;
hdr = (Dtls13HandshakeHeader*)output;
hdr->msg_type = msg_type;
c32to24((word32)msg_length, hdr->length);
c16toa(ssl->keys.dtls_handshake_number, hdr->messageSeq);
c32to24(frag_offset, hdr->fragmentOffset);
c32to24(frag_length, hdr->fragmentLength);
return 0;
}
static byte Dtls13TypeIsEncrypted(enum HandShakeType hs_type)
{
byte ret = 0;
switch (hs_type) {
case hello_request:
case hello_verify_request:
case client_hello:
case hello_retry_request:
case server_hello:
break;
case encrypted_extensions:
case session_ticket:
case end_of_early_data:
case certificate:
case server_key_exchange:
case certificate_request:
case server_hello_done:
case certificate_verify:
case client_key_exchange:
case finished:
case certificate_status:
case key_update:
case change_cipher_hs:
case message_hash:
case no_shake:
ret = 1;
}
return ret;
}
static int Dtls13GetRnMask(WOLFSSL* ssl, const byte* ciphertext, byte* mask,
enum rnDirection dir)
{
RecordNumberCiphers* c;
if (dir == PROTECT)
c = &ssl->dtlsRecordNumberEncrypt;
else
c = &ssl->dtlsRecordNumberDecrypt;
#if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm ||
ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm) {
if (c->aes == NULL)
return BAD_STATE_E;
#if !defined(HAVE_SELFTEST) && \
(!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) \
|| defined(WOLFSSL_KERNEL_MODE))
return wc_AesEncryptDirect(c->aes, mask, ciphertext);
#else
wc_AesEncryptDirect(c->aes, mask, ciphertext);
return 0;
#endif
}
#endif /* HAVE_AESGCM || HAVE_AESCCM */
#ifdef HAVE_CHACHA
if (ssl->specs.bulk_cipher_algorithm == wolfssl_chacha) {
word32 counter;
int ret;
if (c->chacha == NULL)
return BAD_STATE_E;
/* assuming CIPHER[0..3] should be interpreted as little endian 32-bits
integer. The draft rfc isn't really clear on that. See sec 4.2.3 of
the draft. See also Section 2.3 of the Chacha RFC. */
ato32le(ciphertext, &counter);
ret = wc_Chacha_SetIV(c->chacha, &ciphertext[4], counter);
if (ret != 0)
return ret;
XMEMSET(mask, 0, DTLS13_RN_MASK_SIZE);
return wc_Chacha_Process(c->chacha, mask, mask, DTLS13_RN_MASK_SIZE);
}
#endif /* HAVE_CHACHA */
return NOT_COMPILED_IN;
}
static int Dtls13EncryptDecryptRecordNumber(WOLFSSL* ssl, byte* seq,
int SeqLength, const byte* ciphertext, enum rnDirection dir)
{
byte mask[DTLS13_RN_MASK_SIZE];
int ret;
#ifdef HAVE_NULL_CIPHER
/* Do not encrypt record numbers with null cipher. See RFC 9150 Sec 9 */
if (ssl->specs.bulk_cipher_algorithm == wolfssl_cipher_null)
return 0;
#endif /*HAVE_NULL_CIPHER */
ret = Dtls13GetRnMask(ssl, ciphertext, mask, dir);
if (ret != 0)
return ret;
xorbuf(seq, mask, SeqLength);
return 0;
}
static byte Dtls13RtxMsgNeedsAck(WOLFSSL* ssl, enum HandShakeType hs)
{
#ifndef NO_WOLFSSL_SERVER
/* we send an ACK when processing the finished message. In this case either
we already sent an ACK for client's Certificate/CertificateVerify or they
are in our list of seen records and will be included in the ACK
message */
if (ssl->options.side == WOLFSSL_SERVER_END && (hs == finished))
return 1;
#else
(void)ssl;
#endif /* NO_WOLFSSL_SERVER */
if (hs == session_ticket || hs == key_update)
return 1;
return 0;
}
static void Dtls13MsgWasProcessed(WOLFSSL* ssl, enum HandShakeType hs)
{
if (ssl->options.dtlsStateful)
ssl->keys.dtls_expected_peer_handshake_number++;
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0)
#endif
{
/* we need to send ACKs on the last message of a flight that needs
* explicit acknowledgment */
ssl->dtls13Rtx.sendAcks = Dtls13RtxMsgNeedsAck(ssl, hs);
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
}
}
int Dtls13ProcessBufferedMessages(WOLFSSL* ssl)
{
DtlsMsg* msg = ssl->dtls_rx_msg_list;
word32 idx = 0;
int ret = 0;
WOLFSSL_ENTER("Dtls13ProcessBufferedMessages");
while (msg != NULL) {
int downgraded = 0;
idx = 0;
/* message not in order */
if (ssl->keys.dtls_expected_peer_handshake_number != msg->seq)
break;
/* message not complete */
if (!msg->ready)
break;
#ifndef WOLFSSL_DISABLE_EARLY_SANITY_CHECKS
ret = MsgCheckEncryption(ssl, msg->type, msg->encrypted);
if (ret != 0) {
SendAlert(ssl, alert_fatal, unexpected_message);
break;
}
#endif
/* We may have DTLS <=1.2 msgs stored from before we knew which version
* we were going to use. Interpret correctly. */
if (IsAtLeastTLSv1_3(ssl->version)) {
ret = DoTls13HandShakeMsgType(ssl, msg->fullMsg, &idx, msg->type,
msg->sz, msg->sz);
if (!IsAtLeastTLSv1_3(ssl->version))
downgraded = 1;
}
else {
#if !defined(WOLFSSL_NO_TLS12)
ret = DoHandShakeMsgType(ssl, msg->fullMsg, &idx, msg->type,
msg->sz, msg->sz);
#else
WOLFSSL_MSG("DTLS1.2 disabled with WOLFSSL_NO_TLS12");
WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
ret = NOT_COMPILED_IN;
#endif
}
/* processing certificate_request triggers a connect. The error came
* from there, the message can be considered processed successfully.
* WANT_WRITE means that we are done with processing the msg and we are
* waiting to flush the output buffer. */
if ((ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE)) ||
(msg->type == certificate_request &&
ssl->options.handShakeDone &&
ret == WC_NO_ERR_TRACE(WC_PENDING_E))) {
if (IsAtLeastTLSv1_3(ssl->version))
Dtls13MsgWasProcessed(ssl, (enum HandShakeType)msg->type);
else if (downgraded)
/* DoHandShakeMsgType normally handles the hs number but if
* DoTls13HandShakeMsgType processed 1.2 msgs then this wasn't
* incremented. */
ssl->keys.dtls_expected_peer_handshake_number++;
ssl->dtls_rx_msg_list = msg->next;
DtlsMsgDelete(msg, ssl->heap);
msg = ssl->dtls_rx_msg_list;
ssl->dtls_rx_msg_list_sz--;
}
if (ret != 0)
break;
}
WOLFSSL_LEAVE("dtls13_process_buffered_messages()", ret);
return ret;
}
static int Dtls13NextMessageComplete(WOLFSSL* ssl)
{
return ssl->dtls_rx_msg_list != NULL &&
ssl->dtls_rx_msg_list->ready &&
ssl->dtls_rx_msg_list->seq ==
ssl->keys.dtls_expected_peer_handshake_number;
}
static WC_INLINE int FragIsInOutputBuffer(WOLFSSL* ssl, const byte* frag)
{
const byte* OutputBuffer = ssl->buffers.outputBuffer.buffer;
word32 OutputBufferSize = ssl->buffers.outputBuffer.bufferSize;
return frag >= OutputBuffer && frag < OutputBuffer + OutputBufferSize;
}
static int Dtls13SendFragFromBuffer(WOLFSSL* ssl, byte* output, word16 length)
{
byte* buf;
int ret;
if (FragIsInOutputBuffer(ssl, output))
return BAD_FUNC_ARG;
ret = CheckAvailableSize(ssl, length);
if (ret != 0)
return ret;
buf = GetOutputBuffer(ssl);
XMEMCPY(buf, output, length);
ssl->buffers.outputBuffer.length += length;
return SendBuffered(ssl);
}
static int Dtls13SendNow(WOLFSSL* ssl, enum HandShakeType handshakeType)
{
if (!ssl->options.groupMessages || ssl->dtls13SendingFragments)
return 1;
if (handshakeType == client_hello || handshakeType == hello_retry_request ||
handshakeType == finished || handshakeType == session_ticket ||
handshakeType == key_update ||
(handshakeType == certificate_request &&
ssl->options.handShakeState == HANDSHAKE_DONE))
return 1;
return 0;
}
/* Handshake header DTLS only fields are not included in the transcript hash.
* body points to the body of the DTLSHandshake message. */
int Dtls13HashClientHello(const WOLFSSL* ssl, byte* hash, int* hashSz,
const byte* body, word32 length, CipherSpecs* specs)
{
/* msg_type(1) + length (3) */
byte header[OPAQUE32_LEN];
int ret;
WC_DECLARE_VAR(hashCtx, wc_HashAlg, 1, ssl->heap);
int type = wolfSSL_GetHmacType_ex(specs);
if (type < 0)
return type;
WC_ALLOC_VAR_EX(hashCtx, wc_HashAlg, 1, ssl->heap, DYNAMIC_TYPE_HASHES,
return MEMORY_E);
header[0] = (byte)client_hello;
c32to24(length, header + 1);
ret = wc_HashInit_ex(hashCtx, (enum wc_HashType)type, ssl->heap, ssl->devId);
if (ret == 0) {
ret = wc_HashUpdate(hashCtx, (enum wc_HashType)type, header, OPAQUE32_LEN);
if (ret == 0)
ret = wc_HashUpdate(hashCtx, (enum wc_HashType)type, body, length);
if (ret == 0)
ret = wc_HashFinal(hashCtx, (enum wc_HashType)type, hash);
if (ret == 0) {
*hashSz = wc_HashGetDigestSize((enum wc_HashType)type);
if (*hashSz < 0)
ret = *hashSz;
}
wc_HashFree(hashCtx, (enum wc_HashType)type);
}
WC_FREE_VAR_EX(hashCtx, ssl->heap, DYNAMIC_TYPE_HASHES);
return ret;
}
/* Handshake header DTLS only fields are not included in the transcript hash */
int Dtls13HashHandshake(WOLFSSL* ssl, const byte* input, word16 length)
{
int ret;
if (length < DTLS_HANDSHAKE_HEADER_SZ)
return BAD_FUNC_ARG;
/* msg_type(1) + length (3) */
ret = HashRaw(ssl, input, OPAQUE32_LEN);
if (ret != 0)
return ret;
input += OPAQUE32_LEN;
length -= OPAQUE32_LEN;
/* message_seq(2) + fragment_offset(3) + fragment_length(3) */
input += OPAQUE64_LEN;
length -= OPAQUE64_LEN;
return HashRaw(ssl, input, length);
}
static int Dtls13SendFragment(WOLFSSL* ssl, byte* output, word16 output_size,
word16 length, enum HandShakeType handshakeType, int hashOutput,
int sendImmediately)
{
word16 recordHeaderLength;
word16 recordLength;
byte isProtected;
int sendLength;
byte* msg;
int ret;
if (output_size < length)
return BUFFER_ERROR;
isProtected = Dtls13TypeIsEncrypted(handshakeType);
recordHeaderLength = Dtls13GetRlHeaderLength(ssl, isProtected);
if (length <= recordHeaderLength)
return BUFFER_ERROR;
recordLength = length - recordHeaderLength;
if (!isProtected) {
ret = Dtls13RlAddPlaintextHeader(ssl, output, handshake, recordLength);
if (ret != 0)
return ret;
}
else {
msg = output + recordHeaderLength;
if (hashOutput) {
ret = Dtls13HashHandshake(ssl, msg, recordLength);
if (ret != 0)
return ret;
}
sendLength = BuildTls13Message(ssl, output, output_size, msg,
recordLength, handshake, 0, 0, 0);
if (sendLength < 0)
return sendLength;
length = (word16)sendLength;
}
if (!FragIsInOutputBuffer(ssl, output))
return Dtls13SendFragFromBuffer(ssl, output, length);
ssl->buffers.outputBuffer.length += length;
ret = 0;
if (sendImmediately)
ret = SendBuffered(ssl);
return ret;
}
static void Dtls13FreeFragmentsBuffer(WOLFSSL* ssl)
{
XFREE(ssl->dtls13FragmentsBuffer.buffer, ssl->heap,
DYNAMIC_TYPE_TMP_BUFFER);
ssl->dtls13FragmentsBuffer.buffer = NULL;
ssl->dtls13SendingFragments = 0;
ssl->dtls13MessageLength = ssl->dtls13FragOffset = 0;
}
static WC_INLINE void Dtls13FreeRtxBufferRecord(WOLFSSL* ssl,
Dtls13RtxRecord* r)
{
(void)ssl;
XFREE(r->data, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
XFREE(r, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
}
static Dtls13RtxRecord* Dtls13RtxNewRecord(WOLFSSL* ssl, byte* data,
word16 length, enum HandShakeType handshakeType, w64wrapper seq)
{
w64wrapper epochNumber;
Dtls13RtxRecord* r;
WOLFSSL_ENTER("Dtls13RtxNewRecord");
if (ssl->dtls13EncryptEpoch == NULL)
return NULL;
epochNumber = ssl->dtls13EncryptEpoch->epochNumber;
r = (Dtls13RtxRecord*)XMALLOC(sizeof(*r), ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
if (r == NULL)
return NULL;
r->data = (byte*)XMALLOC(length, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
if (r->data == NULL) {
XFREE(r, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
return NULL;
}
XMEMCPY(r->data, data, length);
r->epoch = epochNumber;
r->length = length;
r->next = NULL;
r->handshakeType = handshakeType;
r->seq[0] = seq;
r->rnIdx = 1;
return r;
}
static void Dtls13RtxAddRecord(Dtls13Rtx* fsm, Dtls13RtxRecord* r)
{
WOLFSSL_ENTER("Dtls13RtxAddRecord");
*fsm->rtxRecordTailPtr = r;
fsm->rtxRecordTailPtr = &r->next;
r->next = NULL;
}
static void Dtls13RtxRecordUnlink(WOLFSSL* ssl, Dtls13RtxRecord** prevNext,
Dtls13RtxRecord* r)
{
/* if r was at the tail of the list, update the tail pointer */
if (r->next == NULL) {
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0)
#endif
{
ssl->dtls13Rtx.rtxRecordTailPtr = prevNext;
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
}
}
/* unlink */
*prevNext = r->next;
}
void Dtls13RtxFlushBuffered(WOLFSSL* ssl, byte keepNewSessionTicket)
{
Dtls13RtxRecord *r, **prevNext;
WOLFSSL_ENTER("Dtls13RtxFlushBuffered");
prevNext = &ssl->dtls13Rtx.rtxRecords;
r = ssl->dtls13Rtx.rtxRecords;
/* we process the head at the end */
while (r != NULL) {
if (keepNewSessionTicket && r->handshakeType == session_ticket) {
prevNext = &r->next;
r = r->next;
continue;
}
*prevNext = r->next;
Dtls13FreeRtxBufferRecord(ssl, r);
r = *prevNext;
}
ssl->dtls13Rtx.rtxRecordTailPtr = prevNext;
}
static Dtls13RecordNumber* Dtls13NewRecordNumber(w64wrapper epoch,
w64wrapper seq, void* heap)
{
Dtls13RecordNumber* rn;
(void)heap;
rn = (Dtls13RecordNumber*)XMALLOC(sizeof(*rn), heap,
DYNAMIC_TYPE_DTLS_MSG);
if (rn == NULL)
return NULL;
rn->next = NULL;
rn->epoch = epoch;
rn->seq = seq;
return rn;
}
#ifndef DTLS13_MAX_ACK_RECORDS
#define DTLS13_MAX_ACK_RECORDS 512
#endif
int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq)
{
Dtls13RecordNumber* rn;
int count;
WOLFSSL_ENTER("Dtls13RtxAddAck");
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0)
#endif
{
/* Find location to insert new record */
Dtls13RecordNumber** prevNext = &ssl->dtls13Rtx.seenRecords;
Dtls13RecordNumber* cur = ssl->dtls13Rtx.seenRecords;
if (ssl->dtls13Rtx.seenRecordsCount >= DTLS13_ACK_MAX_RECORDS) {
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return 0; /* list full, silently drop */
}
count = 0;
for (; cur != NULL; prevNext = &cur->next, cur = cur->next) {
count++;
if (w64Equal(cur->epoch, epoch) && w64Equal(cur->seq, seq)) {
/* already in list. no duplicates. */
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return 0;
}
else if (w64LT(epoch, cur->epoch)
|| (w64Equal(epoch, cur->epoch)
&& w64LT(seq, cur->seq))) {
break;
}
}
/* Cap the ACK list to prevent word16 overflow in
* Dtls13GetAckListLength and bound memory consumption */
if (count >= DTLS13_MAX_ACK_RECORDS) {
WOLFSSL_MSG("DTLS 1.3 ACK list full, dropping record");
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return 0;
}
rn = Dtls13NewRecordNumber(epoch, seq, ssl->heap);
if (rn == NULL) {
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return MEMORY_E;
}
*prevNext = rn;
rn->next = cur;
ssl->dtls13Rtx.seenRecordsCount++;
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
}
return 0;
}
static void Dtls13RtxFlushAcks(WOLFSSL* ssl)
{
Dtls13RecordNumber *list, *rn;
(void)ssl;
WOLFSSL_ENTER("Dtls13RtxFlushAcks");
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) == 0)
#endif
{
list = ssl->dtls13Rtx.seenRecords;
while (list != NULL) {
rn = list;
list = rn->next;
XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
}
ssl->dtls13Rtx.seenRecords = NULL;
ssl->dtls13Rtx.seenRecordsCount = 0;
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
}
}
static int Dtls13DetectDisruption(WOLFSSL* ssl, word32 fragOffset)
{
/* retransmission. The other peer may have lost our flight or our ACKs. We
don't account this as a disruption */
if (ssl->keys.dtls_peer_handshake_number <
ssl->keys.dtls_expected_peer_handshake_number)
return 0;
/* out of order message */
if (ssl->keys.dtls_peer_handshake_number >
ssl->keys.dtls_expected_peer_handshake_number) {
return 1;
}
/* first fragment of in-order message */
if (fragOffset == 0)
return 0;
/* is not the next fragment in the message (the check is not 100% perfect,
in the worst case, we don't detect the disruption and wait for the other
peer retransmission) */
if (ssl->dtls_rx_msg_list != NULL) {
DtlsFragBucket* last = ssl->dtls_rx_msg_list->fragBucketList;
while (last != NULL && last->m.m.next != NULL)
last = last->m.m.next;
/* Does this fragment start right after the last fragment we
* have stored? */
if (last != NULL && (last->m.m.offset + last->m.m.sz) != fragOffset)
return 1;
}
else {
/* ssl->dtls_rx_msg_list is NULL and fragOffset != 0 so this is not in
* order */
return 1;
}
return 0;
}
static void Dtls13RtxRemoveCurAck(WOLFSSL* ssl)
{
Dtls13RecordNumber *rn, **prevNext;
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) != 0)
return;
#endif
prevNext = &ssl->dtls13Rtx.seenRecords;
rn = ssl->dtls13Rtx.seenRecords;
while (rn != NULL) {
if (w64Equal(rn->epoch, ssl->keys.curEpoch64) &&
w64Equal(rn->seq, ssl->keys.curSeq)) {
*prevNext = rn->next;
XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
if (ssl->dtls13Rtx.seenRecordsCount > 0)
ssl->dtls13Rtx.seenRecordsCount--;
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return;
}
prevNext = &rn->next;
rn = rn->next;
}
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
}
static void Dtls13SaveOrFlushClientHello(WOLFSSL* ssl)
{
Dtls13RtxRecord *r, **prev_next;
r = ssl->dtls13Rtx.rtxRecords;
prev_next = &ssl->dtls13Rtx.rtxRecords;
if (ssl->options.side == WOLFSSL_CLIENT_END &&
ssl->options.connectState >= CLIENT_HELLO_SENT &&
ssl->options.connectState <= HELLO_AGAIN_REPLY) {
while (r != NULL) {
if (r->handshakeType == client_hello) {
Dtls13RtxRecordUnlink(ssl, prev_next, r);
if (ssl->options.downgrade &&
ssl->options.minDowngrade >= DTLSv1_2_MINOR) {
XFREE(ssl->dtls13ClientHello, ssl->heap,
DYNAMIC_TYPE_DTLS_MSG);
ssl->dtls13ClientHello = r->data;
ssl->dtls13ClientHelloSz = r->length;
r->data = NULL;
}
Dtls13FreeRtxBufferRecord(ssl, r);
return;
}
prev_next = &r->next;
r = r->next;
}
}
}
static int Dtls13RtxMsgRecvd(WOLFSSL* ssl, enum HandShakeType hs,
word32 fragOffset)
{
WOLFSSL_ENTER("Dtls13RtxMsgRecvd");
if (!ssl->options.handShakeDone &&
ssl->keys.dtls_peer_handshake_number >=
ssl->keys.dtls_expected_peer_handshake_number) {
if (hs == server_hello)
Dtls13SaveOrFlushClientHello(ssl);
/* In the handshake, receiving part of the next flight, acknowledge the
* sent flight. */
/* On the server side, receiving the last client flight does not ACK any
* sent new_session_ticket messages. */
/* We don't want to clear the buffer until we have done version
* negotiation in the SH or have received a unified header in the
* DTLS record. */
if (ssl->options.serverState >= SERVER_HELLO_COMPLETE ||
ssl->options.seenUnifiedHdr)
/* Use 1.2 API to clear 1.2 buffers too */
DtlsMsgPoolReset(ssl);
}
if (ssl->keys.dtls_peer_handshake_number <
ssl->keys.dtls_expected_peer_handshake_number) {
/* retransmission detected. */
ssl->dtls13Rtx.retransmit = 1;
/* the other peer may have retransmitted because an ACK for a flight
that needs explicit ACK was lost.*/
if (ssl->dtls13Rtx.seenRecords != NULL)
ssl->dtls13Rtx.sendAcks = 1;
}
if (ssl->keys.dtls_peer_handshake_number ==
ssl->keys.dtls_expected_peer_handshake_number &&
ssl->options.handShakeDone && hs == certificate_request) {
/* the current record, containing a post-handshake certificate request,
is implicitly acknowledged by the
certificate/certificate_verify/finished flight we are about to
send. Please note that if the certificate request came out-of-order
and we didn't send an ACK (sendMoreAcks == 0 and the missing
packet(s) arrive before that fast timeout expired), then we will send
both the ACK and the flight. While unnecessary this it's harmless, it
should be rare and simplifies the code. Otherwise, it would be
necessary to track which record number contained a CertificateRequest
with a particular context id */
Dtls13RtxRemoveCurAck(ssl);
}
if (ssl->options.dtls13SendMoreAcks &&
Dtls13DetectDisruption(ssl, fragOffset)) {
WOLFSSL_MSG("Disruption detected");
ssl->dtls13Rtx.sendAcks = 1;
}
return 0;
}
void Dtls13FreeFsmResources(WOLFSSL* ssl)
{
Dtls13RtxFlushAcks(ssl);
/* Use 1.2 API to clear 1.2 buffers too */
DtlsMsgPoolReset(ssl);
Dtls13RtxFlushBuffered(ssl, 0);
}