-
Notifications
You must be signed in to change notification settings - Fork 20
/
dtls.c
4085 lines (3372 loc) · 120 KB
/
dtls.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
/*******************************************************************************
*
* Copyright (c) 2011, 2012, 2013, 2014, 2015 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Olaf Bergmann - initial API and implementation
* Hauke Mehrtens - memory optimization, ECC integration
* Achim Kraus - session recovery
* Sachin Agrawal - rehandshake support
*
*******************************************************************************/
#include "tinydtls.h"
#include "dtls_time.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_ASSERT_H
#include <assert.h>
#endif
#ifndef WITH_CONTIKI
#include <stdlib.h>
#include "global.h"
#endif /* WITH_CONTIKI */
#include "utlist.h"
#ifndef DTLS_PEERS_NOHASH
#include "uthash.h"
#endif /* DTLS_PEERS_NOHASH */
#include "dtls_debug.h"
#include "numeric.h"
#include "netq.h"
#include "dtls.h"
#include "alert.h"
#include "session.h"
#include "prng.h"
#ifdef WITH_SHA256
# include "sha2/sha2.h"
#endif
#define dtls_set_version(H,V) dtls_int_to_uint16((H)->version, (V))
#define dtls_set_content_type(H,V) ((H)->content_type = (V) & 0xff)
#define dtls_set_length(H,V) ((H)->length = (V))
#define dtls_get_content_type(H) ((H)->content_type & 0xff)
#define dtls_get_version(H) dtls_uint16_to_int((H)->version)
#define dtls_get_epoch(H) dtls_uint16_to_int((H)->epoch)
#define dtls_get_sequence_number(H) dtls_uint48_to_ulong((H)->sequence_number)
#define dtls_get_fragment_length(H) dtls_uint24_to_int((H)->fragment_length)
#ifdef DTLS_PEERS_NOHASH
#define FIND_PEER(head,sess,out) \
do { \
dtls_peer_t * tmp; \
(out) = NULL; \
LL_FOREACH((head), tmp) { \
if (dtls_session_equals(&tmp->session, (sess))) { \
(out) = tmp; \
break; \
} \
} \
} while (0)
#define DEL_PEER(head,delptr) \
if ((head) != NULL && (delptr) != NULL) { \
LL_DELETE(head,delptr); \
}
#define ADD_PEER(head,sess,add) \
LL_PREPEND(ctx->peers, peer);
#else /* DTLS_PEERS_NOHASH */
#define FIND_PEER(head,sess,out) \
HASH_FIND(hh,head,sess,sizeof(session_t),out)
#define ADD_PEER(head,sess,add) \
HASH_ADD(hh,head,sess,sizeof(session_t),add)
#define DEL_PEER(head,delptr) \
if ((head) != NULL && (delptr) != NULL) { \
HASH_DELETE(hh,head,delptr); \
}
#endif /* DTLS_PEERS_NOHASH */
#define DTLS_RH_LENGTH sizeof(dtls_record_header_t)
#define DTLS_HS_LENGTH sizeof(dtls_handshake_header_t)
#define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
#define DTLS_COOKIE_LENGTH_MAX 32
#define DTLS_CH_LENGTH_MAX sizeof(dtls_client_hello_t) + DTLS_COOKIE_LENGTH_MAX + 12 + 26
#define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
#define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
#define DTLS_CE_LENGTH (3 + 3 + 27 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
#define DTLS_SKEXEC_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE + 1 + 1 + 2 + 70)
#define DTLS_SKEXECPSK_LENGTH_MIN 2
#define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
#define DTLS_CKXPSK_LENGTH_MIN 2
#define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
#define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
#define DTLS_FIN_LENGTH 12
#define HS_HDR_LENGTH DTLS_RH_LENGTH + DTLS_HS_LENGTH
#define HV_HDR_LENGTH HS_HDR_LENGTH + DTLS_HV_LENGTH
#define HIGH(V) (((V) >> 8) & 0xff)
#define LOW(V) ((V) & 0xff)
#define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
#define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
#define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
#define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
/* The length check here should work because dtls_*_to_int() works on
* unsigned char. Otherwise, broken messages could cause severe
* trouble. Note that this macro jumps out of the current program flow
* when the message is too short. Beware!
*/
#define SKIP_VAR_FIELD(P,L,T) { \
if (L < dtls_ ## T ## _to_int(P) + sizeof(T)) \
goto error; \
L -= dtls_ ## T ## _to_int(P) + sizeof(T); \
P += dtls_ ## T ## _to_int(P) + sizeof(T); \
}
/* some constants for the PRF */
#define PRF_LABEL(Label) prf_label_##Label
#define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
static const unsigned char prf_label_master[] = "master secret";
static const unsigned char prf_label_key[] = "key expansion";
static const unsigned char prf_label_client[] = "client";
static const unsigned char prf_label_server[] = "server";
static const unsigned char prf_label_finished[] = " finished";
/* first part of Raw public key, the is the start of the Subject Public Key */
static const unsigned char cert_asn1_header[] = {
0x30, 0x59, /* SEQUENCE, length 89 bytes */
0x30, 0x13, /* SEQUENCE, length 19 bytes */
0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
0x04 /* uncompressed, followed by the r und s values of the public key */
};
#ifdef WITH_CONTIKI
PROCESS(dtls_retransmit_process, "DTLS retransmit process");
static dtls_context_t the_dtls_context;
static inline dtls_context_t *
malloc_context() {
return &the_dtls_context;
}
static inline void
free_context(dtls_context_t *context) {
}
#else /* WITH_CONTIKI */
static inline dtls_context_t *
malloc_context() {
return (dtls_context_t *)malloc(sizeof(dtls_context_t));
}
static inline void
free_context(dtls_context_t *context) {
free(context);
}
#endif
void
dtls_init() {
dtls_clock_init();
dtls_crypto_init();
netq_init();
peer_init();
}
/* Calls cb_alert() with given arguments if defined, otherwise an
* error message is logged and the result is -1. This is just an
* internal helper.
*/
#define CALL(Context, which, ...) \
((Context)->h && (Context)->h->which \
? (Context)->h->which((Context), ##__VA_ARGS__) \
: -1)
static int
dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
dtls_security_parameters_t *security , session_t *session,
unsigned char type, uint8 *buf_array[],
size_t buf_len_array[], size_t buf_array_len);
/**
* Sends the fragment of length \p buflen given in \p buf to the
* specified \p peer. The data will be MAC-protected and encrypted
* according to the selected cipher and split into one or more DTLS
* records of the specified \p type. This function returns the number
* of bytes that were sent, or \c -1 if an error occurred.
*
* \param ctx The DTLS context to use.
* \param peer The remote peer.
* \param type The content type of the record.
* \param buf The data to send.
* \param buflen The actual length of \p buf.
* \return Less than zero on error, the number of bytes written otherwise.
*/
static int
dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
uint8 *buf, size_t buflen) {
return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
type, &buf, &buflen, 1);
}
/**
* Stops ongoing retransmissions of handshake messages for @p peer.
*/
static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
dtls_peer_t *
dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
dtls_peer_t *p;
FIND_PEER(ctx->peers, session, p);
return p;
}
/**
* Adds @p peer to list of peers in @p ctx. This function returns @c 0
* on success, or a negative value on error (e.g. due to insufficient
* storage).
*/
static int
dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
ADD_PEER(ctx->peers, session, peer);
return 0;
}
int
dtls_write(struct dtls_context_t *ctx,
session_t *dst, uint8 *buf, size_t len) {
dtls_peer_t *peer = dtls_get_peer(ctx, dst);
/* Check if peer connection already exists */
if (!peer) { /* no ==> create one */
int res;
/* dtls_connect() returns a value greater than zero if a new
* connection attempt is made, 0 for session reuse. */
res = dtls_connect(ctx, dst);
return (res >= 0) ? 0 : res;
} else { /* a session exists, check if it is in state connected */
if (peer->state != DTLS_STATE_CONNECTED) {
return 0;
} else {
return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
}
}
}
static int
dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
/* To access the cookie, we have to determine the session id's
* length and skip the whole thing. */
if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
if (msglen < (*msg & 0xff) + sizeof(uint8))
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
*cookie = msg + sizeof(uint8);
return dtls_uint8_to_int(msg);
error:
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
static int
dtls_create_cookie(dtls_context_t *ctx,
session_t *session,
uint8 *msg, size_t msglen,
uint8 *cookie, int *clen) {
unsigned char buf[DTLS_HMAC_MAX];
size_t len, e;
/* create cookie with HMAC-SHA256 over:
* - SECRET
* - session parameters (only IP address?)
* - client version
* - random gmt and bytes
* - session id
* - cipher_suites
* - compression method
*/
/* We use our own buffer as hmac_context instead of a dynamic buffer
* created by dtls_hmac_new() to separate storage space for cookie
* creation from storage that is used in real sessions. Note that
* the buffer size must fit with the default hash algorithm (see
* implementation of dtls_hmac_context_new()). */
dtls_hmac_context_t hmac_context;
dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
dtls_hmac_update(&hmac_context,
(unsigned char *)&session->addr, session->size);
/* feed in the beginning of the Client Hello up to and including the
session id */
e = sizeof(dtls_client_hello_t);
e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
if (e + DTLS_HS_LENGTH > msglen)
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
/* skip cookie bytes and length byte */
e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
e += sizeof(uint8);
if (e + DTLS_HS_LENGTH > msglen)
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
dtls_hmac_update(&hmac_context,
msg + DTLS_HS_LENGTH + e,
dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
len = dtls_hmac_finalize(&hmac_context, buf);
if (len < *clen) {
memset(cookie + len, 0, *clen - len);
*clen = len;
}
memcpy(cookie, buf, *clen);
return 0;
}
#ifdef DTLS_CHECK_CONTENTTYPE
/* used to check if a received datagram contains a DTLS message */
static char const content_types[] = {
DTLS_CT_CHANGE_CIPHER_SPEC,
DTLS_CT_ALERT,
DTLS_CT_HANDSHAKE,
DTLS_CT_APPLICATION_DATA,
0 /* end marker */
};
#endif
/**
* Checks if \p msg points to a valid DTLS record. If
*
*/
static unsigned int
is_record(uint8 *msg, size_t msglen) {
unsigned int rlen = 0;
if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
#ifdef DTLS_CHECK_CONTENTTYPE
&& strchr(content_types, msg[0])
#endif
&& msg[1] == HIGH(DTLS_VERSION)
&& msg[2] == LOW(DTLS_VERSION))
{
rlen = DTLS_RH_LENGTH +
dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
/* we do not accept wrong length field in record header */
if (rlen > msglen)
rlen = 0;
}
return rlen;
}
/**
* Initializes \p buf as record header. The caller must ensure that \p
* buf is capable of holding at least \c sizeof(dtls_record_header_t)
* bytes. Increments sequence number counter of \p security.
* \return pointer to the next byte after the written header.
* The length will be set to 0 and has to be changed before sending.
*/
static inline uint8 *
dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
uint8 *buf) {
dtls_int_to_uint8(buf, type);
buf += sizeof(uint8);
dtls_int_to_uint16(buf, DTLS_VERSION);
buf += sizeof(uint16);
if (security) {
dtls_int_to_uint16(buf, security->epoch);
buf += sizeof(uint16);
dtls_int_to_uint48(buf, security->rseq);
buf += sizeof(uint48);
/* increment record sequence counter by 1 */
security->rseq++;
} else {
memset(buf, 0, sizeof(uint16) + sizeof(uint48));
buf += sizeof(uint16) + sizeof(uint48);
}
memset(buf, 0, sizeof(uint16));
return buf + sizeof(uint16);
}
/**
* Initializes \p buf as handshake header. The caller must ensure that \p
* buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
* bytes. Increments message sequence number counter of \p peer.
* \return pointer to the next byte after \p buf
*/
static inline uint8 *
dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
int length,
int frag_offset, int frag_length,
uint8 *buf) {
dtls_int_to_uint8(buf, type);
buf += sizeof(uint8);
dtls_int_to_uint24(buf, length);
buf += sizeof(uint24);
if (peer && peer->handshake_params) {
/* and copy the result to buf */
dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
/* increment handshake message sequence counter by 1 */
peer->handshake_params->hs_state.mseq_s++;
} else {
memset(buf, 0, sizeof(uint16));
}
buf += sizeof(uint16);
dtls_int_to_uint24(buf, frag_offset);
buf += sizeof(uint24);
dtls_int_to_uint24(buf, frag_length);
buf += sizeof(uint24);
return buf;
}
/** only one compression method is currently defined */
static uint8 compression_methods[] = {
TLS_COMPRESSION_NULL
};
/** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#ifdef DTLS_ECC
return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
#else
return 0;
#endif /* DTLS_ECC */
}
/** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#ifdef DTLS_PSK
return cipher == TLS_PSK_WITH_AES_128_CCM_8;
#else
return 0;
#endif /* DTLS_PSK */
}
/** returns true if the application is configured for psk */
static inline int is_psk_supported(dtls_context_t *ctx)
{
#ifdef DTLS_PSK
return ctx && ctx->h && ctx->h->get_psk_info;
#else
return 0;
#endif /* DTLS_PSK */
}
/** returns true if the application is configured for ecdhe_ecdsa */
static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
(is_client && ctx->h->verify_ecdsa_key));
#else
return 0;
#endif /* DTLS_ECC */
}
/** Returns true if the application is configured for ecdhe_ecdsa with
* client authentication */
static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
#else
return 0;
#endif /* DTLS_ECC */
}
/**
* Returns @c 1 if @p code is a cipher suite other than @c
* TLS_NULL_WITH_NULL_NULL that we recognize.
*
* @param ctx The current DTLS context
* @param code The cipher suite identifier to check
* @param is_client 1 for a dtls client, 0 for server
* @return @c 1 iff @p code is recognized,
*/
static int
known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
int psk;
int ecdsa;
psk = is_psk_supported(ctx);
ecdsa = is_ecdsa_supported(ctx, is_client);
return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
(ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
}
/**
* This method detects if we already have a established DTLS session with
* peer and the peer is attempting to perform a fresh handshake by sending
* messages with epoch = 0. This is to handle situations mentioned in
* RFC 6347 - section 4.2.8.
*
* @param msg The packet received from Client
* @param msglen Packet length
* @param peer peer who is the sender for this packet
* @return @c 1 if this is a rehandshake attempt by
* client
*/
static int
hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
dtls_peer_t *peer)
{
if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
if (msg[0] == DTLS_CT_HANDSHAKE) {
uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
if (msg_epoch == 0) {
dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
return 1;
}
}
}
}
return 0;
}
/** Dump out the cipher keys and IVs used for the symetric cipher. */
static void dtls_debug_keyblock(dtls_security_parameters_t *config)
{
dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
dtls_debug_dump(" client_MAC_secret",
dtls_kb_client_mac_secret(config, peer->role),
dtls_kb_mac_secret_size(config, peer->role));
dtls_debug_dump(" server_MAC_secret",
dtls_kb_server_mac_secret(config, peer->role),
dtls_kb_mac_secret_size(config, peer->role));
dtls_debug_dump(" client_write_key",
dtls_kb_client_write_key(config, peer->role),
dtls_kb_key_size(config, peer->role));
dtls_debug_dump(" server_write_key",
dtls_kb_server_write_key(config, peer->role),
dtls_kb_key_size(config, peer->role));
dtls_debug_dump(" client_IV",
dtls_kb_client_iv(config, peer->role),
dtls_kb_iv_size(config, peer->role));
dtls_debug_dump(" server_IV",
dtls_kb_server_iv(config, peer->role),
dtls_kb_iv_size(config, peer->role));
}
/** returns the name of the goven handshake type number.
* see IANA for a full list of types:
* https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
*/
static char *dtls_handshake_type_to_name(int type)
{
switch (type) {
case DTLS_HT_HELLO_REQUEST:
return "hello_request";
case DTLS_HT_CLIENT_HELLO:
return "client_hello";
case DTLS_HT_SERVER_HELLO:
return "server_hello";
case DTLS_HT_HELLO_VERIFY_REQUEST:
return "hello_verify_request";
case DTLS_HT_CERTIFICATE:
return "certificate";
case DTLS_HT_SERVER_KEY_EXCHANGE:
return "server_key_exchange";
case DTLS_HT_CERTIFICATE_REQUEST:
return "certificate_request";
case DTLS_HT_SERVER_HELLO_DONE:
return "server_hello_done";
case DTLS_HT_CERTIFICATE_VERIFY:
return "certificate_verify";
case DTLS_HT_CLIENT_KEY_EXCHANGE:
return "client_key_exchange";
case DTLS_HT_FINISHED:
return "finished";
default:
return "unknown";
}
}
/**
* Calculate the pre master secret and after that calculate the master-secret.
*/
static int
calculate_key_block(dtls_context_t *ctx,
dtls_handshake_parameters_t *handshake,
dtls_peer_t *peer,
session_t *session,
dtls_peer_type role) {
unsigned char *pre_master_secret;
int pre_master_len = 0;
dtls_security_parameters_t *security = dtls_security_params_next(peer);
uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
if (!security) {
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
pre_master_secret = security->key_block;
switch (handshake->cipher) {
#ifdef DTLS_PSK
case TLS_PSK_WITH_AES_128_CCM_8: {
unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
int len;
len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
handshake->keyx.psk.identity,
handshake->keyx.psk.id_length,
psk, DTLS_PSK_MAX_KEY_LEN);
if (len < 0) {
dtls_crit("no psk key for session available\n");
return len;
}
/* Temporarily use the key_block storage space for the pre master secret. */
pre_master_len = dtls_psk_pre_master_secret(psk, len,
pre_master_secret,
MAX_KEYBLOCK_LENGTH);
dtls_debug_hexdump("psk", psk, len);
memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
if (pre_master_len < 0) {
dtls_crit("the psk was too long, for the pre master secret\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
break;
}
#endif /* DTLS_PSK */
#ifdef DTLS_ECC
case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecdsa.own_eph_priv,
handshake->keyx.ecdsa.other_eph_pub_x,
handshake->keyx.ecdsa.other_eph_pub_y,
sizeof(handshake->keyx.ecdsa.own_eph_priv),
pre_master_secret,
MAX_KEYBLOCK_LENGTH);
if (pre_master_len < 0) {
dtls_crit("the curve was too long, for the pre master secret\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
break;
}
#endif /* DTLS_ECC */
default:
dtls_crit("calculate_key_block: unknown cipher\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
dtls_prf(pre_master_secret, pre_master_len,
PRF_LABEL(master), PRF_LABEL_SIZE(master),
handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
master_secret,
DTLS_MASTER_SECRET_LENGTH);
dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
/* create key_block from master_secret
* key_block = PRF(master_secret,
"key expansion" + tmp.random.server + tmp.random.client) */
dtls_prf(master_secret,
DTLS_MASTER_SECRET_LENGTH,
PRF_LABEL(key), PRF_LABEL_SIZE(key),
handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
security->key_block,
dtls_kb_size(security, role));
memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
dtls_debug_keyblock(security);
security->cipher = handshake->cipher;
security->compression = handshake->compression;
security->rseq = 0;
return 0;
}
/* TODO: add a generic method which iterates over a list and searches for a specific key */
static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
int i, curve_name;
/* length of curve list */
i = dtls_uint16_to_int(data);
data += sizeof(uint16);
if (i + sizeof(uint16) != data_length) {
dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
/* check if this curve is supported */
curve_name = dtls_uint16_to_int(data);
data += sizeof(uint16);
if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
return 0;
}
dtls_warn("no supported elliptic curve found\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
static int verify_ext_cert_type(uint8 *data, size_t data_length) {
int i, cert_type;
/* length of cert type list */
i = dtls_uint8_to_int(data);
data += sizeof(uint8);
if (i + sizeof(uint8) != data_length) {
dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
/* check if this cert type is supported */
cert_type = dtls_uint8_to_int(data);
data += sizeof(uint8);
if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
return 0;
}
dtls_warn("no supported certificate type found\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
int i, cert_type;
/* length of ec_point_formats list */
i = dtls_uint8_to_int(data);
data += sizeof(uint8);
if (i + sizeof(uint8) != data_length) {
dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
/* check if this ec_point_format is supported */
cert_type = dtls_uint8_to_int(data);
data += sizeof(uint8);
if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
return 0;
}
dtls_warn("no supported ec_point_format found\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
/*
* Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
*/
static int
dtls_check_tls_extension(dtls_peer_t *peer,
uint8 *data, size_t data_length, int client_hello)
{
uint16_t i, j;
int ext_elliptic_curve = 0;
int ext_client_cert_type = 0;
int ext_server_cert_type = 0;
int ext_ec_point_formats = 0;
dtls_handshake_parameters_t *handshake = peer->handshake_params;
if (data_length < sizeof(uint16)) {
/* no tls extensions specified */
if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
goto error;
}
return 0;
}
/* get the length of the tls extension list */
j = dtls_uint16_to_int(data);
data += sizeof(uint16);
data_length -= sizeof(uint16);
if (data_length < j)
goto error;
/* check for TLS extensions needed for this cipher */
while (data_length) {
if (data_length < sizeof(uint16) * 2)
goto error;
/* get the tls extension type */
i = dtls_uint16_to_int(data);
data += sizeof(uint16);
data_length -= sizeof(uint16);
/* get the length of the tls extension */
j = dtls_uint16_to_int(data);
data += sizeof(uint16);
data_length -= sizeof(uint16);
if (data_length < j)
goto error;
switch (i) {
case TLS_EXT_ELLIPTIC_CURVES:
ext_elliptic_curve = 1;
if (verify_ext_eliptic_curves(data, j))
goto error;
break;
case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
ext_client_cert_type = 1;
if (client_hello) {
if (verify_ext_cert_type(data, j))
goto error;
} else {
if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
goto error;
}
break;
case TLS_EXT_SERVER_CERTIFICATE_TYPE:
ext_server_cert_type = 1;
if (client_hello) {
if (verify_ext_cert_type(data, j))
goto error;
} else {
if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
goto error;
}
break;
case TLS_EXT_EC_POINT_FORMATS:
ext_ec_point_formats = 1;
if (verify_ext_ec_point_formats(data, j))
goto error;
break;
case TLS_EXT_ENCRYPT_THEN_MAC:
/* As only AEAD cipher suites are currently available, this
* extension can be skipped.
*/
dtls_info("skipped encrypt-then-mac extension\n");
break;
default:
dtls_warn("unsupported tls extension: %i\n", i);
break;
}
data += j;
data_length -= j;
}
if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
|| !ext_ec_point_formats) {
dtls_warn("not all required tls extensions found in client hello\n");
goto error;
}
} else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
if (!ext_client_cert_type || !ext_server_cert_type) {
dtls_warn("not all required tls extensions found in server hello\n");
goto error;
}
}
return 0;
error:
if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
} else {
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
}
/**
* Parses the ClientHello from the client and updates the internal handshake
* parameters with the new data for the given \p peer. When the ClientHello
* handshake message in \p data does not contain a cipher suite or
* compression method, it is copied from the the current security parameters.
*
* \param ctx The current DTLS context.
* \param peer The remote peer whose security parameters are about to change.
* \param data The handshake message with a ClientHello.
* \param data_length The actual size of \p data.
* \return \c -Something if an error occurred, \c 0 on success.
*/
static int
dtls_update_parameters(dtls_context_t *ctx,
dtls_peer_t *peer,
uint8 *data, size_t data_length) {
int i, j;
int ok;
dtls_handshake_parameters_t *config = peer->handshake_params;
dtls_security_parameters_t *security = dtls_security_params(peer);
assert(config);
assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
/* skip the handshake header and client version information */
data += DTLS_HS_LENGTH + sizeof(uint16);
data_length -= DTLS_HS_LENGTH + sizeof(uint16);
/* store client random in config */
memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
data += DTLS_RANDOM_LENGTH;
data_length -= DTLS_RANDOM_LENGTH;
/* Caution: SKIP_VAR_FIELD may jump to error: */
SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
i = dtls_uint16_to_int(data);
if (data_length < i + sizeof(uint16)) {
/* Looks like we do not have a cipher nor compression. This is ok
* for renegotiation, but not for the initial handshake. */
if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
goto error;
config->cipher = security->cipher;
config->compression = security->compression;
return 0;
}
data += sizeof(uint16);
data_length -= sizeof(uint16) + i;
ok = 0;
while (i && !ok) {
config->cipher = dtls_uint16_to_int(data);
ok = known_cipher(ctx, config->cipher, 0);
i -= sizeof(uint16);
data += sizeof(uint16);
}
/* skip remaining ciphers */
data += i;
if (!ok) {
/* reset config cipher to a well-defined value */
config->cipher = TLS_NULL_WITH_NULL_NULL;
dtls_warn("No matching cipher found\n");
goto error;
}
if (data_length < sizeof(uint8)) {