forked from eclipse/tinydtls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dtls.c
5096 lines (4286 loc) · 156 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-2022 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 */
#ifdef HAVE_INTTYPES_H
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#else
# ifndef PRIu64
# define PRIu64 "llu"
# endif
# ifndef PRIx64
# define PRIx64 "llx"
# endif
#endif /* HAVE_INTTYPES_H */
#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 "dtls_prng.h"
#include "dtls_mutex.h"
#ifdef WITH_SHA256
# include "hmac.h"
#endif /* WITH_SHA256 */
#ifdef WITH_ZEPHYR
LOG_MODULE_DECLARE(TINYDTLS, CONFIG_TINYDTLS_LOG_LEVEL);
#endif /* WITH_ZEPHYR */
#define DTLS10_VERSION 0xfeff
/* Flags for dtls_destroy_peer()
*
* DTLS_DESTROY_CLOSE indicates that the connection should be closed
* when applicable
*/
#define DTLS_DESTROY_CLOSE 0x02
#ifdef RIOT_VERSION
# include <memarray.h>
dtls_context_t dtlscontext_storage_data[DTLS_CONTEXT_MAX];
memarray_t dtlscontext_storage;
#endif /* RIOT_VERSION */
#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) dtls_int_to_uint16(&((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_length(H) dtls_uint16_to_int((H)->length)
#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)
/*
* ClientHello:
*
* session_length := 1 byte
* session := 0 bytes
* cookie_length := 1 byte
* cookie := n bytes
* cipher_length := 2 bytes
* cipher suites (max) := 2 bytes + max * 2 bytes
* empty_renegotiation := 2 bytes
* cipher suites := max * 2 bytes
* compression_length := 1 byte
* compression := 1 byte
* extensions_length := 2 bytes => 10 bytes + max * 2 bytes
*
* client_cert_type := 6 bytes
* server_cert_type := 6 bytes
* ec curves := 8 bytes
* ec point format := 6 bytes => 26
* sign. and hash algos := 8 bytes
* extended master secret := 4 bytes => 12
*
* (The ClientHello uses TLS_EMPTY_RENEGOTIATION_INFO_SCSV
* instead of renegotiation info)
*/
#define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
#define DTLS_COOKIE_LENGTH_MAX 32
#define DTLS_CH_LENGTH_MAX DTLS_CH_LENGTH + DTLS_COOKIE_LENGTH_MAX + 10 + (2 * DTLS_MAX_CIPHER_SUITES) + 26 + 12
#define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
/*
* ServerHello:
*
* version := 2 bytes
* random := 32 bytes
* session_length := 1 byte
* session := 0 bytes
* cipher suite := 2 bytes
* compression := 1 byte
*/
#define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
#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 + max(DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN))
#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 DTLS_ALERT_LENGTH 2 /* length of the Alert message */
#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))
/*
* Skip variable length field.
*
* A variable length field is encoded with a preceding length followed by
* the value. That length itself is encoded in one to three bytes using uint8,
* uint16, or uint24. Decoding a variable length field requires to check first,
* if the length itself is within the bounds, and if so, if the value is also
* within the bounds.
*
* The macro "returns" the calling context with an error when the bounds are
* violated.
*
* \param P pointer to length of the var field. Will be forwarded the end of
* the var field.
* \param L left overall data of P. Will be reduced by the size of the var
* field.
* \param T length type. e.g. uint8 or uint16
* \param A alert description in case of a length violation
* \param M logging message in case of a length violation
*/
#define SKIP_VAR_FIELD(P, L, T, A, M) { \
size_t skip_length = sizeof(T); \
if (L < skip_length) { \
dtls_info("%s: field length exceeds buffer", M); \
return dtls_alert_fatal_create(A); \
} \
skip_length += dtls_ ## T ## _to_int(P); \
if (L < skip_length) { \
dtls_info("%s: field value exceeds buffer", M); \
return dtls_alert_fatal_create(A); \
} \
L -= skip_length; \
P += skip_length; \
}
/*
* Get variable length field.
*
* A variable length field is encoded with a preceding length followed by
* the value. That length itself is encoded in one to three bytes using uint8,
* uint16, or uint24. Decoding a variable length field requires to check first,
* if the length itself is within the bounds, and if so, if the value is also
* within the bounds.
*
* The macro "returns" the calling context with an error when the bounds are
* violated.
*
* \param VL value length, variable to assign the length of the field value.
* \param P pointer to length of the var field. Will be forwarded to the
* value of the field.
* \param L left overall data of P. Will be reduced by the size of the field
* length type
* \param T field length type. e.g. uint8 or uint16
* \param A alert description in case of a length violation
* \param M logging message in case of a length violation
*/
#define GET_VAR_FIELD(VL, P, L, T, A, M) { \
if (L < sizeof(T)) { \
dtls_info("%s: field length exceeds buffer", M); \
return dtls_alert_fatal_create(A); \
} \
VL = dtls_ ## T ## _to_int(P); \
L -= sizeof(T); \
P += sizeof(T); \
if (L < VL) { \
dtls_info("%s: field value exceeds buffer", M); \
return dtls_alert_fatal_create(A); \
} \
}
/* 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_extended_master[] = "extended 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";
#ifdef DTLS_ECC
/* 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 */
};
#endif /* DTLS_ECC */
#ifdef WITH_CONTIKI
PROCESS(dtls_retransmit_process, "DTLS retransmit process");
#endif /* WITH_CONTIKI */
#if defined(WITH_CONTIKI) || defined(WITH_LWIP)
static dtls_context_t the_dtls_context;
static inline dtls_context_t *
malloc_context(void) {
return &the_dtls_context;
}
static inline void
free_context(dtls_context_t *context) {
(void)context;
}
#endif /* WITH_CONTIKI || WITH_LWIP */
#ifdef RIOT_VERSION
static inline dtls_context_t *
malloc_context(void) {
return (dtls_context_t *) memarray_alloc(&dtlscontext_storage);
}
static inline void free_context(dtls_context_t *context) {
memarray_free(&dtlscontext_storage, context);
}
#endif /* RIOT_VERSION */
#if defined(WITH_POSIX) || defined(IS_WINDOWS)
static inline dtls_context_t *
malloc_context(void) {
return (dtls_context_t *)malloc(sizeof(dtls_context_t));
}
static inline void
free_context(dtls_context_t *context) {
free(context);
}
#endif /* WITH_POSIX */
void
dtls_init(void) {
dtls_clock_init();
crypto_init();
netq_init();
peer_init();
#ifdef RIOT_VERSION
memarray_init(&dtlscontext_storage, dtlscontext_storage_data,
sizeof(dtls_context_t), DTLS_CONTEXT_MAX);
#endif /* RIOT_VERSION */
}
/* 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);
static int
handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
uint8 *record_header, uint8 *data, size_t data_length);
/**
* 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_writev(struct dtls_context_t *ctx,
session_t *dst, uint8 *buf_array[],
size_t buf_len_array[], size_t buf_array_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_multi(ctx, peer, dtls_security_params(peer),
&peer->session, DTLS_CT_APPLICATION_DATA,
buf_array, buf_len_array, buf_array_len);
}
}
}
int
dtls_write(struct dtls_context_t *ctx, session_t *session,
uint8 *buf, size_t len) {
return dtls_writev(ctx, session, &buf, &len, 1);
}
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 session id */
SKIP_VAR_FIELD(msg, msglen, uint8, DTLS_ALERT_HANDSHAKE_FAILURE,
"get_cookie, 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);
}
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];
uint8 *start;
int len;
/* create cookie with HMAC-SHA256 over:
* - SECRET
* - session parameters (only IP address?)
* - client version
* - random gmt and bytes
* - session id
* - cipher_suites
* - compression method
*
* See RFC6347, 4.2.1. Denial-of-Service Countermeasures, page 17
*
* "When responding to a HelloVerifyRequest, the client MUST use the same
* parameter values (version, random, session_id, cipher_suites,
* compression_method) as it did in the original ClientHello. The
* server SHOULD use those values to generate its cookie and verify that
* they are correct upon cookie receipt."
*/
/* Note that the buffer size must fit with the default hash algorithm. */
dtls_hmac_context_t hmac_context;
dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
dtls_hmac_update(&hmac_context, (uint8 *)&session->addr, session->size);
if (DTLS_HS_LENGTH + DTLS_CH_LENGTH > msglen)
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
/* skip DTLS_HS_LENGTH */
msg += DTLS_HS_LENGTH;
msglen -= DTLS_HS_LENGTH;
start = msg;
/* add DTLS_CH_LENGTH by forward msg pointer */
msg += DTLS_CH_LENGTH;
msglen -= DTLS_CH_LENGTH;
/* add session_id by forward msg pointer */
SKIP_VAR_FIELD(msg, msglen, uint8, DTLS_ALERT_HANDSHAKE_FAILURE,
"create_cookie, session_id");
dtls_hmac_update(&hmac_context, start, msg - start);
/* skip cookie. */
SKIP_VAR_FIELD(msg, msglen, uint8, DTLS_ALERT_HANDSHAKE_FAILURE,
"create_cookie, cookie");
/* add cipher suites and compression by forward msg pointer. */
start = msg;
SKIP_VAR_FIELD(msg, msglen, uint16, DTLS_ALERT_HANDSHAKE_FAILURE,
"create_cookie, cipher-suites");
SKIP_VAR_FIELD(msg, msglen, uint8, DTLS_ALERT_HANDSHAKE_FAILURE,
"create_cookie, compression");
dtls_hmac_update(&hmac_context, start, msg - start);
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 */
};
/**
* Checks if the content type of \p msg is known. This function returns
* the found content type, or 0 otherwise.
*/
static int
known_content_type(const uint8_t *msg) {
unsigned int n;
assert(msg);
for (n = 0; (content_types[n] != 0) && (content_types[n]) != msg[0]; n++)
;
return content_types[n];
}
#else /* DTLS_CHECK_CONTENTTYPE */
static int
known_content_type(const uint8_t *msg) {
return msg[0];
}
#endif /* DTLS_CHECK_CONTENTTYPE */
/**
* 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? */
uint16_t version = dtls_get_version(DTLS_RECORD_HEADER(msg));
if (DTLS_VERSION == version) {
if (!known_content_type(msg)) {
return 0;
}
} else if (DTLS10_VERSION == version) {
if (DTLS_CT_HANDSHAKE != msg[0] || DTLS_RH_LENGTH == msglen) {
return 0;
} else {
uint8_t handshake_type = msg[DTLS_RH_LENGTH];
if (DTLS_HT_CLIENT_HELLO != handshake_type &&
DTLS_HT_HELLO_VERIFY_REQUEST != handshake_type) {
return 0;
}
}
} else {
return 0;
}
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 records sequence number counter.
* \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,
uint16_t epoch,
uint64_t *rseqn,
uint8 *buf) {
dtls_int_to_uint8(buf, type);
buf += sizeof(uint8);
dtls_int_to_uint16(buf, DTLS_VERSION);
buf += sizeof(uint16);
dtls_int_to_uint16(buf, epoch);
buf += sizeof(uint16);
dtls_int_to_uint48(buf, *rseqn);
buf += sizeof(uint48);
/* increment record sequence counter by 1 */
(*rseqn)++;
/* space for record size */
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.
* \return pointer to the next byte after \p buf
*/
static inline uint8 *
dtls_set_handshake_header(uint8 type,
uint16_t *mseqn,
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);
/* and copy the result to buf */
dtls_int_to_uint16(buf, *mseqn);
buf += sizeof(uint16);
/* increment handshake message sequence counter by 1 */
(*mseqn)++;
dtls_int_to_uint24(buf, frag_offset);
buf += sizeof(uint24);
dtls_int_to_uint24(buf, frag_length);
buf += sizeof(uint24);
return buf;
}
/**
* A copy of default_user_parameters are passed to the get_user_parameters
* callback provided in dtls_handler_t and may be adapted according the user's
* requirements.
*/
static const dtls_user_parameters_t default_user_parameters = {
.cipher_suites =
#ifdef DTLS_DEFAULT_CIPHER_SUITES
DTLS_DEFAULT_CIPHER_SUITES,
#else /* DTLS_DEFAULT_CIPHER_SUITES */
{
#ifdef DTLS_ECC
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
#endif /* DTLS_ECC */
#ifdef DTLS_PSK
TLS_PSK_WITH_AES_128_CCM_8,
TLS_PSK_WITH_AES_128_CCM,
#endif /* DTLS_PSK */
/* TLS_NULL_WITH_NULL_NULL must always be the last entry as it
* indicates the stop marker for the traversal of this table. */
TLS_NULL_WITH_NULL_NULL
},
#endif /* DTLS_DEFAULT_CIPHER_SUITES */
.force_extended_master_secret = 1,
.force_renegotiation_info = 1,
};
/** only one compression method is currently defined */
static uint8 compression_methods[] = {
TLS_COMPRESSION_NULL
};
typedef enum {
DTLS_KEY_EXCHANGE_NONE,
DTLS_KEY_EXCHANGE_PSK,
DTLS_KEY_EXCHANGE_ECDHE_ECDSA
} cipher_suite_key_exchange_algorithm_t;
typedef struct cipher_suite_param_t {
dtls_cipher_t cipher_suite;
uint8_t mac_length;
cipher_suite_key_exchange_algorithm_t key_exchange_algorithm;
} cipher_suite_param_t;
static const struct cipher_suite_param_t cipher_suite_params[] = {
/* The TLS_NULL_WITH_NULL_NULL cipher suite must be the first
* in this table (index DTLS_CIPHER_INDEX_NULL) */
{ TLS_NULL_WITH_NULL_NULL, 0, DTLS_KEY_EXCHANGE_NONE },
#ifdef DTLS_PSK
{ TLS_PSK_WITH_AES_128_CCM_8, 8, DTLS_KEY_EXCHANGE_PSK },
{ TLS_PSK_WITH_AES_128_CCM, 16, DTLS_KEY_EXCHANGE_PSK },
#endif /* DTLS_PSK */
#ifdef DTLS_ECC
{ TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 8, DTLS_KEY_EXCHANGE_ECDHE_ECDSA },
{ TLS_ECDHE_ECDSA_WITH_AES_128_CCM, 16, DTLS_KEY_EXCHANGE_ECDHE_ECDSA },
#endif /* DTLS_ECC */
};
static const dtls_cipher_index_t last_cipher_suite_param =
sizeof(cipher_suite_params) / sizeof(cipher_suite_param_t);
/**
* Check if cipher suite is contained in table.
*
* \param cipher_suites table with cipher suites. Terminated with
* TLS_NULL_WITH_NULL_NULL.
* \param cipher_suite cipher suite
* \return 0 if not contained, != 0 if contained
*/
static inline uint8_t
contains_cipher_suite(const dtls_cipher_t* cipher_suites, const dtls_cipher_t cipher_suite) {
if (cipher_suite == TLS_NULL_WITH_NULL_NULL) {
return 0;
}
while ((*cipher_suites != cipher_suite) &&
(*cipher_suites != TLS_NULL_WITH_NULL_NULL)) {
cipher_suites++;
}
return *cipher_suites == cipher_suite;
}
/**
* Get index to cipher suite params.
*
* \param cipher_suites table with user-selected cipher suites. Terminated with
* TLS_NULL_WITH_NULL_NULL.
* \param cipher cipher suite
* \return index to cipher suite params, DTLS_CIPHER_INDEX_NULL if not found.
*/
static inline dtls_cipher_index_t
get_cipher_index(const dtls_cipher_t* cipher_suites, dtls_cipher_t cipher) {
if (contains_cipher_suite(cipher_suites, cipher)) {
for (int index = 0; index < last_cipher_suite_param ; ++index) {
if (cipher_suite_params[index].cipher_suite == cipher) {
return index;
}
}
}
return DTLS_CIPHER_INDEX_NULL;
}
/**
* Get cipher suite.
* \param cipher_index index to cipher suite params
* \return cipher suite.
*/
static inline dtls_cipher_t
get_cipher_suite(dtls_cipher_index_t cipher_index) {
assert(cipher_index < last_cipher_suite_param);
return cipher_suite_params[cipher_index].cipher_suite;
}
/**
* Get key exchange algorithm of cipher suite.
* \param cipher_index index to cipher suite params
* \return key exchange algorithm.
* \c DTLS_KEY_EXCHANGE_NONE, if cipher is not supported.
*/
static inline cipher_suite_key_exchange_algorithm_t
get_key_exchange_algorithm(dtls_cipher_index_t cipher_index) {
assert(cipher_index < last_cipher_suite_param);
return cipher_suite_params[cipher_index].key_exchange_algorithm;
}
/**
* Get MAC length of cipher suite.
* \param cipher_index index to cipher suite params
* \return MAC length of cipher. \c 0, if cipher is not supported.
*/
static inline uint8_t
get_cipher_suite_mac_len(dtls_cipher_index_t cipher_index) {
assert(cipher_index < last_cipher_suite_param);
return cipher_suite_params[cipher_index].mac_length;
}
/** returns true if the cipher suite uses an ECDHE_ECDSA key exchange */
static inline int
is_key_exchange_ecdhe_ecdsa(dtls_cipher_index_t cipher_index) {
#ifdef DTLS_ECC
return DTLS_KEY_EXCHANGE_ECDHE_ECDSA == get_key_exchange_algorithm(cipher_index);
#else
(void) cipher_index;
return 0;
#endif /* DTLS_ECC */
}
/** returns true if the cipher suite uses an PSK key exchange */
static inline int
is_key_exchange_psk(dtls_cipher_index_t cipher_index) {
#ifdef DTLS_PSK
return DTLS_KEY_EXCHANGE_PSK == get_key_exchange_algorithm(cipher_index);
#else
(void) cipher_index;
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
(void) ctx;
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
(void) ctx;
(void) is_client;
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
(void) ctx;
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 cipher_index The index to cipher suite params 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_index_t cipher_index, int is_client) {
const int psk = is_psk_supported(ctx);
const int ecdsa = is_ecdsa_supported(ctx, is_client);
const cipher_suite_key_exchange_algorithm_t key_exchange_algorithm =
get_key_exchange_algorithm(cipher_index);
return (psk && key_exchange_algorithm == DTLS_KEY_EXCHANGE_PSK) ||
(ecdsa && key_exchange_algorithm == DTLS_KEY_EXCHANGE_ECDHE_ECDSA);
}
/** Dump out the cipher keys and IVs used for the symmetric 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 given 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 const 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";
}
}
static const char *
dtls_message_type_to_name(int type) {
switch (type) {
case DTLS_CT_CHANGE_CIPHER_SPEC:
return "change_cipher_spec";
case DTLS_CT_ALERT:
return "alert";
case DTLS_CT_HANDSHAKE:
return "handshake";
case DTLS_CT_APPLICATION_DATA:
return "application_data";
default:
return NULL;
}
}
/**
* 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) {
(void) ctx;
(void) session;
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];
(void)role; /* The macro dtls_kb_size() does not use role. */
if (!security) {
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
pre_master_secret = security->key_block;
switch (get_key_exchange_algorithm(handshake->cipher_index)) {
case DTLS_KEY_EXCHANGE_PSK:
#ifdef DTLS_PSK
{
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) {